//FILENAME: loadableUtils/utils.java package loadableUtils; import java.util.*; import java.util.zip.*; import java.util.List; import java.util.regex.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; import 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 java.time.Duration; import java.lang.invoke.VarHandle; import java.lang.invoke.MethodHandles; import org.apache.bcel.classfile.ClassParser; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.Const; import org.apache.bcel.generic.*; import java.lang.reflect.Type; import org.ejml.data.*; import org.ejml.dense.row.*; import org.ejml.dense.row.decomposition.eig.*; import me.saharnooby.qoi.plugin.*; import javax.swing.border.TitledBorder; import java.text.*; import javax.swing.border.*; import javax.swing.Timer; import java.util.TimeZone; import java.util.jar.*; import java.awt.image.DataBufferByte; import java.awt.geom.*; import javax.swing.event.AncestorListener; import javax.swing.event.AncestorEvent; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.nio.file.Path; import javax.swing.undo.UndoManager; import javax.imageio.metadata.*; import javax.imageio.stream.*; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.*; import java.awt.geom.Line2D; import com.github.sarxos.webcam.*; import org.fife.ui.rsyntaxtextarea.*; import java.nio.charset.Charset; import java.text.NumberFormat; import java.awt.font.TextAttribute; import java.awt.geom.AffineTransform; import java.awt.dnd.*; import javax.swing.border.Border; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.DataFlavor; import com.jogamp.graph.curve.OutlineShape; import com.jogamp.graph.curve.Region; import com.jogamp.graph.curve.opengl.GLRegion; import com.jogamp.graph.curve.opengl.RegionRenderer; import com.jogamp.graph.curve.opengl.RenderState; import com.jogamp.graph.geom.SVertex; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.*; import com.jogamp.opengl.fixedfunc.GLMatrixFunc; import com.jogamp.opengl.util.Animator; import com.jogamp.opengl.util.PMVMatrix; import javax.swing.plaf.basic.BasicSliderUI; import java.awt.geom.Ellipse2D; import java.awt.datatransfer.UnsupportedFlavorException; import org.fife.ui.rsyntaxtextarea.TokenMakerBase; 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.RSyntaxDocument; import org.fife.ui.rsyntaxtextarea.SyntaxScheme; 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.zip.ZipOutputStream; import java.nio.file.*; import static java.nio.file.StandardWatchEventKinds.*; import java.awt.geom.Path2D; import javax.swing.Icon; import java.util.*; import java.io.*; import java.net.*; import java.nio.channels.FileChannel; import java.security.KeyStore; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPOutputStream; import javax.net.ssl.*; import java.time.Duration; import java.time.temporal.ChronoUnit; import org.bytedeco.javacpp.*; import static org.bytedeco.javacpp.avcodec.*; import static org.bytedeco.javacpp.avformat.*; import static org.bytedeco.javacpp.avutil.*; import org.bytedeco.javacpp.presets.avutil; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.nio.charset.*; import java.nio.*; public class utils { static public String utilsSnippetID() { return "#1033861"; } static public interface Derefable { public Concept get(); } static public class DynamicObject { public String className; public LinkedHashMap fieldValues; public DynamicObject() { } public DynamicObject(String className) { this.className = className; } public Map _map() { return fieldValues; } public String toString() { return getClass() == DynamicObject.class ? "dyn " + className : super.toString(); } } static public File nohupJavax(String javaxargs) { return directNohupJavax(javaxargs); } static public File nohupJavax(String javaxargs, String vmArgs) { return directNohupJavax(javaxargs, vmArgs); } static public interface DynamicMethods { abstract public Object _dynCall(String methodName, Object[] args); } static public class BetterLabel extends JLabel { public boolean autoToolTip = true; public BetterLabel() { final WeakReference me = new WeakReference<>(this); componentPopupMenu(this, BetterLabel_menuItems(me)); } public BetterLabel(String text) { this(); this.setText(text); } public void setText(String text) { super.setText(text); if (autoToolTip) if (!swic(text, "")) setToolTipText(nullIfEmpty(text)); } } static public VF1 BetterLabel_menuItems(final WeakReference me) { return new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try { copyTextToClipboard(me.get().getText()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(me.get().getText());"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(me..."; } }; } static public class SingleComponentPanel extends JPanel { public SingleComponentPanel() { super(new BorderLayout()); } public SingleComponentPanel(Component component) { this(); if (component != null) setComponent(component); } public void set(Swingable component) { set(wrap(component)); } final public void set(Component component) { setComponent(component); } public void setComponent(Component component) { { swing(() -> { if (getComponent() == component) return; removeAll(); if (component != null) add(BorderLayout.CENTER, wrap(component)); _revalidate(SingleComponentPanel.this); }); } } public void setComponentAndRevalidateParent(Component component) { setComponent(component); _revalidate(_getParent(this)); } final public void clear() { noComponent(); } public void noComponent() { setComponent(null); } final public Component get() { return getComponent(); } public Component getComponent() { return swing(() -> getComponentCount() == 0 ? null : getComponent(0)); } public boolean isEmpty() { return getComponent() == null; } public boolean hasComponent() { return getComponent() != null; } } static public class Snippet { public String id, title, md5, type, text; public boolean isPublic = false; public Snippet() { } public Snippet(String id, String title) { this.title = title; this.id = id; } public Snippet(String id, String title, String md5) { this.md5 = md5; this.title = title; this.id = id; } public String toString() { return id + " - " + title; } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } } static final public class BWImage extends Meta implements MakesBufferedImage, IBWImage { public int width, height; public byte[] pixels; public float borderColor = 0.0f; public BWImage() { } public BWImage(int width, int height) { this.height = height; this.width = width; pixels = new byte[width * height]; } public BWImage(int width, int height, float brightness) { this.height = height; this.width = width; pixels = new byte[width * height]; fillArrayUnlessZero(pixels, _toByte(brightness)); } public BWImage(int width, int height, float[] pixels) { this.pixels = new byte[pixels.length]; this.height = height; this.width = width; for (int i = 0; i < pixels.length; i++) this.pixels[i] = _toByte(pixels[i]); } public BWImage(int width, int height, byte[] pixels) { this.height = height; this.width = width; this.pixels = pixels; } public BWImage(BWImage image) { width = image.getWidth(); height = image.getHeight(); byte[] pixels = this.pixels = new byte[width * height]; for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) pixels[y * width + x] = image.getByte(x, y); } public BWImage(RGBImage image) { width = image.getWidth(); height = image.getHeight(); byte[] pixels = this.pixels = new byte[height * width]; for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) { RGB rgb = image.getRGB(x, y); pixels[y * width + x] = BWImage._toByte(rgb.getBrightness()); } } public BWImage(BufferedImage image) { try { width = image.getWidth(); height = image.getHeight(); int[] pixels = new int[width * height]; byte[] bytePixels = this.pixels = new byte[width * height]; PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width); if (!pixelGrabber.grabPixels()) throw fail("Could not grab pixels"); int n = width * height; for (int i = 0; i < n; i++) { int packed = pixels[i]; int r = ((packed >> 16) & 0xFF); int g = ((packed >> 8) & 0xFF); int b = (packed & 0xFF); bytePixels[i] = (byte) ((r + g + b + 1) / 3); } } catch (Exception __e) { throw rethrow(__e); } } static public byte pixelToByte(int packed) { float r = ((packed >> 16) & 0xFF) / 255f; float g = ((packed >> 8) & 0xFF) / 255f; float b = (packed & 0xFF) / 255f; return (byte) ((r + g + b) / 3.0f * 255f); } public byte getByte(int x, int y) { return inRange(x, y) ? getByte_noRangeCheck(x, y) : _toByte(borderColor); } public int getInt(int x, int y) { return ubyteToInt(getByte(x, y)); } public int getInt_noRangeCheck(int idx) { return ubyteToInt(pixels[idx]); } public int getInt(int x, int y, int defaultValue) { return inRange(x, y) ? getInt(x, y) : defaultValue; } public double averageBrightness() { double sum = 0; int n = width * height; for (int i = 0; i < n; i++) sum += getInt_noRangeCheck(i); return sum / n; } public float minimumBrightness() { float min = 1; for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) min = Math.min(min, getPixel(x, y)); return min; } public float maximumBrightness() { float max = 0; for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) max = Math.max(max, getPixel(x, y)); return max; } public float getPixel(int x, int y) { return inRange(x, y) ? _toFloat(getByte(x, y)) : borderColor; } public float getFloatPixel(int x, int y) { return getPixel(x, y); } public float getPixel(Pt p) { return getPixel(p.x, p.y); } static public byte _toByte(float pixel) { return (byte) (pixel * 255f); } static public float _toFloat(byte pixel) { return (((int) pixel) & 255) / 255f; } private boolean inRange(int x, int y) { return x >= 0 && x < width && y >= 0 && y < height; } public int getWidth() { return width; } public int getHeight() { return height; } public RGBImage toRGB() { int[] rgbs = new int[width * height]; for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) { int b = getByte(x, y) & 0xFF; rgbs[y * width + x] = 0xFF000000 | b * 0x010101; } return new RGBImage(width, height, rgbs); } public RGBImage toRGB_slow() { RGB[] rgbs = new RGB[width * height]; for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) { float p = getPixel(x, y); rgbs[y * width + x] = new RGB(p, p, p); } return new RGBImage(width, height, rgbs); } public BWImage clip(int x, int y, int w, int h) { return clip(new Rectangle(x, y, w, h)); } private Rectangle fixClipRect(Rectangle r) { return r.intersection(new Rectangle(0, 0, width, height)); } public BWImage clip(Rect r) { return clip(r.getRectangle()); } public BWImage clip(Rectangle r) { r = fixClipRect(r); byte[] newPixels = new byte[r.height * r.width]; for (int y = 0; y < r.height; y++) for (int x = 0; x < r.width; x++) newPixels[y * r.width + x] = getByte(r.x + x, r.y + y); return new BWImage(r.width, r.height, newPixels); } public void setPixel(int x, int y, float brightness) { setByte(x, y, _toByte(fixPixel(brightness))); } public void setInt(int x, int y, int i) { setByte(x, y, (byte) limitToUByte(i)); } public void setInt(Pt p, int i) { setInt(p.x, p.y, i); } public void setByte(int x, int y, byte b) { if (x >= 0 && x < width && y >= 0 && y < height) pixels[y * width + x] = b; } public byte getByte_noRangeCheck(int x, int y) { return pixels[y * width + x]; } public void setByte(int x, int y, int brightness) { setByte(x, y, (byte) brightness); } private float fixPixel(float pixel) { return Math.max(0, Math.min(1, pixel)); } public float getBorderColor() { return borderColor; } public void setBorderColor(float borderColor) { this.borderColor = borderColor; } public boolean anyPixelBrighterThan(double threshold) { for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) if (getPixel(x, y) > threshold) return true; return false; } public int[] getRGBPixels() { int n = width * height; int[] out = new int[n]; for (int i = 0; i < n; i++) { var b = ubyteToInt(pixels[i]); b |= (b << 8) | (b << 16); out[i] = b | 0xFF000000; } return out; } public BufferedImage getBufferedImage() { return bufferedImage(getRGBPixels(), width, height); } public byte[] getBytes() { return pixels; } } static public class Cache { public Object maker; public A value; public long loaded; static public boolean debug = false; public long changeCount; public Lock lock = lock(); public Cache() { } public Cache(Object maker) { this.maker = maker; } public Cache(IF0 maker) { this.maker = maker; } public A get() { if (hasLock(lock)) return value; Lock __20 = lock; lock(__20); try { if (loaded == 0) { value = make(); changeCount++; loaded = sysNow(); } return value; } finally { unlock(__20); } } public void clear() { Lock __21 = lock; lock(__21); try { if (debug && loaded != 0) print("Clearing cache"); value = null; changeCount++; loaded = 0; } finally { unlock(__21); } } public void clear(double seconds) { Lock __22 = lock; lock(__22); try { if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000) clear(); } finally { unlock(__22); } } public void set(A a) { Lock __23 = lock; lock(__23); try { value = a; ++changeCount; loaded = sysNow(); } finally { unlock(__23); } } public A make() { return (A) callF(maker); } } static abstract public class DynModule extends DynamicObject implements Enterable, ChangeTriggerable, IHasChangeListeners { public String name, toolTip; public PersistableThrowable _error; public Map> mechLists; public Map _persistenceInfo; transient public Object _host; transient public Map timers = newWeakHashMap(); transient public Set _resources = synchroHashSet(); transient public Lock lock; transient public boolean persistOnChangedField = true; transient public int changeCount; transient public Object changeCountSync = new Object(); transient public List onChange; transient public List onTransientChange; transient public boolean verboseTimers = false; transient public ReliableSingleThread rstUpdate; transient public Set componentFieldsToKeep; transient public Map transientGeneralMap = synchroHashMap(); transient public Q q; transient public List onFieldChange; transient public boolean _hasPreviousBounds = false; transient public StringBuffer _printLog = new StringBuffer(); transient public boolean deleted = false; public DynModule() { if (useErrorHandling()) dm_initErrorHandling(); setMainDesktopPane((JDesktopPane) getCreatorOpt("desktop")); } public boolean useErrorHandling() { return true; } public boolean isVisible() { return isTrue(getOpt(_host, "visible")); } public String moduleName() { return name; } public void setModuleName(String name) { String oldName = this.name; if (!eq(name, oldName)) { setField("name", name); possiblyInternalFrameTitle(vis(), name); vmBus_send("moduleNameChange", this, oldName, name); } } public void setModuleToolTip(String toolTip) { this.toolTip = toolTip; } public JComponent vis() { return (JComponent) getOpt(_host, "vis"); } public A ownResource(A a) { if (a != null) _resources.add(a); return a; } public A ownTimer(A timer) { if (timer instanceof AutoCloseable) ownResource((AutoCloseable) timer); else ownTimer(timer, __36 -> cancelTimerOrInterruptThread(__36)); return timer; } public void ownTimer(Object timer, IVF1 closerHelper) { timers.put(timer, closerHelper); } public void singleTimer(java.util.Timer timer) { stopAllTimers(); ownTimer(timer); } public void stopAllTimers() { for (AutoCloseable resource : getAndClearList(_resources)) { if (verboseTimers) print("Releasing resource: " + resource); try { resource.close(); } catch (Throwable __e) { pcallFail(__e); } } for (Map.Entry __26 : _entrySet(getAndClearMap(timers))) { Object timer = __26.getKey(); IVF1 closerHelper = __26.getValue(); if (verboseTimers) print("Stopping timer: " + closerHelper + " / " + timer); pcallF(closerHelper, timer); } } public boolean isDeleted() { return deleted; } public boolean deleted() { return deleted; } public void cleanMeUp_dynModule() { deleted = true; { cleanUp(q); q = null; } stopAllTimers(); } public void persistMe() { synchronized (changeCountSync) { ++changeCount; } pcallFAll(onChange); callOpt(_host, "_change"); updateMe(); } public void fireChangeWithoutPersisting() { pcallFAll(onChange); } public void fireTransientChange() { pcallFAll(onTransientChange); } final public void _change() { persistMe(); } final public void change() { persistMe(); } public void updateMe() { rstUpdate().trigger(); } public void changeAndUpdate() { _change(); updateMe(); } public boolean setField_noPersist(String name, Object value) { return setField(name, value, true); } public boolean _setField(String name, Object value) { return setField(name, value); } public boolean setField(String name, Object value) { return setField(name, value, false); } public boolean setField(String name, Object value, boolean noPersist) { AutoCloseable __32 = enter(); try { try { if (eq(get(this, name), value)) return false; } catch (Throwable __e) { pcallFail(__e); } return setField_noCheck(name, value, noPersist); } finally { _close(__32); } } public boolean setField_noCheck(String name, Object value) { return setField_noCheck(name, value, false); } public boolean setField_noCheck(String name, Object value, boolean noPersist) { AutoCloseable __33 = enter(); try { setOpt(this, name, value); pcallFAll(onFieldChange, name); if (!noPersist && dm_isPersistentField(me(), name)) _change(); return true; } finally { _close(__33); } } public A setFieldAndReturn(String name, A value) { setField(name, value); return value; } public boolean setFields(Object... params) { boolean change = false; for (int i = 0; i < l(params); i += 2) if (setField((String) params[i], params[i + 1])) change = true; return change; } public void start() { _hasPreviousBounds = dm_getBounds() != null; if (hasMethod_onTypes(this, "onTopInput", String.class)) dm_onTopInput_q(new VF1() { public void get(String s) { try { call(module(), "onTopInput", s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "call(module(), 'onTopInput, s)"; } }); } public void revisualize() { call(dm_os(), "revisualizeModule", _host); } public boolean useEnterShortcut() { return false; } public AutoCloseable enter() { AutoCloseable c = tempSetBetterThreadLocalIfNecessary_weakRef(dm_current_generic_tl(), this); if (c == null && useEnterShortcut()) return null; Object realMC = getMainClass(this); if (printToModule()) c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(_printToModuleInterceptor())); if (realMC != mc()) { if (printToModule()) c = combineAutoCloseables(c, (AutoCloseable) callOpt(realMC, "tempInterceptPrintIfNotIntercepted", _printToModuleInterceptor())); else c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(new F1() { public Boolean get(String s) { try { { call(realMC, "print", s); return false; } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret false with call(realMC, 'print, s);"; } })); c = combineAutoCloseables(c, tempSetTL(realMC_tl(), realMC)); } return c; } public F1 _printToModuleInterceptor() { return new F1() { public Boolean get(String s) { try { if (print_preprocess != null) s = (String) callF(print_preprocess, s); s = fixNewLines(s); Appendable loc = _printLog; Appendable buf = print_log; int loc_max = print_log_max; if (buf != loc && buf != null) { print_append(buf, s, print_log_max); loc_max = local_log_max; } if (loc != null) print_append(loc, s, loc_max); if (printAlsoToSystemOut) System.out.print(s); return false; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (print_preprocess != null) s = (S) callF(print_preprocess, s);\r\n s = ..."; } }; } public boolean printToModule() { return true; } public AutoCloseable enterAndLock() { return combineAutoCloseables(enter(), tempLock(lock)); } public boolean setError(Throwable e) { setField("_error", persistableThrowable(e)); return true; } public void clearError() { setField("_error", null); } public DynModule onChange(Runnable r) { Lock __27 = lock; lock(__27); try { if (onChange == null) onChange = synchroList(); addIfNotThere(onChange, r); return this; } finally { unlock(__27); } } public DynModule removeChangeListener(Runnable r) { remove(onChange, r); return this; } public void onFieldChange(VF1 r) { Lock __29 = lock; lock(__29); try { if (onFieldChange == null) onFieldChange = synchroList(); addIfNotThere(onFieldChange, r); } finally { unlock(__29); } } public void removeFieldChangeListener(VF1 r) { remove(onFieldChange, r); } public void onChangeAndNow(JComponent c, Object r) { onUpdateAndNow(c, r); } public void onChangeAndNow(List l, Object r) { utils.onChangeAndNow(l, r); } public void onChangeAndNow(JTextComponent c, IVF1 r) { onUpdateAndNow(c, r); } public A onChange(A tc, Object r) { onUpdate(tc, r); return tc; } public void update() { } public void unvisualize() { zeroAllFieldsOfTypeExcept(this, Component.class, componentFieldsToKeep); } public Object menuItems() { return null; } public void enhanceFrame(Container f) { Object items = menuItems(); if (items instanceof Object[]) items = paramsToAbstractActions((Object[]) items); internalFramePopupMenuFromActions_threaded(f, (List) items); String switchableFields = (String) (callOpt(this, "switchableFields")); Set set = asLinkedHashSet(splitAtSpace(switchableFields)); Matches m = new Matches(); for (String field : allFields(getClass())) if (startsWith(field, "_switchableField_", m)) set.add(m.rest()); for (String field : set) { Class type = fieldType(this, field); if (eq(boolean.class, type)) dm_boolFieldMenuItem(f, field); else if (eq(int.class, type)) dm_intFieldMenuItem(f, field); else if (eq(long.class, type)) dm_longFieldMenuItem(f, field); else if (eq(double.class, type)) dm_doubleFieldMenuItem(f, field); else if (eq(float.class, type)) dm_floatFieldMenuItem(f, field); else if (eq(String.class, type)) dm_stringFieldMenuItem(f, field); else if (eq(File.class, type)) dm_fileFieldMenuItem(f, field); } } public ReliableSingleThread rstUpdate() { if (rstUpdate == null) rstUpdate = dm_rst(this, new Runnable() { public void run() { try { AutoCloseable __34 = enter(); try { update(); } finally { _close(__34); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter(); update();"; } }); return rstUpdate; } public Q q() { AutoCloseable __35 = enter(); try { if (q == null) { Lock __30 = lock; lock(__30); try { if (q == null) q = dm_startQ(); } finally { unlock(__30); } } return q; } finally { _close(__35); } } public A withUpdate(A a) { rstUpdate().trigger(); return a; } public DynModule module() { return this; } public DynModule me() { return this; } public JComponent visualize() { return dm_noVisualisation(); } public String programTitle_cache; public String programTitle() { if (programTitle_cache == null) programTitle_cache = snippetTitle(programID(mainClass(this))); return programTitle_cache; } public void doPersist(String field) { _persistenceInfo = mapMinus(_persistenceInfo, field); } public void dontPersist(String field) { _persistenceInfo = mapPlus(_persistenceInfo, "field", false); } public Appendable _actualPrintLog() { return printToModule() ? _printLog : print_log; } public Object getHost() { return _host; } public boolean addAndChange(Collection cl, A a) { if (cl == null || !cl.add(a)) return false; change(); return true; } public void clearAndChange(Collection cl) { if (cl == null) return; cl.clear(); change(); } public void addAndChange(LongBuffer buf, long a) { if (buf == null) return; buf.add(a); change(); } public void clearAndChange(LongBuffer buf) { if (buf == null) return; buf.clear(); change(); } } static public void _registerTimer(java.util.Timer timer) { _registerTimer_original(timer); var mod = dm_currentModule(); { if (mod != null) mod.ownTimer(timer); } } abstract static public class DynPrintLog extends DynModule { transient public JFastLogView_noWrap printLogView; transient public Lock updatePrintLog_lock = lock(); transient public StringBuffer actualPrintLog; transient public int printLogUpdateInterval = 500; transient public JComponent printLogPanel; public JComponent visualize() { return makePrintLogPanel(); } public JComponent makePrintLogPanel() { JComponent section = printLogPanel = jSection("Log", jscroll_copyBackground(printLogView = jFastLogView_noWrap(getPrintLog()))); componentPopupMenuItem(section, "Clear", new Runnable() { public void run() { try { AutoCloseable __43 = enter(); try { dm_clearModulePrintLog(); } finally { _close(__43); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter(); dm_clearModulePrintLog();"; } }); return awtEvery(section, printLogUpdateInterval, new Runnable() { public void run() { try { updatePrintLog(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "updatePrintLog();"; } }); } public void updatePrintLog() { swing(() -> { Lock __40 = updatePrintLog_lock; lock(__40); try { JFastLogView_noWrap _view = printLogView; if (_view == null) return; if (_view.setText(getPrintLog())) { scrollAllTheWayDown(_view); awtLater(100, new Runnable() { public void run() { try { scrollAllTheWayDown(_view); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "scrollAllTheWayDown(_view)"; } }); } } finally { unlock(__40); } }); } public JFastLogView_noWrap myPrintLogComponent() { return printLogView; } public void enableWordWrap() { } public String getPrintLog() { if (actualPrintLog == null) { if (printToModule()) actualPrintLog = _printLog; else actualPrintLog = liveLocalPrintLog_realMC(this); } return str(actualPrintLog); } } abstract static public class DynObjectTable extends DynModule { public List data = new ArrayList(); transient public JTable table; transient public F1 itemToMap; transient public VF1 defaultAction; transient public boolean debug, fieldsInOrder = true, withSearcher; transient public TableSearcher searcher; transient public List onListChanged; transient public Set hideFields; transient public boolean useStruct = false; public void start() { try { super.start(); itemToMap = new F1() { public Map get(A a) { try { if (a instanceof String) return litorderedmap("", (String) a); Map map = humanizeKeys(fieldsInOrder ? objectToMap_inOrder_withoutFields(a, hideFields) : objectToMap(a)); if (!useStruct) map = mapValues(__87 -> strOrEmpty(__87), map); return map; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (a instanceof S) ret litorderedmap(\"\" := (S) a);\r\n Map map = humanize..."; } }; onChange(new Runnable() { public void run() { try { updateTable(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "updateTable();"; } }); } catch (Exception __e) { throw rethrow(__e); } } public void onListChanged(Runnable r) { if (r == null) return; onListChanged = addDyn_sync(onListChanged, r); } public void onListChangedAndNow(Runnable r) { if (r == null) return; onListChanged(r); r.run(); } public void addCountToName() { onListChangedAndNow(new Runnable() { public void run() { try { addCountToNameNow(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addCountToNameNow();"; } }); } public void addCountToNameNow() { AutoCloseable __47 = enter(); try { setModuleName(programTitle() + " (" + count() + ")"); } finally { _close(__47); } } public JComponent visualize() { List l = map(itemToMap, data); table = dataToTable_uneditable(sexyTable(), l); onDoubleClickOrEnter(table, new VF1() { public void get(Integer row) { try { AutoCloseable __48 = enter(); try { A a = _get(data, row); if (a != null) onDoubleClick(a); } finally { _close(__48); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter();\r\n A a = _get(data, row);\r\n if (a != null) onDoubleCli..."; } }); if (withSearcher) return (searcher = tableWithSearcher2(table)).panel; return table; } public void unvisualize() { super.unvisualize(); searcher = null; } public void onDoubleClick(A line) { callF(defaultAction, line); } public void updateTable() { AutoCloseable __49 = enter(); try { if (table != null) { swing(() -> { Point scrollPosition = enclosingViewPosition(table); if (debug) print("Scroll position: " + scrollPosition); dataToTable_uneditable(table, map(itemToMap, data)); setEnclosingViewPosition(table, scrollPosition); if (searcher != null) searcher.rowIndices = null; if (debug) print("dataToTable done, alerting " + n2(onListChanged, "listener")); }); } pcallFAll(onListChanged); } finally { _close(__49); } } public void dontPersist() { _persistenceInfo = mapPlus(_persistenceInfo, "data", false); } public void clear() { syncClear(data); fireDataChanged(); } public void add(A a) { syncAdd(data, a); fireDataChanged(); } public A addAndReturn(A a) { add(a); return a; } public void add(int idx, A a) { syncAdd(data, idx, a); fireDataChanged(); } public void addAll(Collection l) { if (empty(l)) return; syncAddAll(data, l); fireDataChanged(); } public void addAndScrollDown(A a) { add(a); scrollDown(); } public void remove(A a) { syncRemove(data, a); fireDataChanged(); } public void removeAll(List a) { syncRemoveAll(data, a); fireDataChanged(); } public void setList(Iterable data) { setData(data); } public void removeSelected() { removeAll(allSelected()); } public void setData(Collection data) { setData((Iterable) data); } public void setData(Iterable data) { setData(data, false); } public void setData(Iterable data, boolean force) { { swing(() -> { int[] selection = selectedTableRows_array(table); List cloned = cloneList(data); if (setField("data", cloned) || force) { updateTable(); dm_vmBus_send("listChanged", module(), cloned); } if (force) change(); selectTableRows(table, selection); }); } } public int count() { return syncL(data); } public void setData_force(Collection data) { setData(data, true); } public void fireDataChanged() { setData_force(data); } public int rowFromSearcher(int i) { return searcher == null || searcher.rowIndices == null ? i : or(get(searcher.rowIndices, i), -1); } public A selected() { return syncGet(data, rowFromSearcher(selectedTableRowInModel(table))); } public List allSelected() { return syncListGetMulti(data, selectedIndices()); } public int selectedIndex() { return selectedTableRow(table); } public List selectedIndices() { return map(i -> rowFromSearcher(i), selectedTableRowsInModel(table)); } public boolean selectItem(A a) { int i = indexOf(data, a); selectRow(table, i); return i >= 0; } public void doubleClickItem(A a) { if (selectItem(a)) onDoubleClick(a); } public void popupMenuItem(String text, Object r) { tablePopupMenuItemsThreaded(table, text, _convertRunnable(r)); } public void popupMenuItem_top(String text, Object r) { tablePopupMenuItemsThreaded_top(table, text, _convertRunnable(r)); } public Object _convertRunnable(final Object r) { if (r == null || r instanceof Runnable) return r; return new VF1() { public void get(Integer idx) { try { callF(r, syncGet(data, idx)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(r, syncGet(data, idx))"; } }; } public JTable table() { return table; } public void hideFields(String... fields) { if (hideFields == null) hideFields = new HashSet(); _addAll(hideFields, fields); } public A getRow(int row) { return get(data, row); } public void scrollDown() { scrollTableDownNow(table); } public List getData() { return data; } public List data() { return getData(); } public List list() { return getData(); } public List getList() { return getData(); } public List clonedList() { return cloneList(data); } public File quickBackup() { File f = programFile("backup-" + ymd_minus_hms_minus_millis() + ".gz"); saveGZStructToFile(f, module()); printFileInfo(f); return f; } } abstract static public class DynImageSurface extends DynModule { transient public ImageSurface imageSurface; transient public BufferedImage image; transient public String imageID; transient public boolean useUpdateHack, zoomToWindowOnSetImage; transient public Object onNewImage; static public boolean _switchableField_autoSaveToDisk = true; public boolean autoSaveToDisk = autoSaveToDiskDefault(); static public boolean _switchableField_pixelate = true; public boolean pixelate = false; public JComponent visualize() { return _visualize(); } final private JComponent _visualize() { imageSurface = imageSurface(image); imageSurface.onNewImage = new Runnable() { public void run() { try { newImageFromSurface(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "newImageFromSurface();"; } }; imageSurface_pixelated(imageSurface, pixelate); return jscroll_center(imageSurface); } public void enableDoubleBuffering() { if (imageSurface != null) imageSurface.setDoubleBuffered(true); } public JComponent visualizeWithDoubleBuffering() { JComponent c = _visualize(); enableDoubleBuffering(); return c; } public Object _getReloadData() { return image; } public void _setReloadData(BufferedImage image) { this.image = image; } public void start() { try { super.start(); dm_watchField("pixelate", () -> imageSurface_pixelated(imageSurface, pixelate)); if (autoSaveToDisk) autoLoadNow(); } catch (Exception __e) { throw rethrow(__e); } } public void autoLoadNow() { AutoCloseable __54 = enter(); try { try { File f = autoSaveImageFile(); if (fileExists(f)) { print("Auto-loading " + f); setImage(loadImage2(f), true); } } catch (Throwable __e) { pcallFail(__e); } } finally { _close(__54); } } public void autoSaveNow() { AutoCloseable __55 = enter(); try { try { File f = autoSaveImageFile(); savePNG(f, image); infoBox("Auto-saved " + renderFileInfo(f)); } catch (Throwable __e) { pcallFail(__e); } } finally { _close(__55); } } public boolean autoSaveToDiskDefault() { return false; } public void enhanceFrame(Container f) { super.enhanceFrame(f); internalFramePopupMenuItem(f, "Auto-save now", runnableThread(new Runnable() { public void run() { try { autoSaveNow(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "autoSaveNow();"; } })); } public void setImage(MakesBufferedImage image) { imageID = null; setImage(image == null ? null : image.getBufferedImage()); } public void newImageFromSurface() { setImage(imageSurface.getImage()); } public void setImage(BufferedImage image) { setImage(image, false); } public void setImage(BufferedImage image, boolean loadingFromAutoSave) { this.image = image; imageID = null; if (imageSurface != null) { AutoCloseable __56 = tempSetField(imageSurface, "onNewImage", null); try { imageSurface.setImage(image); if (zoomToWindowOnSetImage) imageSurface.zoomToWindow(); if (autoSaveToDisk && !loadingFromAutoSave) autoSaveNow(); } finally { _close(__56); } } vmBus_send("newImage", this); pcallF(onNewImage, image); } public void setImage(String imageID) { if (sameSnippetID(this.imageID, imageID)) return; setImage(loadImage2(imageID)); this.imageID = imageID; } public File autoSaveImageFile() { String id = dm_moduleID(me()); return javaxDataDir("Image Autosaves/" + id + "-autosave.png"); } public BufferedImage getImage() { if (useUpdateHack) { ImageSurface is = imageSurface; if (is != null && is.getImage() != image) setImage(is.getImage()); } return image; } public boolean hasImage() { return image != null; } public void setZoom(double zoom) { if (imageSurface != null) imageSurface.setZoom(zoom); } public Rect getSelection() { return imageSurface == null ? null : toRect(imageSurface.getSelection()); } public void setSelection(Rect r) { if (imageSurface != null) imageSurface.setSelection(toRectangle(r)); } public int imageWidth() { return imageSurface.getImage().getWidth(); } public int imageHeight() { return imageSurface.getImage().getHeight(); } public void pixelate() { setField("pixelate", true); } } abstract static public class DynCalculatedList extends DynModule { transient public JList list; transient public List results; transient public boolean calculateWhenHidden = false; public JComponent visualize() { return list = jlist(calc()); } public void unvisualize() { list = null; } public void update() { AutoCloseable __61 = enter(); try { if (list != null || calculateWhenHidden) fillListWithStrings(list, results = calc()); } finally { _close(__61); } } abstract public List calc(); public void scrollDown() { scrollAllTheWayDown(list); } public String selected() { return selectedItem(list); } } static public Object creator() { return callOpt(assertNotNull("No real MC", realMC_tl()).get(), "creator"); } static public String programID; static public String getProgramID() { Object mc = realMC_tl().get(); if (mc != null) return getProgramID(mc); return nempty(programID) ? formatSnippetIDOpt(programID) : "?"; } static public String getProgramID(Class c) { String id = (String) getOpt(c, "programID"); if (nempty(id)) return formatSnippetID(id); return "?"; } static public String getProgramID(Object o) { return getProgramID(getMainClass(o)); } static public Concepts db_mainConcepts() { throw fail("No db_mainConcepts"); } static public JButton basicJButton(String text) { return swing(() -> { JButton btn = new JButton(text); setHorizontalMargin(btn, 4); return btn; }); } static public String fastIntern(String s) { return s == null ? null : s.intern(); } static public List myInnerClasses_list = litlist(null, "IVarWithNotify", "NotifyingCollection", "Hi15Image", "DummyPosterizer", "StructureStringIndenter", "IImageRegion", "SnPSettings", "ImageSurface", "JOnScreenKeyboard", "ScreenShotMeta", "ArrayMatrix", "talkToThisVM_IO", "IFieldIndex", "AnimatedLine", "SimpleLiveValue", "GazellePresenceListener", "WebRequest", "WeakIdentityHashMap", "JForm", "SingleComponentPanel", "PosterizeBWImage", "IWebRequest", "RenamedLongIterator", "NumberPt", "HashBufferedImage", "AbstractLayoutManager", "TrayIconLastPosition", "IterableIterator", "betterCIComparator_C", "SynchronizedArrayList", "MakesBufferedImage", "DeleteFilesDialog", "IProbabilisticScheduler", "TextImageAction", "CloseableIterableIterator", "AbstractSSIList", "HuffmanTreeMaker", "PixelPreservingImageOpResult", "ShortBuffer", "HasBounds", "Enterable", "Matches", "WithTimestamp", "SynchronizedLongBuffer", "TableWithTooltips", "Dyn_FieldWatcher", "DoubleRect", "Surface", "WeakVar", "NotifyingList", "Q", "VectorSSIList", "ILongBuffer", "TailFile", "RenderRecognizedBox", "RestartableCountdown", "VStack", "TransientObject", "DynamicVStack", "FixedVarContext", "Htmlable", "DynObjectTable", "mapI_if1_It", "ConceptsComboBox", "HuffmanByteArray", "VarContext", "Average", "IConceptCounter", "IToolTipMaker", "OpenGL_DemoObjects", "RangeSliderUI", "BetterLabel", "componentPopupMenu_Adapter", "BWIntegralImage", "CompressToInterpolatedDoubleArray", "IVStack", "IF0_Pair", "FailedRule", "IHasTokenRangeWithSrc", "IF0_Bool", "IBinaryImage", "IImageRegions", "transpileOnServerWithErrorWindow_DaClass", "StefansOS_ConnectToServer", "LineThroughPoint", "JSection", "RecognizedRegion", "CollapsibleLeftPanel", "IF0WithChangeListeners", "FullChange", "GeneralSSIList", "JECompressionRegime", "WithSideValue", "IntegerIterator", "IStringifier", "CombinedStringifier", "MultiSleeper", "JFilePathLabel", "UTF8Processor", "ReliableSingleThread", "ListAndIndex", "WebSocketFactory", "JVideoLibDownloader", "WindowResizeDragger", "TranspileWithErrorWindow", "NESWDirection", "DoubleBuffer", "ProgramScan", "RegExp", "PersistableOKOrError", "JustCountingOutputStream", "DefaultButtonBorder", "F0", "Snippet", "F1", "DynImageSurface", "RandomAccessAbstractList", "F2", "RGB", "IntPair", "HasChangeListeners", "F3", "BoolVar", "WidthAndHeightFinal", "IHasGlobalID", "ConceptFieldIndexCI", "FormLayout1", "IRecognizedBox", "StringHead", "MakesBWImage", "CenteredComboBoxRenderer", "tablePopupMenu_Maker", "VirtualVar", "Cache", "SynchronizedList", "_MethodCache", "PingSourceCancelledException", "JForwardingLibDownloader", "LiveValue", "Eq", "AbstractHasHi15Color", "IDoubleBuffer", "proxy_InvocationHandler", "MethodMaker", "RunnableWithExceptions", "EphemeralObjectIDs", "JavaXClassLoader", "Probabilistic", "Flattener", "FlexibleRateTimer", "RuleWithParams", "CachedPosterizer", "ByteBuffer", "RangeSlider", "WebSocket", "TransferableImage", "Sleeping", "IConceptIndex", "Updateable", "WithProbability", "BitIO", "SubList", "SecretValue", "GenericArrayTypeImpl", "JSelectableDirLabel", "AppendableChain", "CompactLinkedHashSet", "LoggingBitHead", "FixedRateTimer", "WholeImageFilter", "CompactLongSet", "GridCodec1", "IndexIterator", "GrabbableRGBBytePixels", "MethodOnObject", "MinimumFilter", "XRef", "JGallery", "IUnstructured", "IntegralImage", "ShortIterator", "IntBuffer", "DoublePt", "IIntPred", "SynchronizedNavigableSet", "SynchronizedCircularFifoBuffer", "AbstractMatrix", "Chain", "RegionToBWImage", "ThreadPool", "ComputerCountListener", "JS", "WidthAndHeightImpl", "RunnablesReferenceQueue", "JPopDownButton", "AbstractJavaXExpr", "SSIListFrame", "IDialogHandler", "AWTOnConceptChanges", "VariableSizeUIntForBitHead", "IHasChangeListeners", "JavaCodec", "ImageSurface_PositionToolTip", "TranslucentWindowTest", "FlexWebSocket", "IIntegralImage", "BitHead", "AbstractCompressor_AnyType", "DialogIO", "RegionToImage2B", "Stages", "SynchronizedArrayList_Base", "Scribble", "IAutoCloseableF0", "IPartialStringifier", "BitIOWrapper", "ISleeper_v2", "AlphanumComparator", "JExtendedTabbedPane", "PersistableThrowable", "Animation", "BlockDiff", "talkToSubBot_IO", "IDoublePt", "NumPadFixingInputMap", "PixelUtils", "HasIndex", "WidthAndHeight", "ISubList", "Responder", "TableSearcher", "IMultiSet", "WithToolTip", "VectorSSI", "mapI_It", "ConceptsChange", "JFilePathButton", "TokCondition", "HashRefTokenMaker", "JSyntaxTextFileEditor", "listPopupMenu_Maker", "WAndHImpl", "ConceptWithChangeListeners", "SynchronizedCollection", "OnePathWithOrigin", "TargetAndActual", "CleanExit", "IIntIntPred", "IntMinMax", "ImageSurfaceSelector", "Sentence", "ScreenCamStream", "Concept", "HashedBWImage", "RectAsRecognizedBox", "IRGBImage", "WeightlessShuffledIterator", "MyHTTPD", "RegisteredReference", "TreeMultiMap", "Range", "FreeOfLocalBlockedKeyword", "ContentsIndexedList", "FileTransferable", "AbstractSteppable", "ClassMaker", "IPixelSet", "IContentsIndexedList2", "And", "Value", "ChromeBookmark", "OKOrError", "ImageChooser", "FileBasedLock", "Symbol", "IMeta", "ListToMatrix", "BetterThread", "JFileDropTarget", "BetterThreadLocal", "JTargetAndActualSlider", "Lowest", "CollapsibleNorthPanel", "RegionBorder_innerPoints", "ChangeTrigger", "AnimatedImageSurface", "ScoredSearcher_stable", "DynPrintLog", "JMiniJavaIDE", "AutoVMExit", "BoundsFinder", "MinimalChain", "NamedConcept", "Image2B", "AbstractFastRegions", "SynchronizedSortedSet", "SSI", "IBest", "jLiveValueSection_class", "JE_CompressEachElementIndividually", "DoubleRange", "DynamicObject", "IntegrityCheckable", "DoubleFPSCounter", "Exp", "RenderText", "DynamicMethods", "EGDiff", "Meta", "BStack", "Derefable", "JVMStackCellType", "FastRegions_BWImage", "SingleThread", "JSelfSwingable", "InMemoryClassLoader", "DefunctClassLoader", "CutListToBudget", "IntVar", "BWImage", "PingSource", "Renderable", "jCenteredLiveValueSection_class", "ConceptFieldIndexDesc", "HasTokenRangeWithSrc", "VarMatches", "Best", "DynModule", "ConceptL", "BackgroundProcessesUI", "Rect", "Pt", "TimeoutException_Inner", "BufferedImageWithMeta", "LeftAlignedLine", "RemoteDB", "AverageAndMinMax", "SynchronizedNavigableMap", "Concepts", "RC", "PCallPolicy", "IVF1WithToString", "IBWIntegralImage", "Hasher", "PNGFile", "getOpt_Map", "IFieldsToList", "JTextFileEditor", "IResponder", "WeakValueMap", "structure_Data", "VarWithNotify", "jsonDecode_Y", "Zip4j_MergeZipFilesWithFilter", "JColorBar", "IVar", "DynPrintLogAndEnabled", "Gazelle22_GradientImage", "TokenRangeWithSrc", "ConceptWithGlobalID", "LiteralJavaXExpr", "DynCalculatedList", "SimpleOutlineWalker", "ParameterizedTypeImpl", "Timestamp", "DoLater", "ImageInfiller", "ConceptFieldIndexBase", "ManyCirclePainter", "LongRange", "SSIList", "RawBufferedImageDistance_sameSize", "JECompressionSearch", "OnEnclosingScrollPaneResize", "JComponentWithChangeListeners", "MultiSet", "RuntimeExceptionWithCustomStackTrace", "ListFromFunction", "T3", "IResourceHolder", "CloseablesHolder", "EvalJavaPrep", "SizeInInts", "DynamicStack", "OHLCEntry", "RegionHoleBounds", "IPersistenceInfo", "BoxBlurFilter", "IntRange", "ExtendedCSVParser", "HuffmanTree", "PleaseIncludeFunctionsStatement", "UnsynchronizedCompactHashSet", "ProbabilisticListListener", "TimestampRange", "CopyBlock", "NanoWebSocketServer", "JPaintTool", "Stringifier_ToString", "JavaXClassLoaderWithParent2", "AWTOnConceptChangesByClass", "PtBuffer", "SynchronizedDoubleBuffer", "Frequency", "CompressionRegime_AnyType", "RGBImage", "FileWatchService", "SmartTimerTask", "ComponentResizeDragger", "RegionBorder_innerPoints_v2", "ImageSurfaceScribbleTool", "SimpleCRUD_v2", "ConceptDelete", "SinglePixelPosterizer", "ScanlineBitMatrix", "GoodThingsToTrack", "Literal", "WindowDragger", "unstructure_Handler", "IF2_IntInt_Double", "IMultiMap", "RegionBorder_innerPoints_withDiagonals", "IF1_IntToInt", "ThrowableWithCustomStackTrace", "BoolVarWithNotify", "IBWImage", "PtInComponent", "JConceptsTable", "AutoComboBox", "WebSocketException", "Sentence2", "ConceptFieldIndex", "GrabbableGrayPixels", "IHasBackRefs", "StepperWithStats", "MapI", "VectorOptimizedSSIList", "IfThen", "unstructure_Receiver", "JDraggableBoxDemo", "IF0", "BaseXRef", "IF2", "IF1", "IPosterizer", "IVF3", "IVF1", "IVF2", "NewBlock", "IWithSideValue", "MultiPointGradient", "Options", "IConcept", "structure_ClassInfo", "Func", "ScoredStringSearcher", "TreeSetWithDuplicates", "ScreenOverlay", "TimedCache", "ISetAndGet", "ToJava", "JFFMPEGVideoPlayer", "AbstractSSI", "RSyntaxTextAreaWithSearch", "InterpolatedDoubleArray", "QuickException", "SynchronizedSet", "DialogHandler", "JObjectTable", "ProbabilisticList", "Steppable", "G2Drawable", "UIURLSystem", "ImageSurfaceMouseHandler", "Pair", "Swingable", "FastDownscale2x2", "SingleThreadProfiler", "Percent", "RSTADummyParser", "ProbabilisticListAdapter", "LineAndColumn", "UniqueString", "ICharPred", "ILongQueue", "ChangeTriggerable", "GrabbableIntPixels", "IIVirtualClip", "IBackgroundProcesses", "DynamicHStack", "MetaWithChangeListeners", "ReverseChain", "BresenhamLineDrawer", "ConceptCreate", "CheckerBoard2", "TokenRange", "Seconds", "SynchronizedSortedMap", "ScaledBWImageFromBWIntegralImage", "HInitWebSocket", "PtSet", "MultiSetMap", "Var", "ClassNameResolver", "Best_comparable", "Scorer", "ITokCondition", "PopupMenuMaker", "CountingOutputStream", "INumberOfPixels", "Matrix", "SynchronizedRandomAccessList", "PrecisePolygon", "RunResultWithTimestamps", "ConceptChange", "AbstractProfiler", "CompactAbstractMap", "ExpNot", "TripletLSFR", "BitBuffer", "Fail", "WeakIdentityHashSet", "FunctionTimings", "ISetter", "DoneFlag", "RSTOverQ", "AIStrategy", "IResolvableClass", "SubMatrix", "ScannedBot", "ByteIO", "SimplyLinkedList", "AIStrategy_RandomWithVariation", "WebServable", "FPSCounter", "MechMode", "NotifyingStringBuffer", "IF2_Int", "VolatileImageMakerForComponent", "CompactHashMap", "IProbabilistic", "JVolatileImageSurface", "Complex", "RasterBars", "MultiMap", "RSTVar", "ProbabilisticScheduler", "CriticalAction", "JImageSwitch", "IResourceLoader", "WeakHasherMap", "Either", "Ratio", "FunctionCall", "PosterizeBufferedImage", "NotifyingSet", "CompilerBot", "JMenuScroller", "CharInToken", "ImageFileFilter", "ScalingImageOpResult", "MRUCache", "Angle", "Scored", "IIBWVirtualClip", "HashBWImage", "PadImageToAspectRatio", "VF1", "VF2", "JE_RepElement", "SynchronizedFloatBufferPresentingAsDoubles", "ICachedJavaXExpr", "IStackWithOptions", "RightAlignedLine", "GlobalID", "FastRegions_Hi15Image", "findCodeTokens_Matcher", "Unstructurer", "IntSize", "tempAdd_undo", "FieldVar", "JFastLogView_noWrap", "SimpleLeftToRightParser", "WebSocketFrame", "TimeoutException", "JEInstantCompressor_AnyType", "IRef", "ByteHead", "NotifyingStringBufferRotator", "Flag", "generalizedCIComparator_C", "IRecognizedRegion", "UniquifyUsingHasher", "BijectiveMap", "VStackComputableWithStep", "Producer", "Gazelle22_ImageToRegions", "CountHolesInRegion", "SourceTriggeredStream", "IProgressShower", "tempRememberListener_c", "talkTo_IO", "FlexibleVarContext", "ButtonImageLoader", "RollingAverage", "Timed", "ECJError", "UpdateTrigger", "NanoHTTPD", "ImageStreamFromVideoFile", "IContentsIndexedList", "IMakeEmptyClone", "LetterLayout", "StringIO", "BlockDiffer", "DeQ", "IF1_ObjectToDouble", "SynchronizedMap", "Decolorizer", "CompressionSearch_AnyType", "InstantNeverHideToolTip", "AbstractBufferedImageOp", "WebSocketHTTPD", "Test_ImageInfiller", "WrappedMap", "LongBuffer", "IBStack", "ListCellRendererWithToolTip", "ImageSurfaceDragger", "AbstractBorderTracer", "JavaXPeepholeShortener", "JavaXClassLoaderWithParent", "Transformable", "ClearForAutoRun", "ExplodedLine", "SurfaceShowingAutoZoomedImage", "FitImageInComponentRenderable", "ScaledBufferedImageFromIntegralImage", "Android3", "ComponentDragger", "OnePath", "IBackgroundProcess"); static public List myInnerClasses() { return myInnerClasses_list; } static public RuntimeException rethrow(Throwable t) { if (t instanceof Error) _handleError((Error) t); throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } static public RuntimeException rethrow(String msg, Throwable t) { throw new RuntimeException(msg, t); } static public boolean isAWTThread() { if (isAndroid()) return false; if (isHeadless()) return false; return isAWTThread_awt(); } static public boolean isAWTThread_awt() { return SwingUtilities.isEventDispatchThread(); } static public void _handleError(Error e) { } static public boolean call_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != l(args)) { if (debug) print("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) { Object arg = args[i]; if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) { if (debug) print("Bad parameter " + i + ": " + arg + " vs " + types[i]); return false; } } return true; } static public RuntimeException fail() { throw new RuntimeException("fail"); } static public RuntimeException fail(Throwable e) { throw asRuntimeException(e); } static public RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); } static public RuntimeException fail(Object... objects) { throw new Fail(objects); } static public RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); } static public RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); } static public void multiMapPut(Map> map, A a, B b) { List l = map.get(a); if (l == null) map.put(a, l = new ArrayList()); l.add(b); } static public void multiMapPut(MultiMap mm, A key, B value) { if (mm != null && key != null && value != null) mm.put(key, value); } static public boolean endsWithLetterOrDigit(String s) { return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1)); } static public Throwable getExceptionCause(Throwable e) { Throwable c = e.getCause(); return c != null ? c : e; } static public int isAndroid_flag; static public boolean isAndroid() { if (isAndroid_flag == 0) isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1; return isAndroid_flag > 0; } static public Boolean isHeadless_cache; static public boolean isHeadless() { if (isHeadless_cache != null) return isHeadless_cache; if (isAndroid()) return isHeadless_cache = true; if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true; try { SwingUtilities.isEventDispatchThread(); return isHeadless_cache = false; } catch (Throwable e) { return isHeadless_cache = true; } } public static String join(String glue, Iterable strings) { if (strings == null) return ""; if (strings instanceof Collection) { if (((Collection) strings).size() == 1) return strOrEmpty(first((Collection) strings)); } StringBuilder buf = new StringBuilder(); Iterator i = strings.iterator(); if (i.hasNext()) { buf.append(strOrEmpty(i.next())); while (i.hasNext()) buf.append(glue).append(strOrEmpty(i.next())); } return buf.toString(); } public static String join(String glue, String... strings) { return join(glue, Arrays.asList(strings)); } public static String join(String glue, Object... strings) { return join(glue, Arrays.asList(strings)); } static public String join(Iterable strings) { return join("", strings); } static public String join(Iterable strings, String glue) { return join(glue, strings); } public static String join(String[] strings) { return join("", strings); } static public String join(String glue, Pair p) { return p == null ? "" : str(p.a) + glue + str(p.b); } static public String joinWithSpace(Iterable c) { return join(" ", c); } static public String joinWithSpace(Object... c) { return join(" ", c); } static public Map newWeakHashMap() { return _registerWeakMap(synchroMap(new WeakHashMap())); } static public int javaTok_n, javaTok_elements; static public boolean javaTok_opt = false; static public List javaTok(String s) { ++javaTok_n; ArrayList tok = new ArrayList(); int l = s == null ? 0 : s.length(); int i = 0; while (i < l) { int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !regionMatches(s, j, "*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(javaTok_substringN(s, i, j)); i = j; if (i >= l) break; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) { j += 2; while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j; } else if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { int c2 = s.charAt(j); if (c2 == opener || c2 == '\n' && opener == '\'') { ++j; break; } else if (c2 == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else if (c == '[' && d == '[') { do ++j; while (j < l && !regionMatches(s, j, "]]")); j = Math.min(j + 2, l); } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') { do ++j; while (j + 2 < l && !regionMatches(s, j, "]=]")); j = Math.min(j + 3, l); } else ++j; tok.add(javaTok_substringC(s, i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } static public List javaTok(List tok) { return javaTokWithExisting(join(tok), tok); } static public void print_append(Appendable buf, String s, int max) { try { synchronized (buf) { buf.append(s); if (buf instanceof StringBuffer) rotateStringBuffer(((StringBuffer) buf), max); else if (buf instanceof StringBuilder) rotateStringBuilder(((StringBuilder) buf), max); } } catch (Exception __e) { throw rethrow(__e); } } static public A get(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } static public A get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } static public boolean get(boolean[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : false; } static public Object get(Object o, String field) { try { if (o == null) return null; if (o instanceof Class) return get((Class) o, field); if (o instanceof Map) return ((Map) o).get(field); Field f = getOpt_findField(o.getClass(), field); if (f != null) { makeAccessible(f); return f.get(o); } if (o instanceof DynamicObject) return getOptDynOnly(((DynamicObject) o), field); } catch (Exception e) { throw asRuntimeException(e); } throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName()); } static public Object get_raw(String field, Object o) { return get_raw(o, field); } static public Object get_raw(Object o, String field) { try { if (o == null) return null; Field f = get_findField(o.getClass(), field); makeAccessible(f); return f.get(o); } catch (Exception __e) { throw rethrow(__e); } } static public Object get(Class c, String field) { try { Field f = get_findStaticField(c, field); makeAccessible(f); return f.get(null); } catch (Exception e) { throw new RuntimeException(e); } } static public Field get_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } static public Field get_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } static public Object get(String field, Object o) { return get(o, field); } static public boolean get(BitSet bs, int idx) { return bs != null && bs.get(idx); } static public Object getOpt(Object o, String field) { return getOpt_cached(o, field); } static public Object getOpt(String field, Object o) { return getOpt_cached(o, field); } static public Object getOpt_raw(Object o, String field) { try { Field f = getOpt_findField(o.getClass(), field); if (f == null) return null; makeAccessible(f); return f.get(o); } catch (Exception __e) { throw rethrow(__e); } } static public Object getOpt(Class c, String field) { try { if (c == null) return null; Field f = getOpt_findStaticField(c, field); if (f == null) return null; makeAccessible(f); return f.get(null); } catch (Exception __e) { throw rethrow(__e); } } static public Field getOpt_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static public A set(A o, String field, Object value) { if (o == null) return null; if (o instanceof Class) set((Class) o, field, value); else try { Field f = set_findField(o.getClass(), field); makeAccessible(f); smartSet(f, o, value); } catch (Exception e) { throw new RuntimeException(e); } return o; } static public void set(Class c, String field, Object value) { if (c == null) return; try { Field f = set_findStaticField(c, field); makeAccessible(f); smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } static public Field set_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } static public Field set_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } static public void set(BitSet bs, int idx) { { if (bs != null) bs.set(idx); } } static public Field setOpt_findField(Class c, String field) { HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } return map.get(field); } static public void setOpt(Object o, String field, Object value) { try { if (o == null) return; Class c = o.getClass(); HashMap map; if (getOpt_cache == null) map = getOpt_makeCache(c); else synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } if (map == getOpt_special) { if (o instanceof Class) { setOpt((Class) o, field, value); return; } setOpt_raw(o, field, value); return; } Field f = map.get(field); if (f != null) { smartSet(f, o, value); return; } if (o instanceof DynamicObject) { setDyn(((DynamicObject) o), field, value); return; } if (o instanceof IMeta) setDyn(((IMeta) o), field, value); } catch (Exception __e) { throw rethrow(__e); } } static public void setOpt(Class c, String field, Object value) { if (c == null) return; try { Field f = setOpt_findStaticField(c, field); if (f != null) smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } static public Field setOpt_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) { makeAccessible(f); return f; } _c = _c.getSuperclass(); } while (_c != null); return null; } static public void setOpt_raw(Object o, String field, Object value) { try { if (o == null) return; if (o instanceof Class) setOpt_raw((Class) o, field, value); else { Field f = setOpt_raw_findField(o.getClass(), field); if (f != null) { makeAccessible(f); smartSet(f, o, value); } } } catch (Exception __e) { throw rethrow(__e); } } static public void setOpt_raw(Class c, String field, Object value) { try { if (c == null) return; Field f = setOpt_raw_findStaticField(c, field); if (f != null) { makeAccessible(f); smartSet(f, null, value); } } catch (Exception __e) { throw rethrow(__e); } } static public Field setOpt_raw_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static public Field setOpt_raw_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static public Map> callF_cache = newDangerousWeakHashMap(); static public A callF(F0 f) { return f == null ? null : f.get(); } static public B callF(F1 f, A a) { return f == null ? null : f.get(a); } static public A callF(IF0 f) { return f == null ? null : f.get(); } static public B callF(IF1 f, A a) { return f == null ? null : f.get(a); } static public B callF(A a, IF1 f) { return f == null ? null : f.get(a); } static public C callF(F2 f, A a, B b) { return f == null ? null : f.get(a, b); } static public C callF(IF2 f, A a, B b) { return f == null ? null : f.get(a, b); } static public void callF(VF1 f, A a) { if (f != null) f.get(a); } static public void callF(A a, IVF1 f) { if (f != null) f.get(a); } static public void callF(IVF1 f, A a) { if (f != null) f.get(a); } static public Object callF(Runnable r) { { if (r != null) r.run(); } return null; } static public Object callF(Object f, Object... args) { return safeCallF(f, args); } static public Object safeCallF(Object f, Object... args) { if (f instanceof Runnable) { ((Runnable) f).run(); return null; } if (f == null) return null; Class c = f.getClass(); ArrayList methods; synchronized (callF_cache) { methods = callF_cache.get(c); if (methods == null) methods = callF_makeCache(c); } int n = l(methods); if (n == 0) { if (f instanceof String) throw fail("Legacy call: " + f); throw fail("No get method in " + getClassName(c)); } if (n == 1) return invokeMethod(methods.get(0), f, args); for (int i = 0; i < n; i++) { Method m = methods.get(i); if (call_checkArgs(m, args, false)) return invokeMethod(m, f, args); } throw fail("No matching get method in " + getClassName(c)); } static public ArrayList callF_makeCache(Class c) { ArrayList l = new ArrayList(); Class _c = c; do { for (Method m : _c.getDeclaredMethods()) if (m.getName().equals("get")) { makeAccessible(m); l.add(m); } if (!l.isEmpty()) break; _c = _c.getSuperclass(); } while (_c != null); callF_cache.put(c, l); return l; } static public Object call(Object o) { return callF(o); } static public Object call(Object o, String method, String[] arg) { return call(o, method, new Object[] { arg }); } static public Object call(Object o, String method, Object... args) { return call_withVarargs(o, method, args); } static public Object callOpt(Object o) { return callF(o); } static public Object callOpt(Object o, String method, Object... args) { return callOpt_withVarargs(o, method, args); } static public String fixNewLines(String s) { int i = indexOf(s, '\r'); if (i < 0) return s; int l = s.length(); StringBuilder out = new StringBuilder(l); out.append(s, 0, i); for (; i < l; i++) { char c = s.charAt(i); if (c != '\r') out.append(c); else { out.append('\n'); if (i + 1 < l && s.charAt(i + 1) == '\n') ++i; } } return out.toString(); } static public Map uniqueString_map = weakHashMap(); static public UniqueString uniqueString(String s) { if (s == null) return null; synchronized (uniqueString_map) { UniqueString us = uniqueString_map.get(s); if (us == null) uniqueString_map.put(s, us = new UniqueString(s, true)); return us; } } static public UniqueString uniqueString(CharSequence s) { return s == null ? null : uniqueString(str(s)); } static public FixedRateTimer doEvery(long delay, final Object r) { return doEvery(delay, delay, r); } static public FixedRateTimer doEvery(long delay, long firstDelay, final Object r) { FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80)); timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay)); return vmBus_timerStarted(timer); } static public FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) { return doEvery(toMS(delaySeconds), toMS(initialSeconds), r); } static public FixedRateTimer doEvery(double delaySeconds, final Object r) { return doEvery(toMS(delaySeconds), r); } static public java.util.Timer doLater(long delay, final Object r) { ping(); final java.util.Timer timer = new java.util.Timer(); timer.schedule(timerTask(r, timer), delay); return vmBus_timerStarted(timer); } static public java.util.Timer doLater(double delaySeconds, final Object r) { return doLater(toMS(delaySeconds), r); } static public boolean hasBot(String searchPattern) { try { DialogIO io = findBot(searchPattern); if (io != null) { io.close(); return true; } else return false; } catch (Exception __e) { throw rethrow(__e); } } static public JLabel jlabel(final String text) { return swingConstruct(BetterLabel.class, text); } static public JLabel jlabel() { return jlabel(" "); } static public JTextArea newTypeWriterTextArea() { return newTypeWriterTextArea(""); } static public JTextArea newTypeWriterTextArea(String text) { return withTypeWriterFont(jTextArea(text)); } static public String struct(Object o) { return structure(o); } static public String struct(Object o, structure_Data data) { return structure(o, data); } static public String sfu(Object o) { return structureForUser(o); } static public String loadPageSilentlyWithTimeout(double timeoutSeconds, String url) { return loadPageSilentlyWithTimeout(url, toMS_int(timeoutSeconds)); } static public String loadPageSilentlyWithTimeout(int timeout, String url) { return loadPageSilentlyWithTimeout(url, timeout); } static public String loadPageSilentlyWithTimeout(String url, int timeout) { try { url = loadPage_preprocess(url); URL _url = new URL(url); return loadPage(setURLConnectionTimeouts(_url.openConnection(), timeout), _url); } catch (Exception __e) { throw rethrow(__e); } } static public boolean loadPageWithUserAgent_verbose = false; static public String loadPageWithUserAgent(String url, String userAgent) { try { URL tURL = new URL(url); URLConnection conn = tURL.openConnection(); conn.setRequestProperty("User-Agent", userAgent); loadPage_anonymous = true; if (loadPageWithUserAgent_verbose) print("Loading as " + userAgent + ": " + hideCredentials(url)); return loadPage(conn, tURL); } catch (Exception __e) { throw rethrow(__e); } } static public void db() { conceptsAndBot(); } static public void db(Integer autoSaveInterval) { conceptsAndBot(autoSaveInterval); } static public Object cget(Object c, String field) { c = derefRef(c); Object o = getOpt(c, field); return derefRef(o); } static public Object cget(String field, Object c) { return cget(c, field); } static public int cset(Concept c, Object... values) { try { if (c == null) return 0; warnIfOddCount(values = expandParams(c.getClass(), values)); int changes = 0; for (int i = 0; i + 1 < l(values); i += 2) if (_csetField(c, (String) values[i], values[i + 1])) ++changes; return changes; } catch (Exception __e) { throw rethrow(__e); } } static public int cset(Iterable l, Object... values) { int changes = 0; for (Concept c : unnullForIteration(l)) changes += cset(c, values); return changes; } static public int cset(Concept.Ref c, Object... values) { return cset(getVar(c), values); } static volatile public StringBuffer local_log = new StringBuffer(); static public boolean printAlsoToSystemOut = true; static volatile public Appendable print_log = local_log; static volatile public int print_log_max = 1024 * 1024; static volatile public int local_log_max = 100 * 1024; static public boolean print_silent = false; static public Object print_byThread_lock = new Object(); static volatile public ThreadLocal print_byThread; static volatile public Object print_allThreads; static volatile public Object print_preprocess; static public void print() { print(""); } static public A print(String s, A o) { print(combinePrintParameters(s, o)); return o; } static public A print(A o) { ping_okInCleanUp(); if (print_silent) return o; String s = o + "\n"; print_noNewLine(s); return o; } static public void print_noNewLine(String s) { try { Object f = getThreadLocal(print_byThread_dontCreate()); if (f == null) f = print_allThreads; if (f != null) if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s))) return; } catch (Throwable e) { System.out.println(getStackTrace(e)); } print_raw(s); } static public void print_raw(String s) { if (print_preprocess != null) s = (String) callF(print_preprocess, s); s = fixNewLines(s); Appendable loc = local_log; Appendable buf = print_log; int loc_max = print_log_max; if (buf != loc && buf != null) { print_append(buf, s, print_log_max); loc_max = local_log_max; } if (loc != null) print_append(loc, s, loc_max); if (printAlsoToSystemOut) System.out.print(s); vmBus_send("printed", mc(), s); } static public void print_autoRotate() { } static public ThreadLocal print_byThread() { synchronized (print_byThread_lock) { if (print_byThread == null) print_byThread = new ThreadLocal(); } return print_byThread; } static public ThreadLocal print_byThread_dontCreate() { return print_byThread; } static public List> _threadInfo_makers = synchroList(); static public Object _threadInfo() { if (empty(_threadInfo_makers)) return null; HashMap map = new HashMap(); pcallFAll(_threadInfo_makers, map); return map; } static public List> _threadInheritInfo_retrievers = synchroList(); static public void _threadInheritInfo(Object info) { if (info == null) return; pcallFAll(_threadInheritInfo_retrievers, (Map) info); } static public void _threadInfo_addMakerAndRetriever(VF1 maker, VF1 retriever) { _threadInfo_makers.add(maker); _threadInheritInfo_retrievers.add(retriever); } static public boolean match(String pat, String s) { return match3(pat, s); } static public boolean match(String pat, String s, Matches matches) { return match3(pat, s, matches); } static public boolean match(String pat, List toks, Matches matches) { return match3(pat, toks, matches); } static public Field getField(Object o, String field) { if (o == null) return null; return setOpt_findField(_getClass(o), field); } static public Object getField(Field field, Object o) { return fieldGet(field, o); } static public Class fieldType(Object o, String field) { Field f = getField(o, field); return f == null ? null : f.getType(); } static public String format3(String pat, Object... args) { if (args.length == 0) return pat; List tok = javaTokPlusPeriod(pat); int argidx = 0; for (int i = 1; i < tok.size(); i += 2) if (tok.get(i).equals("*")) tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null")); return join(tok); } static public String format3_formatArg(Object arg) { if (arg == null) return "null"; if (arg instanceof String) { String s = (String) arg; return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s); } if (arg instanceof Integer || arg instanceof Long) return String.valueOf(arg); return quote(structure(arg)); } static public Set vm_generalIdentityHashSet(Object name) { synchronized (vm_generalMap()) { Set set = (Set) (vm_generalMap_get(name)); if (set == null) vm_generalMap_put(name, set = syncIdentityHashSet()); return set; } } static public Map vm_generalHashMap(Object name) { synchronized (vm_generalMap()) { Map m = (Map) (vm_generalMap_get(name)); if (m == null) vm_generalMap_put(name, m = syncHashMap()); return m; } } static public Map vm_generalWeakSubMap(Object name) { synchronized (vm_generalMap()) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = newWeakMap()); return map; } } static public A bindToComponent(A component, Runnable onShow, Runnable onUnShow) { { swing(() -> { final Var flag = new Var<>(false); component.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { if (flag.get()) print("Warning: bindToComponent logic failure"); flag.set(true); pcallF(onShow); } public void ancestorRemoved(AncestorEvent event) { if (!flag.get()) print("Warning: bindToComponent logic failure"); flag.set(false); pcallF(onUnShow); } public void ancestorMoved(AncestorEvent event) { } }); if (component.isShowing()) { flag.set(true); pcallF(onShow); } }); } return component; } static public A bindToComponent(A component, Runnable onShow) { return bindToComponent(component, onShow, null); } static public A bindToComponent(A component, IF0 onShow, IVF1 onUnShow) { Var b = new Var(); return bindToComponent(component, () -> b.set(onShow.get()), () -> { try { onUnShow.get(b.get()); } finally { b.set(null); } }); } static public int loadPage_defaultTimeout = 60000; static public ThreadLocal loadPage_charset = new ThreadLocal(); static public boolean loadPage_allowGzip = true, loadPage_debug; static public boolean loadPage_anonymous = false; static public int loadPage_verboseness = 100000; static public int loadPage_retries = 1; static public ThreadLocal loadPage_silent = new ThreadLocal(); static volatile public int loadPage_forcedTimeout; static public ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal(); static public ThreadLocal>> loadPage_responseHeaders = new ThreadLocal(); static public ThreadLocal> loadPage_extraHeaders = new ThreadLocal(); static public ThreadLocal loadPage_sizeLimit = new ThreadLocal(); public static String loadPageSilently(String url) { try { return loadPageSilently(new URL(loadPage_preprocess(url))); } catch (Exception __e) { throw rethrow(__e); } } public static String loadPageSilently(URL url) { try { if (!networkAllowanceTest(str(url))) throw fail("Not allowed: " + url); IOException e = null; for (int tries = 0; tries < loadPage_retries; tries++) try { URLConnection con = loadPage_openConnection(url); return loadPage(con, url); } catch (IOException _e) { e = _e; if (loadPage_debug) print(exceptionToStringShort(e)); if (tries < loadPage_retries - 1) sleepSeconds(1); } throw e; } catch (Exception __e) { throw rethrow(__e); } } static public String loadPage_preprocess(String url) { if (url.startsWith("tb/")) url = tb_mainServer() + "/" + url; if (url.indexOf("://") < 0) url = "http://" + url; return url; } static public String loadPage(String url) { try { url = loadPage_preprocess(url); if (!isTrue(loadPage_silent.get())) printWithTime("Loading: " + hideCredentials(url)); return loadPageSilently(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } static public String loadPage(URL url) { return loadPage(url.toExternalForm()); } static public String loadPage(URLConnection con, URL url) throws IOException { return loadPage(con, url, true); } static public String loadPage(URLConnection con, URL url, boolean addHeaders) { try { Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders); if (addHeaders) try { if (!loadPage_anonymous) setHeaders(con); if (loadPage_allowGzip) con.setRequestProperty("Accept-Encoding", "gzip"); con.setRequestProperty("X-No-Cookies", "1"); for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key)); } catch (Throwable e) { } return loadPage(con); } catch (Exception __e) { throw rethrow(__e); } } static public String loadPage(URLConnection con) { try { Long limit = optPar(loadPage_sizeLimit); URL url = con.getURL(); vm_generalSubMap("URLConnection per thread").put(currentThread(), con); loadPage_responseHeaders.set(con.getHeaderFields()); InputStream in = null; try { in = urlConnection_getInputStream(con); if (loadPage_debug) print("Put stream in map: " + currentThread()); String contentType = con.getContentType(); if (contentType == null) { throw new IOException("Page could not be read: " + hideCredentials(url)); } String charset = loadPage_charset == null ? null : loadPage_charset.get(); if (charset == null) charset = loadPage_guessCharset(contentType); if ("gzip".equals(con.getContentEncoding())) { if (loadPage_debug) print("loadPage: Using gzip."); in = newGZIPInputStream(in); } Reader r; try { r = new InputStreamReader(in, unquote(charset)); } catch (UnsupportedEncodingException e) { print(toHex(utf8(charset))); throw e; } boolean silent = isTrue(loadPage_silent.get()); StringBuilder buf = new StringBuilder(); int n = 0; while (limit == null || n < limit) { ping(); int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; if (!silent && (n % loadPage_verboseness) == 0) print(" " + n + " chars read"); } return buf.toString(); } finally { if (loadPage_debug) print("loadPage done"); vm_generalSubMap("URLConnection per thread").remove(currentThread()); if (in != null) in.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public String loadPage_guessCharset(String contentType) { Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType); String match = m.matches() ? m.group(1) : null; if (loadPage_debug) print("loadPage: contentType=" + contentType + ", match: " + match); return or(match, "UTF-8"); } static public URLConnection loadPage_openConnection(URL url) { URLConnection con = openConnection(url); int timeout = toInt(loadPage_forcedTimeout_byThread.get()); if (timeout == 0) timeout = loadPage_forcedTimeout; if (timeout != 0) setURLConnectionTimeouts(con, loadPage_forcedTimeout); else setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout); return con; } static public String loadPage_utf8(URL url) { return loadPage_utf8(url.toString()); } static public String loadPage_utf8(String url) { AutoCloseable __1 = tempSetTL(loadPage_charset, "UTF-8"); try { return loadPage(url); } finally { _close(__1); } } static public String loadPage_utf8(URLConnection con, URL url, boolean addHeaders) throws IOException { AutoCloseable __2 = tempSetTL(loadPage_charset, "UTF-8"); try { return loadPage(con, url, addHeaders); } finally { _close(__2); } } static public boolean preferCached = false; static public boolean loadSnippet_debug = false; static public ThreadLocal loadSnippet_silent = new ThreadLocal(); static public ThreadLocal loadSnippet_publicOnly = new ThreadLocal(); static public int loadSnippet_timeout = 30000; static public String loadSnippet(Snippet s) { return loadSnippet(s.id); } static public String loadSnippet(String snippetID) { try { if (snippetID == null) return null; return loadSnippet(parseSnippetID(snippetID), preferCached); } catch (Exception __e) { throw rethrow(__e); } } static public String loadSnippet(String snippetID, boolean preferCached) throws IOException { return loadSnippet(parseSnippetID(snippetID), preferCached); } static public IF1 loadSnippet; static public String loadSnippet(long snippetID) { return loadSnippet != null ? loadSnippet.get(snippetID) : loadSnippet_base(snippetID); } final static public String loadSnippet_fallback(IF1 _f, long snippetID) { return _f != null ? _f.get(snippetID) : loadSnippet_base(snippetID); } static public String loadSnippet_base(long snippetID) { try { return loadSnippet(snippetID, preferCached); } catch (Exception __e) { throw rethrow(__e); } } static public String loadSnippet(long snippetID, boolean preferCached) throws IOException { if (isLocalSnippetID(snippetID)) return loadLocalSnippet(snippetID); IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadSnippet(fsI(snippetID)); return loadSnippet_noResourceLoader(snippetID, preferCached); } static public String loadSnippet_noResourceLoader(long snippetID, boolean preferCached) throws IOException { String text; initSnippetCache(); text = DiskSnippetCache_get(snippetID); if (preferCached && text != null) return text; try { if (loadSnippet_debug && text != null) System.err.println("md5: " + md5(text)); String url = tb_mainServer() + "/getraw.php?id=" + snippetID + "&utf8=1"; if (nempty(text)) url += "&md5=" + md5(text); if (!isTrue(loadSnippet_publicOnly.get())) url += standardCredentials(); String text2 = loadSnippet_loadFromServer(url); boolean same = eq(text2, "==*#*=="); if (loadSnippet_debug) print("loadSnippet: same=" + same); if (!same) text = text2; } catch (RuntimeException e) { e.printStackTrace(); throw new IOException("Snippet #" + snippetID + " not found or not public"); } try { initSnippetCache(); DiskSnippetCache_put(snippetID, text); } catch (IOException e) { System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")"); } return text; } static public File DiskSnippetCache_dir; public static void initDiskSnippetCache(File dir) { DiskSnippetCache_dir = dir; dir.mkdirs(); } public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException { return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null); } private static File DiskSnippetCache_getFile(long snippetID) { return new File(DiskSnippetCache_dir, "" + snippetID); } public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException { saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet); } public static File DiskSnippetCache_getDir() { return DiskSnippetCache_dir; } public static void initSnippetCache() { if (DiskSnippetCache_dir == null) initDiskSnippetCache(getGlobalCache()); } static public String loadSnippet_loadFromServer(String url) { Integer oldTimeout = setThreadLocal(loadPage_forcedTimeout_byThread, loadSnippet_timeout); try { return isTrue(loadSnippet_silent.get()) ? loadPageSilently(url) : loadPage(url); } finally { loadPage_forcedTimeout_byThread.set(oldTimeout); } } static public String loadSnippetQuietly(Snippet s) { return loadSnippetQuietly(s.id); } static public String loadSnippetQuietly(String snippetID) { loadSnippet_silent.set(true); try { return loadSnippet(snippetID); } finally { loadSnippet_silent.set(null); } } static public String sendToLocalBot(String bot, String text, Object... args) { text = format3(text, args); DialogIO channel = findBot(bot); try { if (channel == null) throw fail(quote(bot) + " not found"); try { channel.readLine(); print(bot + "> " + shorten(text, 80)); channel.sendLine(text); String s = channel.readLine(); print(bot + "< " + shorten(s, 80)); return s; } catch (Throwable e) { e.printStackTrace(); return null; } } finally { _close(channel); } } static public String sendToLocalBot(int port, String text, Object... args) { text = format3(text, args); DialogIO channel = talkTo(port); try { try { channel.readLine(); print(port + "> " + shorten(text, 80)); channel.sendLine(text); String s = channel.readLine(); print(port + "< " + shorten(s, 80)); return s; } catch (Throwable e) { e.printStackTrace(); return null; } } finally { _close(channel); } } static public String sendToLocalBotOpt(String bot, String text, Object... args) { if (bot == null) return null; text = format(text, args); DialogIO channel = findBot(bot); try { if (channel == null) { print(quote(bot) + " not found, skipping send: " + quote(text)); return null; } try { channel.readLine(); print(shorten(bot + "> " + text, 200)); channel.sendLine(text); String s = channel.readLine(); print(shorten(bot + "< " + s, 200)); return s; } catch (Throwable e) { e.printStackTrace(); return null; } } finally { _close(channel); } } static public String sendToLocalBotQuietly(String bot, String text, Object... args) { text = format3(text, args); DialogIO channel = newFindBot2(bot); try { if (channel == null) throw fail(quote(bot) + " not found"); try { channel.readLine(); channel.sendLine(text); String s = channel.readLine(); return s; } catch (Throwable e) { e.printStackTrace(); return null; } } finally { _close(channel); } } static public String sendToLocalBotQuietly(int port, String text, Object... args) { text = format3(text, args); DialogIO channel = talkTo(port); try { try { channel.readLine(); channel.sendLine(text); String s = channel.readLine(); return s; } catch (Throwable e) { e.printStackTrace(); return null; } } finally { _close(channel); } } static public JTable sexyTableWithoutDrag() { final JTable table = tableWithToolTips(); tablePopupMenu(table, sexyTableWithoutDrag_popupMenuMaker(table)); table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none"); table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none"); table.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none"); table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none"); table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none"); ((InputMap) UIManager.get("Table.ancestorInputMap")).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none"); return table; } static public VF2 sexyTableWithoutDrag_popupMenuMaker(JTable t) { final WeakReference ref = weakRef(t); return new VF2() { public void get(JPopupMenu menu, Integer row) { try { final JTable table = ref.get(); final String item = first(getTableLine(table, row)); MouseEvent e = tablePopupMenu_mouseEvent.get(); final int col = table.columnAtPoint(e.getPoint()); final Object value = table.getModel().getValueAt(row, col); if (value instanceof ImageIcon) { addMenuItem(menu, "Copy image to clipboard", new Runnable() { public void run() { try { copyImageToClipboard(((ImageIcon) value).getImage()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyImageToClipboard(((ImageIcon) value).getImage());"; } }); } else { final String text = str(value); addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try { copyTextToClipboard(text); print("Copied text to clipboard: " + quote(text)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(text);\r\n print(\"Copied text to clipboard: \" + quot..."; } }); } addMenuItem(menu, "Set row height...", new Runnable() { public void run() { try { final JTextField tf = jTextField(table.getRowHeight()); showTitledForm("Set row height", "Pixels", tf, new Runnable() { public void run() { try { table.setRowHeight(parseInt(trim(tf.getText()))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "table.setRowHeight(parseInt(trim(tf.getText())))"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tf = jTextField(table.getRowHeight());\r\n showTitledForm..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTable table = ref!;\r\n final S item = first(getTableLine(table, row)..."; } }; } static public class tablePopupMenu_Maker { public List menuMakers = new ArrayList(); } static public Map tablePopupMenu_map = newWeakHashMap(); static public ThreadLocal tablePopupMenu_mouseEvent = new ThreadLocal(); static public ThreadLocal tablePopupMenu_first = new ThreadLocal(); static public void tablePopupMenu(final JTable table, final Object menuMaker) { final boolean first = isTrue(getAndClearThreadLocal(tablePopupMenu_first)); { swing(() -> { tablePopupMenu_Maker maker = tablePopupMenu_map.get(table); if (maker == null) { tablePopupMenu_map.put(table, maker = new tablePopupMenu_Maker()); final tablePopupMenu_Maker _maker = maker; table.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { displayMenu(e); } public void mouseReleased(MouseEvent e) { displayMenu(e); } public void displayMenu(MouseEvent e) { if (!e.isPopupTrigger()) return; JPopupMenu menu = new JPopupMenu(); int row = table.rowAtPoint(e.getPoint()); if (table.getSelectedRowCount() < 2) table.setRowSelectionInterval(row, row); int modelRow = convertTableRowToModel(table, row); int emptyCount = menu.getComponentCount(); tablePopupMenu_mouseEvent.set(e); for (Object menuMaker : _maker.menuMakers) pcallF(menuMaker, menu, modelRow); vmBus_send("showingPopupMenu", table, menu); if (menu.getComponentCount() != emptyCount) menu.show(e.getComponent(), e.getX(), e.getY()); } }); } if (first) maker.menuMakers.add(0, menuMaker); else maker.menuMakers.add(menuMaker); }); } } static public void tablePopupMenuFirst(JTable table, final Object menuMaker) { tablePopupMenu_first.set(true); tablePopupMenu(table, menuMaker); } static public void tablePopupMenuFirst(JTable table, IVF2 menuMaker) { tablePopupMenuFirst(table, (Object) menuMaker); } static public ThreadLocal componentPopupMenu_mouseEvent; static public void componentPopupMenu_init() { { swing(() -> { if (componentPopupMenu_mouseEvent == null) componentPopupMenu_mouseEvent = (ThreadLocal) vm_generalMap_get("mouseEvent"); if (componentPopupMenu_mouseEvent == null) vm_generalMap_put("componentPopupMenu_mouseEvent", componentPopupMenu_mouseEvent = new ThreadLocal()); }); } } static public void componentPopupMenu(final JComponent component, IVF1 menuMaker) { componentPopupMenu(component, (Object) menuMaker); } static public void componentPopupMenu(final JComponent component, final Object menuMaker) { if (component == null || menuMaker == null) return; { swing(() -> { Object adapter = componentPopupMenu_initForComponent(component); ((List) _get(adapter, "maker")).add(menuMaker); }); } } static public Object componentPopupMenu_initForComponent(final JComponent component) { return component == null ? null : swing(new F0() { public Object get() { try { componentPopupMenu_init(); Object adapter = findComponentPopupMenuListener_gen(component); if (adapter == null) { componentPopupMenu_Adapter a = new componentPopupMenu_Adapter(); component.addMouseListener(a); adapter = a; } return adapter; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "componentPopupMenu_init();\r\n O adapter = findComponentPopupMenuListener_ge..."; } }); } static public class componentPopupMenu_Adapter extends MouseAdapter { public List maker = new ArrayList(); public boolean internalFrameLeftButtonMagic = false; public boolean allowScrolling = true; public Point pressedAt; public void mousePressed(MouseEvent e) { displayMenu(e); pressedAt = internalFrameLeftButtonMagic && e.getClickCount() == 1 && internalFrameActive(e.getComponent()) ? e.getLocationOnScreen() : null; } public void mouseReleased(MouseEvent e) { if (internalFrameLeftButtonMagic && eq(pressedAt, e.getLocationOnScreen())) displayMenu2(e); else displayMenu(e); } public void displayMenu(MouseEvent e) { if (e.getSource() instanceof JInternalFrame) return; if (e.isPopupTrigger()) displayMenu2(e); } public void populate(JPopupMenu menu, MouseEvent e) { AutoCloseable __1 = tempSetTL(componentPopupMenu_mouseEvent, e); try { for (Object menuMaker : maker) pcallF(menuMaker, menu); vmBus_send("showingPopupMenu", e.getComponent(), menu); } finally { _close(__1); } } public void displayMenu2(MouseEvent e) { new PopupMenuMaker(e, menu -> populate(menu, e)).allowScrolling(allowScrolling).run(); } } static public void componentPopupMenu_top(final JComponent component, final VF1 menuMaker) { if (component != null && menuMaker != null) { swing(() -> { Object adapter = componentPopupMenu_initForComponent(component); ((List) get(adapter, "maker")).add(0, menuMaker); }); } } static public MouseEvent componentPopupMenu_getEvent() { return componentPopupMenu_mouseEvent.get(); } static public Object dm_current_generic() { return getWeakRef(dm_current_generic_tl().get()); } static public Object dm_current_mandatory_generic() { return assertNotNull("No module set", dm_current_generic()); } static public Object withDBLock(Object r) { Lock __0 = db_mainConcepts().lock; lock(__0); try { return callF(r); } finally { unlock(__0); } } static public A withDBLock(F0 r) { return (A) withDBLock((Object) r); } static public Object withDBLock(Concepts concepts, Object r) { Lock __1 = concepts.lock; lock(__1); try { return callF(r); } finally { unlock(__1); } } static public A withDBLock(Concepts concepts, F0 r) { return (A) withDBLock(concepts, (Object) r); } static public A withDBLock(Concept concept, IF0 r) { return (A) withDBLock(concept._concepts, r); } static public void makePopupMenuConditional(JComponent c, F0 condition) { if (c != null && condition != null) { swing(() -> { componentPopupMenu_Adapter adapter = firstInstanceOf(c.getMouseListeners(), componentPopupMenu_Adapter.class); c.removeMouseListener(adapter); c.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (!callF(condition)) adapter.mousePressed(e); } public void mouseReleased(MouseEvent e) { if (!callF(condition)) adapter.mouseReleased(e); } }); }); } } static public boolean dynamicObjectIsLoading() { return isUnstructuring(); } static public Object interceptPrintInThisThread(Object f) { Object old = print_byThread().get(); print_byThread().set(f); return old; } static public void rowSorter_setComparators(JTable table, final Object... params) { setTableModel_fixSorter.put(table, new VF2() { public void get(JTable table, RowSorter sorter) { try { if (sorter instanceof TableRowSorter) { for (Pair p : (List>) (List) paramsToPairs(params)) ((TableRowSorter) sorter).setComparator(p.a, p.b); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "//print(\"Fixing table sorter\");\r\n if (sorter cast TableRowSorter) {\r\n ..."; } }); } static public String addPrefixOptIfNempty(String prefix, String s) { return addPrefixIfNotEmpty2(prefix, s); } static public int year() { return localYear(); } static public int year(Timestamp now) { return localYear(toLong(now)); } static public int year(long now) { return localYear(now); } static public int year(long now, TimeZone tz) { return parseInt(simpleDateFormat("y", tz).format(now)); } static public WithTimestamp withTimestamp(A value) { return withTimestamp(now(), value); } static public WithTimestamp withTimestamp(long timestamp, A value) { return new WithTimestamp(timestamp, value); } static public ICachedJavaXExpr javaObjectToIJavaExpr(Object o) { if (isListOfElementType(Integer.class, o)) return javaExpr(functionCall("lInts", naiveQuote(intsToHex_withLineBreaks((List) o))), () -> o); if (o instanceof List) return javaExpr(functionCall("ll", map(__88 -> javaObjectToIJavaExpr(__88), (List) o)), () -> ((List) o)); Object code = toJavaOpt(o); return javaExpr(code, () -> o); } static public List lambdaMapMethod(IF1 f, Iterable l) { return lambdaMethodMap(f, l); } static public List lambdaMapMethod(IF1 f, A[] l) { return lambdaMethodMap(f, l); } static public double negativeInfinity() { return Double.NEGATIVE_INFINITY; } static public F1 mainFunctionToF1(final String fname) { return new F1() { public Object get(Object a) { try { return callMC(fname, a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callMC(fname, a)"; } }; } static public float score(Scored s) { return s == null ? 0 : s.score(); } static public Set isThreadRunnable_x_exclude = lithashset("sun.nio.fs.WindowsNativeDispatcher.GetQueuedCompletionStatus0", "Java.lang.Thread.start0", "java.lang.Object.wait", "java.net.Inet6AddressImpl.lookupAllHostAddr", "java.io.FileInputStream.readBytes", "jdk.internal.misc.Unsafe.park", "sun.misc.Unsafe.park", "java.net.SocketInputStream.socketRead0", "java.net.PlainSocketImpl.socketConnect", "java.net.PlainSocketImpl.socketAccept", "sun.awt.X11.XToolkit.waitForEvents", "java.net.DualStackPlainSocketImpl.accept0", "org.jnativehook.GlobalScreen$NativeHookThread.enable", "java.lang.Thread.sleep", "sun.nio.ch.EPollArrayWrapper.epollWait", "com.ibm.lang.management.internal.MemoryNotificationThread.processNotificationLoop", "com.ibm.tools.attach.target.IPC.waitSemaphore", "sun.nio.ch.Net.poll", "sun.nio.ch.Net.accept", "sun.nio.ch.Net.connect0", "sun.nio.ch.EPoll.wait", "sun.nio.ch.SocketDispatcher.read0", "sun.nio.fs.LinuxWatchService.poll", "java.lang.ref.Reference.waitForReferencePendingList", "com.sun.java.accessibility.internal.AccessBridge.runDLL", "java.lang.ProcessHandleImpl.waitForProcessExit0"); static public boolean isThreadRunnable_x(StackTraceElement[] trace) { StackTraceElement e = first(trace); if (e == null) return false; String s = e.getClassName() + "." + e.getMethodName(); return !isThreadRunnable_x_exclude.contains(s); } static public boolean isThreadRunnable_x(Thread t, StackTraceElement[] trace) { { Boolean __1 = (Boolean) vmBus_query("isThreadRunnable_x", t, trace); if (__1 != null) return __1; } if (t.getState() != Thread.State.RUNNABLE) return false; return isThreadRunnable_x(trace); } static public RuntimeException asQuickException(Throwable t) { return t instanceof RuntimeException ? (RuntimeException) t : new QuickException(t); } static public long stepAll(Steppable s) { long steps = 0; if (s != null) { var pingSource = pingSource(); while (true) { ping(pingSource); if (s.step()) ++steps; else break; } } return steps; } static public void poorMansProfiling_stopAndPrintResults() { poorMansProfiling_renderFullResults_backwards.set(true); print(poorMansProfiling_stopAndRenderResults()); } static public boolean isRunnableX(Object o) { if (o == null) return false; if (o instanceof String) return hasMethod(mc(), (String) o); return o instanceof Runnable || hasMethod(o, "get"); } static public String jreplaceExpandRefs(String s, List tokref) { if (!contains(s, '$')) return s; List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (t.startsWith("$") && isInteger(t.substring(1))) { String x = tokref.get(-1 + parseInt(t.substring(1)) * 2); tok.set(i, x); } else if (t.equals("\\")) { tok.set(i, ""); i += 2; } } return join(tok); } static public JTextArea wrappedTextArea(final JTextArea ta) { enableWordWrapForTextArea(ta); return ta; } static public JTextArea wrappedTextArea() { return wrappedTextArea(jtextarea()); } static public JTextArea wrappedTextArea(String text) { JTextArea ta = wrappedTextArea(); setText(ta, text); return ta; } static public boolean infoMessage_alwaysOnTop = true; static public double infoMessage_defaultTime = 5.0; static public JWindow infoMessage(String text) { return infoMessage(text, infoMessage_defaultTime); } static public JWindow infoMessage(final String text, final double seconds) { printHidingCredentials(text); return infoMessage_noprint(text, seconds); } static public JWindow infoMessage_noprint(String text) { return infoMessage_noprint(text, infoMessage_defaultTime); } static public JWindow infoMessage_noprint(final String _text, final double seconds) { final String text = hideCredentials(_text); if (empty(text)) return null; logQuotedWithDate(infoBoxesLogFile(), text); if (isHeadless()) return null; return (JWindow) swingAndWait(new F0() { public Object get() { try { JWindow window = makeWindow(infoMessage_makePanel(text)); window.setSize(300, 150); moveToTopRightCorner(window); if (infoMessage_alwaysOnTop) window.setAlwaysOnTop(true); if (vmBus_noObjections("shouldShowInfoBox", window, text)) window.setVisible(true); if (seconds != 0) disposeWindowAfter(iround(seconds * 1000), window); return window; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JWindow window = makeWindow(infoMessage_makePanel(text));\r\n window.setSize..."; } }); } static public JWindow infoMessage(Throwable e) { printStackTrace(e); return infoMessage(exceptionToStringShort(e)); } static public int brightnessToRGBA(int brightness) { return 0xFF000000 | clamp(brightness, 0, 255) * 0x010101; } static public JPanel withBorder(javax.swing.border.Border border, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(new BorderLayout()); p.setBorder(border); p.add(c); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(border);\r\n p.add..."; } }); } static public Set getPlural_specials = litciset("sheep", "fish"); static public String getPlural(String s) { if (contains(getPlural_specials, s)) return s; if (ewic(s, "y")) return dropSuffixIgnoreCase("y", s) + "ies"; if (ewicOneOf(s, "ss", "ch")) return s + "es"; if (ewic(s, "s")) return s; return s + "s"; } static public boolean hasLetters(String s) { for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i))) return true; return false; } static public List sorted(Collection c, Object comparator) { List l = cloneList(c); sort(l, makeComparator(comparator)); return l; } static public List sorted(Collection c) { List l = cloneList(c); sort(l); return l; } static public List sorted(Comparator comparator, Collection c) { List l = cloneList(c); sort(l, comparator); return l; } static public Map loadFont_cached_cache = new HashMap(); static synchronized public Font loadFont_cached(String snippetID) { try { snippetID = formatSnippetID(snippetID); Font f = loadFont_cached_cache.get(snippetID); if (f == null) loadFont_cached_cache.put(snippetID, f = loadFont(snippetID, 12f)); return f; } catch (Exception __e) { throw rethrow(__e); } } static synchronized public Font loadFont_cached(String snippetID, float size) { try { return loadFont_cached(snippetID).deriveFont(size); } catch (Exception __e) { throw rethrow(__e); } } static public String standardCredentials_noCookies() { return standardCredentials() + "&noCookies=1"; } static public Object rcallOpt(String method, Object o, Object... args) { return callOpt_withVarargs(o, method, args); } static public void hideConsole() { final JFrame frame = consoleFrame(); if (frame != null) { autoVMExit(); swingLater(new Runnable() { public void run() { try { frame.setVisible(false); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setVisible(false);"; } }); } } static public String quickSubstring(String s, int i, int j) { if (i >= j) return ""; return s.substring(i, j); } static public boolean machineIsOffline() { return isFalse(callF(vmGeneralMap_get("areWeOnline"))); } static public Set getClassDeclarationName_skippables_cache; static public Set getClassDeclarationName_skippables() { if (getClassDeclarationName_skippables_cache == null) getClassDeclarationName_skippables_cache = getClassDeclarationName_skippables_load(); return getClassDeclarationName_skippables_cache; } static public Set getClassDeclarationName_skippables_load() { return litset("noeq", "mapMethodLike"); } static public List childrenOfType(Component c, Class theClass) { List l = new ArrayList(); scanForComponents(c, theClass, l); return l; } static public List childrenOfType(Class theClass, Component c) { return childrenOfType(c, theClass); } static public void dm_reloadModuleInBackground(Object module) { dm_callOS("reloadModuleInBackground", dm_getStem(module)); } static public void dm_reloadModuleInBackground() { dm_reloadModuleInBackground(dm_current_mandatory_generic()); } static public ThreadLocal poorMansProfiling_renderFullResults_backwards = new ThreadLocal(); static public String poorMansProfiling_renderFullResults(final MultiSet traces) { int samples = poorMansProfiling_samples; boolean backwards = isTrue(getAndClearThreadLocal(poorMansProfiling_renderFullResults_backwards)); final int n = traces.size(); int percent = ratioToIntPercent(l(traces), samples); return (samples == 0 ? "Nothing sampled" : percent + "% core activity [" + n2(samples, "sample") + " taken]") + "\n\n" + joinMap(backwards ? traces.lowestFirst() : traces.highestFirst(), new F1() { public Object get(String trace) { try { return traces.get(trace) + "/" + n + "\n" + trace + "\n\n"; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "traces.get(trace) + \"/\" + n + \"\\n\" + trace + \"\\n\\n\""; } }); } static public String unCurlyBracket(String s) { return tok_unCurlyBracket(s); } static public Pair compileSnippetThroughServer(String progID) { String transpiledSrc = getServerTranspiled2(progID); String md5 = md5(transpiledSrc + "\n" + progID); File jar = CompilerBot.getJarFile(md5); if (jar == null || jar.length() <= 22) { byte[] jarData = null; boolean dontLoad = false; IResourceLoader rl = vm_getResourceLoader(); if (rl != null) { dontLoad = true; File jar2 = rl.getSnippetJar(progID, transpiledSrc); if (jar2 != null) return pair(jar2, transpiledSrc); } if (!dontLoad) { try { jarData = loadBinaryPage(jarBotURL() + psI(progID) + "?md5=" + md5(transpiledSrc)); } catch (Throwable __e) { pcallFail(__e); } } if (!isJAR(jarData)) { if (jarData != null) { print(bytesToHex(takeFirstOfByteArray(8, jarData))); print("fallback to CompilerBot: " + fromUtf8(takeFirstOfByteArray(80, jarData))); } return CompilerBot.compileSnippet2(progID); } saveBinaryFile(jar, jarData); } return pair(jar, transpiledSrc); } static public String dropSpaceEtc(String s) { if (empty(s)) return null; int n = l(s), i = 0; char c = s.charAt(i); boolean totality = !isSpaceEtc(c); for (++i; i < n; i++) { c = s.charAt(i); boolean b = !isSpaceEtc(c); if (b != totality) { StringBuilder buf = new StringBuilder(); if (totality) buf.append(substring(s, 0, i)); while (true) { ping(); if (b) buf.append(c); if (++i >= n) break; c = s.charAt(i); b = !isSpaceEtc(c); } return buf.toString(); } } return totality ? s : ""; } static public ClassLoader getVirtualParent(ClassLoader cl) { return (ClassLoader) rcallOpt("getVirtualParent", cl); } static public boolean titlePopupMenu(final Component c, final Object menuMaker) { JComponent titleBar = getTitlePaneComponent(getPossiblyInternalFrame(c)); if (titleBar == null) { print("Can't add title right click!"); return false; } else { componentPopupMenu(titleBar, menuMaker); return true; } } static public boolean isA(Either e) { return eitherIsA(e); } static public long nanoTime() { return System.nanoTime(); } static public int activateFrame_v3_delay = 100; static public boolean activateFrame_v3(Component c, Object... __) { return swing(() -> { Frame f = getAWTFrame(c); if (f == null) return false; if (!f.isVisible()) f.setVisible(true); int state = f.getState(); boolean iconified = state == Frame.ICONIFIED; boolean maximize = boolPar("maximize", __); if (iconified) f.setState(maximize ? Frame.MAXIMIZED_BOTH : Frame.NORMAL); else { f.setState(Frame.ICONIFIED); print("Restoring frame in " + activateFrame_v3_delay + " ms"); doLater(activateFrame_v3_delay, new Runnable() { public void run() { try { f.setState(state); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.setState(state)"; } }); } f.toFront(); return true; }); } static public String programIDWithCase() { return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID(); } static public Set vm_generalWeakSet(Object name) { synchronized (vm_generalMap()) { Set set = (Set) (vm_generalMap_get(name)); if (set == null) vm_generalMap_put(name, set = newWeakHashSet()); return set; } } static public File associatedInfosFile(File f) { return replaceExtension(f, ".infos"); } static public String addPrefix(String prefix, String s) { return s.startsWith(prefix) ? s : prefix + s; } static public boolean isCurlyBraced(String s) { List tok = tok_combineCurlyBrackets_keep(javaTok(s)); return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}"); } static public String b(Object contents, Object... params) { return fulltag("b", contents, params); } static public File findCmdOnPATH(String cmd) { String path = System.getenv("PATH"); List dirs = splitAt(path, File.pathSeparator); String c = isWindows() ? addSuffix(cmd, ".exe") : cmd; for (String dir : dirs) { File f = new File(dir, c); if (f.isFile()) return f; } return null; } static public File tempDirPossiblyInRAMDisk() { File f = linux_fileInRamDisk(aGlobalID()); if (f != null) { f.mkdirs(); return f; } return makeTempDir(); } static public int javaxIncludeSnippetType() { return 42; } static public boolean ewicOneOf(String s, String... l) { if (s != null) for (String x : l) if (ewic(s, x)) return true; return false; } static public Pt bottomRightCorner(Rect r) { return r == null ? null : pt(r.x2(), r.y2()); } static public FixedRateTimer doEvery_daemon(long delay, final Object r) { return doEvery_daemon(defaultTimerName(), delay, r); } static public FixedRateTimer doEvery_daemon(String timerName, long delay, final Object r) { return doEvery_daemon(timerName, delay, delay, r); } static public FixedRateTimer doEvery_daemon(long delay, long firstDelay, final Object r) { return doEvery_daemon(defaultTimerName(), delay, firstDelay, r); } static public FixedRateTimer doEvery_daemon(String timerName, long delay, long firstDelay, final Object r) { FixedRateTimer timer = new FixedRateTimer(true); timer.scheduleAtFixedRate(smartTimerTask(r, timer, delay), firstDelay, delay); return timer; } static public FixedRateTimer doEvery_daemon(double delaySeconds, final Object r) { return doEvery_daemon(toMS(delaySeconds), r); } static public void pClose(AutoCloseable c) { close_pcall(c); } static public void closeRandomAccessFile(RandomAccessFile f) { if (f != null) try { f.close(); callJavaX("dropIO", f); } catch (Throwable e) { printStackTrace(e); } } static public JPanel jCenteredSection(Component c) { return jCenteredSection("", c); } static public JPanel jCenteredSection(String title, Swingable c) { return jCenteredSection(title, wrap(c)); } static public JPanel jCenteredSection(String title, Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = jSection(title, c); ((TitledBorder) p.getBorder()).setTitleJustification(TitledBorder.CENTER); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = jSection(title, c);\r\n ((TitledBorder) p.getBorder()).setTitleJu..."; } }); } static public JPanel jCenteredSection(String title) { return jCenteredSection(title, jpanel()); } static public Comparator makeComparator(final Object f) { if (f instanceof Comparator) return (Comparator) f; return new Comparator() { public int compare(Object a, Object b) { return (Integer) callF(f, a, b); } }; } static public String manifestTextForMainClass(String mainClass) { return "Manifest-Version: 1.0\n" + "Main-Class: " + mainClass + "\n\n"; } static public JLabel dm_fieldLabel(String fieldName) { return jLiveValueLabel(dm_fieldLiveValue(fieldName)); } static public String n(long l, String name) { return l + " " + trim(l == 1 ? singular(name) : getPlural(name)); } static public String n(Collection l, String name) { return n(l(l), name); } static public String n(Map m, String name) { return n(l(m), name); } static public String n(Object[] a, String name) { return n(l(a), name); } static public String n(MultiSet ms, String name) { return n(l(ms), name); } static public String htmlencode_noQuotes(String s) { if (s == null) return ""; int n = s.length(); StringBuilder out = null; for (int i = 0; i < n; i++) { char c = s.charAt(i); if (c == '<') { if (out == null) out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s)); out.append("<"); } else if (c == '>') { if (out == null) out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s)); out.append(">"); } else if (c > 127 || c == '&') { int cp = s.codePointAt(i); if (out == null) out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s)); out.append("&#x"); out.append(intToHex_flexLength(cp)); out.append(';'); i += Character.charCount(cp) - 1; } else { if (out != null) out.append(c); } } return out == null ? s : out.toString(); } static public Window dm_window(Object module) { return getWindow(dm_vis(module)); } static public class IVF1WithToString implements IVF1, IFieldsToList { static final public String _fieldOrder = "toString f"; public String toString; public IVF1 f; public IVF1WithToString() { } public IVF1WithToString(String toString, IVF1 f) { this.f = f; this.toString = toString; } public boolean equals(Object o) { if (!(o instanceof IVF1WithToString)) return false; IVF1WithToString __1 = (IVF1WithToString) o; return eq(toString, __1.toString) && eq(f, __1.f); } public int hashCode() { int h = 574155786; h = boostHashCombine(h, _hashCode(toString)); h = boostHashCombine(h, _hashCode(f)); return h; } public Object[] _fieldsToList() { return new Object[] { toString, f }; } public void get(A a) { f.get(a); } public String toString() { return toString; } } static public IVF1 ivf1WithToString(String toString, IVF1 f) { return f == null ? null : new IVF1WithToString(toString, f); } static public int abs(int i) { return Math.abs(i); } static public long abs(long i) { return Math.abs(i); } static public float abs(float i) { return Math.abs(i); } static public double abs(double i) { return Math.abs(i); } static public double abs(Complex c) { return c.abs(); } static public void forEachWithPosition(Matrix m, IVF3 f) { if (m == null || f == null) return; int w = m.getWidth(), h = m.getHeight(); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) f.get(x, y, m.get(x, y)); } static public Map runnableThreadsWithStackTraces() { Map map = filterMap((__154, __155) -> isThreadRunnable_x(__154, __155), Thread.getAllStackTraces()); map.remove(currentThread()); return map; } static public BufferedImage scaledBufferedImageFromBWIntegralImage(int w, BWIntegralImage img) { return scaledBufferedImageFromBWIntegralImage(img, w); } static public BufferedImage scaledBufferedImageFromBWIntegralImage(BWIntegralImage img, int w) { return scaledBufferedImageFromBWIntegralImage(img, w, heightForWidth(img.w, img.h, w)); } static public BufferedImage scaledBufferedImageFromBWIntegralImage(BWIntegralImage img, int w, int h) { int w1 = img.w, h1 = img.h; int[] pixels = new int[w * h]; int i = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { int x1 = x * w1 / w, x2 = max(x1 + 1, (x + 1) * w1 / w); int y1 = y * h1 / h, y2 = max(y1 + 1, (y + 1) * h1 / h); int pixel = iround(img.getPixelAverage(x1, y1, x2, y2)); pixels[i++] = brightnessToRGBA(pixel); } return bufferedImage(w, h, pixels); } public static String winQuote(String text) { if (text == null) return null; return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r") + "\""; } static public String winQuote(File f) { return winQuote(f.getAbsolutePath()); } static public Map stdFunctions_uncached() { return stdFunctions_uncached(new HashMap()); } static public Map stdFunctions_uncached(Map map) { for (var snippetID : stdFunctionListSnippetIDs()) parseStdFunctionsList(loadSnippet(snippetID), map); return map; } static public boolean isJavaxModuleSnippetType(int type) { return type == snippetType_javaxModule() || type == snippetType_javaxDesktopModule(); } static public int findEndOfBracketPart(List cnc, int i) { int j = i + 2, level = 1; while (j < cnc.size()) { if (eqOneOf(cnc.get(j), "{", "(")) ++level; else if (eqOneOf(cnc.get(j), "}", ")")) --level; if (level == 0) return j + 1; ++j; } return cnc.size(); } static public File prepareProgramFile(String name) { return mkdirsForFile(getProgramFile(name)); } static public File prepareProgramFile(String progID, String name) { return mkdirsForFile(getProgramFile(progID, name)); } static public boolean rectEmpty(Rect r) { return r == null || r.w <= 0 || r.h <= 0; } static public Set tok_returnTypesOfStaticFunction_uncleaned(List tok, String functionName) { List> funcs = findFullFunctionDefs(tok, true); TreeSet out = new TreeSet(); for (List tokF : funcs) { int i = indexOfAny(tokF, 0, "(", "{"); if (i < 0) continue; String fname = get(tokF, i - 2); if (!eq(fname, functionName)) continue; out.add(joinSubList(tokF, 1, i - 3)); } return out; } static public BufferedImage intMatrixToImage(Matrix m) { return intMatrixToBufferedImage(m); } static public void interruptThreads(Collection threads) { for (Thread t : unnull(threads)) interruptThread(t); } static public void interruptThreads(Class mainClass) { interruptThreads(registeredThreads(mainClass)); } static public List hotwire_collectJars(File jar) { List libIDs = hotwire_libraryIDsFromJar_deleteJarOnFail(jar); List files = ll(jar); for (String libID : libIDs) files.add(loadLibraryOrSrcLib(libID)); return files; } static public A callMain(A c, String... args) { callOpt(c, "main", new Object[] { args }); return c; } static public void callMain() { callMain(mc()); } static public Either eitherB(B b) { return new Either(2, b); } static public String evalJava_prep(String code) { return evalJava_prep(code, "calc"); } static public String evalJava_prep(String code, String mainName) { return evalJava_prep(code, mainName, ""); } static public ThreadLocal evalJava_prep_args = new ThreadLocal(); static public String evalJava_prep(String code, String mainName, String preCode) { EvalJavaPrep prep = new EvalJavaPrep(); List tok = evalJava_prePrep(code, prep); code = tok_addReturn(tok); String returnType = containsReturnWithArgument(code) ? "Object" : "void"; String main = lines(prep.global) + "static " + returnType + " " + mainName + "(" + unnull(evalJava_prep_args.get()) + ") throws Exception {\n" + preCode + code + "\n" + "}"; return main; } static public Either eitherA(A a) { return new Either(1, a); } static public void markAsSrcLib(String snippetID) { saveTextFile(javaxCodeDir("srclibs/" + psI(snippetID)), ""); } static public int lIntArray(int[] a) { return a == null ? 0 : a.length; } static public ThreadLocal evalJava_myProgramID_main_time = new ThreadLocal(); static public ThreadLocal evalJava_myProgramID_main_mainClass = new ThreadLocal(); static public Object evalJava_myProgramID_main(String main, Object... args) { Object obj = veryQuickJava(main); setOpt(obj, "programID", programID()); makeDependent(obj); if (evalJava_myProgramID_main_mainClass.get() != null) evalJava_myProgramID_main_mainClass.set(obj); return evalJava_myProgramID_main_2(obj, args); } static public Object evalJava_myProgramID_main_2(Object obj, Object... args) { long time = sysNow(); try { return callCalc(obj, args); } finally { evalJava_myProgramID_main_time.set(sysNow() - time); } } static public void addMouseAndMotionListener(Component c, MouseAdapter ma) { if (c != null && ma != null) { swing(() -> { c.addMouseListener(ma); c.addMouseMotionListener(ma); }); } } static public void containerAddFirst(Container c, Component... l) { if (c != null) { swing(() -> { for (int i = 0; i < l(l); i++) c.add(l[i], i); revalidate(c); }); } } static public Comparator caseInsensitiveComparator() { return betterCIComparator(); } static public File dropExtension(File f) { return f == null ? null : fileInSameDir(f, dropExtension(f.getName())); } static public String dropExtension(String s) { return takeFirst(s, smartLastIndexOf(s, '.')); } static public String asciiHeading2(String title) { return asciiHeading(title) + "\n"; } static public List getComponents(final Component c) { return !(c instanceof Container) ? emptyList() : asList(swing(new F0() { public Component[] get() { try { return ((Container) c).getComponents(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return ((Container) c).getComponents();"; } })); } static public List> paramsToPairs(A... params) { if (l(params) == 1 && params[0] instanceof Map) return mapToPairs((Map) params[0]); List> l = emptyList(l(params) / 2); for (int i = 0; i + 1 < l(params); i += 2) l.add(pair(params[i], params[i + 1])); return l; } static public String rep(int n, char c) { return repeat(c, n); } static public String rep(char c, int n) { return repeat(c, n); } static public List rep(A a, int n) { return repeat(a, n); } static public List rep(int n, A a) { return repeat(n, a); } static public int area(Rect r) { return rectArea(r); } static public double area(DoubleRect r) { return r == null ? 0 : r.w * r.h; } static public int area(WidthAndHeight img) { return img == null ? 0 : img.getWidth() * img.getHeight(); } static public int area(BufferedImage img) { return img == null ? 0 : img.getWidth() * img.getHeight(); } static public void add(BitSet bs, int i) { bs.set(i); } static public boolean add(Collection c, A a) { return c != null && c.add(a); } static public void add(Container c, Component x) { addToContainer(c, x); } static public long add(AtomicLong l, long b) { return l.addAndGet(b); } static public SingleComponentPanel singleComponentPanel() { return singleComponentPanel(null); } static public SingleComponentPanel singleComponentPanel(final Component c) { return swing(new F0() { public SingleComponentPanel get() { try { return new SingleComponentPanel(c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return new SingleComponentPanel(c);"; } }); } static public SimpleDateFormat simpleDateFormat_local(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(localTimeZone()); return sdf; } static public int withMargin_defaultWidth = 6; static public JPanel withMargin(Component c) { return withMargin(withMargin_defaultWidth, c); } static public JPanel withMargin(int w, Component c) { return withMargin(w, w, c); } static public JPanel withMargin(int w, int h, Component c) { return withMargin(w, h, w, h, c); } static public JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = marginPanel(); p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right)); p.add(c); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = marginPanel();\r\n p.setBorder(BorderFactory.createEmptyBorder(to..."; } }); } static public File getCodeProgramDir() { return getCodeProgramDir(getProgramID()); } static public File getCodeProgramDir(String snippetID) { return new File(javaxCodeDir(), formatSnippetID(snippetID)); } static public File getCodeProgramDir(long snippetID) { return getCodeProgramDir(formatSnippetID(snippetID)); } static public void addActionListener(JTextField tf, final Runnable action) { onEnter(tf, action); } static public void addActionListener(final JComboBox cb, final Runnable action) { if (cb != null) { swing(() -> { cb.addActionListener(actionListener(action)); }); } } static public void addActionListener(final AbstractButton b, final Runnable action) { if (b != null) { swing(() -> { b.addActionListener(actionListener(action)); }); } } static public Matrix imageToMatrix(MakesBufferedImage img) { return imageToMatrix(toBufferedImage(img)); } static public Matrix imageToMatrix(BufferedImage img) { if (img == null) return null; int _w = img.getWidth(), _h = img.getHeight(); class ImageToMatrix extends AbstractMatrix { public ImageToMatrix() { super(_w, _h); } public Integer get(int x, int y) { assertPointInBounds(x, y, w, h); return img.getRGB(x, y); } public void set(int x, int y, Integer val) { assertPointInBounds(x, y, w, h); img.setRGB(x, y, val); } } ; return new ImageToMatrix(); } static public int hashAboutObjects(Object... l) { int hash = 0, n = l(l); for (int i = 0; i < n; i++) hash = boostHashCombine(hash, hashCode(l[i])); return hash; } static public boolean hasMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args) != null; } static public void clearTokens(List tok) { clearAllTokens(tok); } static public void clearTokens(List tok, int i, int j) { clearAllTokens(tok, i, j); } static public void clearTokens(List tok, IntRange r) { clearAllTokens(tok, r.start, r.end); } static public KeyListener enterKeyListener(final Object action) { return new KeyAdapter() { public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_ENTER) pcallF(action); } }; } static public String poorMansProfiling_stopAndRenderResults() { return poorMansProfiling_renderFullResults(poorMansProfiling_stopAndGetResults()); } static public int areaFromPoints(int x1, int y1, int x2, int y2) { return (x1 - x1) * (y2 - y1); } static public List countIteratorToList(int b) { return countIteratorToList(0, b); } static public List countIteratorToList(int a, int b) { return asList(countIterator(a, b)); } static public List countIteratorToList(int b, IF1 f) { return countIteratorToList(0, b, f); } static public List countIteratorToList(int a, int b, IF1 f) { return asList(countIterator(a, b, f)); } static public List countIteratorToList(int a, int b, int step) { return asList(countIterator(a, b, step)); } static public List countIteratorToList(double a, double b, double step, IF1 f) { return asList(countIterator(a, b, step, f)); } static public List countIteratorToList(double a, double b, double step) { return asList(countIterator(a, b, step)); } static public List countIteratorToList(IF1 f, double a, double b, double step) { return asList(countIterator(f, a, b, step)); } static public List countIteratorToList(IF1 f, int b) { return countIteratorToList(f, 0, b); } static public List countIteratorToList(IF1 f, int a, int b) { return asList(countIterator(f, a, b)); } static public List javaTokWithExisting(String s, List existing) { ++javaTok_n; int nExisting = javaTok_opt && existing != null ? existing.size() : 0; ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList(); int l = s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(javaTok_substringN(s, i, j)); ++n; i = j; if (i >= l) break; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) { j += 2; while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j; } else if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else if (c == '[' && d == '[') { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') { do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]")); j = Math.min(j + 3, l); } else ++j; if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } static public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) { return t.length() == j - i && s.regionMatches(i, t, 0, j - i); } static public Object hotwire_onCompile; static public boolean hotwire_serially = false; static public Lock hotwire_overInternalBot_lock = lock(); static public boolean hotwire_compileOnServer = false; static public Class hotwire_overInternalBot(String progID) { return hotwire_overInternalBot(progID, "main"); } static public Class hotwire_overInternalBot(String progID, String mainClass) { return hotwire_overInternalBot(progID, __ -> mainClass); } static public Class hotwire_overInternalBot(String progID, IF1 calculateMainClass) { try { Pair p; try { p = hotwire_compile(progID); } catch (Throwable e) { throw rethrow("Error hotwiring " + progID, e); } File jar = p.a; assertTrue(jar.getAbsolutePath(), jar.isFile()); List files = hotwire_collectJars(jar); JavaXClassLoader classLoader = hotwire_makeClassLoader(files); classLoader.progID = progID; String mainClass = calculateMainClass == null ? "main" : calculateMainClass.get(classLoader); return hotwire_finish(classLoader, progID, p.b, mainClass); } catch (Exception __e) { throw rethrow(__e); } } static public Pair hotwire_compile(String progID) { Pair p = hotwire_compileOnServer && !isLocalSnippetID(progID) ? compileSnippetThroughServer(progID) : CompilerBot.compileSnippet2(progID); Lock __0 = hotwire_serially ? hotwire_overInternalBot_lock : null; lock(__0); try { callF(hotwire_onCompile, p); return p; } finally { unlock(__0); } } static public A printStruct(String prefix, A a) { printStructure(prefix, a); return a; } static public A printStruct(A a) { printStructure(a); return a; } static public boolean containsOneOf(Collection l, A... x) { if (l instanceof Set) { if (x != null) for (A a : x) if (l.contains(a)) return true; } else { for (A a : unnull(l)) if (eqOneOf(a, x)) return true; } return false; } static public boolean containsOneOf(Collection l, Set set) { if (set == null) return false; for (A a : unnull(l)) if (set.contains(a)) return true; return false; } static public boolean containsOneOf(String s, String... x) { for (String o : x) if (contains(s, o)) return true; return false; } static public AutoCloseable dm_registerAs_direct(String... msgs) { return dm_registerAs_directLink(msgs); } static public JFrame setFrameIconLater(Component c, final String imageID) { final JFrame frame = getFrame(c); if (frame != null) startThread("Loading Icon", new Runnable() { public void run() { try { final Image i = imageIcon(or2(imageID, "#1005557")).getImage(); swingLater(new Runnable() { public void run() { try { frame.setIconImage(i); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setIconImage(i);"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n swingL..."; } }); return frame; } static public Rect intersectRects(Rect a, Rect b) { int x = max(a.x, b.x), y = max(a.y, b.y); int x2 = min(a.x + a.w, b.x + b.w), y2 = min(a.y + a.h, b.y + b.h); return new Rect(x, y, x2 - x, y2 - y); } static public Rect intersectRects(Rect a, int x1, int y1, int w, int h) { if (a == null || a.x >= x1 && a.y >= y1 && a.x2() < x1 + w && a.y2() < y1 + h) return a; return rectFromPoints(max(a.x, x1), max(a.y, y1), min(a.x2(), x1 + w), min(a.y2(), y1 + h)); } static public String loadCachedTranspilation(String id) { try { return loadTextFilePossiblyGZipped(getCachedTranspilationFile(id)); } catch (Throwable __e) { return null; } } static public File infoBoxesLogFile() { return new File(javaxDataDir(), "Logs/infoBoxes.txt"); } static public boolean addToCollection(Collection c, A a) { return c != null && c.add(a); } static public List dropFirstThreeAndLastThree(List l) { return dropFirstAndLast(3, l); } static public double minusInfinity() { return negativeInfinity(); } static public boolean deleteFile(File file) { return file != null && file.delete(); } static public Matrix listOfListsToMatrix(List> data) { if (data == null) return null; int _h = l(data); if (_h == 0) return null; int _w = l(data.get(0)); class ListsToMatrix extends AbstractMatrix { public ListsToMatrix() { super(_w, _h); } public A get(int x, int y) { return data.get(y).get(x); } public void set(int x, int y, A a) { data.get(y).set(x, a); } } ; return new ListsToMatrix(); } static public String firstToken(String s) { return firstJavaToken(s); } static public String firstToken(List tok) { return get(tok, 1); } static public JPanel centerAndSouthWithMargins(Swingable c, Swingable s) { return centerAndSouthWithMargins(c, toComponent(s)); } static public JPanel centerAndSouthWithMargins(Swingable c, Component s) { return centerAndSouthWithMargins(toComponent(c), s); } static public JPanel centerAndSouthWithMargins(Component c, Swingable s) { return centerAndSouthWithMargins(c, toComponent(s)); } static public JPanel centerAndSouthWithMargins(Component c, Component s) { return applyDefaultMargin(centerAndSouth(c, withTopMargin(s))); } static public JPanel centerAndSouthWithMargins(int margin, Swingable c, Swingable s) { return centerAndSouthWithMargins(margin, c, toComponent(s)); } static public JPanel centerAndSouthWithMargins(int margin, Swingable c, Component s) { return centerAndSouthWithMargins(margin, toComponent(c), s); } static public JPanel centerAndSouthWithMargins(int margin, Component c, Swingable s) { return centerAndSouthWithMargins(margin, c, toComponent(s)); } static public JPanel centerAndSouthWithMargins(int margin, Component c, Component s) { return applyMargin(margin, centerAndSouth(c, withTopMargin(margin, s))); } static public void setSCPComponent(SingleComponentPanel scp, Component c) { if (scp != null) scp.setComponent(c); } static public void stopTimer(java.util.Timer timer) { if (timer != null) timer.cancel(); } static public Object dm_os() { { var __1 = vm_generalMap_get("stefansOS"); if (__1 != null) return __1; } return creator(); } static public void hideWindow(final Component c) { final Window w = getWindow(c); if (w != null) { swing(() -> { w.setVisible(false); }); } } static public A cyclicGet(List l, int i) { return empty(l) ? null : get(l, mod(i, l(l))); } static public boolean cyclicGet(BitSet bs, int n, int i) { return bs != null && bs.get(mod(i, n)); } static public long cyclicGet(LongBuffer l, int i) { return l.get(mod(i, l.size())); } static public String ymdMinusHMS() { return ymdMinusHMS(now()); } static public String ymdMinusHMS(long now) { return ymd_minus_hms(now); } static public String addSlash(String s) { return empty(s) || s.endsWith("/") ? s : s + "/"; } static public int toIntPercent(double ratio) { return roundToInt(ratio * 100); } static public int toIntPercent(float ratio) { return toIntPercent((double) ratio); } static public boolean tok_classHasModifier(List classDecl, String modifier) { if (classDecl == null) return false; int i = classDecl.indexOf("class"); return subList(classDecl, 0, i).contains(modifier); } static public String prependSquareBracketed(Object o) { String s = strOrEmpty(o); return empty(s) ? "" : squareBracketed(s) + " "; } static public int withLeftMargin_defaultWidth = 6; static public JPanel withLeftMargin(Swingable c) { return withLeftMargin(toComponent(c)); } static public JPanel withLeftMargin(Component c) { return withLeftMargin(withLeftMargin_defaultWidth, c); } static public JPanel withLeftMargin(int margin, Swingable c) { return withLeftMargin(margin, toComponent(c)); } static public JPanel withLeftMargin(int margin, Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createEmptyBorder(0, margin, 0, 0)); p.add(c); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat..."; } }); } static public BetterThreadLocal pingSource_tl_var = new BetterThreadLocal() { @Override public PingSource initialValue() { return ping_v3_pingSourceMaker().get(); } }; static public BetterThreadLocal pingSource_tl() { return pingSource_tl_var; } static public JPanel jSection(Component c) { return jSection("", c); } static public JPanel jSection(final String title, final Component c) { return swing(new F0() { public JPanel get() { try { Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED); border = BorderFactory.createTitledBorder(border, title); JSection panel = new JSection(c); panel.setBorder(border); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n bo..."; } }); } static public JPanel jSection(String title) { return jSection(title, jpanel()); } static public JPanel jSection(LiveValue lv, Component c) { return jLiveValueSection(lv, c); } static public JButton jPopDownButton_noText(final Object... menuParams) { return toolTip("Additional commands", jPopDownButton("", menuParams)); } static public java.text.SimpleDateFormat simpleDateFormat(String format, TimeZone timeZone) { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format); sdf.setTimeZone(timeZone); return sdf; } static public List replaceElementsUsingMap(Iterable l, final Map map) { return map(l, new F1() { public A get(A a) { try { return getOrKeep(map, a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getOrKeep(map, a)"; } }); } static public void swingLater(long delay, final Object r) { javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r))); timer.setRepeats(false); timer.start(); } static public void swingLater(Object r) { var runnable = toRunnable(r); executingSwingCode(runnable); SwingUtilities.invokeLater(runnable); } static public String tok_unCurlyBracket(String s) { return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s; } static public void copyListPart(List a, int i1, List b, int i2, int n) { if (a == null || b == null) return; for (int i = 0; i < n; i++) b.set(i2 + i, a.get(i1 + i)); } static public boolean makeNotifyingStringBufferRotate_verbose = false; static public class NotifyingStringBufferRotator implements Runnable { public NotifyingStringBuffer buf; public IF0 getMaxChars; public boolean processing = false; public NotifyingStringBufferRotator(NotifyingStringBuffer buf, IF0 getMaxChars) { this.getMaxChars = getMaxChars; this.buf = buf; } public void run() { try { if (processing) return; AutoCloseable __1 = tempSet(this, "processing", true); try { Integer max = callF(getMaxChars); if (max == null || buf.length() <= max) return; if (makeNotifyingStringBufferRotate_verbose) print("Rotating NotifyingStringBuffer (" + buf.length() + "/" + max + ")"); try { int newLength = max / 2; int ofs = buf.length() - newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } buf.trimToSize(); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } } static public void makeNotifyingStringBufferRotate(NotifyingStringBuffer buf, IF0 getMaxChars) { if (hasElementWithClassShortNamed("NotifyingStringBufferRotator", buf.onChange)) return; buf.onChange(new NotifyingStringBufferRotator(buf, getMaxChars)); } static public List matrixToList(Matrix m) { if (m == null) return null; int w = m.getWidth(), h = m.getHeight(), n = w * h; return new RandomAccessAbstractList() { public int size() { return n; } public A get(int i) { return m.get(i % w, i / w); } public A set(int i, A val) { A old = m.get(i % w, i % h); m.set(i % w, i / w, val); return old; } }; } static public Object[] mapObjectArray(IF1 f, Object[] l) { if (empty(l)) return l; int n = l.length; Object[] a2 = new Object[n]; for (int i = 0; i < n; i++) a2[i] = f.get(l[i]); return a2; } static public String defaultTimerName_name; static public String defaultTimerName() { if (defaultTimerName_name == null) defaultTimerName_name = "A timer by " + programID(); return defaultTimerName_name; } static public ThreadLocal currentImage_var = new ThreadLocal(); static public BufferedImage currentImage() { return currentImage_var.get(); } static public void currentImage(BufferedImage img) { currentImage_var.set(img); } static public int imageMergeSpacing = 5; static public int imageMergeSpacing() { return imageMergeSpacing; } static public void imageMergeSpacing(int pixels) { imageMergeSpacing = pixels; } static public Object _defaultClassFinder_value = defaultDefaultClassFinder(); static public Object _defaultClassFinder() { return _defaultClassFinder_value; } static public boolean boolOptParam(ThreadLocal tl) { return isTrue(optPar(tl)); } static public boolean boolOptParam(Object[] __, String name) { return isTrue(optParam(__, name)); } static public boolean boolOptParam(String name, Object[] __) { return boolOptParam(__, name); } static public boolean boolOptParam(String name, Map __) { return isTrue(optPar(name, __)); } static public MultiSet poorMansProfiling_results = new MultiSet(); static public int poorMansProfiling_samples; static public java.util.Timer poorMansProfiling_timer; static public Lock poorMansProfiling_lock = lock(); static public Thread poorMansProfiling_threadToSample; static public void poorMansProfiling() { poorMansProfiling(poorMansProfiling_defaultInterval()); } static public void poorMansProfiling(Thread thread) { poorMansProfiling(poorMansProfiling_defaultInterval(), thread); } static public void poorMansProfiling(int interval) { poorMansProfiling(interval, null); } static public void poorMansProfiling(int interval, Thread thread) { Lock __0 = poorMansProfiling_lock; lock(__0); try { poorMansProfiling_threadToSample = thread; poorMansProfiling_stop(); poorMansProfiling_clear(); poorMansProfiling_timer = doEvery_daemon(interval, new Runnable() { public void run() { try { Map map = poorMansProfiling_threadToSample != null ? litmap(poorMansProfiling_threadToSample, poorMansProfiling_threadToSample.getStackTrace()) : runnableThreadsWithStackTraces(); Lock __1 = poorMansProfiling_lock; lock(__1); try { poorMansProfiling_samples++; for (Thread t : keys(map)) { { if (isSystemThread(t)) continue; } StringBuilder buf = new StringBuilder(); for (StackTraceElement e : map.get(t)) buf.append(e).append("\n"); poorMansProfiling_results.add(str(buf)); } } finally { unlock(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Map map =\r\n poorMansProfiling_threadToSampl..."; } }); } finally { unlock(__0); } } static public void poorMansProfiling_stop() { Lock __2 = poorMansProfiling_lock; lock(__2); try { if (poorMansProfiling_timer != null) { stopTimer(poorMansProfiling_timer); poorMansProfiling_timer = null; } } finally { unlock(__2); } } static public void poorMansProfiling_clear() { Lock __3 = poorMansProfiling_lock; lock(__3); try { poorMansProfiling_results.clear(); poorMansProfiling_samples = 0; } finally { unlock(__3); } } static public MultiSet poorMansProfiling_results() { return new MultiSet(poorMansProfiling_results); } static public MultiSet poorMansProfiling_stopAndGetResults() { Lock __4 = poorMansProfiling_lock; lock(__4); try { poorMansProfiling_stop(); return poorMansProfiling_results(); } finally { unlock(__4); } } static public Object getOptMC(String field) { return getOpt(mc(), field); } static public JLabel setImage(final BufferedImage img, final JLabel lbl) { if (lbl != null) { swing(() -> { lbl.setIcon(imageIcon(img)); }); } return lbl; } static public JLabel setImage(JLabel lbl, BufferedImage img) { return setImage(img, lbl); } static public JLabel setImage(final String imageID, final JLabel lbl) { if (lbl != null) { swing(() -> { lbl.setIcon(imageIcon(imageID)); }); } return lbl; } static public JLabel setImage(JLabel lbl, String imageID) { return setImage(imageID, lbl); } static public A setImage(A is, BufferedImage img) { { if (is != null) is.setImage(img); } return is; } static public boolean isJavaIdentifier(String s) { if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0))) return false; for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i))) return false; return true; } static public Matcher regexp(String pat, String s) { return regexp(compileRegexp(pat), unnull(s)); } static public Matcher regexp(java.util.regex.Pattern pat, String s) { return pat.matcher(unnull(s)); } static public java.util.regex.Pattern regexp(String pat) { return compileRegexp(pat); } static public void bindTimerToComponent(final Timer timer, JFrame f) { bindTimerToComponent(timer, f.getRootPane()); } static public void bindTimerToComponent(final Timer timer, JComponent c) { if (c.isShowing()) timer.start(); c.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { timer.start(); } public void ancestorRemoved(AncestorEvent event) { timer.stop(); } public void ancestorMoved(AncestorEvent event) { } }); } static public IntegerIterator integerIterator(int[] l) { return l == null ? null : new IntegerIterator() { public int i = 0; public boolean hasNext() { return i < l.length; } public int next() { return l[i++]; } }; } static public boolean containsRegexp(String s, String pat) { return regexpFinds(pat, s); } static public int numLines(String s) { return countLines(s); } static public String simpleQuote(String s) { return s == null ? "null" : "\"" + s + "\""; } static public int indexOfAny(List l, int i, A... x) { while (i < l(l)) if (eqOneOf(l.get(i), x)) return i; else ++i; return -1; } static public int indexOfAny(List l, Collection x) { return indexOfAny(l, 0, x); } static public int indexOfAny(List l, int i, Collection x) { if (nempty(x)) while (i < l(l)) if (x.contains(l.get(i))) return i; else ++i; return -1; } static public int indexOfAny(String s, int i, String chars) { for (; i < l(s); i++) if (chars.indexOf(s.charAt(i)) >= 0) return i; return -1; } static public int indexOfAny(String s, String chars) { return indexOfAny(s, 0, chars); } static public BufferedImage gridLOLToImage(List cellWidths, List cellHeights, List> lol) { List> lom = mapWithIndex(lol, (i, m) -> listToMatrix(cyclicGet(cellWidths, i), m)); Matrix> mom = listToMatrix_cols(l(cellWidths), lom); List cellX1s = partialSums_firstIs0(cellWidths); List cellY1s = partialSums_firstIs0(cellHeights); int w = last(cellX1s), h = last(cellY1s); BufferedImage restored = newBufferedImage(w, h); forEachWithPosition(mom, (x, y, cell) -> drawIntMatrix(restored, cell, cyclicGet(cellX1s, x), cyclicGet(cellY1s, y))); return restored; } static public Object html_valueLessParam_cache; static public Object html_valueLessParam() { if (html_valueLessParam_cache == null) html_valueLessParam_cache = html_valueLessParam_load(); return html_valueLessParam_cache; } static public Object html_valueLessParam_load() { return new Object(); } static public Producer javaTokC_iterator(String s) { return new Producer() { final public int l = strL(s); public int i = 0; public String next() { if (i >= l) return null; int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } i = j; if (i >= l) return null; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else if (c == '[' && d == '[') { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') { do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]")); j = Math.min(j + 3, l); } else ++j; String t = quickSubstring(s, i, j); i = j; return t; } }; } static public String htmlQuote(String s) { return "\"" + htmlencode_forParams(s) + "\""; } static public A alwaysOnTop(A c) { return alwaysOnTop(c, true); } static public A alwaysOnTop(A c, boolean on) { { swing(() -> { Window w = getWindow(c); if (w != null && w.isAlwaysOnTop() != on) w.setAlwaysOnTop(on); }); } return c; } static public A setFrameTitle(A c, final String title) { final Frame f = getAWTFrame(c); if (f != null) { swing(() -> { f.setTitle(title); }); } return c; } static public A setFrameTitle(String title, A c) { return setFrameTitle(c, title); } static public JFrame setFrameTitle(String title) { Object f = getOpt(mc(), "frame"); if (f instanceof JFrame) return setFrameTitle((JFrame) f, title); return null; } static public boolean _inCore() { return false; } static public int getScreenWidth() { return getScreenSize().width; } static public Set javaxVoidAliases_cache; static public Set javaxVoidAliases() { if (javaxVoidAliases_cache == null) javaxVoidAliases_cache = javaxVoidAliases_load(); return javaxVoidAliases_cache; } static public Set javaxVoidAliases_load() { return litset("void", "svoid"); } static public ClassLoader myClassLoader() { return _getClass(mc()).getClassLoader(); } static public Timestamp tsNow() { return new Timestamp(); } static public Object makeDependent_postProcess; static public void makeDependent(Object c) { if (c == null) return; assertTrue("Not a class", c instanceof Class); dependentClasses(); hotwire_classes.add(new WeakReference(c)); Object local_log = getOpt(mc(), "local_log"); if (local_log != null) setOpt(c, "local_log", local_log); Object print_byThread = getOpt(mc(), "print_byThread"); if (print_byThread != null) setOpt(c, "print_byThread", print_byThread); callF(makeDependent_postProcess, c); } static public Rectangle boundsOnScreen(Component c) { if (c == null) return null; if (c.getParent() instanceof JViewport && c.getParent().getParent() instanceof JScrollPane) c = c.getParent().getParent(); try { return new Rectangle(c.getLocationOnScreen(), c.getSize()); } catch (IllegalComponentStateException e) { return null; } } static public int jfind(String s, String in) { return jfind(javaTok(s), in); } static public int jfind(List tok, String in) { return jfind(tok, 1, in); } static public int jfind(List tok, int startIdx, String in) { return jfind(tok, startIdx, in, (ITokCondition) null); } static public int jfind(List tok, String in, Object condition) { return jfind(tok, 1, in, condition); } static public int jfind(List tok, String in, IIntPred condition) { return jfind(tok, 1, in, condition); } static public int jfind(List tok, int startIndex, String in, IIntPred condition) { return jfind(tok, startIndex, in, tokCondition(condition)); } static public int jfind(List tok, String in, ITokCondition condition) { return jfind(tok, 1, in, condition); } static public int jfind(List tok, int startIndex, String in, ITokCondition condition) { return jfind(tok, startIndex, in, (Object) condition); } static public int jfind(List tok, int startIdx, String in, Object condition) { return jfind(tok, startIdx, javaTokForJFind_array(in), condition); } static public int jfind(List tok, List tokin) { return jfind(tok, 1, tokin); } static public int jfind(List tok, int startIdx, List tokin) { return jfind(tok, startIdx, tokin, null); } static public int jfind(List tok, int startIdx, String[] tokinC, Object condition) { return findCodeTokens(tok, startIdx, false, tokinC, condition); } static public int jfind(List tok, int startIdx, List tokin, Object condition) { return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition); } static public List jfind_preprocess(List tok) { for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">")); replaceSublist(tok, ll("\\", "", "*"), ll("\\*")); return tok; } static public String formatFunctionCall(String fname, Object... args) { return formatFunctionCall((Object) fname, args); } static public String formatFunctionCall(Object fname, Object... args) { return fname + "(" + joinWithComma(allToString(args)) + ")"; } static public String formatFunctionCall(String fname, Iterable args) { return formatFunctionCall((Object) fname, args); } static public String formatFunctionCall(Object fname, Iterable args) { return formatFunctionCall(fname, toObjectArray(args)); } static public void copyBufferedImage(BufferedImage src, int srcx, int srcy, BufferedImage dest, int destx, int desty, int w, int h) { copyImagePart(src, srcx, srcy, dest, destx, desty, w, h); } static public void copyBufferedImage(BufferedImage src, BufferedImage dest, int destx, int desty) { if (src != null) copyBufferedImage(src, 0, 0, dest, destx, desty, src.getWidth(), src.getHeight()); } static public void copyBufferedImage(BufferedImage src, BufferedImage dest, Pt destP) { copyBufferedImage(src, dest, destP.x, destP.y); } static public List dependentClasses() { return cleanUpAndGetWeakReferencesList(hotwire_classes); } static public Object dm_evalJava_veryQuickJava; static public Object dm_evalJava_withModule(String expression, Object... args) { Object m = dm_current_generic(); String code = evalJava_prep(expression) + "\r\n static new InheritableThreadLocal dm_currentModule_value;\r\n \r\n sO dm_current_mandatory_generic_value;\r\n \r\n sO dm_current_mandatory_generic() { ret dm_current_mandatory_generic_value; }\r\n sO dm_current_generic() { ret dm_current_mandatory_generic(); }\r\n "; Object obj; if (dm_evalJava_veryQuickJava != null) obj = callF(dm_evalJava_veryQuickJava, code); else obj = veryQuickJava(code); setOpt(obj, "programID", programID()); makeDependent(obj); setOpt(obj, "creator_class", newWeakReference(dm_os())); dm_pointSubmoduleToMe(obj, m); return evalJava_myProgramID_main_2(obj, args); } static public String localDateWithSeconds(long time) { SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss"); return format.format(time); } static public String localDateWithSeconds() { return localDateWithSeconds(now()); } static public void dm_reload() { dm_reloadMe(); } static public A foldl(F2 f, A seed, Iterable l) { A a = seed; if (l != null) for (B b : l) a = callF(f, a, b); return a; } static public A foldl(F2 f, A seed, B[] l) { A a = seed; if (l != null) for (B b : l) a = callF(f, a, b); return a; } static public A foldl(Object f, A seed, B[] l) { A a = seed; if (l != null) for (B b : l) a = (A) callF(f, a, b); return a; } static public String localSnippetTitle(String snippetID) { if (!isLocalSnippetID(snippetID)) return null; File f = localSnippetFile(snippetID); if (!f.exists()) return null; return or2(getFileInfoField(dropExtension(f), "Title"), "Unnamed"); } static public int localMonth(long time) { return parseInt(simpleDateFormat_local("MM").format(time)); } static public int localMonth() { return localMonth(now()); } static public File fileInSameDir(File f, String newName) { return newFile(parentFile(f), newName); } static public ImageSurface doubleBufferedImageSurface() { ImageSurface is = imageSurface(); setDoubleBuffered(is, true); return is; } static public String getDBProgramID_id; static public String getDBProgramID() { return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase(); } static public String renderFunctionCall(String fname, Object... args) { return formatFunctionCall(fname, args); } static public A addMargin(final int top, final int left, final int bottom, final int right, final A c) { if (c != null) { swing(() -> { Border margin = BorderFactory.createEmptyBorder(top, left, bottom, right); c.setBorder(jCompoundBorder(c.getBorder(), margin)); }); } return c; } static public A addMargin(int w, A c) { return addMargin(w, w, w, w, c); } static public A dm_getOSOpt(String field) { return (A) getOpt(dm_os(), field); } static public double[] subDoubleArray(double[] b, int start) { return subDoubleArray(b, start, l(b)); } static public double[] subDoubleArray(double[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new double[0]; double[] x = new double[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public boolean isJavaxCompilableSnippetTypeExceptInclude(int type) { return isJavaxApplicationSnippetType(type) || isJavaxModuleSnippetType(type) || type == snippetType_dynModule(); } static public A setFrameIcon(A c, String imageID) { setFrameIconLater(c, imageID); return c; } static public A setFrameIcon(String imageID, A c) { return setFrameIcon(c, imageID); } static public JDesktopPane dm_desktopPane() { return dm_getOSOpt("desktop"); } static public boolean isListOfElementType(Object o, Class type) { if (!(o instanceof List)) return false; return allElementsAreOfType((List) o, type); } static public boolean isListOfElementType(Class type, Object o) { return isListOfElementType(o, type); } static public boolean isIdentifier(String s) { return isJavaIdentifier(s); } static public String getSnippetTitle(String id) { if (id == null) return null; if (!isSnippetID(id)) return "?"; IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.getSnippetTitle(id); return getSnippetTitle_noResourceLoader(id); } static public String getSnippetTitle_noResourceLoader(String id) { try { if (isLocalSnippetID(id)) return localSnippetTitle(id); long parsedID = parseSnippetID(id); String url; if (isImageServerSnippet(parsedID)) url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery(); else if (isGeneralFileServerSnippet(parsedID)) url = "http://butter.botcompany.de:8080/files/name/" + parsedID; else url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies(); String title = trim(loadPageSilently(url)); if (title != null) try { saveTextFileIfChanged(snippetTitle_cacheFile(id), title); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } return or(title, "?"); } catch (Exception __e) { throw rethrow(__e); } } static public String getSnippetTitle(long id) { return getSnippetTitle(fsI(id)); } static public TimeZone getTimeZone(String name) { return TimeZone.getTimeZone(name); } static public JPanel jFullCenter(final Component c) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new GridBagLayout()); panel.add(c); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new GridBagLayout);\r\n panel.add(c);\r\n ret panel;"; } }); } static public LiveValue dm_calculatedLiveValue(final DynModule module, final Class type, final F0 calc) { Lock __0 = module.lock; lock(__0); try { final SimpleLiveValue value = new SimpleLiveValue(type, callF(calc)); module.onChange(new Runnable() { public void run() { try { value.set(callF(calc)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "value.set(callF(calc))"; } }); return value; } finally { unlock(__0); } } static public LiveValue dm_calculatedLiveValue(Class type, F0 calc) { return dm_calculatedLiveValue(dm_current_mandatory(), type, calc); } static public LiveValue dm_calculatedLiveValue(Class type, IF0 calc) { return dm_calculatedLiveValue(type, if0ToF0(calc)); } static public LiveValue dm_calculatedLiveValue(IF0 calc) { return dm_calculatedLiveValue(Object.class, (F0) if0ToF0(calc)); } static public MouseAdapter leftClickMouseAdapter_noPt(final Object r) { return new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getButton() == 1) pcallF(r); } }; } static public List getJavaModifiers_list = litlist("static", "abstract", "public", "private", "protected", "final", "native", "volatile", "synchronized", "transient", "default"); static public List getJavaModifiers() { return getJavaModifiers_list; } static public boolean dm_setFlag(String flagName) { return dm_setFlag(flagName, true); } static public boolean dm_setFlag(String flagName, boolean value) { Object mod = dm_current_generic(); Object stem = dm_stem(mod); Integer flagCode = (Integer) (getOpt("flagName", stem)); if (flagCode == null) return false; call(stem, value ? "setFlag" : "clearFlag", flagCode); return true; } static public boolean isEitherB(Either e) { return eitherIsB(e); } static public DynModule dm_currentModuleMandatory() { return dm_current_mandatory(); } static public Object quickEval(String t) { if (isQuoted(t)) return unquote(t); if (isInteger(t)) return parseIntOrLong(t); if (isLongConstant(t)) return parseLong(t); if (eq(t, "null")) return null; if (eq(t, "false")) return false; if (eq(t, "true")) return true; if (isIdentifier(t)) return getMC(t); if (isSnippetID(t)) return t; throw quickFail("Can't quick eval: " + t); } static public IAutoCloseableF0 tempMetaMutex(IMeta o) { return o == null ? null : o._tempMetaMutex(); } static public JCheckBox dm_fieldCheckBox(String field) { return dm_fieldCheckBox(humanizeFormLabel(field), field); } static public JCheckBox dm_fieldCheckBox(String text, String field) { if (isIdentifier(text) && !isIdentifier(field)) { String temp = field; field = text; text = temp; } return jLiveValueCheckBox(text, dm_fieldLiveValue(field)); } static public boolean hasLettersAllUpperCase(String s) { return hasLetters(s) && !containsLowerCase(s); } static public JTextArea jTextArea() { return jTextArea(""); } static public JTextArea jTextArea(final String text) { return jTextAreaWithUndo(text); } static public List classNamesInJarOrDir(File dir) { return classNamesInJarOrDir(dir, ""); } static public List classNamesInJarOrDir(File dir, String prefixInJar) { List classes = new ArrayList(); if (dir == null) { } else if (dir.isDirectory()) { for (File f : listFiles(dir)) { String s = f.getName(); if (s.endsWith(".class")) classes.add(dropSuffix(".class", s)); } } else if (dir.isFile()) { try { JarFile jarFile = new JarFile(dir); try { Enumeration e = jarFile.entries(); while (e.hasMoreElements()) { JarEntry je = e.nextElement(); if (je.isDirectory() || je.getName().startsWith("META-INF/") || !je.getName().endsWith(".class")) continue; String className = dropSuffix(".class", je.getName()); className = dropPrefixOrNull(prefixInJar, className); if (className == null) continue; if (className.contains("-")) continue; className = className.replace('/', '.'); classes.add(className); } } finally { jarFile.close(); } } catch (Throwable __e) { pcallFail(__e); } } return classes; } static public double toMinutes(long ms) { return ms / 60000.0; } static public void printShortenedFunctionCall(Object fname, Object... args) { printShortenedFunctionCall(100, fname, args); } static public void printShortenedFunctionCall(int len, Object fname, Object... args) { print(shorten(len, formatFunctionCall(fname, args))); } static public void dm_reloadMe() { dm_reloadModule(dm_currentModule()); } static public IterableIterator iteratorFromFunction_withEndMarker_f0(final F0 f) { class IFF2 extends IterableIterator { public A a; public boolean have, done; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; have = false; return _a; } public void getNext() { if (done || have) return; Object o = f.get(); if (o == iteratorFromFunction_endMarker) { done = true; return; } a = (A) o; have = true; } } ; return new IFF2(); } static public JLabel dm_calculatedLabel(IF0 calc) { return jLiveValueLabel(dm_calculatedLiveValue(Object.class, calc)); } static public void scanForComponents(final Component c, final Class theClass, final List l) { if (theClass.isInstance(c)) l.add((A) c); if (c instanceof Container) { swing(() -> { for (Component comp : ((Container) c).getComponents()) scanForComponents(comp, theClass, l); }); } } static public boolean scaffoldingEnabled(Object o) { return metaGet(o, "scaffolding") != null; } static public String defaultJavaXTranslatorID_value = "#759"; static public String defaultJavaXTranslatorID() { return defaultJavaXTranslatorID_value; } static public List vmBus_queryAll(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); List out = new ArrayList(); for (Object o : unnullForIteration(vm_busListeners_live())) addIfNotNull(out, pcallF(o, msg, arg)); for (Object o : unnullForIteration(vm_busListenersByMessage_live().get(msg))) addIfNotNull(out, pcallF(o, msg, arg)); return out; } static public List hotwire_libraryIDsFromJar(File jar) { String dehlibs = unnull(loadTextFileFromZip(jar, "libraries")); return regexpExtractAll("\\d+", dehlibs); } static public int indent_default = 2; static public String indent(int indent) { return repeat(' ', indent); } static public String indent(int indent, String s) { return indent(repeat(' ', indent), s); } static public String indent(String indent, String s) { return indent + replace(unnull(s), "\n", "\n" + indent); } static public String indent(String s) { return indent(indent_default, s); } static public List indent(String indent, List lines) { List l = new ArrayList(); if (lines != null) for (String s : lines) l.add(indent + s); return l; } static public boolean isAlwaysOnTop(JFrame f) { return f != null && swing(() -> f.isAlwaysOnTop()); } static public boolean isAlwaysOnTop(Window w) { return w != null && swing(() -> w.isAlwaysOnTop()); } static public F0 f0_const(final A a) { return new F0() { public A get() { try { return a; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return a;"; } }; } static public JWindow infoBox(Object text) { return infoMessage(strOrNull(text)); } static public JWindow infoBox(String text) { return infoMessage(text); } static public JWindow infoBox(String text, double seconds) { return infoMessage(text, seconds); } static public JWindow infoBox(Throwable e) { return infoMessage(e); } static public double toSeconds(long ms) { return ms / 1000.0; } static public String toSeconds(long ms, int digits) { return formatDouble(toSeconds(ms), digits); } static public double toSeconds(double ms) { return ms / 1000.0; } static public String toSeconds(double ms, int digits) { return formatDouble(toSeconds(ms), digits); } static public Rect rect(int x, int y, int w, int h) { return new Rect(x, y, w, h); } static public Rect rect(Pt p, int w, int h) { return new Rect(p.x, p.y, w, h); } static public Rect rect(int w, int h) { return new Rect(0, 0, w, h); } static public A navigableSet_find(NavigableSet set, A a) { if (set == null || a == null) return null; A b = set.floor(a); return b != null && sortedSet_compare(set, a, b) == 0 ? b : null; } static public AutoCloseable tempCleaningUp() { AutoCloseable result = null; return result; } static public boolean cleanUp_interruptThreads = false; static public void cleanUp(Object c) { if (c == null) return; if (c instanceof AutoCloseable) { close_pcall((AutoCloseable) c); return; } if (c instanceof java.util.Timer) { ((java.util.Timer) c).cancel(); return; } if (c instanceof Collection) { cleanUp((Collection) c); return; } if (c instanceof Map) { for (Object o : keysList((Map) c)) cleanUp(o); for (Object o : valuesList((Map) c)) cleanUp(o); syncClear((Map) c); return; } try { preCleanUp(c); setOpt_raw(c, "ping_pauseAll", false); innerCleanUp(c); List androids = (List) getOpt(c, "record_list"); for (Object android : unnull(androids)) pcallOpt(android, "dispose"); List classes = (List) (getOpt(c, "hotwire_classes")); if (classes != null) for (WeakReference cc : classes) { try { cleanUp(cc.get()); } catch (Throwable __e) { pcallFail(__e); } } if (cleanUp_interruptThreads) { List threads = registeredThreads(c); if (nempty(threads)) { print("cleanUp: Interrupting " + n2(threads, "thread") + ": " + joinWithComma(allToString(threads))); interruptThreads(threads); } } } catch (Throwable __e) { pcallFail(__e); } setOpt_raw(c, "cleaningUp_flag", false); if (c instanceof Class && ((Class) c).getName().equals("main")) retireClassLoader(((Class) c).getClassLoader()); } static public void cleanUp(Collection l) { if (l == null) return; for (Object c : l) cleanUp(c); l.clear(); } static public Object dm_stem() { return dm_stem(dm_current_generic()); } static public Object dm_stem(Object moduleOrID) { return dm_getStem(moduleOrID); } static public Object defaultDefaultClassFinder() { return new F1() { public Class get(String name) { name = replacePrefix("main$main$", "main$", name); Class c = get2(name); printVars_str("ddcf", "name", name, "c", c); return c; } public Class get2(String name) { if (eq(name, "
")) return mc(); { Class c = findClass_fullName(name); if (c != null) return c; } if (startsWithAny(name, "loadableUtils.utils$", "main$", mcDollar())) for (String pkg : ll("loadableUtils.utils$", mcDollar())) { String newName = pkg + afterDollar(name); print("ddcf looking for ", newName); { Class c = findClass_fullName(newName); if (c != null) return c; } } return null; } }; } static public IterableIterator countIterator_exclusive_step(final int a, final int b, final int step) { assertTrue("step > 0", step > 0); return new IterableIterator() { public int i = a; public boolean hasNext() { return i < b; } public Integer next() { var j = i; i += step; return j; } }; } static public IterableIterator countIterator_exclusive_step(double a, double b, double step) { assertTrue("step > 0", step > 0); return new IterableIterator() { public double i = a; public boolean hasNext() { return i < b; } public Double next() { var j = i; i += step; return j; } }; } static public IterableIterator countIterator_exclusive_step(double a, double b, double step, IF1 f) { return mapI_if1(f, countIterator_exclusive_step(a, b, step)); } static public List cleanUpAndGetWeakReferencesList(List> l) { if (l == null) return null; synchronized (l) { List out = new ArrayList(); for (int i = 0; i < l(l); i++) { A a = l.get(i).get(); if (a == null) l.remove(i--); else out.add(a); } return out; } } static public void forEach(Iterable l, IVF1 f) { if (f != null && l != null) for (A a : l) callF(f, a); } static public void forEach(IVF1 f, Iterable l) { forEach(l, f); } static public void forEach(A[] l, IVF1 f) { if (f != null && l != null) for (A a : l) callF(f, a); } static public void forEach(IVF1 f, A[] l) { forEach(l, f); } static public void forEach(Map map, IVF2 f) { for (Map.Entry __0 : _entrySet(map)) { A a = __0.getKey(); B b = __0.getValue(); f.get(a, b); } } static public boolean standardFunctionAlwaysReturnsVoid_uncached(String name) { return tok_staticFunctionAlwaysReturnsVoid(javaTok(textOfStandardFunction_uncached(name)), name); } static public int findEndOfBlock(List tok, int i) { return tok_findEndOfBlock(tok, i); } static public void disposeWindow(final Window window) { if (window != null) { swing(() -> { window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); myFrames_list.remove(window); window.dispose(); }); } } static public void disposeWindow(final Component c) { disposeWindow(getWindow(c)); } static public void disposeWindow(Object o) { if (o != null) disposeWindow(((Component) o)); } static public void disposeWindow() { disposeWindow(heldInstance(Component.class)); } static public JTextField textFieldFromComboBox(JComboBox cb) { return (JTextField) cb.getEditor().getEditorComponent(); } static public void logQuotedWithTime(String s) { logQuotedWithTime(standardLogFile(), s); } static public void logQuotedWithTime(File logFile, String s) { logQuoted(logFile, logQuotedWithTime_format(s)); } static public void logQuotedWithTime(String logFile, String s) { logQuoted(logFile, logQuotedWithTime_format(s)); } static public String logQuotedWithTime_format(String s) { return (now()) + " " + s; } static public boolean isInRAMDisk(File f) { return startsWithOneOf(f2s(f), "/dev/shm/", "/run/shm/"); } static public String muricaCredentialsQuery() { return htmlQuery(muricaCredentials()); } static public float getScore(Scored s) { return s == null ? 0 : s.score; } static public String formatColonProperties_noNulls(Object... params) { return formatColonProperties(nonNullPairs(paramsToPairs(params))); } static public boolean containsNewLines(String s) { return containsNewLine(s); } static public int moveToTopRightCorner_inset = 20; static public A moveToTopRightCorner(A a) { return moveToTopRightCorner(moveToTopRightCorner_inset, moveToTopRightCorner_inset, a); } static public A moveToTopRightCorner(int insetX, int insetY, A a) { { swing(() -> { Window w = getWindow(a); if (w != null) { var bounds = preferredScreenBounds(); w.setLocation(bounds.x2() - w.getWidth() - insetX, bounds.y1() + insetY); } }); } return a; } static public boolean objectArraysEqual(Object[] a, Object[] b) { return arraysEqual(a, b); } static public int stdcompare(Number a, Number b) { return cmp(a, b); } static public int stdcompare(String a, String b) { return cmp(a, b); } static public int stdcompare(long a, long b) { return a < b ? -1 : a > b ? 1 : 0; } static public int stdcompare(Object a, Object b) { return cmp(a, b); } static public JPanel centerAndEast(final Component c, final Component e) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.CENTER, wrap(c)); panel.add(BorderLayout.EAST, wrap(e)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT..."; } }); } static public String aGlobalID() { return randomID(globalIDLength()); } static public String aGlobalID(Random random) { return randomID(random, globalIDLength()); } static public int preferredWidth(Component c) { return c == null ? 0 : getPreferredSize(c).width; } static public void metaMapPut(IMeta o, Object key, Object value) { { if (o != null) o.metaPut(key, value); } } static public void metaMapPut(Object o, Object key, Object value) { var meta = initIMeta(o); { if (meta != null) meta.metaPut(key, value); } } static public String quoteBorderless(Object o) { if (o == null) return "null"; return quoteBorderless(str(o)); } static public String quoteBorderless(String s) { if (s == null) return "null"; StringBuilder out = new StringBuilder((int) (l(s) * 1.5)); quoteBorderless_impl(s, out); return out.toString(); } static public void quoteBorderless_impl(String s, StringBuilder out) { int l = s.length(); for (int i = 0; i < l; i++) { char c = s.charAt(i); if (c == '\\' || c == '"') out.append('\\').append(c); else if (c == '\r') out.append("\\r"); else if (c == '\n') out.append("\\n"); else out.append(c); } } static public boolean eqGetOneOf(List l, int i, A... options) { return eqOneOf(get(l, i), options); } static public String makeFrame_defaultIcon; static public boolean makeFrame_hideConsole = false; static public ThreadLocal> makeFrame_post = new ThreadLocal(); static public JFrame makeFrame() { return makeFrame((Component) null); } static public JFrame makeFrame(Object content) { return makeFrame(programTitle(), content); } static public JFrame makeFrame(String title) { return makeFrame(title, null); } static public JFrame makeFrame(String title, Object content) { return makeFrame(title, content, true); } static public JFrame makeFrame(final String title, final Object content, final boolean showIt) { final VF1 post = optParam(makeFrame_post); return swing(new F0() { public JFrame get() { try { if (getFrame(content) != null) return getFrame(setFrameTitle((Component) content, title)); final JFrame frame = new JFrame(title); if (makeFrame_defaultIcon != null) setFrameIconLater(frame, makeFrame_defaultIcon); _initFrame(frame); Component wrapped = wrap(content); if (wrapped != null) frame.getContentPane().add(wrapped); restrictWindowToScreenSize(frame); frame.setBounds(defaultNewFrameBounds()); callF(post, frame); if (showIt) frame.setVisible(true); if (showIt && makeFrame_hideConsole) { hideConsole(); makeFrame_hideConsole = false; } return frame; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (getFrame(content) != null)\r\n ret getFrame(setFrameTitle((Component) ..."; } }); } static public OKOrError okOrError(IF0 f) { return okOrError(f, true); } static public OKOrError okOrError(IF0 f, boolean printStackTrace) { try { return OKOrError_ok(f.get()); } catch (Throwable e) { if (printStackTrace) printStackTrace(e); return OKOrError_error(e); } } static public OKOrError okOrError(Runnable r) { return okOrError(runnableToIF0(r)); } static public A setDoubleBuffered(A c) { return setDoubleBuffered(c, true); } static public A setDoubleBuffered(A c, boolean b) { { swing(() -> { { if (c != null) c.setDoubleBuffered(b); } }); } return c; } static public List asVirtualList(A[] a) { return wrapArrayAsList(a); } static public BufferedImage bufferedImage(int[] pixels, int w, int h) { return intArrayToBufferedImage(pixels, w, h); } static public BufferedImage bufferedImage(int[] pixels, WidthAndHeight size) { return bufferedImage(pixels, size.getWidth(), size.getHeight()); } static public BufferedImage bufferedImage(int w, int h, int[] pixels) { return intArrayToBufferedImage(pixels, w, h); } static public BufferedImage bufferedImage(int w, int h) { return newBufferedImage(w, h); } static public BufferedImage bufferedImage(int w, int h, RGB rgb) { return newBufferedImage(w, h, rgb); } static public BufferedImage bufferedImage(int w, Color color) { return bufferedImage(w, w, color); } static public BufferedImage bufferedImage(int w, int h, Color color) { return newBufferedImage(w, h, color); } static public BufferedImage bufferedImage(Pt p, Color color) { return newBufferedImage(p, color); } static public BufferedImage bufferedImage(WidthAndHeight size, Color color) { return newBufferedImage(size.w(), size.h(), color); } static public BufferedImage bufferedImage(Color color, WidthAndHeight size) { return bufferedImage(size, color); } static public String asciiHeading(String title) { return "\n" + title + "\n" + rep(l(title), '-'); } static public Object[] mapToObjectArray(Map map) { List l = new ArrayList(); for (Object o : keys(map)) { l.add(o); l.add(map.get(o)); } return toObjectArray(l); } static public Object[] mapToObjectArray(Object f, Collection l) { int n = l(l); Object[] array = new Object[n]; if (n != 0) { Iterator it = iterator(l); for (int i = 0; i < n; i++) array[i] = callF(f, it.next()); } return array; } static public Object[] mapToObjectArray(Object f, Object[] l) { int n = l(l); Object[] array = new Object[n]; for (int i = 0; i < n; i++) array[i] = callF(f, l[i]); return array; } static public Object[] mapToObjectArray(Collection l, IF1 f) { return mapToObjectArray(f, l); } static public Object[] mapToObjectArray(A[] l, IF1 f) { return mapToObjectArray(f, l); } static public Object[] mapToObjectArray(IF1 f, A[] l) { int n = l(l); Object[] array = new Object[n]; for (int i = 0; i < n; i++) array[i] = f.get(l[i]); return array; } static public Object[] mapToObjectArray(IF1 f, Collection l) { int n = l(l); Object[] array = new Object[n]; if (n != 0) { Iterator it = iterator(l); for (int i = 0; i < n; i++) array[i] = callF(f, it.next()); } return array; } static public Set synchroWeakHashSet() { return Collections.newSetFromMap((Map) newWeakHashMap()); } static public int maximumSafeArraySize() { return Integer.MAX_VALUE - 8; } static public void replaceListPart(List l, int i, int j, List l2) { replaceSublist(l, i, j, l2); } static public Q dm_q() { return dm_current_mandatory().q(); } static public void dm_q(Runnable r) { dm_inQ(r); } static public void dm_q(DynModule module, Runnable r) { module.q().add(r); } static public A dm_q(IF0 f) { return dm_evalInQ(if0ToF0(f)); } static public AutoCloseable tempActivity(Object r) { return null; } static public Map javaTokForJFind_array_cache = synchronizedMRUCache(1000); static public String[] javaTokForJFind_array(String s) { String[] tok = javaTokForJFind_array_cache.get(s); if (tok == null) javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s)))); return tok; } static public int withLeftAndRightMargin_defaultWidth = 6; static public JPanel withLeftAndRightMargin(Component c) { return withLeftAndRightMargin(withLeftAndRightMargin_defaultWidth, c); } static public JPanel withLeftAndRightMargin(int w, Component c) { return withLeftAndRightMargin(w, w, c); } static public JPanel withLeftAndRightMargin(final int w1, final int w2, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = marginPanel(); p.setBorder(BorderFactory.createEmptyBorder(0, w1, 0, w2)); p.add(c); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = marginPanel();\r\n p.setBorder(BorderFactory.createEmptyBorder(0,..."; } }); } static public void preCleanUp(Object c) { if (c instanceof Collection) { for (Object o : ((Collection) c)) preCleanUp(o); return; } callOpt(c, "licensed_off"); setOpt_raw(c, "ping_anyActions", true); setOpt_raw(c, "cleaningUp_flag", true); } static public List dropFirstAndLast(int n, List l) { return cloneSubList(l, n, l(l) - n); } static public List dropFirstAndLast(int m, int n, List l) { return cloneSubList(l, m, l(l) - n); } static public List dropFirstAndLast(List l) { return dropFirstAndLast(1, l); } static public String dropFirstAndLast(String s) { return substring(s, 1, l(s) - 1); } static public A getAndClearTL(ThreadLocal tl) { return getAndClearThreadLocal(tl); } static public String getClassDeclarationName(List tok) { if (tok != null) for (int i = 1; i + 2 < tok.size(); i += 2) if (allClasses_keywords.contains(tok.get(i)) && isIdentifier(tok.get(i + 2))) { while (contains(getClassDeclarationName_skippables(), get(tok, i + 2))) i += 2; return tok.get(i + 2); } return null; } static public AutoCloseable dm_registerAs_directLink(String... msgs) { Object mod = dm_current_mandatory_generic(); return combineAutoCloseables(map(msgs, msg -> dm_vmBus_answerToMessage(msg, fConst(mod)))); } static public String addPrefixIfNempty(String prefix, String s) { return addPrefixIfNotEmpty(prefix, s); } static public FixedRateTimer dm_doEvery(long delay, Runnable r) { return dm_ownTimer(doEvery(delay, delay, dm_rEnter(r))); } static public FixedRateTimer dm_doEvery(long delay, long firstDelay, Runnable r) { return dm_ownTimer(doEvery(delay, firstDelay, dm_rEnter(r))); } static public FixedRateTimer dm_doEvery(double initialSeconds, double delaySeconds, Runnable r) { return dm_ownTimer(doEvery(initialSeconds, delaySeconds, dm_rEnter(r))); } static public FixedRateTimer dm_doEvery(double delaySeconds, Runnable r) { return dm_ownTimer(doEvery(delaySeconds, dm_rEnter(r))); } static public String platformQuoteOpt(String s) { return empty(s) || containsUnsafePlatformCmdLineChar(s) ? platformQuote(s) : s; } static public String platformQuoteOpt(File f) { return platformQuoteOpt(f2s(f)); } static public String platformQuoteOpt(Object o) { if (o instanceof File) return platformQuoteOpt((File) o); return platformQuoteOpt(strOrEmpty(o)); } static public List> gridOfRects3(int w, int h, int cols, int rows) { return gridOfRects3(new Rect(0, 0, w, h), cols, rows); } static public List> gridOfRects3(Rect r, int cols, int rows) { List> l = new ArrayList(); for (int row = 0; row < rows; row++) { List line = new ArrayList(); int y1 = r.y + iround(r.h * (double) row / rows); int y2 = r.y + iround(r.h * (double) (row + 1) / rows); for (int col = 0; col < cols; col++) { int x1 = r.x + iround(r.w * (double) col / cols); int x2 = r.x + iround(r.w * (double) (col + 1) / cols); line.add(new Rect(x1, y1, x2 - x1, y2 - y1)); } l.add(line); } return l; } static public BufferedImage mergeBufferedImagesHorizontally(BufferedImage... images) { return mergeBufferedImagesHorizontally(toList(images)); } static public BufferedImage mergeBufferedImagesHorizontally(List images, Object... __) { if (empty(images)) return null; int spacing = optPar("spacing", __, imageMergeSpacing()); RGB spaceColor = new RGB(0.9f); int w = intSum(mapMethod("getWidth", images)) + (l(images) - 1) * spacing, h = intMax(mapMethod("getHeight", images)); BufferedImage out = newBufferedImage(w, h, spaceColor); int x = 0; for (int i = 0; i < l(images); i++) { BufferedImage img = images.get(i); int y = (h - img.getHeight()) / 2; copyBufferedImage(img, out, x, y); x += img.getWidth() + spacing; } return out; } static public IterableIterator enumerationToIterator(final Enumeration e) { return e == null ? null : new IterableIterator() { public boolean hasNext() { return e.hasMoreElements(); } public A next() { return e.nextElement(); } }; } static public boolean allPaused() { return ping_pauseAll; } static public List partialSums_firstIs0(List l) { int n = l(l); IntBuffer out = new IntBuffer(n); int sum = 0; for (int i = 0; i < n; i++) { out.add(sum); sum += l.get(i); } out.add(sum); return out.asVirtualList(); } static public Object[] params_unpackList(Object[] params) { if (l(params) == 1 && params[0] instanceof List) return toObjectArray((List) params[0]); return params; } static public Object pcallOpt(Object o, String method, Object... args) { try { return callOpt(o, method, args); } catch (Throwable __e) { pcallFail(__e); } return null; } static public A childOfType(Component c, Class theClass) { return first(childrenOfType(c, theClass)); } static public A childOfType(Class theClass, Component c) { return childOfType(c, theClass); } static public boolean isMac() { return System.getProperty("os.name").toLowerCase().contains("mac"); } static public JLabel dm_centeredCalculatedLabel(IF0 calc) { return centerLabel(dm_calculatedLabel(calc)); } static public String shortName(Object o) { return shortClassName(o); } static public void copyStreamAndCloseAll(InputStream in, OutputStream out) { try { try { copyStreamAndCloseInput(in, out); } finally { out.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public boolean md5OfFile_verbose = false; static public String md5OfFile(String path) { return md5OfFile(newFile(path)); } static public String md5OfFile(File f) { try { if (!f.exists()) return "-"; if (md5OfFile_verbose) print("Getting MD5 of " + f); MessageDigest md5 = MessageDigest.getInstance("MD5"); FileInputStream in = new FileInputStream(f); try { byte[] buf = new byte[65536]; int l; while (true) { l = in.read(buf); if (l <= 0) break; md5.update(buf, 0, l); } return bytesToHex(md5.digest()); } finally { _close(in); } } catch (Exception __e) { throw rethrow(__e); } } static public JPanel hgrid(final Object... parts) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(); Object[] _parts = flattenArray2(parts); panel.setLayout(new GridLayout(1, _parts.length)); smartAdd(panel, _parts); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new JPanel panel;\r\n O[] _parts = flattenArray2(parts);\r\n panel.setLayou..."; } }); } static public List ai_splitCamelCase(String s) { int j = 0; List l = new ArrayList(); if (isAllUpperCase(s)) { l.add(s); return l; } for (int i = 0; i < l(s); i++) if (i > j && isUpperCaseLetter(s.charAt(i))) { l.add(substring(s, j, i)); j = i; } if (j < l(s)) l.add(substring(s, j)); return l; } static public boolean containsLowerCase(String s) { for (int i = 0; i < l(s); i++) if (isLowerCase(s.charAt(i))) return true; return false; } static public String findTranslators2(String src, List libsOut) { return join(findTranslators2(javaTok(src), libsOut)); } static public List findTranslators2(List tok, List libsOut) { int i; while ((i = jfind(tok, "!")) >= 0) { setAdd(libsOut, tok.get(i + 2)); clearTokens(tok, i, i + 3); } return tok; } static public Class getFieldType(Object o, String field) { return fieldType(o, field); } static public BufferedImage screenshot() { return shootScreen2(); } static public BufferedImage screenshot(Rectangle area) { try { return shootScreen2(area); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedImage screenshot(Rect area) { return shootScreen2(area); } static public BufferedImage screenshot(int x, int y, int w, int h) { return shootScreen2(x, y, w, h); } static public String decimalFormatEnglish(String format, double d) { return decimalFormatEnglish(format).format(d); } static public java.text.DecimalFormat decimalFormatEnglish(String format) { return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)); } static public DynModule dm_current() { return dm_currentModule(); } static public Object mainBot; static public Object getMainBot() { return mainBot; } static public boolean ping_v3() { return ping_v3(pingSource()); } static public boolean ping_v3(PingSource source) { { if (source != null) source.get(); } return true; } static public File standardLogFile() { return getProgramFile("log"); } static public IterableIterator emptyIterableIterator_instance = new IterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; static public IterableIterator emptyIterableIterator() { return emptyIterableIterator_instance; } static public Object toJavaOpt(Object o) { return new ToJava().getOpt(o); } static public List findBlock(String pat, List tok) { List tokpat = javaTok(pat); int i = findCodeTokens(tok, toStringArray(codeTokensOnly(tokpat))); if (i < 0) return null; int bracketIdx = i + tokpat.size() - 3; assertEquals("{", tok.get(bracketIdx)); int endIdx = findEndOfBlock(tok, bracketIdx); return subList(tok, i - 1, endIdx + 1); } static public JWindow showLoadingAnimation() { return showLoadingAnimation("Hold on user..."); } static public JWindow showLoadingAnimation(String text) { try { return showAnimationInTopRightCorner("#1003543", text); } catch (Throwable __e) { return null; } } static public List> mapLevelTwo(IF1 f, Iterable> l) { return mapTwoLevelsDown(f, l); } static public int[] hexToInts_dropSpaces(String s) { return hexToInts(dropSpaceEtc(s)); } static public Object[] flattenArray2(Object... a) { List l = new ArrayList(); if (a != null) for (Object x : a) if (x instanceof Object[]) l.addAll(asList((Object[]) x)); else if (x instanceof Collection) l.addAll((Collection) x); else l.add(x); return asObjectArray(l); } static public ThreadLocal evalJava_prep_voidMagic = new ThreadLocal(); static public List evalJava_prePrep(String code) { return evalJava_prePrep(code, new EvalJavaPrep()); } static public List evalJava_prePrep(String code, EvalJavaPrep prep) { List tok = javaTok(trim(code)); int idx; while ((idx = jfind(tok, "global {")) >= 0) { int j = findEndOfBracketPart(tok, idx + 2); prep.global.add(joinSubList(tok, idx + 3, j - 1)); clearTokens_reTok(tok, idx, j + 1); } if (eqGet(tok, 1, "=")) tok = subList(tok, 2); if (tok_isStaticLevelCode(tok)) return tok; if (!isFalse(evalJava_prep_voidMagic.get()) && tok_shouldAddReturn(tok) && eqGet(tok, 3, "(") && isIdentifier(get(tok, 1)) && isKnownVoidFunction_uncached(get(tok, 1))) tokAppend_reTok(tok, l(tok) - 2, ";"); String name = null; if (l(tok) == 3 && isIdentifier(name = firstToken(tok))) tokAppend_reTok(tok, 1, "()" + (isKnownVoidFunction_uncached(name) ? ";" : "")); return tok; } static public String formatDouble(double d, int digits) { String format = digits <= 0 ? "0" : "0." + rep(digits, '#'); return decimalFormatEnglish(format, d); } static public String formatDouble(double d) { return str(d); } static public String formatDouble(DoubleRange r, int digits) { return r == null ? "null" : "[" + formatDouble(r.start, digits) + ";" + formatDouble(r.end, digits) + "]"; } static public Container getParent(final Component c) { return c == null ? null : swing(new F0() { public Container get() { try { return c.getParent(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getParent();"; } }); } static public String strOrEmpty(Object o) { return o == null ? "" : str(o); } static public boolean dir2zip_recurse_verbose = false; static public int dir2zip_recurse(File inDir, File zip) { return dir2zip_recurse(inDir, zip, ""); } static public int dir2zip_recurse(File inDir, File zip, String outPrefix) { try { mkdirsForFile(zip); FileOutputStream fout = newFileOutputStream(zip); ZipOutputStream outZip = new ZipOutputStream(fout); try { return dir2zip_recurse(inDir, outZip, outPrefix, 0); } finally { outZip.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public int dir2zip_recurse(File inDir, ZipOutputStream outZip) { return dir2zip_recurse(inDir, outZip, "", 0); } static public int dir2zip_recurse(File inDir, ZipOutputStream outZip, String outPrefix, int level) { try { if (++level >= 20) throw fail("woot? 20 levels in zip?"); List files = new ArrayList(); for (File f : listFiles(inDir)) files.add(f); int n = 0; sortFilesByName(files); for (File f : files) { if (f.isDirectory()) { if (dir2zip_recurse_verbose) print("dir2zip_recurse: Scanning " + f.getAbsolutePath()); n += dir2zip_recurse(f, outZip, outPrefix + f.getName() + "/", level); } else { if (dir2zip_recurse_verbose) print("Copying " + f.getName()); outZip.putNextEntry(new ZipEntry(outPrefix + f.getName())); InputStream fin; try { fin = new FileInputStream(f); } catch (Throwable e) { print(e); continue; } AutoCloseable __1 = fin; try { copyStream(fin, outZip); ++n; } finally { _close(__1); } } } return n; } catch (Exception __e) { throw rethrow(__e); } } static public Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400); static public Rectangle defaultNewFrameBounds() { return swing(new F0() { public Rectangle get() { try { defaultNewFrameBounds_r.translate(60, 20); var bounds = preferredScreenBounds(); if (!bounds.contains(defaultNewFrameBounds_r)) defaultNewFrameBounds_r.setLocation(centerX(bounds) + random_incl(-30, 30), centerY(bounds) + random_incl(-20, 20)); return new Rectangle(defaultNewFrameBounds_r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "defaultNewFrameBounds_r.translate(60, 20);\r\n var bounds = preferredScreenB..."; } }); } static public byte[] hexToBytes_dropSpaces(String s) { return hexToBytes(dropSpaceEtc(s)); } static public String pqO(String s) { return platformQuoteOpt(s); } static public String pqO(File f) { return platformQuoteOpt(f); } static public class jLiveValueSection_class extends SingleComponentPanel { public LiveValue liveValue; public String getTitle() { return strOrEmpty(liveValue.get()); } public jLiveValueSection_class(LiveValue lv, Component c) { super(c); bindLiveValueListenerToComponent(this, liveValue = lv, new Runnable() { public void run() { try { swingLater(new Runnable() { public void run() { try { setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED), getTitle())); revalidate(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setBorder(BorderFactory.createTitledBorder(\r\n BorderFactory.createBeve..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "swingLater(r {\r\n setBorder(BorderFactory.createTitledBorder(\r\n Bo..."; } }); } } static public JPanel jLiveValueSection(LiveValue lv, Component c) { return swingNu(jLiveValueSection_class.class, lv, c); } static public Producer javaTokC_producer(String s) { return javaTokC_iterator(s); } static public OKOrError OKOrError_ok(A a) { return new OKOrError(a); } static public TreeSet toCaseInsensitiveSet_treeSet(Iterable c) { if (isCISet(c)) return (TreeSet) c; TreeSet set = caseInsensitiveSet_treeSet(); addAll(set, c); return set; } static public TreeSet toCaseInsensitiveSet_treeSet(String... x) { TreeSet set = caseInsensitiveSet_treeSet(); addAll(set, x); return set; } static public String toStringWithClassName(Object o) { return toStringWithClass(o); } static public File linux_fileInRamDisk(String name) { if (!isLinux()) return null; File dir = newFile("/dev/shm"); if (dir.isDirectory()) return newFile(dir, name); return null; } static public ICachedJavaXExpr javaExpr(Object expr) { if (expr instanceof ICachedJavaXExpr) return ((ICachedJavaXExpr) expr); return new LiteralJavaXExpr(expr); } static public ICachedJavaXExpr javaExpr(Object expr, IF0 quickEval) { LiteralJavaXExpr e = new LiteralJavaXExpr<>(expr); e.quickEval = quickEval; return e; } static public String shorten_str(Object o) { return shorten(str(o)); } static public String shorten_str(Object o, int max) { return shorten(str(o), max); } static public String shorten_str(int max, Object o) { return shorten_str(o, max); } static public Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource) { return hotwire_finish(classLoader, progID, javaSource, "main"); } static public Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource, String mainClass) { try { Class theClass = classLoader.loadClass(mainClass); Class j = getJavaX(); setOpt(theClass, "myJavaSource_code", javaSource); synchronized (j) { call(j, "setVars", theClass, progID); callOpt(j, "addInstance", progID, theClass); } hotwire_copyOver(theClass); vmBus_send("hotwireFinished", theClass, mc()); return theClass; } catch (Exception __e) { throw rethrow(__e); } } static public Pt topLeftCorner(Rect r) { return rectTopLeftCorner(r); } static public String platformQuote(String s) { return isWindows() ? winQuote(s) : bashQuote(s); } static public String platformQuote(File f) { return platformQuote(f2s(f)); } static public int indexOfSubList(List x, List y) { return indexOfSubList(x, y, 0); } static public int indexOfSubList(List x, List y, int i) { outer: for (; i + l(y) <= l(x); i++) { for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y.get(j))) continue outer; return i; } return -1; } static public int indexOfSubList(List x, A[] y, int i) { outer: for (; i + l(y) <= l(x); i++) { for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y[j])) continue outer; return i; } return -1; } static public Class run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } static public HashSet allClasses_keywords = lithashset("class", "interface", "enum", "sclass", "sinterface", "record", "srecord", "strecord", "asclass", "concept"); static public List> allClasses(List tok) { List> l = new ArrayList(); int n = tok.size(); HashSet _allClasses_keywords = allClasses_keywords; for (int i = 1; i < n; i += 2) { String t = tok.get(i); if ("{".equals(t)) i = findEndOfBlock(tok, i) - 1; else if (_allClasses_keywords.contains(t) && (tok_isJavaxMetaCommandLeftOf(tok, i) || !(eqGetOneOf(tok, i - 2, ".", "include") && !containsNewLine(tok.get(i - 1))))) { int j = i; while (j < n && !tok.get(j).equals("{")) j += 2; j = findEndOfBlock(tok, j) + 1; i = leftScanModifiers(tok, i); l.add(subList(tok, i - 1, Math.min(n, j))); i = j - 2; } } return l; } static public List> allClasses(String text) { return allClasses(javaTok(text)); } static public String getServerTranspiled(String snippetID) { return getServerTranspiled(snippetID, null); } static public boolean getServerTranspiled_printStackTrace = false; static public String getServerTranspiled(String snippetID, String expectedMD5) { try { if (getServerTranspiled_printStackTrace) printStackTrace(); long id = parseSnippetID(snippetID); String text = loadPage_utf8(tb_mainServer() + "/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id + "&utf8=1" + (l(expectedMD5) > 1 ? "&md5=" + urlencode(expectedMD5) : "") + standardCredentials()); if (nempty(text) && neq(text, "SAME")) saveTranspiledCode(snippetID, text); return text; } catch (Exception __e) { throw rethrow(__e); } } static public List> nonNullPairs(Iterable> l) { return filter(l, p -> p != null && p.a != null && p.b != null); } static public Boolean grabbableGrayPixels_succeeded; static public Throwable grabbableGrayPixels_error; static public boolean grabbableGrayPixels_enable = true; static public GrabbableGrayPixels grabbableGrayPixels(BufferedImage img) { if (img == null || !grabbableGrayPixels_enable) return null; try { var result = grabbableGrayPixels_impl(img); grabbableGrayPixels_succeeded = result != null; return result; } catch (Throwable e) { grabbableGrayPixels_error = e; grabbableGrayPixels_succeeded = false; throw rethrow(e); } } static public GrabbableGrayPixels grabbableGrayPixels_impl(BufferedImage img) { Raster raster = img.getRaster(); SampleModel sampleModel = raster.getSampleModel(); if (!(sampleModel instanceof PixelInterleavedSampleModel)) return null; DataBufferByte dataBuffer = (DataBufferByte) (raster.getDataBuffer()); assertEquals(1, dataBuffer.getNumBanks()); assertEquals(DataBuffer.TYPE_BYTE, dataBuffer.getDataType()); int w = img.getWidth(), h = img.getHeight(); int scanlineStride = ((PixelInterleavedSampleModel) sampleModel).getScanlineStride(); byte[] pixels = dataBuffer.getData(); int offset = dataBuffer.getOffset(); int translateX = raster.getSampleModelTranslateX(); int translateY = raster.getSampleModelTranslateY(); offset += -translateX - translateY * scanlineStride; return new GrabbableGrayPixels(pixels, w, h, offset, scanlineStride); } static public List> indexAsSideValue(List l) { List> out = emptyList(l); int n = l(l); for (int i = 0; i < n; i++) out.add(withSideValue(i, l.get(i))); return out; } static public File replaceExtension(File f, String extOld, String extNew) { return newFile(replaceExtension(f2s(f), extOld, extNew)); } static public File replaceExtension(File f, String extNew) { return replaceExtension(f, fileExtension(f), extNew); } static public String replaceExtension(String s, String extOld, String extNew) { s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s); return s + addPrefixOptIfNempty(".", extNew); } static public String replaceExtension(String name, String extNew) { return replaceExtension(name, fileExtension(name), extNew); } static public String structure_addTokenMarkers(String s) { return join(structure_addTokenMarkers(javaTokForStructure(s))); } static public List structure_addTokenMarkers(List tok) { TreeSet refs = new TreeSet(); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (t.startsWith("t") && isInteger(t.substring(1))) refs.add(parseInt(t.substring(1))); } if (empty(refs)) return tok; for (int i : refs) { int idx = i * 2 + 1; if (idx >= l(tok)) continue; String t = ""; if (endsWithLetterOrDigit(tok.get(idx - 1))) t = " "; tok.set(idx, t + "m" + i + " " + tok.get(idx)); } return tok; } static public Set findFullFunctionDefs_keywords = new HashSet(splitAtSpace("static svoid ssvoid ssynchronized sbool sS sO sL")); static public List> findFullFunctionDefs(List tok, boolean topLevelOnly) { int n = l(tok); List> functions = new ArrayList(); for (int i = 1; i < n; i += 2) { String t = tok.get(i); if (topLevelOnly && eq(t, "{")) i = findEndOfBlock(tok, i) - 1; else if (findFullFunctionDefs_keywords.contains(t)) { int j = i + 2; while (j < n && !eqOneOf(tok.get(j), ";", "=", "(", "{")) j += 2; if ((eqGet(tok, j, "(") || eq(t, "svoid") && eqGet(tok, j, "{")) && isIdentifier(tok.get(j - 2)) && !contains(subList(tok, i, j), "new")) { int k = smartIndexOf(tok, "{", j); if (k < l(tok)) { k = findEndOfBlock(tok, k) + 1; functions.add(subList(tok, i - 1, k)); i = k - 2; } } } } return functions; } static public List> findFullFunctionDefs(String s, boolean topLevelOnly) { return findFullFunctionDefs(javaTok(s), topLevelOnly); } static public File makeFileNameUnique_withExtension(File f, String ext) { File orig = f; int n = 0; ext = addPrefixIfNempty(".", dropPrefix(".", ext)); String name = dropSuffixIC(ext, orig.getName()); f = new File(dirOfFile(orig), name + ext); while (f.exists()) f = new File(dirOfFile(orig), name + "." + (++n) + ext); return f; } static public boolean has(String a, String b, String c) { return false; } static public boolean has(T3 t) { return false; } static public OKOrError OKOrError_error(Throwable e) { return new OKOrError(false, e); } static public A last(List l) { return empty(l) ? null : l.get(l.size() - 1); } static public char last(String s) { return empty(s) ? '#' : s.charAt(l(s) - 1); } static public byte last(byte[] a) { return l(a) != 0 ? a[l(a) - 1] : 0; } static public int last(int[] a) { return l(a) != 0 ? a[l(a) - 1] : 0; } static public long last(long[] a) { return l(a) != 0 ? a[l(a) - 1] : 0; } static public double last(double[] a) { return l(a) != 0 ? a[l(a) - 1] : 0; } static public A last(A[] a) { return l(a) != 0 ? a[l(a) - 1] : null; } static public A last(Iterator it) { A a = null; while (it.hasNext()) { ping(); a = it.next(); } return a; } static public A last(Collection l) { if (l == null) return null; if (l instanceof List) return (A) last((List) l); if (l instanceof SortedSet) return (A) last((SortedSet) l); Iterator it = iterator(l); A a = null; while (it.hasNext()) { ping(); a = it.next(); } return a; } static public A last(SortedSet l) { return l == null ? null : l.last(); } static public A last(ReverseChain l) { return l == null ? null : l.element; } static public int last(IntBuffer buf) { return buf.get(buf.size() - 1); } static public byte last(ByteBuffer buf) { return buf.get(buf.size() - 1); } static public double last(DoubleBuffer l) { return l.last(); } static public double last(IDoubleBuffer l) { return l.last(); } static public long last(ILongBuffer l) { return l.last(); } static public long last(LongBuffer l) { return l.last(); } static public double last(SynchronizedDoubleBuffer l) { return l.last(); } static public long last(SynchronizedLongBuffer l) { return l.last(); } static public A last(CompactLinkedHashSet set) { return set == null ? null : set.last(); } static public TreeSet caseInsensitiveSet() { return caseInsensitiveSet_treeSet(); } static public TreeSet caseInsensitiveSet(Collection c) { return caseInsensitiveSet_treeSet(c); } static public boolean checkCondition(Object condition, Object... args) { return isTrue(callF(condition, args)); } static public boolean checkCondition(IF1 condition, A arg) { return isTrue(callF(condition, arg)); } static public String intsToHex(List l) { if (l == null) return null; return bytesToHex(intListToByteArray(l)); } static public int intSum(Collection c, String field) { int sum = 0; for (Object o : unnull(c)) sum += toInt(getOpt(o, field)); return sum; } static public int intSum(Iterable l) { int sum = 0; for (Integer i : unnull(l)) if (i != null) sum += i; return sum; } static public int intSum(int... l) { int sum = 0; for (int i : unnull(l)) sum += i; return sum; } static public String formatDouble_noLeadingZero(double d, int digits) { String s = formatDouble(d, digits); if (startsWith(s, "-")) return startsWith(s, "-0.") ? "-." + dropFirst(3, s) : s; else return startsWith(s, "0.") ? dropFirst(s) : s; } static public byte[] takeFirstOfByteArray(byte[] b, int n) { return subByteArray(b, 0, n); } static public byte[] takeFirstOfByteArray(int n, byte[] b) { return takeFirstOfByteArray(b, n); } static public List filesWithExtension(String ext, List files) { return filesEndingWith(files, addPrefixIfNotEmpty2(".", ext)); } static public boolean warn_on = true; static public ThreadLocal> warn_warnings = new ThreadLocal(); static public void warn(String s) { if (warn_on) print("Warning: " + s); } static public void warn(String s, List warnings) { warn(s); if (warnings != null) warnings.add(s); addToCollection(warn_warnings.get(), s); } static public Map getMultipleKeys(Map map, A... keys) { Map map2 = similarEmptyMap(map); if (map != null && keys != null) for (A key : keys) map2.put(key, map.get(key)); return map2; } static public Map getMultipleKeys(Map map, Iterable keys) { Map map2 = similarEmptyMap(map); if (map != null && keys != null) for (A key : keys) map2.put(key, map.get(key)); return map2; } static public boolean dm_moduleIsPoppedOut() { return dm_moduleIsPoppedOut(dm_current_mandatory_generic()); } static public boolean dm_moduleIsPoppedOut(Object mod) { return isTrue(dm_callOSOpt("stefansOS_moduleIsPoppedOut", dm_getStem(mod))); } static public File actualUserDir() { return new File(actualUserHome()); } static public File actualUserDir(String path) { return new File(actualUserHome(), path); } static public String beautifyStructure(String s) { List tok = javaTokForStructure(s); structure_addTokenMarkers(tok); jreplace(tok, "lhm", ""); return join(tok); } static public double distance(double ax, double ay, double bx, double by) { return sqrt(sqr(bx - ax) + sqr(by - ay)); } static public int distance(int a, int b) { return abs(a - b); } static public JPanel jrightAlignedLine(final Component... components) { return swing(new F0() { public RightAlignedLine get() { try { return new RightAlignedLine(components); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return RightAlignedLine(components);"; } }); } static public JPanel jrightAlignedLine(List components) { return jrightAlignedLine(asArray(Component.class, components)); } static public Rect toRect(Rectangle r) { return r == null ? null : new Rect(r); } static public Rect toRect(RectangularShape r) { return r == null ? null : toRect(r.getBounds()); } static public Rect toRect(DoubleRect r) { if (r == null) return null; int x = iround(r.x), y = iround(r.y); return new Rect(x, y, iround(r.x2()) - x, iround(r.y2()) - y); } static public Rect toRect(Rect r) { return r; } static public Set synchroSet() { return synchroHashSet(); } static public Set synchroSet(Set set) { return synchronizedSet(set); } static public String formatDouble_significant2(double d, int digits) { try { digits -= Math.floor(max(-10, Math.log10(abs(d)) + 1)); return formatDouble(d, digits); } catch (Throwable _e) { print("Had number: " + d + ", digits: " + digits); throw rethrow(_e); } } static public Object callJavaX(String method, Object... args) { return callOpt(getJavaX(), method, args); } static public void assertPointInBounds(int x, int y, int w, int h) { if (x < 0) throw fail("x < 0", x); if (y < 0) throw fail("y < 0", y); if (x >= w) throw fail("x >= w", x, w); if (y >= h) throw fail("y >= h", y, h); } static public boolean isJavaxCompilableSnippetType(int type) { return isJavaxCompilableSnippetTypeExceptInclude(type) || type == javaxIncludeSnippetType(); } static public A installWindowDragger(A c) { onMouseDown(c, event -> new WindowDragger(event)); return c; } static public A onLeftClick(final A c, final Object runnable) { { swing(() -> { c.addMouseListener(leftClickMouseAdapter(runnable)); }); } return c; } static public TrayIcon onLeftClick(final TrayIcon c, final Object runnable) { { swing(() -> { c.addMouseListener(leftClickMouseAdapter_noPt(runnable)); }); } return c; } static public A onLeftClick(final Object runnable, A c) { return onLeftClick(c, runnable); } static public A onLeftClick(Runnable runnable, A c) { return onLeftClick((Object) runnable, c); } static public A onLeftClick(A c, Runnable r) { return onLeftClick(r, c); } static public A onLeftClick(A c, IVF1 r) { return onLeftClick(c, (Object) r); } static public boolean addIfNotNull(Collection l, A a) { return a != null && l != null & l.add(a); } static public void addIfNotNull(MultiSet ms, A a) { if (a != null && ms != null) ms.add(a); } static public TimeZone localTimeZone() { return getTimeZone(standardTimeZone()); } static public TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) { return new SmartTimerTask(r, timer, delay, _threadInfo()); } static public class SmartTimerTask extends TimerTask implements IFieldsToList { public Object r; public java.util.Timer timer; public long delay; public Object threadInfo; public SmartTimerTask() { } public SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) { this.threadInfo = threadInfo; this.delay = delay; this.timer = timer; this.r = r; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")"; } public Object[] _fieldsToList() { return new Object[] { r, timer, delay, threadInfo }; } public long lastRun; public void run() { if (!licensed()) timer.cancel(); else { _threadInheritInfo(threadInfo); AutoCloseable __1 = tempActivity(r); try { lastRun = fixTimestamp(lastRun); long now = now(); if (now >= lastRun + delay * 0.9) { lastRun = now; if (eq(false, pcallF(r))) timer.cancel(); } } finally { _close(__1); } } } } static public boolean isString(Object o) { return o instanceof String; } static public Timer installTimer(JComponent component, Object r, long delay) { return installTimer(component, r, delay, delay); } static public Timer installTimer(RootPaneContainer frame, long delay, Object r) { return installTimer(frame.getRootPane(), r, delay, delay); } static public Timer installTimer(JComponent component, long delay, Object r) { return installTimer(component, r, delay, delay); } static public Timer installTimer(JComponent component, long delay, long firstDelay, Object r) { return installTimer(component, r, delay, firstDelay); } static public Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) { return installTimer(component, r, delay, firstDelay, true); } static public Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) { if (component == null) return null; return (Timer) swingAndWait(new F0() { public Object get() { try { final Var timer = new Var(); timer.set(new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { AutoCloseable __1 = tempActivity(r); try { try { if (!allPaused()) if (isFalse(callF(r))) cancelTimer(timer.get()); } catch (Throwable __e) { pcallFail(__e); } } finally { _close(__1); } } catch (Throwable __e) { messageBox(__e); } } })); timer.get().setInitialDelay(toInt(firstDelay)); timer.get().setRepeats(repeats); bindTimerToComponent(timer.get(), component); return timer.get(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new Var timer;\r\n timer.set(new Timer(toInt(delay), actionList..."; } }); } static public Timer installTimer(RootPaneContainer frame, long delay, long firstDelay, Object r) { return installTimer(frame.getRootPane(), delay, firstDelay, r); } static public boolean setAdd(Collection c, A a) { if (c == null || c.contains(a)) return false; c.add(a); return true; } static public JECompressionSearch jeCompressionSearch(Data data, long inputSize) { return new JECompressionSearch(data, inputSize); } static public void syncMapPutOrRemove(Map map, A key, B value) { syncMapPut2(map, key, value); } static public BufferedImage clipBufferedImage(BufferedImage src, Rectangle clip) { return clipBufferedImage(src, new Rect(clip)); } static public BufferedImage clipBufferedImage(BufferedImage src, Rect r) { if (src == null || r == null) return null; r = intersectRects(r, new Rect(0, 0, src.getWidth(), src.getHeight())); if (rectEmpty(r)) return null; return src.getSubimage(r.x, r.y, r.w, r.h); } static public BufferedImage clipBufferedImage(BufferedImage src, int x, int y, int w, int h) { return clipBufferedImage(src, new Rect(x, y, w, h)); } static public AutoCloseable temp_loadPage_silent() { return tempSetThreadLocal(loadPage_silent, true); } static public List lInts(String hex) { return byteArrayToIntList_littleEndian(hexToBytes_dropSpaces(hex)); } static public boolean veryQuickJava_silent = true; static public boolean veryQuickJava_useCompilerBot = true; static public ThreadLocal veryQuickJava_transpiled = new ThreadLocal(); static public Object veryQuickJava3_cacheFunction; static public ThreadLocal> veryQuickJava_onJavaSource = new ThreadLocal(); static public Class veryQuickJava3(String mainJava) { return veryQuickJava3(mainJava, emptyList()); } static public Class veryQuickJava3(String mainJava, List libs) { Class c = (Class) (callF(veryQuickJava3_cacheFunction, mainJava, libs)); if (c != null) return c; transpileRaw_silent = veryQuickJava_silent; String src = transpileRaw(mainJava); if (empty(src)) { printWithIndent("JAVAX> ", mainJava); throw fail("Transpiler returned empty result"); } if (veryQuickJava_transpiled.get() != null) veryQuickJava_transpiled.set(src); callF(veryQuickJava_onJavaSource.get(), src); return veryQuickJava_finish(src, libs); } static public Border jCompoundBorder(Border inner, Border outer) { if (inner == null) return outer; if (outer == null) return inner; return BorderFactory.createCompoundBorder(inner, outer); } static public String afterLastSpace(String s) { return s == null ? null : substring(s, s.lastIndexOf(' ') + 1); } static public void dm_reloadModule(Object module) { dm_reloadModuleInBackground(module); } static public void dm_reloadModule() { dm_reloadModuleInBackground(); } static public List registeredThreads(Object o) { Map map = (Map) (getOpt(o, "_registerThread_threads")); if (map == null) return ll(); map.size(); synchronized (map) { return asList(keys(map)); } } static public List registeredThreads() { _registerThread_threads.size(); return asList(keys(_registerThread_threads)); } static public ThreadLocal htmlencode_forParams_useV2 = new ThreadLocal(); static public String htmlencode_forParams(String s) { if (s == null) return ""; if (isTrue(htmlencode_forParams_useV2.get())) return htmlencode_forParams_v2(s); StringBuilder out = new StringBuilder(Math.max(16, s.length())); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c > 127 || c == '"' || c == '<' || c == '>') { out.append("&#"); out.append((int) c); out.append(';'); } else out.append(c); } return out.toString(); } static public String formatDouble1(double d) { return formatDouble(d, 1); } static public void methodForEach(IVF1 f, Iterable l) { forEach(f, l); } static public void methodForEach(IVF1 f, A[] l) { forEach(f, l); } static public File tempDir() { return makeTempDir(); } static public JPanel centerAndNorth(final Component c, final Component n) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.CENTER, wrap(c)); panel.add(BorderLayout.NORTH, wrap(n)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT..."; } }); } static public boolean setText_opt = true; static public A setText(A c, Object text) { setText((JComponent) c, text); return c; } static public A setText(final A c, Object text) { final String s = strUnnull(text); { swing(() -> { c.getEditor().setItem(s); }); } return c; } static public void setText(JLabel c, Object text) { setText((JComponent) c, text); } static public JButton setText(JButton c, Object text) { setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text))); return c; } static public A setText(final A c, Object text) { if (c == null) return null; final String s = strUnnull(text); { swing(() -> { if (!setText_opt || neq(callOpt(c, "getText"), s)) call(c, "setText", s); }); } return c; } static public String intToHex(int i) { return bytesToHex(intToBytes(i)); } static public A vmBus_timerStarted(A timer) { vmBus_send("timerStarted", timer, costCenter()); return timer; } static public String jlabel_textAsHTML_center(String text) { return "
" + replace(htmlencode2(text), "\n", "
") + "
"; } static public int findBeginningOfBlock(List cnc, int i) { int j = i - 2, level = 1; while (j > 0) { if (eq(cnc.get(j), "}")) ++level; else if (eq(cnc.get(j), "{")) --level; if (level == 0) return j; j -= 2; } return -1; } static public TreeSet litciset(String... items) { TreeSet set = caseInsensitiveSet(); for (String a : items) set.add(a); return set; } static public TreeSet litciset(Symbol... items) { TreeSet set = treeSet(); for (Symbol a : items) set.add(a); return set; } static public JButton findButton(Component c, String name) { for (JButton b : childrenOfType(c, JButton.class)) if (eq(b.getText(), name)) return b; for (JButton b : childrenOfType(getFrame(c), JButton.class)) if (eq(b.getText(), name)) return b; return null; } static public JButton findButton(Component c) { return childOfType(c, JButton.class); } static public List splitAtSpace(String s) { return empty(s) ? emptyList() : asList(s.split("\\s+")); } static public File getCanonicalFile(String path) { try { return path == null ? null : newFile(path).getCanonicalFile(); } catch (Exception __e) { throw rethrow(__e); } } static public File getCanonicalFile(File f) { try { return f == null ? null : f.getCanonicalFile(); } catch (Exception __e) { throw rethrow(__e); } } static public String htmlQuery(Map params) { return empty(params) ? "" : "?" + makePostData(params); } static public String htmlQuery(Object... data) { return empty(data) ? "" : "?" + makePostData(data); } static public Number parseIntOrLong(String s) { long l = parseLong(s); return longIsInt(l) ? (Number) (int) l : (Number) l; } static public MouseAdapter leftClickMouseAdapter(final Object r) { return new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getButton() == 1) pcallF(r, new Pt(e.getPoint())); } }; } static public String toJava(Object o) { return str(new ToJava().get(o)); } static public Rectangle getBounds(final Component c) { return c == null ? null : swing(new F0() { public Rectangle get() { try { return c.getBounds(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getBounds();"; } }); } static public JPanel northAndCenterWithMargin(int margin, Swingable n, Swingable c) { return northAndCenterWithMargin(margin, n, toComponent(c)); } static public JPanel northAndCenterWithMargin(int margin, Swingable n, Component c) { return northAndCenterWithMargin(margin, toComponent(n), c); } static public JPanel northAndCenterWithMargin(int margin, Component n, Swingable c) { return northAndCenterWithMargin(margin, n, toComponent(c)); } static public JPanel northAndCenterWithMargin(int margin, Component n, Component c) { return northAndCenter(withBottomMargin(margin, n), c); } static public JPanel northAndCenterWithMargin(Swingable n, Swingable c) { return northAndCenterWithMargin(n, toComponent(c)); } static public JPanel northAndCenterWithMargin(Swingable n, Component c) { return northAndCenterWithMargin(toComponent(n), c); } static public JPanel northAndCenterWithMargin(Component n, Swingable c) { return northAndCenterWithMargin(n, toComponent(c)); } static public JPanel northAndCenterWithMargin(Component n, Component c) { return northAndCenter(withBottomMargin(n), c); } static public
A printIndent(A o) { print(indentx(str(o))); return o; } static public A printIndent(String indent, A o) { print(indentx(indent, str(o))); return o; } static public void printIndent(int indent, Object o) { print(indentx(indent, str(o))); } static public List getAndClearList(Collection l) { if (l == null) return emptyList(); synchronized (collectionMutex(l)) { List out = cloneList(l); l.clear(); return out; } } static public String loadTextFileResource(ClassLoader cl, String name) { return inputStreamToString(cl.getResourceAsStream(name)); } static public int leftScanModifiers(List tok, int i) { return leftScanModifiers(tok, i, getJavaModifiers()); } static public int leftScanModifiers(List tok, int i, Collection modifiers) { while (i > 1 && contains(modifiers, tok.get(i - 2))) i -= 2; return i; } static public String renderUserThreadsWithStackTraces() { return renderUserThreadsWithStackTraces(mapWithout(Thread.getAllStackTraces(), currentThread())); } static public String renderUserThreadsWithStackTraces(Map threadMap) { return renderUserThreadsWithStackTraces(threadMap, "thread"); } static public String renderUserThreadsWithStackTraces(Map threadMap, String threadDescription) { StringBuilder bufRunnable = new StringBuilder(); StringBuilder bufWaiting = new StringBuilder(); int nRunnable = 0, nWaiting = 0, nSystem = 0; for (var __0 : _entrySet(threadMap)) { var t = __0.getKey(); var stackTrace = __0.getValue(); boolean runnable = isThreadRunnable_x(t, stackTrace); var buf = runnable ? bufRunnable : bufWaiting; ThreadGroup g = t.getThreadGroup(); if (g != null && g.getName().equals("system")) { ++nSystem; continue; } if (runnable) ++nRunnable; else ++nWaiting; printTo(buf, t); for (StackTraceElement e : threadMap.get(t)) printTo(buf, " " + e); printTo(buf); } return asciiHeading2(n2(nRunnable, "runnable " + threadDescription)) + "\n" + bufRunnable + asciiHeading2(n2(nWaiting, "sleeping " + threadDescription) + " (+" + n2(nSystem, "system thread") + ")") + "\n" + bufWaiting; } static public String nBytes(long n) { return n2(n, "byte"); } static public String nBytes(Collection l) { return nBytes(l(l)); } static public String nBytes(byte[] l) { return nBytes(l(l)); } static public String loadTextFilePossiblyGZipped(String fileName) { return loadTextFilePossiblyGZipped(fileName, null); } static public String loadTextFilePossiblyGZipped(String fileName, String defaultContents) { File gz = new File(fileName + ".gz"); return gz.exists() ? loadGZTextFile(gz) : loadTextFile(fileName, defaultContents); } static public String loadTextFilePossiblyGZipped(File fileName) { return loadTextFilePossiblyGZipped(fileName, null); } static public String loadTextFilePossiblyGZipped(File fileName, String defaultContents) { return loadTextFilePossiblyGZipped(fileName.getPath(), defaultContents); } static public Concepts newConceptsWithClassFinder(String progID) { Concepts cc = new Concepts(progID); cc.classFinder = _defaultClassFinder(); return cc; } static public Concepts newConceptsWithClassFinder(File conceptsFile) { Concepts cc = new Concepts(assertNotNull(conceptsFile)); cc.classFinder = _defaultClassFinder(); return cc; } static public Concepts newConceptsWithClassFinder(File conceptsFile, IF1 classFinder) { Concepts cc = new Concepts(assertNotNull(conceptsFile)); cc.classFinder = classFinder; return cc; } static public float getSwingFontScale() { return or((Float) vm_generalMap_get("swingFontScale_value"), 1f); } static public String addPrefixIfNotEmpty2(String prefix, String s) { return empty(s) ? "" : addPrefix(prefix, s); } static public int snippetType_javaxDesktopModule() { return 58; } static public boolean substanceLookAndFeelEnabled() { return startsWith(getLookAndFeel(), "org.pushingpixels."); } static public List replaceSublist(List l, List x, List y) { if (x == null) return l; int i = 0; while (true) { i = indexOfSubList(l, x, i); if (i < 0) break; replaceSublist(l, i, i + l(x), y); i += l(y); } return l; } static public List replaceSublist(List l, int fromIndex, int toIndex, List y) { int n = y.size(), toIndex_new = fromIndex + n; if (toIndex_new < toIndex) { removeSubList(l, toIndex_new, toIndex); copyListPart(y, 0, l, fromIndex, n); } else { copyListPart(y, 0, l, fromIndex, toIndex - fromIndex); if (toIndex_new > toIndex) l.addAll(toIndex, subList(y, toIndex - fromIndex)); } return l; } static public List replaceSublist(List l, IntRange r, List y) { return replaceSublist(l, r.start, r.end, y); } static public String selectedItem(JList l) { return getSelectedItem(l); } static public String selectedItem(JComboBox cb) { return getSelectedItem(cb); } static public List codeTokensOnly(List tok) { int n = l(tok); List l = emptyList(n / 2); for (int i = 1; i < n; i += 2) l.add(tok.get(i)); return l; } static public String standardCredentialsUser() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username")))); } static public int[] matrixToIntArray(Matrix m) { int w = m.getWidth(), h = m.getHeight(), n = w * h; int[] a = new int[n]; int i = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) a[i++] = m.get(x, y); return a; } static public void printTo(StringBuilder buf, Object o) { buf.append(str(o)).append("\n"); } static public void printTo(StringBuilder buf) { printTo(buf, ""); } static public File appendToFileNameBeforeExtension(File f, String s) { String ext = fileExtension(f); String name = dropSuffixIC(ext, f.getName()); name += s; return newFile(parentFile(f), name + ext); } static public F1 functionToF1(final Object f) { if (isString(f)) return mainFunctionToF1((String) f); if (f instanceof F1) return (F1) f; return new F1() { public Object get(Object a) { try { return callF(f, a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret callF(f, a);"; } }; } static public boolean isSpaceEtc(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } static public long fixTimestamp(long timestamp) { return timestamp > now() ? 0 : timestamp; } static public boolean isNormalQuoted(String s) { int l = l(s); if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"')) return false; int j = 1; while (j < l) if (s.charAt(j) == '"') return j == l - 1; else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; return false; } static public String joinSubList(List l, int i, int j) { return join(subList(l, i, j)); } static public String joinSubList(List l, int i) { return join(subList(l, i)); } static public String joinSubList(List l, IntRange r) { return r == null ? null : joinSubList(l, r.start, r.end); } static public boolean isMultilineQuoted(String s) { if (!startsWith(s, "[")) return false; int i = 1, n = s.length(); while (i < n && s.charAt(i) == '=') ++i; return i < n && s.charAt(i) == '['; } static public JWindow loadingAnim() { return showLoadingAnimation(); } static public JWindow loadingAnim(String text) { return showLoadingAnimation(text); } static public void saveGZTextFile(File file, String contents) { saveGZTextFile(file, contents, "UTF-8"); } static public void saveGZTextFile(File file, String contents, String encoding) { try { File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = file.getPath() + "_temp"; File tempFile = new File(tempFileName); if (contents != null) { if (tempFile.exists()) try { String saveName = tempFileName + ".saved." + now(); copyFile(tempFile, new File(saveName)); } catch (Throwable e) { printStackTrace(e); } FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath()); GZIPOutputStream gos = new GZIPOutputStream(fileOutputStream); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gos, encoding); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); gos.close(); fileOutputStream.close(); } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + file.getPath()); if (contents != null) if (!tempFile.renameTo(file)) throw new IOException("Can't rename " + tempFile + " to " + file); } catch (Exception __e) { throw rethrow(__e); } } static public Frame getAWTFrame(final Object _o) { return swing(new F0() { public Frame get() { try { Object o = _o; if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof Frame) return (Frame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n /*\r\n ifdef HaveProcessing\r\n if (o instanceof PApplet) ..."; } }); } static public BufferedImage defaultScreenshot() { if (hasGlobalOption("canDefaultScreenshot")) return shootScreen2(); return null; } static public boolean setVar_trueIfChanged(IVar v, A value) { if (v == null) return false; synchronized (v) { if (eq(v.get(), value)) return false; v.set(value); return true; } } static public String nEntries(long n) { return n2(n, "entry", "entries"); } static public String nEntries(Collection l) { return nEntries(l(l)); } static public String nEntries(Map map) { return nEntries(l(map)); } static public int[] hexToInts(String s) { if (odd(l(s))) throw fail("Hex string has odd length: " + quote(shorten(10, s))); int n = l(s) / 8; int[] ints = new int[n]; for (int i = 0; i < n; i++) { int value = 0; for (int j = 0; j < 4; j++) { int idx = i * 8 + j * 2; int a = parseHexChar(s.charAt(idx)); int b = parseHexChar(s.charAt(idx + 1)); if (a < 0 || b < 0) throw fail("Bad hex byte: " + quote(substring(s, idx, idx + 2)) + " at " + idx + "/" + l(s)); value |= ((a << 4) | b) << (j * 8); } ints[i] = value; } return ints; } static public void syncMapPut2(Map map, A key, B value) { if (map != null && key != null) synchronized (collectionMutex(map)) { if (value != null) map.put(key, value); else map.remove(key); } } static public List> mapToPairs(Map map) { List> l = emptyList(l(map)); if (map != null) for (Map.Entry e : map.entrySet()) l.add(pair(e.getKey(), e.getValue())); return l; } static public boolean isJavaxApplicationSnippetType(int type) { return type == snippetType_javaxSource() || type == snippetType_JavaXDesktop(); } static public List javaTokC(String s) { if (s == null) return null; int l = s.length(); ArrayList tok = new ArrayList(); int i = 0; while (i < l) { int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } i = j; if (i >= l) break; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else if (c == '[' && d == '[') { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') { do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]")); j = Math.min(j + 3, l); } else ++j; tok.add(javaTok_substringC(s, i, j)); i = j; } return tok; } static public JComboBox onSelectedItem(final JComboBox cb, final VF1 f) { addActionListener(cb, new Runnable() { public void run() { try { pcallF(f, selectedItem(cb)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(f, selectedItem(cb))"; } }); return cb; } static public JComboBox onSelectedItem(final JComboBox cb, IVF1 f) { addActionListener(cb, new Runnable() { public void run() { try { pcallF(f, selectedItem(cb)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(f, selectedItem(cb))"; } }); return cb; } static public Boolean askTripleBool(String q) { print(q + " no idea"); return null; } static public A dm_ownResource(A resource) { dm_currentModuleMandatory().ownResource(resource); return resource; } static public int ratioToIntPercent(double x, double y) { return roundToInt(x * 100 / y); } static public BufferedImage loadPNG(File file) { return loadBufferedImage(file); } static public String jreplace(String s, String in, String out) { return jreplace(s, in, out, null); } static public String jreplace(String s, String in, String out, Object condition) { List tok = javaTok(s); return jreplace(tok, in, out, condition) ? join(tok) : s; } static public boolean jreplace(List tok, String in, String out) { return jreplace(tok, in, out, false, true, null); } static public boolean jreplace(List tok, String in, String out, Object condition) { return jreplace(tok, in, out, false, true, condition); } static public boolean jreplace(List tok, String in, ITokCondition condition, String out) { return jreplace(tok, in, out, (Object) condition); } static public boolean jreplace(List tok, String in, String out, IF2, Integer, Boolean> condition) { return jreplace(tok, in, out, (Object) condition); } static public boolean jreplace(List tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) { String[] toks = javaTokForJFind_array(in); int lTokin = toks.length * 2 + 1; boolean anyChange = false; int i = -1; for (int n = 0; n < 10000; n++) { i = findCodeTokens(tok, i + 1, ignoreCase, toks, condition); if (i < 0) return anyChange; List subList = tok.subList(i - 1, i + lTokin - 1); String expansion = jreplaceExpandRefs(out, subList); int end = i + lTokin - 2; clearAllTokens(tok, i, end); tok.set(i, expansion); if (reTok) reTok(tok, i, end); i = end; anyChange = true; } throw fail("woot? 10000! " + quote(in) + " => " + quote(out)); } static public boolean jreplace_debug = false; static public class tempRememberListener_c implements IFieldsToList { static final public String _fieldOrder = "mainObject removeMethod listener"; public Object mainObject; public String removeMethod; public Object listener; public tempRememberListener_c() { } public tempRememberListener_c(Object mainObject, String removeMethod, Object listener) { this.listener = listener; this.removeMethod = removeMethod; this.mainObject = mainObject; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + mainObject + ", " + removeMethod + ", " + listener + ")"; } public boolean equals(Object o) { if (!(o instanceof tempRememberListener_c)) return false; tempRememberListener_c __1 = (tempRememberListener_c) o; return eq(mainObject, __1.mainObject) && eq(removeMethod, __1.removeMethod) && eq(listener, __1.listener); } public int hashCode() { int h = 1262836985; h = boostHashCombine(h, _hashCode(mainObject)); h = boostHashCombine(h, _hashCode(removeMethod)); h = boostHashCombine(h, _hashCode(listener)); return h; } public Object[] _fieldsToList() { return new Object[] { mainObject, removeMethod, listener }; } } static public AutoCloseable tempRememberListener(Object mainObject, String removeMethod, Object listener) { return tempHoldInstance(new tempRememberListener_c(mainObject, removeMethod, listener)); } static public Object[] muricaCredentials() { String pass = muricaPassword(); return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0]; } static public boolean newButton_autoToolTip = true; static public boolean newButton_autoToolTip() { return newButton_autoToolTip; } static public JButton newButton(final String text, final Object action) { return swing(new F0() { public JButton get() { try { String text2 = dropPrefix("[disabled] ", text); JButton btn = basicJButton(text2); if (l(text2) < l(text)) btn.setEnabled(false); if (newButton_autoToolTip) { btn.setToolTipText(btn.getText()); } if (action != null) btn.addActionListener(actionListener(action, btn)); return btn; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "S text2 = dropPrefix(\"[disabled] \", text);\r\n JButton btn = basicJButton(te..."; } }); } static public String smartJoin(String[] args) { if (empty(args)) return ""; if (args.length == 1) return args[0]; String[] a = new String[args.length]; for (int i = 0; i < a.length; i++) a[i] = !isJavaIdentifier(args[i]) && !isQuoted(args[i]) ? quote(args[i]) : args[i]; return join(" ", a); } static public String smartJoin(List args) { return smartJoin(toStringArray(args)); } static public TreeSet treeSet() { return new TreeSet(); } static public void onUpdate(JComponent c, Runnable r) { onUpdate(c, (Object) r); } static public void onUpdate(JTextComponent c, IVF1 r) { if (c == null || r == null) return; c.getDocument().addDocumentListener(runnableToDocumentListener(() -> r.get(c.getText()))); } static public void onUpdate(JComponent c, Object r) { if (c instanceof JTextComponent) ((JTextComponent) c).getDocument().addDocumentListener(runnableToDocumentListener(toRunnable(r))); else if (c instanceof ItemSelectable) ((ItemSelectable) c).addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { pcallF(r); } }); else if (c instanceof JSpinner) onChange(((JSpinner) c), r); else print("Warning: onUpdate doesn't know " + getClassName(c)); } static public void onUpdate(List l, Object r) { for (JComponent c : l) onUpdate(c, r); } static public File snippetTitle_cacheFile(String snippetID) { return javaxCachesDir("Snippet Titles/" + psI(snippetID)); } static public String formatInt(int i, int digits) { return padLeft(str(i), '0', digits); } static public String formatInt(long l, int digits) { return padLeft(str(l), '0', digits); } static public List hotwire_copyOver_after = synchroList(); static public void hotwire_copyOver(Class c) { for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field)); setOptIfNotNull(c, "mainBot", getMainBot()); setOpt(c, "creator_class", new WeakReference(mc())); pcallFAll(hotwire_copyOver_after, c); } static public List flattenIterablesAndArrays(Iterable a) { List l = new ArrayList(); for (Object x : a) if (x instanceof Iterable) l.addAll(flattenIterablesAndArrays((Iterable) x)); else if (x instanceof Iterator) l.addAll(flattenIterablesAndArrays(asList((Iterator) x))); else if (x instanceof Object[]) l.addAll(flattenIterablesAndArrays(asList((Object[]) x))); else l.add(x); return l; } static public int intMax(Collection c, String field) { int max = Integer.MIN_VALUE; for (Object o : c) max = Math.max(max, toInt(getOpt(o, field))); return max; } static public int intMax(Iterable l) { int max = Integer.MIN_VALUE; for (int i : unnullForIteration(l)) max = Math.max(max, i); return max; } static public int intMax(int... l) { int max = Integer.MIN_VALUE; if (l != null) for (int i : l) max = Math.max(max, i); return max; } static public > A addAndReturnCollection(A c, B a) { if (c != null) c.add(a); return c; } static public boolean activateFrame(final Component c, Object... __) { return swing(new F0() { public Boolean get() { try { Frame f = getAWTFrame(c); if (f == null) return false; if (!f.isVisible()) f.setVisible(true); boolean windowsHack = optPar("windowsHack", __, true); boolean iconified = f.getState() == Frame.ICONIFIED; boolean maximize = boolPar("maximize", __); if (iconified) f.setState(maximize ? Frame.MAXIMIZED_BOTH : Frame.NORMAL); if (windowsHack && !iconified && isWindows()) { boolean fullscreen = f.getExtendedState() == Frame.MAXIMIZED_BOTH; f.setExtendedState(JFrame.ICONIFIED); f.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL); } f.toFront(); return true; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Frame f = getAWTFrame(c);\r\n if (f == null) false;\r\n if (!f.isVisible())..."; } }); } static public void awtLater(int delay, final Object r) { swingLater(delay, r); } static public void awtLater(int delay, Runnable r) { swingLater(delay, r); } static public void awtLater(Object r) { swingLater(r); } static public void awtLater(double delaySeconds, Runnable r) { swingLater(toMS(delaySeconds), r); } static public void awtLater(JComponent component, int delay, Object r) { installTimer(component, r, delay, delay, false); } static public void awtLater(JFrame frame, int delay, Object r) { awtLater(frame.getRootPane(), delay, r); } static public List replace(List l, A a, A b) { for (int i = 0; i < l(l); i++) if (eq(l.get(i), a)) l.set(i, b); return l; } static public List replace(A a, A b, List l) { return replace(l, a, b); } static public String replace(String s, String a, String b) { return s == null ? null : a == null || b == null ? s : s.replace(a, b); } static public String replace(String s, char a, char b) { return s == null ? null : s.replace(a, b); } static public FunctionCall functionCall_list(Object fname, Iterable args) { return new FunctionCall(fname, toObjectArray(args)); } static public ThreadLocal assertVerbose_value = new ThreadLocal(); static public void assertVerbose(boolean b) { assertVerbose_value.set(b); } static public boolean assertVerbose() { return isTrue(assertVerbose_value.get()); } static public String getOneLineFileInfoField(File f, String field) { File infoFile = associatedInfosFile(f); List lines = lines(loadTextFile(infoFile)); return firstStartingWithIC_drop(lines, field + ": "); } static public void profileToConsole(Runnable r) { poorMansProfileToConsole(r); } static public A profileToConsole(IF0 r) { if (r == null) return null; Var var = new Var(); poorMansProfileToConsole(new Runnable() { public void run() { try { var.set(r.get()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var.set(r!)"; } }); return var.get(); } static public boolean neqOneOf(Object o, Object... l) { for (Object x : l) if (eq(o, x)) return false; return true; } static public List myLibraryFiles() { Collection files = (Collection) (getOpt(myClassLoader(), "files")); if (files != null) return asList(files); return ll(getBytecodePathForClass(mc())); } static public Object dm_javaEval(String expression) { return dm_evalJava_withModule(expression); } static public Object dm_javaEval(ICachedJavaXExpr expression) { return dm_evalJava_withModule(str(expression)); } static public String nChars(long n) { return n2(n, "char"); } static public String nChars(String s) { return nChars(l(s)); } static public int findCodeTokens(List tok, String... tokens) { return findCodeTokens(tok, 1, false, tokens); } static public int findCodeTokens(List tok, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, 1, ignoreCase, tokens); } static public int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, startIdx, ignoreCase, tokens, null); } static public HashSet findCodeTokens_specials = lithashset("*", "", "", "", "\\*"); static public int findCodeTokens_bails, findCodeTokens_nonbails; static public interface findCodeTokens_Matcher { public boolean get(String token); } static public int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) { int end = tok.size() - tokens.length * 2 + 2, nTokens = tokens.length; int i = startIdx | 1; findCodeTokens_Matcher[] matchers = new findCodeTokens_Matcher[nTokens]; IContentsIndexedList2 indexedList = tok instanceof IContentsIndexedList2 ? (IContentsIndexedList2) tok : null; TreeSet indices = null; int indicesOfs = 0; for (int j = 0; j < nTokens; j++) { String p = tokens[j]; findCodeTokens_Matcher matcher; if (p.equals("*")) matcher = t -> true; else if (p.equals("")) matcher = t -> isQuoted(t); else if (p.equals("")) matcher = t -> isIdentifier(t); else if (p.equals("")) matcher = t -> isInteger(t); else if (p.equals("\\*")) matcher = t -> t.equals("*"); else if (ignoreCase) matcher = t -> eqic(p, t); else { matcher = t -> t.equals(p); if (indexedList != null) { TreeSet indices2 = indexedList.indicesOf_treeSetOfHasIndex(p); if (indices2 == null) return -1; if (indices == null || indices2.size() < indices.size()) { indices = indices2; indicesOfs = j; } } } matchers[j] = matcher; } if (indices != null) { int min = i + indicesOfs * 2; SortedSet tailSet = min == 1 ? indices : indices.tailSet(new HasIndex(min)); outer: for (HasIndex h : tailSet) { int idx = h.idx - indicesOfs * 2; if (idx >= end) break; for (int j = 0; j < nTokens; j++) try { if (!matchers[j].get(tok.get(idx + j * 2))) continue outer; } catch (IndexOutOfBoundsException e) { print("fct indicesOfs=" + indicesOfs + ", h=" + h + ", idx=" + idx); throw e; } if (condition == null || checkTokCondition(condition, tok, idx - 1)) return idx; } return -1; } outer: for (; i < end; i += 2) { for (int j = 0; j < nTokens; j++) if (!matchers[j].get(tok.get(i + j * 2))) continue outer; if (condition == null || checkTokCondition(condition, tok, i - 1)) return i; } return -1; } static public A withTypeWriterFont(A c) { return setFont(c, typeWriterFont()); } static public String dropTranslators(String src) { return findTranslators2(src, null); } static public List dropTranslators(List tok) { return findTranslators2(tok, null); } static public void printWithMS(A a) { printWithMS("", a); } static public void printWithMS(String prefix, A a) { printWithMSTime(prefix, a); } static public void tokAppend(List tok, int i, String s) { tok.set(i, tok.get(i) + s); } static public List lambdaMethodMap(IF1 f, Iterable l) { return map(f, l); } static public List lambdaMethodMap(IF1 f, A[] l) { return map(f, l); } static public BufferedImage matrixToImage(Matrix m) { return intMatrixToBufferedImage(m); } static public JSplitPane setSplitPaneOnFirstShowing(Component c, double value) { return setSplitPaneOnFirstShowing(c, value, 0); } static public JSplitPane setSplitPaneOnFirstShowing(Component c, double value, int delay) { final JSplitPane sp = first(childrenOfType(c, JSplitPane.class)); if (sp != null) onFirstResize(sp, new Runnable() { public void run() { try { if (delay == 0) sp.setDividerLocation(value); else awtLater(delay, new Runnable() { public void run() { try { sp.setDividerLocation(value); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "sp.setDividerLocation(value);"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef setSplitPaneOnFirstShowing_debug\r\n printVars setSplitPaneOnFirst..."; } }); return sp; } static public boolean vmBus_noObjections(String msg, Object... args) { return !vmBus_anyFalse(msg, args); } static public String format(String pat, Object... args) { return format3(pat, args); } static public Object vmGeneralMap_get(Object key) { return vm_generalMap_get(key); } static public int heightForWidth(int w, int h, int newWidth) { return iround(newWidth * doubleRatio(h, w)); } static public int heightForWidth(BufferedImage img, int newWidth) { return heightForWidth(img.getWidth(), img.getHeight(), newWidth); } static public int heightForWidth(int newWidth, BufferedImage img) { return heightForWidth(img, newWidth); } static public int heightForWidth(WidthAndHeight img, int newWidth) { return heightForWidth(img.getWidth(), img.getHeight(), newWidth); } static public String strUnnull(Object o) { return o == null ? "" : str(o); } static public boolean isSymLink(File f) { return f != null && Files.isSymbolicLink(toPath(f)); } static public Object get2(Object o, String field1, String field2) { return get(get(o, field1), field2); } static public A eitherAOpt(Either e) { return e != null && e.isA() ? e.a() : null; } static public JTextField onEnter(JTextField tf, JButton btn) { if (btn != null) onEnter(tf, new Runnable() { public void run() { try { clickButton(btn); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "clickButton(btn)"; } }); return tf; } static public JTextField onEnter(JTextField tf, Object action) { if (action == null || tf == null) return tf; tf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { tf.selectAll(); callF(action); } catch (Throwable __e) { messageBox(__e); } } }); return tf; } static public JButton onEnter(JButton btn, final Object action) { if (action == null || btn == null) return btn; btn.addActionListener(actionListener(action)); return btn; } static public JList onEnter(JList list, Object action) { list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action))); return list; } static public JComboBox onEnter(final JComboBox cb, Runnable action) { { swing(() -> { if (cb.isEditable()) { JTextField text = (JTextField) cb.getEditor().getEditorComponent(); onEnter(text, action); } else { cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter"); cb.getActionMap().put("enter", abstractAction("", new Runnable() { public void run() { try { cb.hidePopup(); callF(action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.hidePopup(); callF(action);"; } })); } }); } return cb; } static public JTable onEnter(final JTable table, final Object action) { table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter"); table.getActionMap().put("Enter", new AbstractAction() { public void actionPerformed(ActionEvent e) { callF(action, table.getSelectedRow()); } }); return table; } static public JTextField onEnter(Runnable action, JTextField tf) { return onEnter(tf, action); } static public boolean vmBus_anyFalse(String msg, Object... args) { return contains(vmBus_queryAll(msg, args), false); } static public File localSnippetsDir() { return javaxDataDir("Personal Programs"); } static public File localSnippetsDir(String sub) { return newFile(localSnippetsDir(), sub); } static public Matrix listToMatrix(int w, List data) { int n = l(data); int h = n / w; if (w * h != n) throw fail("Bad size", "n", n, "w", w, "h", h); return new ListToMatrix(w, h, data); } static public JSplitPane hsplit(Component l, Component r) { return jhsplit(l, r); } static public JSplitPane hsplit(Component l, Component r, double splitPoint, int delay) { return jhsplit(l, r, splitPoint, delay); } static public JSplitPane hsplit(Component l, Component r, double splitPoint) { return jhsplit(l, r, splitPoint); } static public JSplitPane hsplit(double splitPoint, Component l, Component r) { return jhsplit(splitPoint, l, r); } static public String mcDollar() { return mcName() + "$"; } static public ChangeListener changeListener(final Object r) { return new ChangeListener() { public void stateChanged(ChangeEvent e) { pcallF(r); } }; } static public Rectangle screenRectangle() { return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); } static public Rectangle screenRectangle(GraphicsDevice device) { if (device == null) return null; DisplayMode mode = device.getDisplayMode(); return new Rectangle(0, 0, mode.getWidth(), mode.getHeight()); } static public List mapWithIndex(List l, IF2 f) { List out = emptyList(l); for (int i = 0; i < l(l); i++) out.add(f.get(i, l.get(i))); return out; } static public List mapWithIndex(IF2 f, List l) { return mapWithIndex(l, f); } static public boolean set_trueIfChanged(Object o, String field, Object value) { if (eq(get(o, field), value)) return false; set(o, field, value); return true; } static public boolean set_trueIfChanged(IVar v, A value) { return setVar_trueIfChanged(v, value); } static public boolean containsNewLine(String s) { return contains(s, '\n'); } static public void copyStreamAndCloseInput(InputStream in, OutputStream out) { try { try { copyStream(in, out); } finally { in.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public JPanel centerAndEastWithMargin(Swingable c, Swingable e) { return centerAndEastWithMargin(c, toComponent(e)); } static public JPanel centerAndEastWithMargin(Swingable c, Component e) { return centerAndEastWithMargin(toComponent(c), e); } static public JPanel centerAndEastWithMargin(Component c, Swingable e) { return centerAndEastWithMargin(c, toComponent(e)); } static public JPanel centerAndEastWithMargin(Component c, Component e) { return centerAndEastWithMarginInbetween(c, e); } static public void retireClassLoader(ClassLoader cl) { try { if (isJavaXClassLoader(cl)) setOptAll(cl, "retired", true, "retiredMarker", new DefunctClassLoader()); } catch (Throwable __e) { pcallFail(__e); } } static public JFrame getFrame(final Object _o) { return swing(new F0() { public JFrame get() { try { Object o = _o; if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof JFrame) return (JFrame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; } }); } static public A dm_evalInQ(F0 f) { return dm_evalInQ(dm_current_mandatory(), f); } static public A dm_evalInQ(IF0 f) { return dm_evalInQ(dm_current_mandatory(), if0ToF0(f)); } static public A dm_evalInQ(DynModule module, F0 f) { return evalInQ(module.q(), f); } static public IterableIterator countIterator_exclusive(int b) { return countIterator_exclusive(0, b); } static public IterableIterator countIterator_exclusive(int a, int b) { return new IterableIterator() { public int i = a; public boolean hasNext() { return i < b; } public Integer next() { return i++; } }; } static public IterableIterator countIterator_exclusive(int b, IF1 f) { return countIterator_exclusive(0, b, f); } static public IterableIterator countIterator_exclusive(int a, int b, IF1 f) { return mapI_if1(f, countIterator_exclusive(a, b)); } static public JPanel centerAndSouth(final Component c, final Component s) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.CENTER, wrap(c)); if (s != null) panel.add(BorderLayout.SOUTH, wrap(s)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT..."; } }); } static public JScrollPane jscroll_center(Component c) { return jscroll_centered(c); } static public JSplitPane jhsplit(Swingable l, Swingable r) { return jhsplit(l, toComponent(r)); } static public JSplitPane jhsplit(Swingable l, Component r) { return jhsplit(toComponent(l), r); } static public JSplitPane jhsplit(Component l, Swingable r) { return jhsplit(l, toComponent(r)); } static public JSplitPane jhsplit(Component l, Component r) { return jhsplit(l, r, 0.5); } static public JSplitPane jhsplit(Swingable l, Swingable r, double splitPoint, int delay) { return jhsplit(l, toComponent(r), splitPoint, delay); } static public JSplitPane jhsplit(Swingable l, Component r, double splitPoint, int delay) { return jhsplit(toComponent(l), r, splitPoint, delay); } static public JSplitPane jhsplit(Component l, Swingable r, double splitPoint, int delay) { return jhsplit(l, toComponent(r), splitPoint, delay); } static public JSplitPane jhsplit(Component l, Component r, double splitPoint, int delay) { return jhsplit(l, r, splitPoint); } static public JSplitPane jhsplit(Swingable l, Swingable r, double splitPoint) { return jhsplit(l, toComponent(r), splitPoint); } static public JSplitPane jhsplit(Swingable l, Component r, double splitPoint) { return jhsplit(toComponent(l), r, splitPoint); } static public JSplitPane jhsplit(Component l, Swingable r, double splitPoint) { return jhsplit(l, toComponent(r), splitPoint); } static public JSplitPane jhsplit(Component l, Component r, double splitPoint) { return setSplitPaneOnFirstShowing(swingNu(JSplitPane.class, JSplitPane.HORIZONTAL_SPLIT, wrap(l), wrap(r)), splitPoint); } static public JSplitPane jhsplit(double splitPoint, Swingable l, Swingable r) { return jhsplit(splitPoint, l, toComponent(r)); } static public JSplitPane jhsplit(double splitPoint, Swingable l, Component r) { return jhsplit(splitPoint, toComponent(l), r); } static public JSplitPane jhsplit(double splitPoint, Component l, Swingable r) { return jhsplit(splitPoint, l, toComponent(r)); } static public JSplitPane jhsplit(double splitPoint, Component l, Component r) { return jhsplit(l, r, splitPoint); } static public SimpleLiveValue dm_fieldLiveValue(String fieldName) { return dm_fieldLiveValue(dm_current_mandatory(), fieldName); } static public SimpleLiveValue dm_fieldLiveValue(DynModule module, String fieldName) { Lock __0 = module.lock; lock(__0); try { AutoCloseable __2 = module.enter(); try { Class type = getFieldType(module, fieldName); final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName)); dm_watchField(fieldName, new Runnable() { public void run() { try { Object o = get(module, fieldName); value.set(o); ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting \" + fi..."; } }); value.onChange(new Runnable() { public void run() { try { module.setField(fieldName, value.get()); ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting 2 \" + ..."; } }); return value; } finally { _close(__2); } } finally { unlock(__0); } } static public SimpleLiveValue dm_fieldLiveValue(String fieldName, DynModule module) { return dm_fieldLiveValue(module, fieldName); } static public boolean isLetter(char c) { return Character.isLetter(c); } static public double elapsedMinutes_timestamp(long time) { return toMinutes(now() - time); } static public void toggleAlwaysOnTop(Window frame) { if (frame == null) return; { swing(() -> { frame.setAlwaysOnTop(!frame.isAlwaysOnTop()); }); } } static public String percentRatioStrOneDigit(double x) { return percentRatioStrOneDigit(x, 1); } static public String percentRatioStrOneDigit(double x, double y) { return formatDouble1(doublePercentRatio(x, y)) + " %"; } static public String ymd() { return ymd(now()); } static public String ymd(long now) { return year(now) + formatInt(month(now), 2) + formatInt(dayOfMonth(now), 2); } static public String ymd(long now, TimeZone tz) { return year(now, tz) + formatInt(month(now, tz), 2) + formatInt(dayOfMonth(now, tz), 2); } static public Class veryQuickJava_finish(String src, List libs) { libs = cloneList(libs); src = findTranslators2(src, libs); String dehlibs = join(" ", libs); File bytecode = null; bytecode = javaCompile_overInternalBot(src, dehlibs); return hotwireCore(concatLists(ll(bytecode), loadLibraries(libs))); } static public List findAllFiles_noDirs(List dirs) { return findAllFiles_noDirs(asObjectArray(dirs)); } static public List findAllFiles_noDirs(Object... dirs) { List l = new ArrayList(); for (Object dir : dirs) { ping(); if (dir instanceof String && ((String) dir).endsWith("/.")) { for (File f : listFiles(dropSuffix("/.", ((String) dir)))) { ping(); if (f.isFile()) l.add(f); } } else findAllFiles_noDirs_impl(toFile(dir), l); } return l; } static public void findAllFiles_noDirs_impl(File dir, List l) { for (File f : listFiles(dir)) { ping(); if (f.isDirectory()) findAllFiles_noDirs_impl(f, l); else l.add(f); } } static public Object[] toObjectArray(Collection c) { return toObjectArray((Iterable) c); } static public Object[] toObjectArray(Iterable c) { List l = asList(c); return l.toArray(new Object[l.size()]); } static public double nanoSecondsToSeconds(double nanos) { return nanos * 1e-9; } static public Dimension getScreenSize() { return Toolkit.getDefaultToolkit().getScreenSize(); } static public Dimension getScreenSize(int iScreen) { return toDimension(screenBounds(iScreen).widthAndHeight()); } static public ImageSurface imageSurface(BufferedImage img) { return swingNu(ImageSurface.class, img); } static public ImageSurface imageSurface(MakesBufferedImage img) { return swingNu(ImageSurface.class, img); } static public ImageSurface imageSurface() { return swingNu(ImageSurface.class); } static public Rect rectFromPoints(int x1, int y1, int x2, int y2) { return pointsRect(x1, y1, x2, y2); } static public Rect rectFromPoints(Pt a, Pt b) { return pointsRect(a.x, a.y, b.x, b.y); } static public Runnable runnableThread(final Runnable r) { return new Runnable() { public void run() { try { startThread(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "startThread(r)"; } }; } static public String addPrefixIfNotEmpty(String prefix, String s) { return empty(s) ? "" : prefix + s; } static public A toolTip(A c, final Object toolTip) { return setToolTipText(c, toolTip); } static public A toolTip(Object toolTip, A c) { return setToolTipText(toolTip, c); } static public String getLine(String s, int lineNr) { return safeGet(toLines(s), lineNr - 1); } static public Class hotwireOnce(String programID) { return hotwireCached(programID, false); } static public String fromUtf8(byte[] bytes) { try { return bytes == null ? null : new String(bytes, utf8charset()); } catch (Exception __e) { throw rethrow(__e); } } static public String firstToUpper(String s) { if (empty(s)) return s; return Character.toUpperCase(s.charAt(0)) + s.substring(1); } static public List allScreenBounds() { return map(__89 -> screenBounds(__89), screenDevices()); } static public String standardCredentialsPass() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass")))); } static public void rangeCheck(int i, int n) { if (i < 0 || i >= n) throw fail("Range check fail: " + i + "/" + n); } static public void rangeCheck(long i, long n) { if (i < 0 || i >= n) throw fail("Range check fail: " + i + "/" + n); } static public String compilerBotDestDirSubName() { return "JavaX-Caches/Compilations"; } static public HashMap findClass_fullName_cache = new HashMap(); static public Class findClass_fullName(String name) { synchronized (findClass_fullName_cache) { if (findClass_fullName_cache.containsKey(name)) return findClass_fullName_cache.get(name); Class c; try { c = Class.forName(name); } catch (ClassNotFoundException e) { c = null; } findClass_fullName_cache.put(name, c); return c; } } static public Runnable rCallOnSelectedListItem(final JList list, final Object action) { return new Runnable() { public void run() { try { pcallF(action, getSelectedItem(list)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, getSelectedItem(list))"; } }; } static public int withBottomMargin_defaultWidth = 6; static public JPanel withBottomMargin(Swingable c) { return withBottomMargin(toComponent(c)); } static public JPanel withBottomMargin(Component c) { return withBottomMargin(withBottomMargin_defaultWidth, c); } static public JPanel withBottomMargin(int w, Swingable c) { return withBottomMargin(w, toComponent(c)); } static public JPanel withBottomMargin(int w, Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createEmptyBorder(0, 0, w, 0)); p.add(c); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat..."; } }); } static public Font typeWriterFont() { return typeWriterFont(iround(14 * getSwingFontScale())); } static public Font typeWriterFont(int size) { return new Font(localCourierFontName(), Font.PLAIN, size); } static public A typeWriterFont(A c) { return withTypeWriterFont(c); } static public List> hotwire_classes = synchroList(); static public Class hotwireDependent(String src) { Class c = hotwire(src); makeDependent(c); return c; } static public File javaCompile_overInternalBot(String src) { return javaCompile_overInternalBot(src, ""); } static synchronized public File javaCompile_overInternalBot(String src, String dehlibs) { return CompilerBot.compile(src, dehlibs); } static public AutoCloseable tempLoadingAnim(String msg) { return tempDisposeWindow(loadingAnim(msg)); } static public void removeMouseAdapter(Component c, MouseAdapter a) { if (c != null && a != null) { swing(() -> { c.removeMouseListener(a); c.removeMouseMotionListener(a); }); } } static public A disposeWindowAfter(int delay, final A w) { if (w != null) swingLater(delay, new Runnable() { public void run() { try { w.dispose(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "w.dispose();"; } }); return w; } static public A disposeWindowAfter(A w, double seconds) { return disposeWindowAfter(toMS_int(seconds), w); } static public A disposeWindowAfter(double seconds, A w) { return disposeWindowAfter(w, seconds); } static public int indexOfNonDigit(String s) { int n = l(s); for (int i = 0; i < n; i++) if (!isDigit(s.charAt(i))) return i; return -1; } static public List tok_combineCurlyBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eq(t, "{")) { int j = findEndOfCurlyBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } static public String hms() { return hms(now()); } static public String hms(long time) { return new SimpleDateFormat("HHmmss").format(time); } static public List> mapTwoLevelsDown(F1 f, Iterable> l) { List> out = new ArrayList(); if (l != null) for (List x : l) out.add(map(f, x)); return out; } static public List> mapTwoLevelsDown(IF1 f, Iterable> l) { List> out = new ArrayList(); if (l != null) for (List x : l) out.add(map(f, x)); return out; } static public void copyLocalLog(Object src, Object dest) { Object log = getOpt(src, "local_log"); if (log != null) setOpt(dest, "local_log", local_log); } static public int compareWithComparator(Comparator comparator, A a, A b) { return comparator == null ? cmp(a, b) : comparator.compare(a, b); } static public int tok_findEndOfMethodDecl(List tok, int i) { i = tok_findEndOfMethodHeader(tok, i); return findEndOfBlock(tok, i); } static public JScrollPane jscroll_centered(Component c) { return c instanceof JScrollPane ? ((JScrollPane) c) : jscroll(jFullCenter(c)); } static public Complex complex(double re, double im) { return new Complex(re, im); } static public Complex complex(double re) { return new Complex(re, 0.0); } static public Complex complex(double[] reIm) { if (empty(reIm)) return null; if (l(reIm) != 2) throw fail("Need 2 doubles to make complex number"); return complex(reIm[0], reIm[1]); } static public TreeMap hotwireCached_cache = new TreeMap(); static public Lock hotwireCached_lock = lock(); static public Class hotwireCached(String programID) { return hotwireCached(programID, true); } static public Class hotwireCached(String programID, boolean runMain) { return hotwireCached(programID, runMain, false); } static public Class hotwireCached(String programID, boolean runMain, boolean dependent) { Lock __0 = hotwireCached_lock; lock(__0); try { programID = formatSnippetID(programID); Class c = hotwireCached_cache.get(programID); if (c == null) { c = hotwire(programID); if (dependent) makeDependent(c); if (runMain) callMain(c); hotwireCached_cache.put(programID, c); } return c; } finally { unlock(__0); } } public static boolean isWindows() { return System.getProperty("os.name").contains("Windows"); } static public int rectArea(Rect r) { return r == null ? 0 : r.w * r.h; } static public String bashQuote(String text) { if (text == null) return null; return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r") + "\""; } static public String bashQuote(File f) { return bashQuote(f.getAbsolutePath()); } static public String tok_firstClassName(List tok) { int i = jfind(tok, "class "); return i < 0 ? null : tok.get(i + 2); } static public File parentFile(File f) { return dirOfFile(f); } static public void intToBytes_inArray_littleEndian(int i, byte[] array, int idx) { array[idx] = (byte) i; array[idx + 1] = (byte) (i >>> 8); array[idx + 2] = (byte) (i >>> 16); array[idx + 3] = (byte) (i >>> 24); } static public String dropSuffixIC(String suffix, String s) { return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } static public int roundToInt(double d) { return (int) Math.round(d); } static public A evalInQ(Q q, IF0 f) { return evalInQ(q, if0ToF0(f)); } static public A evalInQ(Q q, F0 f) { if (isInQ(q)) return callF(f); final Var> var = new Var(); q.add(new Runnable() { public void run() { try { try { var.set(eitherA(callF(f))); } catch (Throwable e) { var.set(eitherB(e)); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n var.set(eitherA(callF(f)));\r\n } catch (Throwable e) {\r\n ..."; } }); return returnOrThrow_either(waitForVarToBeNotNull(var)); } static public List regexpExtractAll(String pat, String s) { if (s == null) return null; Matcher m = regexpMatcher(pat, s); List out = new ArrayList(); while (m.find()) out.add(m.group()); return out; } static public AutoCloseable vmBus_addListener_basic(String msg, Object listener) { Map map = vm_busListenersByMessage_live(); synchronized (map) { Set listeners = map.get(msg); if (listeners == null) map.put(msg, listeners = syncIdentityHashSet()); return tempAdd(listeners, listener); } } static public ArrayList cloneListSynchronizingOn(Collection l, Object mutex) { if (l == null) return new ArrayList(); synchronized (mutex) { return new ArrayList(l); } } static public Map synchroLinkedHashMap() { return synchronizedMap(new LinkedHashMap()); } static public JWindow showInTopRightCorner(Component c) { return swing(() -> { JWindow w = new JWindow(); w.add(c); w.pack(); moveToTopRightCorner(w); w.setVisible(true); return w; }); } static public byte[] intListToByteArray_littleEndian(List l) { if (l == null) return null; int n1 = l(l), n = n1 * 4; byte[] a = new byte[n]; for (int i = 0; i < n1; i++) intToBytes_inArray_littleEndian(l.get(i), a, i * 4); return a; } static public void listSet(List l, int i, A a, A emptyElement) { if (i < 0) return; while (i >= l(l)) l.add(emptyElement); l.set(i, a); } static public void listSet(List l, int i, A a) { listSet(l, i, a, null); } static public JComponent getTitlePaneComponent(RootPaneContainer window) { if (window instanceof JInternalFrame) return getInternalFrameTitlePaneComponent((JInternalFrame) window); if (!substanceLookAndFeelEnabled() || window == null) return null; JRootPane rootPane = window.getRootPane(); if (rootPane != null) { Object ui = rootPane.getUI(); return (JComponent) call(ui, "getTitlePane"); } return null; } static public void deleteDirectory(File dir) { deleteDirectory(dir, false, false); } static public void deleteDirectory(File dir, boolean verbose, boolean testRun) { deleteAllFilesInDirectory(dir, verbose, testRun); if (verbose) print((testRun ? "Would delete " : "Deleting ") + dir.getAbsolutePath()); if (!testRun) dir.delete(); } static public int poorMansProfiling_defaultInterval() { return 25; } static public void cancelTimers(Collection timers) { for (Object timer : timers) cancelTimer(timer); } static public int screenWidth() { return getScreenWidth(); } static public int screenWidth(int iDevice) { return screenBounds(iDevice).getWidth(); } static public String hfulltag(String tag) { return hfulltag(tag, ""); } static public String hfulltag(String tag, Object contents, Object... params) { return hopeningTag(tag, params) + str(contents) + ""; } static public double[] takeFirstOfDoubleArray(double[] b, int n) { return subDoubleArray(b, 0, n); } static public double[] takeFirstOfDoubleArray(int n, double[] b) { return takeFirstOfDoubleArray(b, n); } static public void showConsole() { callOpt(get(javax(), "console"), "showConsole"); } static public List splitAt(String s, String splitter) { if (empty(splitter)) return null; List parts = new ArrayList(); int i = 0; if (s != null) while (i < l(s)) { int j = indexOf(s, splitter, i); if (j < 0) j = l(s); parts.add(substring(s, i, j)); i = j + l(splitter); } return parts; } static public String dropSuffixIgnoreCase(String suffix, String s) { return ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } static public boolean isLowerCase(char c) { return Character.isLowerCase(c); } static public JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) { return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane"); } static public Rect toRect_floor(DoubleRect r) { if (r == null) return null; int x = ifloor(r.x), y = ifloor(r.y); return new Rect(x, y, ifloor(r.x2()) - x, ifloor(r.y2()) - y); } static public F1 toF1(final Object f) { return functionToF1(f); } static public String htmlencode2(String s) { return htmlencode_noQuotes(s); } static public int[] subIntArray(int[] b, int start) { return subIntArray(b, start, l(b)); } static public int[] subIntArray(int[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new int[0]; int[] x = new int[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public int[] subIntArray(int[] a, IntRange r) { return r == null ? null : subIntArray(a, r.start, r.end); } static public Object endMarker() { return iteratorFromFunction_endMarker; } static public void onFirstResize(Component c, Object r) { onFirstResize(c, toRunnable(r)); } static public void onFirstResize(Component c, Runnable r) { if (c != null && r != null) { swing(() -> { c.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { c.removeComponentListener(this); pcallF(r); } }); }); } } static public void duplicateThisProgram() { nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs")))); } static public JComponent gazelle_wavySpacer() { return gazelle_wavySpacer(gazelle_color1(), gazelle_color2()); } static public JComponent gazelle_wavySpacer(Color color1, Color color2) { return jMinWidth(30, swing(() -> new JComponent() { public void paintComponent(Graphics g) { int w = getWidth(), h = getHeight(); var points = graphAsPolygon(x -> 1 - sineSigmoid(x), w, h); fillRect(((Graphics2D) g), 0, 0, w, h, color2); fillPrecisePolygon(((Graphics2D) g), points, color1); } })); } static public String getCanonicalPath(File f) { try { return f == null ? null : f.getCanonicalPath(); } catch (Exception __e) { throw rethrow(__e); } } static public String getCanonicalPath(String path) { return getCanonicalPath(newFile(path)); } static public Object iteratorFromFunction_endMarker = new Object(); static public IterableIterator iteratorFromFunction_withEndMarker(final Object f) { class IFF extends IterableIterator { public A a; public boolean have, done; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; have = false; return _a; } public void getNext() { if (done || have) return; Object o = callF(f); if (o == iteratorFromFunction_endMarker) { done = true; return; } a = (A) o; have = true; } } ; return new IFF(); } static public IterableIterator iteratorFromFunction_withEndMarker(final F0 f) { return iteratorFromFunction_withEndMarker_f0(f); } static public String appendSlash(String s) { return addSlash(s); } static public void callOnLoadMethods(Class c) { for (String name : methodsStartingWith(c, "_onLoad_")) pcallOpt(c, name); pcallOpt(c, "_onLoad"); } static public F0 dm_rEnter() { return dm_rEnter(dm_current()); } static public F0 dm_rEnter(DynModule mod) { return mod == null ? null : new F0() { public AutoCloseable get() { try { return mod.enter(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return mod.enter();"; } }; } static public Runnable dm_rEnter(Runnable r) { return dm_rEnter(dm_current(), r); } static public Runnable dm_rEnter(DynModule mod, Runnable r) { return mod == null || r == null ? r : new Runnable() { public void run() { try { AutoCloseable __1 = mod.enter(); try { r.run(); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp mod.enter(); r.run();"; } }; } static public List reTok(List tok) { replaceCollection(tok, javaTok(tok)); return tok; } static public List reTok(List tok, int i) { return reTok(tok, i, i + 1); } static public List reTok(List tok, int i, int j) { i = max(i & ~1, 0); j = min(l(tok), j | 1); if (i >= j) return tok; List t = javaTok(joinSubList(tok, i, j)); replaceListPart(tok, i, j, t); return tok; } static public List reTok(List tok, IntRange r) { if (r != null) reTok(tok, r.start, r.end); return tok; } static public boolean isOneOfSingleChars(String s, char... chars) { if (l(s) != 1) return false; char real = s.charAt(0); for (char c : unnullForIteration(chars)) if (real == c) return true; return false; } static public boolean startsWithAny(String a, Collection b) { for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix)) return true; return false; } static public boolean startsWithAny(String a, String... b) { if (b != null) for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix)) return true; return false; } static public boolean startsWithAny(String a, Collection b, Matches m) { for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix, m)) return true; return false; } static public boolean getServerTranspiled2_allowLocalFallback = true, getServerTranspiled2_localFallbackVerbose = true; static public Map getServerTranspiled2_tempCache; static public String getServerTranspiled2(String id) { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.getTranspiled(id); return getServerTranspiled2_noResourceLoader(id); } static public String getServerTranspiled2_noResourceLoader(String id) { id = fsIOpt(id); String transpiled = mapGet(getServerTranspiled2_tempCache, id); if (transpiled != null) return transpiled; transpiled = loadCachedTranspilation(id); String md5 = null; if (machineIsOffline() || isOfflineMode() || isLocalSnippet(id)) return transpiled; if (transpiled != null) md5 = md5(transpiled); String transpiledSrc; try { transpiledSrc = getServerTranspiled(formatSnippetID(id), md5); } catch (Throwable e) { if (!getServerTranspiled2_allowLocalFallback) rethrow(e); printExceptionShort(e); if (getServerTranspiled2_localFallbackVerbose) print("Fallback to local code"); return transpiled; } if (eq(transpiledSrc, "SAME")) { if (!isTrue(loadPage_silent.get())) printWithMS("SAME"); return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiled); } return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiledSrc); } static public boolean loadLibraryOrSrcLib_srcLibsEnabled = true; static public ThreadLocal> loadLibraryOrSrcLib_tempCache = new ThreadLocal(); static public ThreadLocal> loadLibraryOrSrcLib_compiler = new ThreadLocal(); static public File loadLibraryOrSrcLib(String snippetID) { return loadLibraryOrSrcLib(snippetID, loadLibraryOrSrcLib_compiler.get()); } static public File loadLibraryOrSrcLib(String snippetID, IF1 compiler) { try { vmBus_send("loadLibraryOrSrcLib", snippetID); long id = parseSnippetID(snippetID); if (loadLibraryOrSrcLib_tempCache.get() != null) { File f = loadLibraryOrSrcLib_tempCache.get().get(id); if (f != null) { print(snippetID + " from tempCache: " + f); return f; } } boolean srcLib = loadLibraryOrSrcLib_srcLibsEnabled && isMarkedAsSrcLib(snippetID); if (srcLib) { print(snippetID + " marked as src lib, compiling"); File f; if (compiler != null) f = compiler.get(snippetID); else f = pairA(hotwire_compile(snippetID)); print("Src lib: " + f); mapPut(loadLibraryOrSrcLib_tempCache.get(), id, f); return f; } File f = DiskSnippetCache_getLibrary(id); if (fileSize(f) != 0) return f; try { print("Trying " + snippetID + " as binary library"); return loadDataSnippetToFile(snippetID); } catch (Throwable e) { if (loadLibraryOrSrcLib_srcLibsEnabled) { print("Trying " + snippetID + " as src lib"); if (nempty(loadSnippet(snippetID))) { print("Is src lib."); markAsSrcLib(snippetID); return pairA(hotwire_compile(snippetID)); } } throw rethrow(e); } } catch (Exception __e) { throw rethrow(__e); } } static public int fullAlphaMask() { return 0xFF000000; } static public List findMainClass(List tok) { for (List c : reversedList(allClasses(tok))) { String name = getClassDeclarationName(c); if (eq(name, "main") || name.startsWith("x")) return c; } return findBlock("m {", tok); } static public String toString(Object o) { return strOrNull(o); } static public Object callCalc(Object o, Object... args) { return call(o, "calc", args); } static public void saveTranspiledCode(String progID, String code) { File dir = getCodeProgramDir(progID); new File(dir, "Transpilation").delete(); saveGZTextFile(new File(dir, "Transpilation.gz"), code); } static public Matrix> matrixToMNGrid(Matrix m, int cols, int rows) { if (m == null) return null; cols = clamp(cols, 1, m.getWidth()); rows = clamp(rows, 1, m.getHeight()); List> rects = gridOfRects3(m.getWidth(), m.getHeight(), cols, rows); List>> matrices = mapLevelTwo(r -> new SubMatrix(m, r), rects); return listOfListsToMatrix(matrices); } static public List colToList(Matrix m, int x) { if (m == null) return null; rangeCheck(x, m.getWidth()); int h = m.getHeight(); return new RandomAccessAbstractList() { public int size() { return h; } public A get(int y) { return m.get(x, y); } public A set(int y, A val) { A old = m.get(x, y); m.set(x, y, val); return old; } }; } static public class mapI_if1_It extends IterableIterator { public IF1 f; public Iterator i; public mapI_if1_It() { } public mapI_if1_It(IF1 f, Iterator i) { this.i = i; this.f = f; } public boolean hasNext() { return i.hasNext(); } public B next() { return f.get(i.next()); } public String toString() { return formatFunctionCall("mapI_if1", f, i); } } static public IterableIterator mapI_if1(IF1 f, Iterable i) { return new mapI_if1_It(f, i.iterator()); } static public IterableIterator mapI_if1(Iterable i, IF1 f) { return mapI_if1(f, i); } static public boolean showAnimationInTopRightCorner_alwaysOnTop = true; static public boolean showAnimationInTopRightCorner_on = true; static public JWindow showAnimationInTopRightCorner(String imageID, String text) { if (isHeadless() || !showAnimationInTopRightCorner_on) return null; return showAnimationInTopRightCorner(imageIcon(imageID), text); } static public JWindow showAnimationInTopRightCorner(final Image image, final String text) { if (image == null || isHeadless() || !showAnimationInTopRightCorner_on) return null; return showAnimationInTopRightCorner(imageIcon(image), text); } static public JWindow showAnimationInTopRightCorner(final ImageIcon imageIcon, final String text) { if (isHeadless() || !showAnimationInTopRightCorner_on) return null; return (JWindow) swingAndWait(new F0() { public Object get() { try { JLabel label = new JLabel(imageIcon); if (nempty(text)) { label.setText(text); label.setVerticalTextPosition(SwingConstants.BOTTOM); label.setHorizontalTextPosition(SwingConstants.CENTER); } final JWindow window = showInTopRightCorner(label); onClick(label, new Runnable() { public void run() { try { window.dispose(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispose()"; } }); if (showAnimationInTopRightCorner_alwaysOnTop) window.setAlwaysOnTop(true); return window; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JLabel label = new JLabel(imageIcon);\r\n if (nempty(text)) {\r\n label.s..."; } }); } static public JWindow showAnimationInTopRightCorner(final String imageID) { return showAnimationInTopRightCorner(imageID, ""); } static public JWindow showAnimationInTopRightCorner(String imageID, double seconds) { return showAnimationInTopRightCorner(imageID, "", seconds); } static public JWindow showAnimationInTopRightCorner(String imageID, String text, double seconds) { if (isHeadless()) return null; return disposeWindowAfter(iround(seconds * 1000), showAnimationInTopRightCorner(imageID, text)); } static public JWindow showAnimationInTopRightCorner(BufferedImage img, String text, double seconds) { return disposeWindowAfter(iround(seconds * 1000), showAnimationInTopRightCorner(img, text)); } static public BigInteger div(BigInteger a, BigInteger b) { return a.divide(b); } static public BigInteger div(BigInteger a, int b) { return a.divide(bigint(b)); } static public Complex div(Complex a, double b) { return new Complex(a.re / b, a.im / b); } static public double div(double a, double b) { return a / b; } static public double div(double a, int b) { return a / b; } static public long div(long a, long b) { return a / b; } static public int div(int a, int b) { return a / b; } static public void addComponentsFirst(Container c, Component... l) { containerAddFirst(c, l); } static public String squareBracket(String s) { return "[" + s + "]"; } static public File makeFileNameUnique_beforeExtension(File f) { File orig = f; int n = 0; while (f.exists()) f = appendToFileBaseName(orig, "." + ++n); return f; } static public void stepAllWithTimeout(double timeout, Steppable s) { if (s == null) return; long endTime = sysNow() + toMS(timeout); do { ping(); } while (s.step() && sysNow() < endTime); } static public boolean isQuoted(String s) { if (isNormalQuoted(s)) return true; return isMultilineQuoted(s); } static public boolean tok_isJavaxMetaCommandLeftOf(List tok, int i) { int j = i - 2 * 4 - 1; if (j >= 0 && jfind(subList(tok, j, i), "set flag .") == 1) return true; return false; } static public String getProgramTitle() { return getProgramName(); } static public boolean checkTokCondition(Object condition, List tok, int i) { if (condition instanceof TokCondition) return ((TokCondition) condition).get(tok, i); return checkCondition(condition, tok, i); } static public void fixACCInClassLoader(Object o) { } static public String formatLocalDateWithSeconds(long time) { return localDateWithSeconds(time); } static public String formatLocalDateWithSeconds() { return localDateWithSeconds(); } static public boolean isLocalSnippetID(String snippetID) { return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID)); } static public boolean isLocalSnippetID(long snippetID) { return snippetID >= 1000 && snippetID <= 9999; } static public A applyDefaultMargin(final A c) { if (c != null) { swing(() -> { c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth)); }); } return c; } static public void removeFromParent(final Component c) { if (c != null) { swing(() -> { Container cc = c.getParent(); if (cc != null) { cc.remove(c); revalidate(cc); } }); } } static public int month() { return localMonth(); } static public int month(Timestamp now) { return localMonth(toLong(now)); } static public int month(long now) { return localMonth(now); } static public int month(long now, TimeZone tz) { return parseInt(simpleDateFormat("M", tz).format(now)); } static public boolean containsSpaces(String s) { return indexOf(s, ' ') >= 0; } static public boolean renameFile(File a, File b) { mkdirsForFile(b); return a.renameTo(b); } static public boolean renameFile(File a, String newName) { return renameFile(a, fileInSameDir(a, newName)); } static public boolean isDigit(char c) { return Character.isDigit(c); } static public String flexLines(Object... l) { return lines(flattenIterablesAndArrays(ll(l))); } static public boolean eitherIsA(Either e) { return e != null && e.isA(); } static public Object[] unrollParams(Object[] params) { if (l(params) == 1 && params[0] instanceof Map) return mapToParams((Map) params[0]); return params; } static public boolean eitherIsB(Either e) { return e != null && e.isB(); } static public List mapQuickEval_javaExpr(Iterable l) { return map(e -> e.quickEval(), l); } static public Object dm_callOS(String functionName, Object... args) { return call(dm_os(), functionName, args); } static public String tok_addReturn(List tok) { if (tok_shouldAddReturn(tok)) { tokPrepend(tok, 1, "return "); tokAppend(tok, l(tok) - 2, ";"); } return join(tok); } static public String tok_addReturn(String s) { return tok_addReturn(javaTok(s)); } static public String loadTextFileFromZip(File inZip, String fileName) { return loadTextFileFromZipFile(inZip, fileName); } static public void setOptIfNotNull(Object o, String field, Object value) { if (value != null) setOpt(o, field, value); } static public Object dm_current_generic_mandatory() { return dm_current_mandatory_generic(); } static public boolean regionMatches(String a, int offsetA, String b, int offsetB, int len) { return a != null && b != null && a.regionMatches(offsetA, b, offsetB, len); } static public boolean regionMatches(String a, int offsetA, String b) { return regionMatches(a, offsetA, b, 0, l(b)); } static public String naiveQuote(String s) { return simpleQuote(s); } static public void warnIfOddCount(Object... list) { if (odd(l(list))) printStackTrace("Odd list size: " + list); } static public int snippetType_javaxModule() { return 54; } static public void logQuoted(String logFile, String line) { logQuoted(getProgramFile(logFile), line); } static public void logQuoted(File logFile, String line) { appendToFile(logFile, quote(line) + "\n"); } static public WithSideValue withSideValue(A sideValue, B value) { return new WithSideValue(sideValue, value); } static public RandomAccessFile newRandomAccessFile(File path, String mode) { try { boolean forWrite = mode.indexOf('w') >= 0; if (forWrite) mkdirsForFile(path); RandomAccessFile f = new RandomAccessFile(path, mode); callJavaX("registerIO", f, path, forWrite); return f; } catch (Exception __e) { throw rethrow(__e); } } static public Boolean grabbableIntPixels_succeeded; static public boolean grabbableIntPixels_enable = true; static public GrabbableIntPixels grabbableIntPixels(BufferedImage img) { if (img == null || !grabbableIntPixels_enable) return null; try { var result = grabbableIntPixels_impl(img); grabbableIntPixels_succeeded = result != null; return result; } catch (Throwable _e) { grabbableIntPixels_succeeded = false; throw rethrow(_e); } } static public GrabbableIntPixels grabbableIntPixels_impl(BufferedImage img) { Raster raster = img.getRaster(); SampleModel _sampleModel = raster.getSampleModel(); if (!(_sampleModel instanceof SinglePixelPackedSampleModel)) return null; SinglePixelPackedSampleModel sampleModel = (SinglePixelPackedSampleModel) _sampleModel; DataBufferInt dataBuffer = (DataBufferInt) (raster.getDataBuffer()); assertEquals(1, dataBuffer.getNumBanks()); assertEquals(DataBuffer.TYPE_INT, dataBuffer.getDataType()); int w = img.getWidth(), h = img.getHeight(); int scanlineStride = sampleModel.getScanlineStride(); int[] pixels = dataBuffer.getData(); int offset = dataBuffer.getOffset(); int translateX = raster.getSampleModelTranslateX(); int translateY = raster.getSampleModelTranslateY(); offset += -translateX - translateY * scanlineStride; return new GrabbableIntPixels(pixels, w, h, offset, scanlineStride); } static public double doublePercentRatio(double x, double y) { return doubleRatio(x, y) * 100; } static public double doublePercentRatio(Seconds x, Seconds y) { return doublePercentRatio(x.get(), y.get()); } static public Map synchronizedMRUCache(int maxSize) { return synchroMap(new MRUCache(maxSize)); } static public List loadLibraries(List snippetIDs) { return map(__90 -> loadLibrary(__90), snippetIDs); } static public void logQuotedWithDate(String s) { logQuotedWithTime(s); } static public void logQuotedWithDate(String logFile, String s) { logQuotedWithTime(logFile, s); } static public void logQuotedWithDate(File logFile, String s) { logQuotedWithTime(logFile, s); } static public Object[] asObjectArray(Collection l) { return toObjectArray(l); } static public File printFileInfo(File f) { return printFileInfo("", f); } static public File printFileInfo(String s, File f) { print(s, renderFileInfo(f)); return f; } static public JComponent dm_getVisualization(Object module) { return (JComponent) callOpt(dm_getStem(module), "vis"); } static public JComponent dm_getVisualization() { return dm_getVisualization(dm_current_mandatory_generic()); } static public String padLeft(String s, char c, int n) { return rep(c, n - l(s)) + s; } static public String padLeft(String s, int n) { return padLeft(s, ' ', n); } static public int snippetType_javaxSource() { return 34; } static public Object dm_callOSOpt(String functionName, Object... args) { return callOpt(dm_os(), functionName, args); } static public boolean interruptThread_verbose = false; static public void interruptThread(Thread t) { if (t == null) return; if (interruptThread_verbose) print("Interrupting thread " + t); vm_threadInterruptionReasonsMap().put(t, getStackTrace()); t.interrupt(); URLConnection c = (URLConnection) (vm_generalSubMap("URLConnection per thread").get(t)); if (c != null) { try { print("Closing URLConnection of interrupted thread."); call(c, "disconnect"); } catch (Throwable __e) { pcallFail(__e); } } } static public A bindLiveValueListenerToComponent(A component, IHasChangeListeners lv, Runnable listener) { return bindHasChangeListenersToComponent(component, lv, listener); } static public void setOptAll(Object o, Map fields) { if (fields == null) return; for (String field : keys(fields)) setOpt(o, field, fields.get(field)); } static public void setOptAll(Object o, Object... values) { warnIfOddCount(values); for (int i = 0; i + 1 < l(values); i += 2) { String field = (String) values[i]; Object value = values[i + 1]; setOpt(o, field, value); } } static public int screenHeight() { return getScreenHeight(); } static public int getPreferredWidth(Component c) { return preferredWidth(c); } static public boolean isOfflineMode() { return eq("1", trim(loadProgramTextFile("#1005806", "offline-mode"))); } static public Rect screenBounds(GraphicsDevice screen) { return screen == null ? null : toRect(screen.getDefaultConfiguration().getBounds()); } static public Rect screenBounds(int iScreen) { return screenBounds(get(screenDevices(), iScreen)); } static public Map myFrames_list = weakHashMap(); static public List myFrames() { return swing(new F0>() { public List get() { try { return keysList(myFrames_list); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return keysList(myFrames_list);"; } }); } static public String callStringifier(Object stringifier, Object o) { return stringifier != null ? str(callF(stringifier, o)) : str(o); } static public void metaSet(IMeta o, Object key, Object value) { metaMapPut(o, key, value); } static public void metaSet(Object o, Object key, Object value) { metaMapPut(o, key, value); } static public int calculateLengthOfFunctionCall(String fname, int... argLengths) { return l(fname) + 2 + intSum(argLengths); } static public String loadSnippetSilently(Snippet s) { return loadSnippetQuietly(s); } static public String loadSnippetSilently(String snippetID) { return loadSnippetQuietly(snippetID); } static public File touchFile(File file) { try { closeRandomAccessFile(newRandomAccessFile(mkdirsForFile(file), "rw")); return file; } catch (Exception __e) { throw rethrow(__e); } } static public Object[] paramsWithout(Object[] a1, Object... keys) { if (l(a1) == 1 && a1[0] instanceof Map) return new Object[] { mapMinus((Map) a1[0], keys) }; Set set = lithashset(keys); List l = new ArrayList(); int n = l(a1); for (int i = 0; i < n; i += 2) if (i == n - 1) l.add(a1[i]); else if (!set.contains(a1[i])) { l.add(a1[i]); l.add(a1[i + 1]); } return toObjectArray(l); } static public Rectangle toRectangle(Rect r) { return r == null ? null : r.getRectangle(); } static public List allMethodNames(Object o) { Class c = _getClass(o); TreeSet names = new TreeSet(); while (c != null) { for (Method m : c.getDeclaredMethods()) names.add(m.getName()); c = c.getSuperclass(); } return asList(names); } static public boolean saveTextFileIfChanged(File f, String contents) { return saveTextFileIfDifferent(f, contents); } static public Throwable printStackTrace2(Throwable e) { print(getStackTrace2(e)); return e; } static public void printStackTrace2() { printStackTrace2(new Throwable()); } static public void printStackTrace2(String msg) { printStackTrace2(new Throwable(msg)); } static public JFrame consoleFrame() { return (JFrame) getOpt(get(getJavaX(), "console"), "frame"); } static public JECompressionRegime jeCompressionRegime() { return new JECompressionRegime(); } static public int widthForHeight(int w, int h, int newHeight) { return iround(newHeight * doubleRatio(w, h)); } static public int widthForHeight(double w, double h, int newHeight) { return iround(newHeight * doubleRatio(w, h)); } static public int widthForHeight(WidthAndHeight img, int newHeight) { return widthForHeight(img.getWidth(), img.getHeight(), newHeight); } static public Class hotwireCore(List files) { try { JavaXClassLoader classLoader = hotwire_makeClassLoader(files); Class theClass = classLoader.loadClass("main"); setOpt(theClass, "__javax", getJavaX()); if (getOpt(theClass, "programID") == null) setOpt(theClass, "programID", "#3999999"); if (!_inCore()) hotwire_copyOver(theClass); return theClass; } catch (Exception __e) { throw rethrow(__e); } } static public A returnOrThrow_either(Either e) { if (isEitherB(e)) throw rethrow(e.b()); return eitherAOpt(e); } static public int tok_findEndOfBlock(List tok, int i) { if (tok instanceof IContentsIndexedList2) return tok_findEndOfBlock_IContentsIndexedList2_v2(((IContentsIndexedList2) tok), i); int j = i + 2, level = 1, n = l(tok); while (j < n) { String t = tok.get(j); if ("{".equals(t)) ++level; else if ("}".equals(t)) --level; if (level == 0) return j + 1; j += 2; } return n; } static public A centerLabel(A l) { if (l != null) l.setHorizontalAlignment(SwingConstants.CENTER); return l; } static public String nohup_sanitize(String s) { return empty(s) ? s : takeFirst(50, s.replaceAll("[^.a-zA-Z0-9\\-_]", "")); } static public File javaxCodeDir_dir; static public File javaxCodeDir() { return javaxCodeDir_dir != null ? javaxCodeDir_dir : new File(userHome(), "JavaX-Code"); } static public File javaxCodeDir(String sub) { return newFile(javaxCodeDir(), sub); } static public BufferedImage imageFromHex(int w, int h, String pixelsAsHex) { return intArrayToBufferedImage(hexToInts_dropSpaces(pixelsAsHex), w, h); } static public JLabel jLiveValueLabel(IF0WithChangeListeners var) { return jVarLabel(var); } static public AutoCloseable tempSet(Object o, final String field, Object value) { return tempSetField(o, field, value); } static public AutoCloseable combineAutoCloseables(final AutoCloseable a, final AutoCloseable b) { return a == null ? b : b == null ? a : new AutoCloseable() { public String toString() { return "pClose(a); pClose(b);"; } public void close() throws Exception { pClose(a); pClose(b); } }; } static public AutoCloseable combineAutoCloseables(AutoCloseable a, AutoCloseable b, AutoCloseable c, AutoCloseable... more) { return combineAutoCloseables(concatLists(ll(a, b, c), asList(more))); } static public AutoCloseable combineAutoCloseables(Iterable l) { return foldl(new F2() { public AutoCloseable get(AutoCloseable a, AutoCloseable b) { try { return combineAutoCloseables(a, b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "combineAutoCloseables(a,b)"; } }, null, l); } static public String systemHashCodeHex(Object o) { return intToHex(identityHashCode(o)); } static public String shortClassName_dropNumberPrefix(Object o) { return dropNumberPrefix(shortClassName(o)); } static public int findEndOfCurlyBracketPart(List cnc, int i) { int j = i + 2, level = 1; while (j < cnc.size()) { if (eq(cnc.get(j), "{")) ++level; else if (eq(cnc.get(j), "}")) --level; if (level == 0) return j + 1; ++j; } return cnc.size(); } static public int identityHashCode(Object o) { return System.identityHashCode(o); } static public void minimizeWindow(JFrame f) { if (f != null) { swing(() -> { f.setState(JFrame.ICONIFIED); }); } } static public List allClassNamesOnPath(Collection files) { List classes = new ArrayList(); for (File dir : files) classes.addAll(classNamesInJarOrDir(dir)); return classes; } static public double sqrt(double x) { return Math.sqrt(x); } static public List listFilesWithSuffix(File dir, String suffix) { List l = new ArrayList(); for (File f : listFiles(dir)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix))) l.add(f); return l; } static public List listFilesWithSuffix(String suffix, File dir) { return listFilesWithSuffix(dir, suffix); } static public void closeAllWriters(Collection l) { for (Writer w : unnull(l)) { try { w.close(); } catch (Throwable __e) { pcallFail(__e); } } } static public int globalIDLength() { return 16; } static public boolean isSubstanceLAF() { return substanceLookAndFeelEnabled(); } static public File localSnippetFile(long snippetID) { return localSnippetsDir(snippetID + ".text"); } static public File localSnippetFile(String snippetID) { return localSnippetFile(parseSnippetID(snippetID)); } static public String standardTimeZone_name = "Europe/Berlin"; static public String standardTimeZone() { return standardTimeZone_name; } static public File appendToFileBaseName(File f, String s) { return appendToFileNameBeforeExtension(f, s); } static public Set synchroLinkedHashSet() { return synchronizedSet(new CompactLinkedHashSet()); } static public JButton jbutton(String text, Runnable action) { return newButton(text, action); } static public JButton jbutton(String text, Object action) { return newButton(text, action); } static public JButton jbutton(String text) { return newButton(text, null); } static public JButton jbutton(Action action) { return swingNu(JButton.class, action); } static public JTextArea jtextarea() { return jTextArea(); } static public JTextArea jtextarea(String text) { return jTextArea(text); } static public Matrix listToMatrix_cols(int w, List data) { return listToMatrix(w, data); } static public Collection addDyn(Collection l, A a) { if (l == null) l = new ArrayList(); l.add(a); return l; } static public List addDyn(List l, A a) { if (l == null) l = new ArrayList(); l.add(a); return l; } static public A setEnabled(A c, boolean enable) { if (c != null) { swing(() -> { c.setEnabled(enable); }); } return c; } static public A setEnabled(boolean enable, A c) { return setEnabled(c, enable); } static public void setEnabled(boolean enable, JComponent... l) { for (var c : unnullForIteration(l)) setEnabled(c, enable); } static public FunctionCall functionCall(Object fname, Object... args) { return new FunctionCall(fname, args); } static public boolean isInstanceOf(Object o, Class type) { return type.isInstance(o); } static public String charToString(char c) { return String.valueOf(c); } static public String charToString(int c) { return String.valueOf((char) c); } static public boolean isMarkedAsSrcLib(String snippetID) { if (snippetID == null) return false; IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return isJavaxCompilableSnippetType(rl.getSnippetType(snippetID)); return fileExists(javaxCodeDir("srclibs/" + psI(snippetID))); } static public byte[] intListToByteArray(List l) { return intListToByteArray_littleEndian(l); } static public TimerTask timerTask(final Object r, final java.util.Timer timer) { return new TimerTask() { public void run() { if (!licensed()) timer.cancel(); else pcallF(r); } }; } static public String getFileInfoField(File f, String field) { return getOneLineFileInfoField(f, field); } static public List javaTokForStructure(String s) { return javaTok_noMLS(s); } static public boolean isCISet(Iterable l) { return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator(); } static public JPanel northAndCenter(Component n, Component c) { return centerAndNorth(c, n); } static public Matrix> matrixToMNGrid_rows(Matrix m, int rows) { if (m == null) return null; int cols = widthForHeight(m.getWidth(), m.getHeight(), rows); return matrixToMNGrid(m, cols, rows); } static public JPanel jline(final Component... components) { return swing(() -> { return new LeftAlignedLine(components); }); } static public JPanel jline(List components) { return jline(asArray(Component.class, components)); } static public ItemListener itemListener(final Object r) { return new ItemListener() { public void itemStateChanged(ItemEvent e) { pcallF(r); } }; } static public long toMS(double seconds) { return (long) (seconds * 1000); } static public long toMS(Duration d) { return d == null ? 0 : d.toMillis(); } static public void dm_pointSubmoduleToMe(Object subModule) { dm_pointSubmoduleToMe(subModule, dm_current_mandatory_generic()); } static public void dm_pointSubmoduleToMe(Object subModule, Object me) { setOpt(subModule, "dm_current_mandatory_generic_value", me); } static public void cancelTimer(javax.swing.Timer timer) { if (timer != null) timer.stop(); } static public void cancelTimer(java.util.Timer timer) { if (timer != null) timer.cancel(); } static public void cancelTimer(Object o) { if (o instanceof java.util.Timer) cancelTimer((java.util.Timer) o); else if (o instanceof javax.swing.Timer) cancelTimer((javax.swing.Timer) o); else if (o instanceof AutoCloseable) { try { ((AutoCloseable) o).close(); } catch (Throwable __e) { pcallFail(__e); } } } static public boolean isLongConstant(String s) { if (!s.endsWith("L")) return false; s = s.substring(0, l(s) - 1); return isInteger(s); } static public int bwIntegralImage_sumRect(BWIntegralImage img, int x1, int y1, int x2, int y2) { int bottomLeft = img.getIIValue(x1 - 1, y2 - 1); int bottomRight = img.getIIValue(x2 - 1, y2 - 1); int topLeft = img.getIIValue(x1 - 1, y1 - 1); int topRight = img.getIIValue(x2 - 1, y1 - 1); return bottomRight + topLeft - topRight - bottomLeft; } static public int bwIntegralImage_sumRect(IBWIntegralImage img, int x1, int y1, int x2, int y2) { int bottomLeft = img.getIIValue(x1 - 1, y2 - 1); int bottomRight = img.getIIValue(x2 - 1, y2 - 1); int topLeft = img.getIIValue(x1 - 1, y1 - 1); int topRight = img.getIIValue(x2 - 1, y1 - 1); return bottomRight + topLeft - topRight - bottomLeft; } static public double bwIntegralImage_sumRect(IBWIntegralImage img, double x1, double y1, double x2, double y2) { double bottomLeft = img.getIIValue(x1 - 1, y2 - 1); double bottomRight = img.getIIValue(x2 - 1, y2 - 1); double topLeft = img.getIIValue(x1 - 1, y1 - 1); double topRight = img.getIIValue(x2 - 1, y1 - 1); return bottomRight + topLeft - topRight - bottomLeft; } static public boolean endsWithLetter(String s) { return nempty(s) && isLetter(last(s)); } static public int intFromBytes_littleEndian_partial(byte[] a, int i) { return (ubyteToInt(i + 3 >= a.length ? 0 : a[i + 3]) << 24 | (ubyteToInt(i + 2 >= a.length ? 0 : a[i + 2]) << 16 | (ubyteToInt(i + 1 >= a.length ? 0 : a[i + 1]) << 8 | ubyteToInt(a[i])))); } static public boolean containsSpace(String s) { return containsSpaces(s); } static public Class hotwireSharingLibraries(String progID) { try { Pair p = CompilerBot.compileSnippet2(progID); File jar = p.a; assertTrue(f2s(jar), jar.isFile()); List files = ll(jar); String dehlibs = unnull(loadTextFileFromZip(jar, "libraries")); List myLibraries = myLibraryFiles(); Matcher matcher = Pattern.compile("\\d+").matcher(dehlibs); while (matcher.find()) { String libID = matcher.group(); File lib = loadLibrary(libID); if (myLibraries.contains(lib)) { } else { files.add(lib); } } JavaXClassLoaderWithParent classLoader = new JavaXClassLoaderWithParent(progID, files, myClassLoader()); return hotwire_finish(classLoader, progID, p.b); } catch (Exception __e) { throw rethrow(__e); } } static public String htmlencode_forParams_v2(String s) { if (s == null) return ""; StringBuilder out = new StringBuilder(Math.max(16, s.length())); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') { out.append("&#"); out.append((int) c); out.append(';'); } else out.append(c); } return out.toString(); } static public String forward(String bot, String msg, Object... args) { return format("please forward to bot *: *", bot, format(msg, args)); } static public Object vmBus_query(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); { var __1 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg); if (__1 != null) return __1; } return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg); } static public Object vmBus_query(String msg) { return vmBus_query(msg, (Object) null); } static public void change() { callOpt(getOptMC("mainConcepts"), "allChanged"); } static public String quoteIfNotIdentifierOrInteger(String s) { if (s == null) return null; return isJavaIdentifier(s) || isInteger(s) ? s : quote(s); } static public A assertEquals(Object x, A y) { return assertEquals("", x, y); } static public A assertEquals(String msg, Object x, A y) { if (assertVerbose()) return assertEqualsVerbose(msg, x, y); if (!(x == null ? y == null : x.equals(y))) throw fail((msg != null ? msg + ": " : "") + y + " != " + x); return y; } static public void assertEquals(Scorer scorer, Object x, Object y) { assertEquals(scorer, "", x, y); } static public void assertEquals(Scorer scorer, String msg, Object x, Object y) { if (scorer == null) { assertEquals(msg, x, y); return; } scorer.add(eq(x, y), nullIfEmpty(msg)); } static public String joinMap(Object f, Iterable l) { return join(map(f, l)); } static public String joinMap(Iterable l, Object f) { return joinMap(f, l); } static public String joinMap(Iterable l, IF1 f) { return joinMap(f, l); } static public String joinMap(A[] l, IF1 f) { return joinMap(f, l); } static public String joinMap(IF1 f, Iterable l) { return join(map(f, l)); } static public String joinMap(IF1 f, A[] l) { return join(map(f, l)); } static public String joinMap(String separator, Map map, IF2 f) { return join(separator, map(map, f)); } static public byte[] isJAR_magic = bytesFromHex("504B0304"); static public boolean isJAR(byte[] data) { return byteArrayStartsWith(data, isJAR_magic); } static public boolean isJAR(File f) { return isJAR(loadBeginningOfBinaryFile(f, l(isJAR_magic))); } static public void clearAllTokens(List tok) { for (int i = 0; i < tok.size(); i++) tok.set(i, ""); } static public void clearAllTokens(List tok, int i, int j) { for (; i < j; i++) tok.set(i, ""); } static public String programTitle() { return getProgramName(); } static public WithProbability withProbability(double probability, A a) { return new WithProbability(probability, a); } static public List> withProbability(IF1 makeProbability, Iterable l) { return map(a -> withProbability(makeProbability.get(a), a), l); } static public Path toPath(File f) { return f == null ? null : f.toPath(); } static public JTextArea jTextAreaWithUndo() { return jTextAreaWithUndo(""); } static public JTextArea jTextAreaWithUndo(final String text) { return jenableUndoRedo(swingNu(JTextArea.class, text)); } static public Dimension getPreferredSize(final Component c) { return c == null ? null : swing(new F0() { public Dimension get() { try { return c.getPreferredSize(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getPreferredSize();"; } }); } static public int[] takeFirstOfIntArray(int[] b, int n) { return subIntArray(b, 0, n); } static public int[] takeFirstOfIntArray(int n, int[] b) { return takeFirstOfIntArray(b, n); } static public String unicode_downPointingTriangle() { return charToString(0x25BC); } static public Window dm_windowIfSingleModule(Object module) { Window w = dm_window(module); return w == null || w != getWindow(dm_desktopPane()) ? w : null; } static public int backtick_exitValue; static public boolean backtick_verbose, backtick_keepScript; static public ThreadLocal backtick_scriptFile = new ThreadLocal(); static public ThreadLocal backtick_uninterruptable = new ThreadLocal(); static public boolean backtick_win_cmd = false; static public String backtick(String cmd) { try { ping(); File outFile = File.createTempFile("_backtick", ""); backtickToFile(cmd, outFile); String result = loadTextFile(outFile.getPath(), ""); if (backtick_verbose) { print("[[\n" + result + "]]"); } outFile.delete(); return result; } catch (Exception __e) { throw rethrow(__e); } } static public java.lang.Process backtickToFile(String cmd, File outFile) { try { try { java.lang.Process process = backtickToFile_noWait(cmd, outFile); process.waitFor(); backtick_exitValue = process.exitValue(); if (backtick_verbose) System.out.println("Process return code: " + backtick_exitValue); return process; } finally { if (!backtick_keepScript) deleteFile(backtick_scriptFile.get()); backtick_scriptFile.set(null); } } catch (Exception __e) { throw rethrow(__e); } } static public java.lang.Process backtickToFile_noWait(String cmd, File outFile) { try { ping(); File scriptFile; String ext = isWindows() ? ".bat" : ""; if (backtick_keepScript) scriptFile = makeFileNameUnique_withExtension(javaxCachesDir("Cmd Scripts/backtick"), ".bat"); else scriptFile = File.createTempFile("_backtick", ext); backtick_scriptFile.set(scriptFile); if (backtick_verbose) print("backtick: scriptFile " + f2s(scriptFile)); boolean makeInterruptable = !isTrue(backtick_uninterruptable.get()) && !isWindows(); cmd = trim(cmd); if (makeInterruptable && numLines(cmd) > 1) throw fail("No multi-line commands allowed when making interruptable"); String command = cmd + " >" + bashQuote(outFile.getPath()) + " 2>&1"; if (makeInterruptable) command = fixNewLines("\r\ninterruptable() {\r\n\r\n # handle options\r\n local setsid=\"\"\r\n local debug=false\r\n while true; do\r\n case \"${1:-}\" in\r\n --killall) setsid=setsid; shift ;;\r\n --debug) debug=true; shift ;;\r\n --*) echo \"Invalid option: $1\" 1>&2; exit 1;;\r\n *) break;; # no more options\r\n esac\r\n done\r\n\r\n # start the specified command\r\n $setsid \"$@\" &\r\n local child_pid=$!\r\n\r\n # arrange to propagate a signal to the child process\r\n trap '\r\n exec 1>&2\r\n set +e\r\n trap \"\" SIGPIPE # ensure a possible sigpipe from the echo does not prevent the kill\r\n echo \"${BASH_SOURCE[0]} caught SIGTERM while executing $* (pid $child_pid), sending SIGTERM to it\"\r\n # (race) child may have exited in which case kill will report an error\r\n # if setsid is used then prefix the pid with a \"-\" to indicate that the signal\r\n # should be sent to the entire process group\r\n kill ${setsid:+-}$child_pid\r\n exit 143\r\n ' SIGTERM\r\n # ensure that the trap doesn't persist after we return\r\n trap 'trap - SIGTERM' RETURN\r\n\r\n $debug && echo \"interruptable wait (child $child_pid, self $$) for: $*\"\r\n\r\n # An error status from the child process will trigger an exception (via set -e)\r\n # here unless the caller is checking the return status\r\n wait $child_pid # last command, so status of waited for command is returned\r\n}\r\n\r\ninterruptable ") + command; if (backtick_verbose) { print("backtick: command " + command); print("backtick: saving to " + scriptFile.getPath()); } saveTextFile(scriptFile.getPath(), command); if (backtick_verbose) print("backtick: command length=" + l(command) + ", file length=" + scriptFile.length()); String[] command2; if (isWindows()) if (backtick_win_cmd) command2 = new String[] { "cmd", "/c", scriptFile.getPath() }; else command2 = new String[] { scriptFile.getPath() }; else command2 = new String[] { "/bin/bash", scriptFile.getPath() }; if (backtick_verbose) print("backtick: command2 " + structure(command2)); return Runtime.getRuntime().exec(command2); } catch (Exception __e) { throw rethrow(__e); } } static public String textOfStandardFunction_uncached(String sfName) { return loadSnippet(stdFunctions_uncached().get(sfName)); } static public JCheckBox jLiveValueCheckBox(String text, SimpleLiveValue lv) { JCheckBox cb = jCheckBox(text); bindCheckBoxToLiveValue(cb, lv); return cb; } static public JCheckBox jLiveValueCheckBox(String text, IVarWithNotify lv) { JCheckBox cb = jCheckBox(text); bindCheckBoxToLiveValue(cb, lv); return cb; } static public String md5(String text) { try { if (text == null) return "-"; return bytesToHex(md5AsByteArray(toUtf8(text))); } catch (Exception __e) { throw rethrow(__e); } } static public String md5(byte[] data) { if (data == null) return "-"; return bytesToHex(md5AsByteArray(data)); } static public String md5(File file) { return md5OfFile(file); } static public Border getBorder(final JComponent c) { return c == null ? null : swing(new F0() { public Border get() { try { return c.getBorder(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getBorder();"; } }); } static public A onClick(A c, IVF1 runnable) { return onClick(c, (Object) runnable); } static public A onClick(A c, Object runnable) { if (c != null) { swing(() -> { c.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { callF(runnable, e); } }); }); } return c; } static public void onClick(JButton btn, Object runnable) { onEnter(btn, runnable); } static public List screenDevices() { return asList(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()); } static public boolean isAllUpperCase(String s) { return hasLettersAllUpperCase(s); } static public String getLookAndFeel() { return getClassName(UIManager.getLookAndFeel()); } static public List rowToList(Matrix m, int y) { if (m == null) return null; rangeCheck(y, m.getHeight()); int w = m.getWidth(); return new RandomAccessAbstractList() { public int size() { return w; } public A get(int x) { return m.get(x, y); } public A set(int x, A val) { A old = m.get(x, y); m.set(x, y, val); return old; } }; } static public boolean allElementsAreOfType(Collection c, Class type) { for (Object o : c) if (!isInstanceX(type, o)) return false; return true; } static public boolean containsUnsafePlatformCmdLineChar(String s) { return containsRegexp(s, "[\\|&;<>()\\$`\\\\\"' \t\r\n\\*\\?\\[#~=%]"); } static public String renderFileInfo(File f) { return f == null ? "-" : f2s(f) + " " + (f.isFile() ? "(file, " + n2(fileSize(f)) + " bytes)" : f.isDirectory() ? "(dir)" : "(not found)"); } static public JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) { final JCheckBoxMenuItem mi = swing(() -> new JCheckBoxMenuItem(text, checked)); addActionListener(mi, new Runnable() { public void run() { try { callF(r, isChecked(mi)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(r, isChecked(mi))"; } }); return mi; } static public JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, IVF1 r) { return jCheckBoxMenuItem(text, checked, (Object) r); } static public B mapPut_returnValue(Map map, A key, B value) { mapPut(map, key, value); return value; } static public Lock appendToFile_lock = lock(); static public boolean appendToFile_keepOpen = false; static public HashMap appendToFile_writers = new HashMap(); static public void appendToFile(String path, String s) { try { Lock __0 = appendToFile_lock; lock(__0); try { mkdirsForFile(new File(path)); path = getCanonicalPath(path); Writer writer = appendToFile_writers.get(path); if (writer == null) { writer = new BufferedWriter(new OutputStreamWriter(newFileOutputStream(path, true), "UTF-8")); if (appendToFile_keepOpen) appendToFile_writers.put(path, writer); } writer.write(s); if (!appendToFile_keepOpen) writer.close(); } finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } } static public void appendToFile(File path, String s) { if (path != null) appendToFile(path.getPath(), s); } static public void cleanMeUp_appendToFile() { AutoCloseable __3 = tempCleaningUp(); try { Lock __1 = appendToFile_lock; lock(__1); try { closeAllWriters(values(appendToFile_writers)); appendToFile_writers.clear(); } finally { unlock(__1); } } finally { _close(__3); } } static public String find(String pattern, String text) { Matcher matcher = Pattern.compile(pattern).matcher(text); if (matcher.find()) return matcher.group(1); return null; } static public A find(Collection c, Object... data) { for (A x : c) if (checkFields(x, data)) return x; return null; } static public A jenableUndoRedo(A textcomp) { { swing(() -> { UndoManager undo = new UndoManager(); vm_generalWeakSet("Undo Managers").add(undo); setMeta(textcomp, "UndoManager", undo); textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent evt) { undo.addEdit(evt.getEdit()); } }); textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() { public void run() { try { if (undo.canUndo()) undo.undo(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canUndo()) undo.undo()"; } })); textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() { public void run() { try { if (undo.canRedo()) undo.redo(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canRedo()) undo.redo()"; } })); textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo"); textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo"); }); } return textcomp; } static public void setChecked(JCheckBox checkBox, boolean b) { if (checkBox != null) { swing(() -> { if (isChecked(checkBox) != b) checkBox.setSelected(b); }); } } static public void setChecked(JCheckBoxMenuItem mi, boolean b) { if (mi != null) { swing(() -> { mi.setSelected(b); }); } } static public String joinPairWithColon(Pair p) { return p == null ? "" : str(p.a) + ": " + str(p.b); } static public String quoteUnlessIdentifierOrInteger(String s) { return quoteIfNotIdentifierOrInteger(s); } static public A setFont(final Font font, final A a) { if (a != null) { swing(() -> { a.setFont(font); }); } return a; } static public A setFont(A a, Font font) { return setFont(font, a); } static public A setFont(final String fontID, float fontSize, final A a) { return setFont(loadFont_cached(fontID, fontSize), a); } static public List syncList() { return synchroList(); } static public List syncList(List l) { return synchroList(l); } static public List takeFirst(List l, int n) { return l(l) <= n ? l : newSubListOrSame(l, 0, n); } static public List takeFirst(int n, List l) { return takeFirst(l, n); } static public String takeFirst(int n, String s) { return substring(s, 0, n); } static public String takeFirst(String s, int n) { return substring(s, 0, n); } static public CharSequence takeFirst(int n, CharSequence s) { return subCharSequence(s, 0, n); } static public List takeFirst(int n, Iterator it) { if (it == null) return null; List l = new ArrayList(); for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) { if (it.hasNext()) l.add(it.next()); else break; } return l; } static public List takeFirst(int n, Iterable i) { if (i == null) return null; return i == null ? null : takeFirst(n, i.iterator()); } static public List takeFirst(int n, IterableIterator i) { return takeFirst(n, (Iterator) i); } static public int[] takeFirst(int n, int[] a) { return takeFirstOfIntArray(n, a); } static public short[] takeFirst(int n, short[] a) { return takeFirstOfShortArray(n, a); } static public byte[] takeFirst(int n, byte[] a) { return takeFirstOfByteArray(n, a); } static public byte[] takeFirst(byte[] a, int n) { return takeFirstOfByteArray(n, a); } static public double[] takeFirst(int n, double[] a) { return takeFirstOfDoubleArray(n, a); } static public double[] takeFirst(double[] a, int n) { return takeFirstOfDoubleArray(n, a); } static public Map takeFirst(int n, Map map) { return takeFirstFromMap(n, map); } static public boolean isEditableComboBox(final JComboBox cb) { return cb != null && swing(new F0() { public Boolean get() { try { return cb.isEditable(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return cb.isEditable();"; } }); } static public JPanel jrightalignedline(Component... components) { return jrightAlignedLine(components); } static public JPanel jrightalignedline(List components) { return jrightAlignedLine(components); } static public String formatColonProperties(Map map) { return mapToLines(__91 -> joinPairWithColon(__91), mapToPairs(map)); } static public String formatColonProperties(List> l) { return mapToLines(__92 -> joinPairWithColon(__92), l); } static public String formatColonProperties(Object... params) { return formatColonProperties(paramsToPairs(params)); } static volatile public int numberOfCores_value; static public int numberOfCores() { if (numberOfCores_value == 0) numberOfCores_value = Runtime.getRuntime().availableProcessors(); return numberOfCores_value; } static public String cleanJavaCompilerOutput(String s) { return dropPrefixTrim("Annotation processing got disabled, since it requires a 1.6 compliant JVM", s); } static public A showWindow(A w) { if (w != null) { swing(() -> { w.setVisible(true); }); } return w; } static public BigInteger plus(BigInteger a, BigInteger b) { return a.add(b); } static public BigInteger plus(BigInteger a, long b) { return a.add(bigint(b)); } static public long plus(long a, long b) { return a + b; } static public int plus(int a, int b) { return a + b; } static public float plus(float a, float b) { return a + b; } static public double plus(double a, double b) { return a + b; } static public A optPar_ignoreOddLength(Object[] opt, String name, A defaultValue) { int n = l(opt); if (n == 1 && opt[0] instanceof Map) { Map map = (Map) (opt[0]); return map.containsKey(name) ? (A) map.get(name) : defaultValue; } for (int i = 0; i + 1 < l(opt); i += 2) if (eq(opt[i], name)) return (A) opt[i + 1]; return defaultValue; } static public Object optPar_ignoreOddLength(Object[] opt, String name) { return optPar_ignoreOddLength(opt, name, null); } static public Object optPar_ignoreOddLength(String name, Object[] params) { return optPar_ignoreOddLength(params, name); } static public int tok_findEndOfMethodHeader(List tok, int i) { i |= 1; int level = 0; while (i < l(tok)) { String t = tok.get(i); if (eq(t, "(")) ++level; else if (eq(t, ")")) --level; else if (level == 0 && eqOneOf(t, "{", ";")) return i; i += 2; } return i; } static public Map filterMap(Map map, IF2 f) { if (map == null) return null; Map m2 = similarEmptyMap(map); for (Map.Entry __0 : _entrySet(map)) { A a = __0.getKey(); B b = __0.getValue(); if (f.get(a, b)) m2.put(a, b); } return m2; } static public Map filterMap(IF2 f, Map map) { return filterMap(map, f); } static public Map filterMap(Map map, A... keys) { return getMultipleKeys(map, keys); } static public Map filterMap(Map map, Iterable keys) { return getMultipleKeys(map, keys); } static public boolean saveTextFileIfDifferent(File f, String contents) { if (eq(loadTextFile(f), contents)) return false; { saveTextFile(f, contents); return true; } } static public void dm_watchField(String field, Runnable onChange) { new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange); } static public void fillJPopupMenu(JPopupMenu m, Object... x) { if (x == null) return; for (int i = 0; i < l(x); i++) { Object o = x[i], y = get(x, i + 1); if (o instanceof IVF1) callF(o, m); else if (o instanceof List) fillJPopupMenu(m, asArray((List) o)); else if (isMenuSeparatorIndicator(o)) m.addSeparator(); else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) { final LiveValue lv = (LiveValue) o; final JMenuItem mi = jmenuItem("", y); bindLiveValueListenerToComponent(mi, lv, new Runnable() { public void run() { try { String s = lv.get(); if (isCurlyBracketed(s)) { setEnabled(mi, false); s = unCurlyBracket(s); } else setEnabled(mi, true); setText(mi, s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = lv!;\r\n if (isCurlyBracketed(s)) {\r\n setEnabled(mi,..."; } }); m.add(mi); } else if (o instanceof String && isRunnableX(y)) { m.add(jmenuItem((String) o, y)); ++i; } else if (o instanceof JMenuItem) m.add((JMenuItem) o); else if (o instanceof String || o instanceof Action || o instanceof Component) call(m, "add", o); else if (o != null) print("Unknown menu item: " + o); } } static public JavaXClassLoader hotwire_makeClassLoader(List files) { Collection toShare = hotwire_classesToShare(); return nempty(toShare) ? new JavaXClassLoaderWithParent2(null, files, myClassLoader(), cloneList(toShare)) : new JavaXClassLoader(null, files); } static public String[] codeTokensAsStringArray(List tok) { int n = max(0, (l(tok) - 1) / 2); String[] out = new String[n]; for (int i = 0; i < n; i++) out[i] = tok.get(i * 2 + 1); return out; } static public int ifloor(double d) { return (int) Math.floor(d); } static public IntRange ifloor(DoubleRange r) { return r == null ? null : intRange(ifloor(r.start), ifloor(r.end)); } static public boolean tok_isStaticLevelCode(List tok) { return eqOneOf(firstCodeToken(tok), "static", "sclass", "sinterface", "sS", "sO"); } static public boolean tok_isStaticLevelCode(String src) { return tok_isStaticLevelCode(javaTok(src)); } static public boolean isUpperCaseLetter(char c) { return Character.isUpperCase(c); } static public String hmsWithColonsAndMS() { return hmsWithColonsAndMS(now()); } static public String hmsWithColonsAndMS(long time) { return simpleDateFormat_local("HH:mm:ss:SSS").format(time); } static public int blend(int x, int y, double yish) { double xish = 1 - yish; return (int) (x * xish + y * yish); } static public double blend(double x, double y, double yish) { double xish = 1 - yish; return x * xish + y * yish; } static public void scpSet(SingleComponentPanel scp, Component c) { setSCPComponent(scp, c); } static public JTextArea enableWordWrapForTextArea(JTextArea ta) { return enableWordWrapForTextArea(ta, true); } static public JTextArea enableWordWrapForTextArea(JTextArea ta, boolean enabled) { if (ta != null) { swing(() -> { ta.setLineWrap(enabled); ta.setWrapStyleWord(true); }); } return ta; } static public boolean isSystemThread(Thread t) { ThreadGroup g = t.getThreadGroup(); return g != null && g.getName().equals("system"); } static public int smartIndexOf(String s, String sub, int i) { if (s == null) return 0; i = s.indexOf(sub, min(i, l(s))); return i >= 0 ? i : l(s); } static public int smartIndexOf(String s, int i, char c) { return smartIndexOf(s, c, i); } static public int smartIndexOf(String s, char c, int i) { if (s == null) return 0; i = s.indexOf(c, min(i, l(s))); return i >= 0 ? i : l(s); } static public int smartIndexOf(String s, String sub) { return smartIndexOf(s, sub, 0); } static public int smartIndexOf(String s, char c) { return smartIndexOf(s, c, 0); } static public int smartIndexOf(List l, A sub) { return smartIndexOf(l, sub, 0); } static public int smartIndexOf(List l, int start, A sub) { return smartIndexOf(l, sub, start); } static public int smartIndexOf(List l, A sub, int start) { int i = indexOf(l, sub, start); return i < 0 ? l(l) : i; } static public void tokAppend_reTok(List tok, int i, String s) { tok.set(i, tok.get(i) + s); reTok(tok, i, i + 1); } static public JLabel dm_calculatedCenteredLabel(IF0 calc) { return dm_centeredCalculatedLabel(calc); } static public A printHidingCredentials(A o) { print(hideCredentials(str(o))); return o; } static public int sqr(int i) { return i * i; } static public long sqr(long l) { return l * l; } static public double sqr(double d) { return d * d; } static public float sqr(float f) { return f * f; } static public String repeat(char c, int n) { n = Math.max(n, 0); char[] chars = new char[n]; for (int i = 0; i < n; i++) chars[i] = c; return new String(chars); } static public List repeat(A a, int n) { n = Math.max(n, 0); List l = new ArrayList(n); for (int i = 0; i < n; i++) l.add(a); return l; } static public List repeat(int n, A a) { return repeat(a, n); } static public Component childWithClassNameEndingWith(Component c, String suffix) { if (endsWith(className(c), suffix)) return c; Component x; for (Component comp : getComponents(c)) if ((x = childWithClassNameEndingWith(comp, suffix)) != null) return x; return null; } static public int stepMax(int max, Steppable s) { if (s == null) return 0; int steps = 0; while (max-- > 0 && s.step()) { ping(); ++steps; } return steps; } static public int stepMax(Steppable s, int max) { return stepMax(max, s); } static public String structureForUser(Object o) { return structureForUser(o, new structure_Data()); } static public String structureForUser(Object o, structure_Data d) { d.noStringSharing = true; d.warnIfUnpersistable(false); return beautifyStructure(structure(o, d)); } static public String ok(Object o) { return format("ok *", o); } static public Map mapMinus(Map map, Object... keys) { if (empty(keys)) return map; Map m2 = cloneMap(map); for (Object key : keys) m2.remove(key); return m2; } static public String firstCodeToken(String s) { return firstJavaToken(s); } static public String firstCodeToken(List tok) { return get(tok, 1); } static public boolean nohup_debug = false; static public boolean nohup_noSlashB = false; static public boolean nohup_keepScriptFile = false; static public ThreadLocal nohup_exitValue = new ThreadLocal(); public static File nohup(File cmd) { return nohup(f2s(cmd)); } public static File nohup(String cmd) { try { File outFile = File.createTempFile("nohup_" + nohup_sanitize(cmd) + "_", ".out"); nohup(cmd, outFile, false); return outFile; } catch (Exception __e) { throw rethrow(__e); } } public static void nohup(String cmd, File outFile, boolean append) { try { String command = nohup_makeNohupCommand(cmd, outFile, append); File scriptFile = File.createTempFile("_realnohup", isWindows() ? ".bat" : ""); print("[nohup] " + command); try { if (nohup_debug) print("[nohup] Script file: " + scriptFile.getPath()); saveTextFile(scriptFile.getPath(), command); String[] command2; if (isWindows()) if (nohup_noSlashB) command2 = new String[] { "cmd", "/c", "start", scriptFile.getPath() }; else command2 = new String[] { "cmd", "/c", "start", "/b", scriptFile.getPath() }; else command2 = new String[] { "/bin/bash", scriptFile.getPath() }; print("[nohup] " + joinWithSpace(quoteAll(command2))); Process process = Runtime.getRuntime().exec(command2); try { process.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e); } int value = process.exitValue(); nohup_exitValue.set(value); if (value != 0) warn("nohup exit value != 0: " + value); } finally { if (!nohup_keepScriptFile && !isWindows()) scriptFile.delete(); } } catch (Exception __e) { throw rethrow(__e); } } static public String nohup_makeNohupCommand(String cmd, File outFile, boolean append) { mkdirsForFile(outFile); String command; if (isWindows()) command = cmd + (append ? " >>" : " >") + winQuote(outFile.getPath()) + " 2>&1"; else command = "nohup " + cmd + (append ? " >>" : " >") + bashQuote(outFile.getPath()) + " 2>&1 &"; return command; } static public Rect pointsRect(int x1, int y1, int x2, int y2) { return new Rect(x1, y1, x2 - x1, y2 - y1); } static public JCheckBox jCheckBox() { return swingNu(JCheckBox.class); } static public JCheckBox jCheckBox(boolean checked) { return swingNu(JCheckBox.class, "", checked); } static public JCheckBox jCheckBox(String text, boolean checked) { return swingNu(JCheckBox.class, text, checked); } static public JCheckBox jCheckBox(String text) { return swingNu(JCheckBox.class, text); } static public JCheckBox jCheckBox(String text, boolean checked, Object onChange) { JCheckBox cb = jCheckBox(text, checked); cb.setText(text); return cb; } static public JCheckBox jCheckBox(boolean checked, final Object onChange) { final JCheckBox cb = jCheckBox(checked); cb.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { pcallF(onChange, cb.isSelected()); } }); return cb; } static public JCheckBox jCheckBox(boolean checked, String text, IVF1 onChangeAndNow) { var cb = jCheckBox(text, checked); onChangeAndNow(cb, new Runnable() { public void run() { try { onChangeAndNow.get(isChecked(cb)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "onChangeAndNow.get(isChecked(cb));"; } }); return cb; } static public void poorMansProfileToConsole(Runnable r) { poorMansProfiling(); try { r.run(); } finally { poorMansProfiling_stopAndPrintResults(); } } static public int toMS_int(double seconds) { return toInt_checked((long) (seconds * 1000)); } static public String jlabel_textAsHTML_center_ifNeeded(String text) { if (swic(text, "") && ewic(text, "")) return text; if (!containsNewLines(text)) return text; return jlabel_textAsHTML_center(text); } static public List hotwire_libraryIDsFromJar_deleteJarOnFail(File jar) { try { return hotwire_libraryIDsFromJar(jar); } catch (Throwable _e) { jar.delete(); throw rethrow(_e); } } static public IF0 runnableToIF0(Runnable r) { return r == null ? null : () -> { r.run(); return null; }; } static public Pt rectTopLeftCorner(Rect r) { return r == null ? null : pt(r.x, r.y); } static public Scored scored(A a, float score) { return new Scored(a, score); } static public Scored scored(A a, double score) { return new Scored(a, (float) score); } static public Scored scored(A a, Scored scored) { return new Scored(a, getScore(scored)); } static public Scored scored(double score, A a) { return scored(a, score); } static public File makeTempDir() { return (File) call(getJavaX(), "TempDirMaker_make"); } static public A onWindowClosing(A w, Object r) { return onWindowClosing(w, toRunnable(r)); } static public A onWindowClosing(A w, Runnable r) { if (w != null) { swing(() -> { w.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { AutoCloseable __1 = tempRememberListener(w, "removeWindowListener", this); try { pcallF(r); } finally { _close(__1); } } }); }); } return w; } static public A onWindowClosing(Runnable r, A w) { return onWindowClosing(w, r); } static public List filesEndingWith(File dir, String suffix) { return listFilesWithSuffix(dir, suffix); } static public List filesEndingWith(List l, String suffix) { List out = new ArrayList(); for (File f : unnull(l)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix))) out.add(f); return out; } static public List filesEndingWith(String suffix, File dir) { return filesEndingWith(dir, suffix); } static public String manifestPathInJar() { return "META-INF/MANIFEST.MF"; } static public String htag(String tag) { return htag(tag, ""); } static public String htag(String tag, Object contents, Object... params) { String openingTag = hopeningTag(tag, params); String s = str(contents); if (empty(s) && neqic(tag, "script")) return dropLast(openingTag) + "/>"; return openingTag + s + ""; } static public Object[] asArray(List l) { return toObjectArray(l); } static public A[] asArray(Class type, List l) { return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size())); } static public Pt pt(int x, int y) { return new Pt(x, y); } static public Pt pt(int x) { return new Pt(x, x); } static public List mapMethod(Object[] l, final String methodName) { return map(l, new F1() { public Object get(Object o) { try { return callOpt(o, methodName); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callOpt(o, methodName)"; } }); } static public List mapMethod(Iterable c, final String methodName) { return map(c, new F1() { public Object get(Object o) { try { return callOpt(o, methodName); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callOpt(o, methodName)"; } }); } static public List mapMethod(String methodName, Iterable c) { return mapMethod(c, methodName); } static public List mapMethod(String methodName, Enumeration c) { return mapMethod(methodName, enumerationToIterator(c)); } static public JTextArea showText(final String title, Object text) { return showText(null, title, text); } static public JTextArea showText(JTextArea ta, final String title, Object text) { final String _text = str(text); if (ta != null) return activateFrameAndReturnComponent(setFrameTitle(title, setText(ta, _text))); return swing(new F0() { public JTextArea get() { try { JTextArea textArea = newTypeWriterTextArea(_text); makeFrame(title, new JScrollPane(textArea)); return textArea; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JTextArea textArea = newTypeWriterTextArea(_text);\r\n makeFrame(title, new ..."; } }); } static public JTextArea showText(Object text) { return showText(str(text)); } static public JTextArea showText(String text) { return showText(autoFrameTitle(), text); } static public JTextArea showText() { return showText(""); } static public Map convertObjectMetaToMap(IMeta o) { return convertObjectMetaToMap(o, () -> makeObjectMetaMap()); } static public Map convertObjectMetaToMap(IMeta o, IF0 createEmptyMap) { if (o == null) return null; Object meta = o._getMeta(); if (meta instanceof Map) return ((Map) meta); var mutex = tempMetaMutex(o); try { var actualMutex = mutex.get(); synchronized (actualMutex) { meta = o._getMeta(); if (meta instanceof Map) return ((Map) meta); Map map = createEmptyMap.get(); if (meta != null) map.put("previousMeta", meta); o._setMeta(map); return map; } } finally { _close(mutex); } } static public String repSimple(int n, char c) { return repeat(c, n); } static public List repSimple(int n, A a) { return repeat(n, a); } static public boolean neqic(String a, String b) { return !eqic(a, b); } static public boolean neqic(char a, char b) { return !eqic(a, b); } static public JPanel infoMessage_makePanel(String text) { final JTextArea ta = wrappedTextArea(text); onClick(ta, new Runnable() { public void run() { try { disposeWindow(ta); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disposeWindow(ta)"; } }); int size = 14; if (l(text) <= 50) size *= 2; else if (l(text) < 100) size = iround(size * 1.5); ta.setFont(typeWriterFont(size)); JScrollPane sp = jscroll(ta); return withMargin(sp); } static public void setDefaultClassFinder(Object cf) { _defaultClassFinder_value = cf; } static public int countLines(String s) { return l(toLines(s)); } static public boolean isCurlyBracketed(String s) { return isCurlyBraced(s); } static public String intsToHex_withLineBreaks(List l) { return intsToHex_withLineBreaks(80, l); } static public String intsToHex_withLineBreaks(int charsPerLine, List l) { return regularLineBreaks(charsPerLine, intsToHex(l)); } static public String intsToHex_withLineBreaks(int... l) { return intsToHex_withLineBreaks(80, l); } static public String intsToHex_withLineBreaks(int charsPerLine, int... l) { return intsToHex_withLineBreaks(charsPerLine, wrapIntArrayAsList(l)); } static public ImageSurface doubleBufferedImageSurface_noAlpha() { ImageSurface is = doubleBufferedImageSurface(); is.noAlpha = true; return is; } static public int snippetType_dynModule() { return 57; } static public AutoCloseable dm_vmBus_answerToMessage(String msg, final IF0 f) { final DynModule m = dm_current_mandatory(); return dm_ownResource(vmBus_addListener_basic(msg, new F2() { public Object get(String _msg, Object arg) { try { AutoCloseable __1 = m.enter(); try { return callF(f); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n ret callF(f);"; } })); } static public AutoCloseable dm_vmBus_answerToMessage(String msg, final F0 f) { final DynModule m = dm_current_mandatory(); return dm_ownResource(vmBus_addListener_basic(msg, new F2() { public Object get(String _msg, Object arg) { try { AutoCloseable __2 = m.enter(); try { return callF(f); } finally { _close(__2); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n ret callF(f);"; } })); } static public AutoCloseable dm_vmBus_answerToMessage(String msg, final F1 f) { final DynModule m = dm_current_mandatory(); return dm_ownResource(vmBus_addListener_basic(msg, new F2() { public Object get(String _msg, Object arg) { try { AutoCloseable __3 = m.enter(); try { return callF(f, arg); } finally { _close(__3); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n ret callF(f, arg);"; } })); } static public AutoCloseable dm_vmBus_answerToMessage(String msg, F2 f) { final DynModule m = dm_current_mandatory(); return dm_ownResource(vmBus_addListener_basic(msg, new F2() { public Object get(String _msg, Object arg) { try { if (arg instanceof Object[]) { if (((Object[]) arg).length != 2) return null; AutoCloseable __4 = m.enter(); try { return callF(f, ((Object[]) arg)[0], ((Object[]) arg)[1]); } finally { _close(__4); } } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (arg cast O[]) {\r\n if (arg.length != 2) null;\r\n temp m.enter();\r..."; } })); } static public AutoCloseable dm_vmBus_answerToMessage(String msg, F3 f) { final DynModule m = dm_current_mandatory(); return dm_ownResource(vmBus_addListener_basic(msg, new F2() { public Object get(String _msg, Object arg) { try { if (arg instanceof Object[]) { if (((Object[]) arg).length != 3) return null; AutoCloseable __5 = m.enter(); try { return callF(f, ((Object[]) arg)[0], ((Object[]) arg)[1], ((Object[]) arg)[2]); } finally { _close(__5); } } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (arg cast O[]) {\r\n if (arg.length != 3) null;\r\n temp m.enter();\r..."; } })); } static public A getOrKeep(Map map, A a) { if (map == null) return a; A v = map.get(a); return v != null ? v : a; } static public List toByteList(Object o) { if (o == null) return null; if (o instanceof List) return ((List) o); if (o instanceof Iterable) return toList((Iterable) o); if (o instanceof byte[]) return wrapPrimitiveArrayAsImmutableList((byte[]) o); throw fail(); } static public String afterDollar(String s) { return substring(s, smartIndexOf(s, '$') + 1); } static public String filterChars(IF1 pred, String s) { if (empty(s)) return null; int n = l(s), i = 0; char c = s.charAt(i); boolean totality = pred.get(c); for (++i; i < n; i++) { c = s.charAt(i); boolean b = pred.get(c); if (b != totality) { StringBuilder buf = new StringBuilder(); if (totality) buf.append(substring(s, 0, i)); while (true) { ping(); if (b) buf.append(c); if (++i >= n) break; c = s.charAt(i); b = pred.get(c); } return buf.toString(); } } return totality ? s : ""; } static public String firstStartingWithIC_drop(Collection l, final String prefix) { for (String s : unnull(l)) if (swic(s, prefix)) return substring(s, l(prefix)); return null; } static public String firstStartingWithIC_drop(String prefix, Collection l) { return firstStartingWithIC_drop(l, prefix); } static public Object costCenter() { return mc(); } static public File getBytecodePathForClass(Object o) { return getBytecodePathForClass(_getClass(o)); } static public File getBytecodePathForClass(Class c) { try { return c == null ? null : new File(c.getProtectionDomain().getCodeSource().getLocation().toURI()); } catch (Exception __e) { throw rethrow(__e); } } static public JPanel smartAdd(JPanel panel, List parts) { for (Object o : parts) addToContainer(panel, wrapForSmartAdd(o)); return panel; } static public JPanel smartAdd(JPanel panel, Object... parts) { return smartAdd(panel, asList(parts)); } static public void replaceCollection(Collection dest, Collection src) { if (dest == src) return; dest.clear(); if (src != null) dest.addAll(src); } static public Color gazelle_color2() { return awtColor("EEEEEE"); } static public boolean transpileRaw_silent = true; static public boolean transpileRaw_useDiskCache = false; static public Class transpileRaw_trans; static public boolean transpileRaw_mine = true; static public boolean transpileRaw_verySilent = false; static public boolean transpileRaw_dontCopyFromCreator = false; static public Lock transpileRaw_lock = lock(); static public ThreadLocal transpileRaw_asInclude = new ThreadLocal(); static public ThreadLocal transpileRaw_progID = new ThreadLocal(); static public String transpileRaw(String mainJava) { return transpileRaw(mainJava, false, transpileRaw_useDiskCache); } static public String transpileRaw(String mainJava, boolean fragment) { return transpileRaw(mainJava, fragment, transpileRaw_useDiskCache); } static public String transpileRaw(String mainJava, boolean fragment, boolean useDiskCache) { mainJava = dropTranslators(mainJava); if (!transpileRaw_dontCopyFromCreator) transpileRaw_copyFromCreator(); Lock __0 = transpileRaw_lock; lock(__0); try { File cacheFile = null; if (useDiskCache) { cacheFile = new File(javaxCodeDir(), "Transpilations/" + uniqueFileNameUsingMD5_80_v2(mainJava) + ".java"); { String __3 = loadTextFile(cacheFile); if (!empty(__3)) return __3; } } AutoCloseable __4 = transpileRaw_verySilent ? null : tempLoadingAnim("Transpiling..."); try { transpileRaw_translator(); setOpt(transpileRaw_trans, "localStuffOnly", fragment); setOpt(transpileRaw_trans, "asInclude", isTrue(transpileRaw_asInclude.get())); setOpt(transpileRaw_trans, "mainSnippetID", transpileRaw_progID.get()); set(transpileRaw_trans, "mainJava", mainJava); set(transpileRaw_trans, "print_byThread", print_byThread); if (!transpileRaw_verySilent) print("Running translator " + getOpt(transpileRaw_trans, "programID")); callMain(transpileRaw_trans); String main = (String) (get(transpileRaw_trans, "mainJava")); if (useDiskCache) { saveTextFile(new File(cacheFile.getPath() + "x"), mainJava); saveTextFile(cacheFile, main); } return main; } finally { _close(__4); } } finally { unlock(__0); } } static public IF0 transpileRaw_translator; static public Class transpileRaw_translator() { return transpileRaw_translator != null ? transpileRaw_translator.get() : transpileRaw_translator_base(); } final static public Class transpileRaw_translator_fallback(IF0 _f) { return _f != null ? _f.get() : transpileRaw_translator_base(); } static public Class transpileRaw_translator_base() { if (transpileRaw_trans == null) { transpileRaw_trans = transpileRaw_makeTranslator(); transpileRaw_mine = true; makeDependent(transpileRaw_trans); } setOpt(transpileRaw_trans, "print_silent", transpileRaw_silent); return transpileRaw_trans; } static public IF0 transpileRaw_makeTranslator; static public Class transpileRaw_makeTranslator() { return transpileRaw_makeTranslator != null ? transpileRaw_makeTranslator.get() : transpileRaw_makeTranslator_base(); } final static public Class transpileRaw_makeTranslator_fallback(IF0 _f) { return _f != null ? _f.get() : transpileRaw_makeTranslator_base(); } static public Class transpileRaw_makeTranslator_base() { return hotwireSharingLibraries_silently(defaultJavaXTranslatorID()); } static public void transpileRaw_copyFromCreator() { Lock __1 = transpileRaw_lock; lock(__1); try { if (transpileRaw_trans != null) return; Object c = creator(); if (c == null) return; Class trans = (Class) (getOpt(c, "transpileRaw_trans")); Lock lock = (Lock) (getOpt(c, "transpileRaw_lock")); if (trans != null && lock != null) { print("Using creator's transpiler: " + getProgramID(c) + " => " + programID()); transpileRaw_lock = lock; transpileRaw_trans = trans; transpileRaw_mine = false; } } finally { unlock(__1); } } static public void cleanMeUp_transpileRaw() { if (transpileRaw_mine) cleanUp(transpileRaw_trans); transpileRaw_trans = null; } static public B rCallF(A a, IF1 f) { return f == null ? null : f.get(a); } static public void rCallF(A a, IVF1 f) { { if (f != null) f.get(a); } } static public String standardCredentials() { String user = standardCredentialsUser(); String pass = standardCredentialsPass(); if (nempty(user) && nempty(pass)) return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass); return ""; } static public void installWindowResizeDraggerOnBorder(JComponent c) { if (c != null) { swing(() -> { new WindowResizeDragger(c); }); } } static public String linesLL(Object... x) { return lines(ll(x)); } static public int dayOfMonth() { return localDayOfMonth(); } static public int dayOfMonth(long now) { return localDayOfMonth(now); } static public int dayOfMonth(long now, TimeZone tz) { return parseInt(simpleDateFormat("d", tz).format(now)); } static public A safeGet(List l, int i) { return i >= 0 && i < l(l) ? l.get(i) : null; } static public void clearTokens_reTok(List tok, int i, int j) { clearTokens(tok, i, j); reTok(tok, i, j); } static public void clearTokens_reTok(List tok, IntRange r) { if (r != null) clearTokens_reTok(tok, r.start, r.end); } static public int sortedSet_compare(SortedSet set, A a, A b) { return compareWithComparator(set.comparator(), a, b); } static public void stepForNSeconds(double timeout, Steppable s) { stepAllWithTimeout(timeout, s); } static public Map singular_specials = litmap("children", "child", "images", "image", "chess", "chess"); static public Set singular_specials2 = litciset("time", "machine", "line", "rule"); static public String singular(String s) { if (s == null) return null; { String __1 = singular_specials.get(s); if (!empty(__1)) return __1; } if (singular_specials2.contains(dropSuffix("s", afterLastSpace(s)))) return dropSuffix("s", s); if (s.endsWith("ness")) return s; if (s.endsWith("ges")) return dropSuffix("s", s); if (endsWith(s, "bases")) return dropLast(s); s = dropSuffix("es", s); s = dropSuffix("s", s); return s; } static public boolean javaCompileToJar_useRAMDisk = false; static public ThreadLocal> javaCompileToJar_localLibraries = new ThreadLocal(); static public ThreadLocal> javaCompileToJar_addMoreFiles = new ThreadLocal(); static public File javaCompileToJar_optionalRename(String src, File destJar, String progIDForRename) { return javaCompileToJar_optionalRename(src, "", destJar, progIDForRename); } static synchronized public File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename) { return javaCompileToJar_optionalRename(src, dehlibs, destJar, progIDForRename, null); } static synchronized public File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename, String progID) { String javaTarget = null; String dummyClass = "main"; if (progIDForRename != null) { dummyClass = dummyMainClassName(progIDForRename); src += "\nclass " + dummyClass + "{}"; } String md5 = md5(src); File jar = destJar; Class j = getJavaX(); if (javaTarget != null) setOpt(j, "javaTarget", javaTarget); File srcDir = tempDir(); String fileName = dummyClass + ".java"; List tok = javaTok(src); String packageName = tok_packageName(tok); if (packageName != null) fileName = packageName.replace(".", "/") + "/" + tok_firstClassName(tok) + ".java"; File mainJava = new File(srcDir, fileName); saveTextFile(mainJava, src); File classesDir = javaCompileToJar_useRAMDisk ? tempDirPossiblyInRAMDisk() : tempDir(); try { List libraries = cloneList(getAndClearTL(javaCompileToJar_localLibraries)); Matcher m = Pattern.compile("\\d+").matcher(dehlibs); while (m.find()) { String libID = m.group(); assertTrue(isSnippetID(libID)); libraries.add(loadLibraryOrSrcLib(libID)); } libraries.add(pathToJavaxJar()); String compilerOutput; try { compilerOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir); } catch (Throwable e) { compilerOutput = (String) get(getJavaX(), "javaCompilerOutput"); if (!swic(e.getMessage(), "Java compiler returned errors.")) compilerOutput = appendWithNewLine(compilerOutput, str(e)); throw fail(compilerOutput, e); } compilerOutput = cleanJavaCompilerOutput("Annotation processing got disabled, since it requires a 1.6 compliant JVM"); if (nempty(compilerOutput)) { print("Compiler said: " + compilerOutput); } if (!anyFileWithExtensionInDir(classesDir, ".class")) { printWithIndent("SRC> ", src); throw fail("No classes generated (was compiling " + nChars(src) + ")"); } saveTextFile(new File(classesDir, "main.java"), src); if (nempty(dehlibs)) saveTextFile(new File(classesDir, "libraries"), dehlibs); saveTextFile(new File(classesDir, "progID"), progID); callF(javaCompileToJar_addMoreFiles.get(), classesDir); dir2zip_recurse_verbose = false; int n = dir2zip_recurse(classesDir, jar); return jar; } finally { if (isInRAMDisk(classesDir)) deleteDirectory(classesDir); } } static public File getCachedTranspilationFile(String id) { return newFile(getCodeProgramDir(id), "Transpilation"); } static public void _initFrame(JFrame f) { myFrames_list.put(f, Boolean.TRUE); standardTitlePopupMenu(f); } static public List minus(Collection a, Object... b) { Set set = asSet(b); List l = new ArrayList(); for (Object s : unnull(a)) if (!set.contains(s)) l.add(s); return l; } static public BigInteger minus(BigInteger a, BigInteger b) { return a.subtract(b); } static public Complex minus(Complex c) { return c == null ? null : complex(-c.re(), -c.im()); } static public int minus(int a, int b) { return a - b; } static public int minus(int a) { return -a; } static public double minus(double a, double b) { return a - b; } static public double minus(double a) { return -a; } static public long minus(long a, long b) { return a - b; } static public long minus(long a) { return -a; } static public A printWithIndent(A o) { return printIndent(o); } static public A printWithIndent(String indent, A o) { return printIndent(indent, o); } static public void printWithIndent(int indent, Object o) { printIndent(indent, o); } static public boolean hasElementWithClassShortNamed(String shortName, Iterable l) { return firstWithClassShortNamed(shortName, l) != null; } static public boolean hasElementWithClassShortNamed(String shortName, A[] l) { return firstWithClassShortNamed(shortName, l) != null; } static public List syncAddOrCreate(List l, A a) { if (l == null) l = syncList(); l.add(a); return l; } static public void tokPrepend(List tok, String s) { tokPrepend(tok, 0, s); } static public void tokPrepend(List tok, int i, String s) { tok.set(i, s + tok.get(i)); } static public List keysList(Map map) { return cloneListSynchronizingOn(keys(map), map); } static public List keysList(MultiSet ms) { return ms == null ? null : keysList(ms.map); } static public boolean containsReturnWithArgument(List tok) { for (int i = 1; i + 2 < l(tok); i += 2) { String t = tok.get(i); if (eqOneOf(t, "ret", "return") && neqOneOf(tok.get(i + 2), ";", "if", "unless", "with")) return true; if (eqOneOf(t, "embedded", "class") && isIdentifier(get(tok, i + 2)) || eq(t, "(") && eqGet(tok, i + 2, ")") && eqGet(tok, i + 4, "{")) i = tok_findEndOfMethodDecl(tok, i) - 1; if (eqOneOf(t, "r", ">") && eqGet(tok, i + 2, "{")) i = findEndOfBlock(tok, i + 2) - 1; } return false; } static public boolean containsReturnWithArgument(String code) { return containsReturnWithArgument(javaTok(code)); } static public String fileNameEncode_safeChars = " "; static public String fileNameEncode(String s) { s = dropLeadingDots(s); StringBuilder buf = new StringBuilder(); int n = l(s); for (int i = 0; i < n; i++) { char c = s.charAt(i); if (contains(fileNameEncode_safeChars, c)) buf.append(c); else buf.append(urlencode(str(c))); } return str(buf); } static public AutoCloseable tempHoldInstance(Object o) { return holdInstance(o); } static public String getSnippetTitleOpt(String s) { try { return isSnippetID(s) ? getSnippetTitle(s) : s; } catch (Throwable __e) { pcallFail(__e); } return s; } static public List reversedList(Iterable l) { List x = cloneList(l); Collections.reverse(x); return x; } static public IntRange intRange(int start, int end) { return new IntRange(start, end); } static public int localYear() { return localYear(now()); } static public int localYear(long time) { return parseInt(simpleDateFormat_local("yyyy").format(time)); } static public int getScreenHeight() { return getScreenSize().height; } static public List byteArrayToIntList_littleEndian(byte[] a) { if (a == null) return null; int n = (a.length + 3) / 4; return new RandomAccessAbstractList() { public int size() { return n; } public Integer get(int i) { return intFromBytes_littleEndian_partial(a, i * 4); } public Integer set(int i, Integer val) { Integer old = get(i); if ((int) old != (int) val) intToBytes_inArray_littleEndian_partial(val, a, i * 4); return old; } }; } static public void dm_ownTimer(Object resource, Object closerHelper) { call(dm_current_generic(), "ownTimer", resource, closerHelper); } static public A dm_ownTimer(A resource) { call(dm_current_generic(), "ownTimer", resource); return resource; } static public void dm_ownTimer(IVF1 closerHelper, A resource) { dm_ownTimer(resource, closerHelper); } static public double ratio(double x, double y) { return y == 0 ? 0 : x / y; } static public IterableIterator countIterator(int b) { return countIterator(0, b); } static public IterableIterator countIterator(int a, int b) { return countIterator_exclusive(a, b); } static public IterableIterator countIterator(int b, IF1 f) { return countIterator(0, b, f); } static public IterableIterator countIterator(int a, int b, IF1 f) { return countIterator_exclusive(a, b, f); } static public IterableIterator countIterator(int a, int b, int step) { return countIterator_exclusive_step(a, b, step); } static public IterableIterator countIterator(double a, double b, double step, IF1 f) { return countIterator_exclusive_step(a, b, step, f); } static public IterableIterator countIterator(double a, double b, double step) { return countIterator_exclusive_step(a, b, step); } static public IterableIterator countIterator(IF1 f, double a, double b, double step) { return countIterator(a, b, step, f); } static public IterableIterator countIterator(IF1 f, int b) { return countIterator(f, 0, b); } static public IterableIterator countIterator(IF1 f, int a, int b) { return countIterator_exclusive(a, b, f); } static public IterableIterator countIterator(List l) { return countIterator(l(l)); } static public PopupMenu makePopupMenu(Object... x) { if (x == null) return null; if (l(x) == 1 && x[0] instanceof PopupMenu) return (PopupMenu) x[0]; PopupMenu m = new PopupMenu(); for (int i = 0; i < l(x); i++) { Object o = x[i]; if (eqOneOf(o, "***", "---", "===", "")) m.addSeparator(); else if (o instanceof String && get(x, i + 1) instanceof Runnable) m.add(menuItem((String) o, get(x, ++i))); else if (o instanceof String || o instanceof Menu || o instanceof MenuItem) call(m, "add", o); else print("Unknown menu item: " + o); } return m; } static public List methodsStartingWith(Object o, final String prefix) { return filter(allMethodNames(o), new F1() { public Object get(String s) { try { return startsWith(s, prefix); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "startsWith(s, prefix)"; } }); } static public short[] subShortArray(short[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new short[0]; short[] x = new short[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public boolean boolPar(ThreadLocal tl) { return boolOptParam(tl); } static public boolean boolPar(Object[] __, String name) { return boolOptParam(__, name); } static public boolean boolPar(String name, Object[] __) { return boolOptParam(__, name); } static public boolean boolPar(String name, Map __) { return boolOptParam(name, __); } static public boolean boolPar(String name, Object[] params, boolean defaultValue) { return optParam(params, name, defaultValue); } static public boolean isNaN(double d) { return Double.isNaN(d); } static public boolean isNaN(float f) { return Float.isNaN(f); } static public void fillRect(BufferedImage image, int x, int y, int w, int h, Color color) { Graphics2D g = imageGraphics(image); fillRect(g, x, y, w, h, color); g.dispose(); } static public void fillRect(Graphics g, Color color, int x, int y, int w, int h) { fillRect(g, x, y, w, h, color); } static public void fillRect(Graphics g, int x, int y, int w, int h, Color color) { g.setColor(color); g.fillRect(x, y, w, h); } static public void fillRect(int x, int y, int w, int h, Color color) { fillRect(currentImage(), x, y, w, h, color); } static public void fillRect(Rect r, Color color) { fillRect(r.x, r.y, r.w, r.h, color); } static public void fillRect(BufferedImage image, Rect r, Color c) { if (r != null) fillRect(image, r.x, r.y, r.w, r.h, c); } static public void fillRect(Graphics g, Rect r, Color c) { if (r != null) fillRect(g, r.x, r.y, r.w, r.h, c); } static public int[] resizeIntArray(int[] a, int n) { if (n == lIntArray(a)) return a; int[] b = new int[n]; arraycopy(a, 0, b, 0, Math.min(lIntArray(a), n)); return b; } static public JPanel westCenterAndEastWithMargin(Component w, Component c, Component e) { return westCenterAndEast(w, withLeftAndRightMargin(c), e); } static public A lookupDynamicInterface(Class intrface, Object o) { if (o instanceof DynamicObject) { A a = (A) (mapGet((Map) ((DynamicObject) o).fieldValues, intrface)); if (a != null) return a; } if (isInstance(intrface, o)) return (A) o; return null; } static public A lookupDynamicInterface(Object o, Class intrface) { return lookupDynamicInterface(intrface, o); } static public String indentx(Object s) { return indentx(strOrEmpty(s)); } static public String indentx(String s) { return indentx(indent_default, s); } static public String indentx(int n, String s) { return dropSuffix(repeat(' ', n), indent(n, s)); } static public String indentx(String indent, String s) { return dropSuffix(indent, indent(indent, s)); } static public String getSelectedItem(JList l) { return (String) l.getSelectedValue(); } static public String getSelectedItem(JComboBox cb) { return strOrNull(cb.getSelectedItem()); } static public double elapsedSeconds_timestamp(long time) { return toSeconds(now() - time); } static public boolean startsWithAndEndsWith(String s, String prefix, String suffix) { return startsWith(s, prefix) && endsWith(s, suffix); } static public int loadAllClassesInByteCodePath(File path) { int n = 0; for (String name : allClassNamesOnPath(ll(path))) try { Class.forName(name); ++n; } catch (Throwable __e) { print(exceptionToStringShort(__e)); } return n; } static public A activateFrameAndReturnComponent(A c) { activateFrame(c); return c; } static public short[] takeFirstOfShortArray(short[] b, int n) { return subShortArray(b, 0, n); } static public short[] takeFirstOfShortArray(int n, short[] b) { return takeFirstOfShortArray(b, n); } static public boolean tok_shouldAddReturn(List tok) { String lastToken = get(tok, l(tok) - 2); if (eqOneOf(lastToken, ";", null)) return false; if (eq(lastToken, "}")) { int i = findBeginningOfBlock(tok, l(tok) - 2); return eqGet(tok, i - 4, "-") && eqGet(tok, i - 3, "") && eqGet(tok, i - 2, ">"); } return true; } static public boolean tok_shouldAddReturn(String s) { return tok_shouldAddReturn(javaTok(s)); } static public JLabel dm_centeredFieldLabel(String fieldName) { return centerLabel(dm_fieldLabel(fieldName)); } static public String ymd_minus_hms() { return ymd_minus_hms(now()); } static public String ymd_minus_hms(long now) { return ymd(now) + "-" + hms(now); } static public boolean isChecked(JCheckBox checkBox) { return checkBox != null && (boolean) swing(new F0() { public Boolean get() { try { return checkBox.isSelected(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return checkBox.isSelected();"; } }); } static public boolean isChecked(JCheckBoxMenuItem mi) { return mi != null && (boolean) swing(new F0() { public Boolean get() { try { return mi.isSelected(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return mi.isSelected();"; } }); } static public boolean isChecked(JRadioButton rb) { return rb != null && (boolean) swing(() -> rb.isSelected()); } static public JButton jPopDownButton(String text, final Object... menuParams) { return jbutton((empty(text) ? "" : text + " ") + unicode_downPointingTriangle(), new Runnable() { public void run() { try { JPopupMenu menu = new JPopupMenu(); int emptyCount = menu.getComponentCount(); String position = (String) (optPar_ignoreOddLength("position", menuParams)); fillJPopupMenu(menu, paramsWithout(menuParams, "position")); if (menu.getComponentCount() != emptyCount) { JButton btn = heldInstance(JButton.class); int x = 0; if (eq(position, "center")) x = (btn.getWidth() - getPreferredWidth(menu)) / 2; else if (eq(position, "right")) x = btn.getWidth() - getPreferredWidth(menu); menu.show(btn, x, btn.getHeight()); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new JPopupMenu menu;\r\n int emptyCount = menu.getComponentCount();\r\n Str..."; } }); } static public void innerCleanUp(Object c) { if (!isFalse(pcallOpt(c, "cleanMeUp"))) for (String name : sorted(methodsStartingWith(c, "cleanMeUp_"))) try { callOpt(c, name); } catch (Throwable e) { print("Error cleaning up: " + programID(c)); _handleException(e); } } static public void innerCleanUp() { innerCleanUp(mc()); } static public Map similarEmptyMap(Map m) { if (m instanceof TreeMap) return new TreeMap(((TreeMap) m).comparator()); if (m instanceof LinkedHashMap) return new LinkedHashMap(); return new HashMap(); } static public Map similarEmptyMap(Iterable m) { if (m instanceof TreeSet) return new TreeMap(((TreeSet) m).comparator()); if (m instanceof LinkedHashSet) return new LinkedHashMap(); return new HashMap(); } static public Object getMC(String field) { return get(mc(), field); } static public File toFile(Object o) { if (o instanceof File) return (File) o; if (o instanceof String) return new File((String) o); throw fail("Not a file: " + o); } static public byte[] gunzipBytes(byte[] data) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copyStreamAndCloseAll(newGZIPInputStream(new ByteArrayInputStream(data)), baos); return baos.toByteArray(); } catch (Exception __e) { throw rethrow(__e); } } static public ArrayList intArrayToList(int[] a) { if (a == null) return null; return intArrayToList(a, 0, a.length); } static public ArrayList intArrayToList(int[] a, int from, int to) { if (a == null) return null; ArrayList l = new ArrayList<>(to - from); for (int i = from; i < to; i++) l.add(a[i]); return l; } static public String[] drop(int n, String[] a) { n = Math.min(n, a.length); String[] b = new String[a.length - n]; System.arraycopy(a, n, b, 0, b.length); return b; } static public Object[] drop(int n, Object[] a) { n = Math.min(n, a.length); Object[] b = new Object[a.length - n]; System.arraycopy(a, n, b, 0, b.length); return b; } static public List drop(Iterable c, Object pred) { return antiFilter(c, pred); } static public List drop(Object pred, Iterable c) { return antiFilter(pred, c); } static public List drop(Object pred, Object[] c) { return antiFilter(pred, c); } static public List drop(Iterable c, F1 pred) { return antiFilter(c, pred); } static public List drop(F1 pred, Iterable c) { return antiFilter(pred, c); } static public List drop(Iterable c, IF1 pred) { return antiFilter(c, pred); } static public List drop(IF1 pred, Iterable c) { return antiFilter(pred, c); } static public int snippetType_JavaXDesktop() { return 55; } static public void intToBytes_inArray_littleEndian_partial(int i, byte[] array, int idx) { if (idx < array.length) array[idx] = (byte) i; if (idx + 1 < array.length) array[idx + 1] = (byte) (i >>> 8); if (idx + 2 < array.length) array[idx + 2] = (byte) (i >>> 16); if (idx + 3 < array.length) array[idx + 3] = (byte) (i >>> 24); } static public File compilerBotDestDir() { return actualUserDir(compilerBotDestDirSubName()); } static public File compilerBotDestDir(String sub) { return newFile(compilerBotDestDir(), sub); } static public Object metaMapGet(IMeta o, Object key) { return o == null ? null : o.metaGet(key); } static public Object metaMapGet(Object o, Object key) { return metaMapGet(toIMeta(o), key); } static public boolean eqGet(List l, int i, Object o) { return eq(get(l, i), o); } static public boolean eqGet(Map map, A key, Object o) { return eq(mapGet(map, key), o); } static public void standardTitlePopupMenu(final JFrame frame) { if (!isSubstanceLAF()) return; titlePopupMenu(frame, new VF1() { public void get(JPopupMenu menu) { try { boolean alwaysOnTop = frame.isAlwaysOnTop(); menu.add(jmenuItem("Restart Program", new Runnable() { public void run() { try { restart(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "restart();"; } })); menu.add(jmenuItem("Duplicate Program", new Runnable() { public void run() { try { duplicateThisProgram(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "duplicateThisProgram();"; } })); menu.add(jmenuItem("Show Console", new Runnable() { public void run() { try { showConsole(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showConsole();"; } })); menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() { public void run() { try { toggleAlwaysOnTop(frame); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "toggleAlwaysOnTop(frame)"; } })); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n ifndef standardTitlePopupMenu_..."; } }); } static public AutoCloseable tempAdd(Collection l, A a) { if (l == null || l.contains(a)) return null; l.add(a); return new tempAdd_undo(l, a); } static public class tempAdd_undo implements AutoCloseable, IFieldsToList { public Collection l; public A a; public tempAdd_undo() { } public tempAdd_undo(Collection l, A a) { this.a = a; this.l = l; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + l + ", " + a + ")"; } public Object[] _fieldsToList() { return new Object[] { l, a }; } public void close() { try { l.remove(a); } catch (Exception __e) { throw rethrow(__e); } } } static public AutoCloseable tempAdd(Container a, Component b) { if (a == null || b == null) return null; { return swing(() -> { if (b.getParent() == a) return null; a.add(b); return () -> { swing(() -> { if (b.getParent() == a) removeFromParent(b); }); }; }); } } static public String loadProgramTextFile(String name) { return loadTextFile(getProgramFile(name)); } static public String loadProgramTextFile(String progID, String name) { return loadTextFile(getProgramFile(progID, name)); } static public String loadProgramTextFile(String progID, String name, String defaultText) { return loadTextFile(getProgramFile(progID, name), defaultText); } static public String mcName() { return mc().getName(); } static public MouseAdapter onMouseDown(Component c, Runnable r) { return onMouseDown(c, runnableToIVF1(r)); } static public MouseAdapter onMouseDown(Component c, IVF1 f) { return c == null || f == null ? null : swing(() -> { MouseAdapter ma = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) f.get(e); } }; c.addMouseListener(ma); return ma; }); } static public AutoCloseable tempDisposeWindow(final Window w) { return new AutoCloseable() { public void close() { disposeWindow(w); } }; } static public Cache isLinux_cache = new Cache<>(() -> isLinux_load()); static public boolean isLinux() { return isLinux_cache.get(); } static public Boolean isLinux_load() { return !isWindows() && !isMac() && !isAndroid(); } static public boolean checkFields(Object x, Object... data) { for (int i = 0; i < l(data); i += 2) if (neq(getOpt(x, (String) data[i]), data[i + 1])) return false; return true; } static public int localDayOfMonth(long time) { return parseInt(simpleDateFormat_local("dd").format(time)); } static public int localDayOfMonth() { return localDayOfMonth(now()); } static public IterableIterator iff(Object f) { return iteratorFromFunction_withEndMarker(f); } static public IterableIterator iff(F0 f) { return iteratorFromFunction_withEndMarker(f); } static public IterableIterator iff(IF0 f) { return iteratorFromFunction_withEndMarker(f); } static public JWindow makeWindow(final Component c) { return swing(new F0() { public JWindow get() { try { JWindow w = new JWindow(); w.add(wrap(c)); return w; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new JWindow w;\r\n w.add(wrap(c));\r\n ret w;"; } }); } static public int pixelCount(BufferedImage img) { return img == null ? 0 : img.getWidth() * img.getHeight(); } static public F0 if0ToF0(IF0 f) { return f == null ? null : new F0() { public A get() { try { return f.get(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return f.get();"; } }; } static public A pairA(Pair p) { return p == null ? null : p.a; } static public void autoVMExit() { call(getJavaX(), "autoVMExit"); } static public File appendToBaseName(File f, String s) { return appendToFileNameBeforeExtension(f, s); } static public List javaTok_noMLS(String s) { ArrayList tok = new ArrayList(); int l = s == null ? 0 : s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(javaTok_substringN(s, i, j)); ++n; i = j; if (i >= l) break; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { int c2 = s.charAt(j); if (c2 == opener || c2 == '\n' && opener == '\'') { ++j; break; } else if (c2 == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j))); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else ++j; tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static public String[] dropFirst(int n, String[] a) { return drop(n, a); } static public String[] dropFirst(String[] a) { return drop(1, a); } static public Object[] dropFirst(Object[] a) { return drop(1, a); } static public List dropFirst(List l) { return dropFirst(1, l); } static public List dropFirst(int n, Iterable i) { return dropFirst(n, toList(i)); } static public List dropFirst(Iterable i) { return dropFirst(toList(i)); } static public List dropFirst(int n, List l) { return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size())); } static public List dropFirst(List l, int n) { return dropFirst(n, l); } static public String dropFirst(int n, String s) { return substring(s, n); } static public String dropFirst(String s, int n) { return substring(s, n); } static public String dropFirst(String s) { return substring(s, 1); } static public Chain dropFirst(Chain c) { return c == null ? null : c.next; } static volatile public PersistableThrowable _handleException_lastException; static public List _handleException_onException = synchroList(ll((IVF1) (__1 -> printStackTrace2(__1)))); static public boolean _handleException_showThreadCancellations = false; static public void _handleException(Throwable e) { _handleException_lastException = persistableThrowable(e); Throwable e2 = innerException(e); if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException) { if (_handleException_showThreadCancellations) System.out.println(getStackTrace_noRecord(e2)); return; } for (Object f : cloneList(_handleException_onException)) try { callF(f, e); } catch (Throwable e3) { try { printStackTrace2(e3); } catch (Throwable e4) { System.out.println(getStackTrace(e3)); System.out.println(getStackTrace(e4)); } } } static public Set newWeakHashSet() { return synchroWeakHashSet(); } static public A waitForVarToBeNotNull(Var v) { try { synchronized (v) { while (!v.has()) v.wait(); return v.get(); } } catch (Exception __e) { throw rethrow(__e); } } static public String nClasses(long n) { return n2(n, "class", "classes"); } static public String nClasses(Collection l) { return nClasses(l(l)); } static public String nClasses(Map map) { return nClasses(l(map)); } static public String struct_noStringSharing(Object o) { structure_Data d = new structure_Data(); d.noStringSharing = true; return structure(o, d); } static public int mod(int n, int m) { return (n % m + m) % m; } static public long mod(long n, long m) { return (n % m + m) % m; } static public BigInteger mod(BigInteger n, int m) { return n.mod(bigint(m)); } static public double mod(double n, double m) { return (n % m + m) % m; } static public String javaTok_substringC(String s, int i, int j) { return s.substring(i, j); } static public A lookupInterface(Class intrface, Object o) { return lookupDynamicInterface(intrface, o); } static public A lookupInterface(Object o, Class intrface) { return lookupDynamicInterface(o, intrface); } static public String inputStreamToString(InputStream in) { return utf8streamToString(in); } static public String javaTok_substringN(String s, int i, int j) { if (i == j) return ""; if (j == i + 1 && s.charAt(i) == ' ') return " "; return s.substring(i, j); } static public String squareBracketed(String s) { return "[" + s + "]"; } static public JFrame makeUndecoratedFrame(String title, Object content) { return swing(() -> { JFrame frame = new JFrame(title); frame.setUndecorated(true); Component wrapped = wrap(content); if (wrapped != null) frame.getContentPane().add(wrapped); frame.setBounds(defaultNewFrameBounds()); return frame; }); } static public JPanel centerAndEastWithMarginInbetween(Component c, final Component e) { return centerAndEast(c, withLeftMargin(e)); } static public int seconds() { return seconds(java.util.Calendar.getInstance()); } static public int seconds(java.util.Calendar c) { return c.get(java.util.Calendar.SECOND); } static public boolean regexpFinds(String pat, String s) { return regexp(pat, s).find(); } static public boolean regexpFinds(Pattern pat, String s) { return regexp(pat, s).find(); } static public boolean isLocalSnippet(String snippetID) { return isLocalSnippetID(snippetID); } static public boolean isLocalSnippet(long snippetID) { return isLocalSnippetID(snippetID); } static public String getStackTrace2(Throwable e) { return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n"); } static public boolean useDummyMainClasses() { return true; } static public boolean longIsInt(long l) { return l == (int) l; } static public byte[] subByteArray(byte[] b, int start) { return subByteArray(b, start, l(b)); } static public byte[] subByteArray(byte[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new byte[0]; byte[] x = new byte[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public byte[] subByteArray(byte[] b, IntRange r) { return r == null ? null : subByteArray(b, r.start, r.end); } static public Object pcallFAll_returnFirstNotNull(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) { var __1 = pcallF(f, args); if (__1 != null) return __1; } return null; } static public Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) { while (it.hasNext()) { var __2 = pcallF(it.next(), args); if (__2 != null) return __2; } return null; } static public RuntimeException quickFail() { throw new QuickException("fail"); } static public RuntimeException quickFail(Throwable e) { throw asQuickException(e); } static public RuntimeException quickFail(Object msg) { throw new QuickException(String.valueOf(msg)); } static public RuntimeException quickFail(String msg) { throw new QuickException(unnull(msg)); } static public RuntimeException quickFail(String msg, Throwable innerException) { throw new QuickException(msg, innerException); } static public boolean isJavaXClassLoader(ClassLoader cl) { return startsWithOneOf(className(cl), "main$JavaXClassLoader", "x30$JavaXClassLoader"); } static public HashMap findClass_cache = new HashMap(); static public Class findClass(String name) { synchronized (findClass_cache) { if (findClass_cache.containsKey(name)) return findClass_cache.get(name); if (!isJavaIdentifier(name)) return null; Class c; try { c = Class.forName("main$" + name); } catch (ClassNotFoundException e) { c = null; } findClass_cache.put(name, c); return c; } } static public double nanosToSeconds(double nanos) { return nanoSecondsToSeconds(nanos); } static public boolean anyFileWithExtensionInDir(File dir, String ext) { return nempty(filesWithExtension(ext, findAllFiles_noDirs(dir))); } static public String readerToString(Reader r) { try { if (r == null) return null; try { StringBuilder buf = new StringBuilder(); int n = 0; while (true) { int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; } return buf.toString(); } finally { r.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public void drawIntMatrix(BufferedImage g, Matrix m, int x, int y) { drawIntMatrix(graphics(g), m, x, y); } static public void drawIntMatrix(Graphics2D g, Matrix m, int x, int y) { if (g == null || m == null) return; drawImage(g, matrixToImage(m), x, y); } static public void dm_toggleAlwaysOnTop() { if (dm_moduleIsPoppedOut()) { boolean aot = !isTrue(dm_getFlag("ALWAYSONTOPWHENPOPPEDOUT")); dm_setFlag("ALWAYSONTOPWHENPOPPEDOUT", aot); alwaysOnTop(dm_windowIfSingleModule(dm_current_generic()), aot); } } static public String joinNemptiesWithDot(Object... strings) { return joinNempties(".", strings); } static public String joinNemptiesWithDot(Iterable strings) { return joinNempties(".", strings); } static public Map humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5"); static public String humanizeFormLabel(String s) { if (!isIdentifier(s)) return s; return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID")); } static public java.util.Timer doLater_daemon(long delay, final Object r) { final java.util.Timer timer = new java.util.Timer(true); timer.schedule(timerTask(r, timer), delay); return timer; } static public java.util.Timer doLater_daemon(double delaySeconds, final Object r) { return doLater_daemon(toMS(delaySeconds), r); } static public Set hotwire_classesToShare = synchroSet(); static public Set hotwire_classesToShare() { return hotwire_classesToShare; } static public GrabbableIntPixels grabbableIntPixels_fastOrSlow(BufferedImage image) { try { try { GrabbableIntPixels gp = grabbableIntPixels(image); if (gp != null) return gp; } catch (Throwable __e) { pcallFail(__e); } int w = image.getWidth(), h = image.getHeight(); int[] data = new int[w * h]; PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, w, h, data, 0, w); if (!pixelGrabber.grabPixels()) throw fail("Could not grab pixels"); return new GrabbableIntPixels(data, w, h, 0, w); } catch (Exception __e) { throw rethrow(__e); } } static public int countPred(Iterable c, Object pred) { return nfilter(c, pred); } static public int countPred(Object pred, Iterable c) { return nfilter(pred, c); } static public int countPred(Iterable c, IF1 pred) { return nfilter(c, pred); } static public BWImage scaleDownUsingIntegralImageBW(int w, BWIntegralImage img) { return scaleDownUsingIntegralImageBW(img, w); } static public BWImage scaleDownUsingIntegralImageBW(BWIntegralImage img, int w) { return scaleDownUsingIntegralImageBW(img, w, iround(w * img.h / (double) img.w)); } static public BWImage scaleDownUsingIntegralImageBW(BWIntegralImage img, int w, int h) { int w1 = img.w, h1 = img.h; BWImage out = new BWImage(w, h); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { int x1 = x * w1 / w, x2 = max(x1 + 1, (x + 1) * w1 / w); int y1 = y * h1 / h, y2 = max(y1 + 1, (y + 1) * h1 / h); int area = (x2 - x1) * (y2 - y1); int pixel = bwIntegralImage_sumRect(img, x1, y1, x2, y2) / area; out.setByte(x, y, (byte) pixel); } return out; } static public BWImage scaleDownUsingIntegralImageBW(IBWIntegralImage img, int w) { return scaleDownUsingIntegralImageBW(img, w, iround(w * img.getHeight() / (double) img.getWidth())); } static public BWImage scaleDownUsingIntegralImageBW(IBWIntegralImage img, int w, int h) { int w1 = img.getWidth(), h1 = img.getHeight(); BWImage out = new BWImage(w, h); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { int x1 = x * w1 / w, x2 = max(x1 + 1, (x + 1) * w1 / w); int y1 = y * h1 / h, y2 = max(y1 + 1, (y + 1) * h1 / h); int area = (x2 - x1) * (y2 - y1); int pixel = bwIntegralImage_sumRect(img, x1, y1, x2, y2) / area; out.setByte(x, y, (byte) pixel); } return out; } static public String addSuffix(String s, String suffix) { return s == null || s.endsWith(suffix) ? s : s + suffix; } static public RuntimeException augmentException(Throwable e, Object... info) { return new Fail(e, info); } static public String dummyMainClassName(String progID) { return "m" + psI(progID); } static public void printExceptionShort(Throwable e) { printExceptionShort("", e); } static public void printExceptionShort(String prefix, Throwable e) { print(prefix, exceptionToStringShort(e)); } static public void printWithMSTime(A a) { printWithMSTime("", a); } static public void printWithMSTime(String prefix, A a) { print(hmsWithColonsAndMS() + ": " + combinePrintParameters(prefix, a)); } static public void close_pcall(AutoCloseable c) { if (c != null) { try { c.close(); } catch (Throwable __e) { pcallFail(__e); } } } static public Component wrapForSmartAdd(Object o) { if (o == null) return jpanel(); if (o instanceof String) return jlabel((String) o); return wrap(o); } static public String intToHex_flexLength(int i) { return Integer.toHexString(i); } static public Map parseStdFunctionsList(String snippetSrc) { return parseStdFunctionsList(snippetSrc, new LinkedHashMap()); } static public Map parseStdFunctionsList(String snippetSrc, Map map) { List tok = javaTok(snippetSrc); int i = findCodeTokens(tok, "standardFunctions", "=", "litlist", "("); int opening = i + 6; int closing = indexOf(tok, ")", opening) - 1; for (i = opening + 2; i < closing; i += 4) { String[] f = unquote(tok.get(i)).split("/"); map.put(f[1], f[0]); } return map; } static public Set asSet(Object[] array) { HashSet set = new HashSet(); for (Object o : array) if (o != null) set.add(o); return set; } static public Set asSet(String[] array) { TreeSet set = new TreeSet(); for (String o : array) if (o != null) set.add(o); return set; } static public Set asSet(Iterable l) { if (l instanceof Set) return (Set) l; HashSet set = new HashSet(); for (A o : unnull(l)) if (o != null) set.add(o); return set; } static public Set asSet(MultiSet ms) { return ms == null ? null : ms.asSet(); } static public String autoFrameTitle_value; static public String autoFrameTitle() { return autoFrameTitle_value != null ? autoFrameTitle_value : getProgramTitle(); } static public void autoFrameTitle(Component c) { setFrameTitle(getFrame(c), autoFrameTitle()); } static public JPanel westCenterAndEast(Component w, Component c, Component e) { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.WEST, wrap(w)); panel.add(BorderLayout.CENTER, wrap(c)); panel.add(BorderLayout.EAST, wrap(e)); return panel; } static public boolean hasLock(Lock lock) { return ((ReentrantLock) lock).isHeldByCurrentThread(); } static public void scaffoldCalled(Object obj, Object function, Object... args) { printShortenedFunctionCall(200, (obj == null ? "" : shorten(20, str(obj)) + " :: ") + function, args); } static public void restart() { Object j = getJavaX(); call(j, "cleanRestart", get(j, "fullArgs")); } static public boolean trayIcon_imageAutoSize = true; static public TrayIcon installTrayIcon(String imageID, String tooltip) { return installTrayIcon(imageID, tooltip, null); } static public TrayIcon installTrayIcon(String imageID, String tooltip, Object... menuItems) { try { if (!isSnippetID(imageID) && isSnippetID(tooltip)) { String s = tooltip; tooltip = imageID; imageID = s; } Image image = loadImage2(imageID); return installTrayIcon(image, tooltip, menuItems); } catch (Exception __e) { throw rethrow(__e); } } static public TrayIcon installTrayIcon(final Image image, final String tooltip, final Object... _menuItems) { try { return swing(new F0() { public TrayIcon get() { try { Runnable leftClick = null; Object[] menuItems = params_unpackList(_menuItems); if (l(menuItems) > 0 && menuItems[0] instanceof Runnable) { leftClick = (Runnable) menuItems[0]; menuItems = dropFirst(menuItems); } PopupMenu menu = makePopupMenu(menuItems); TrayIcon trayIcon = new TrayIcon(image, tooltip, menu); trayIcon.setImageAutoSize(trayIcon_imageAutoSize); if (leftClick != null) { final Runnable _leftClick = leftClick; onLeftClick(trayIcon, _leftClick); } SystemTray.getSystemTray().add(trayIcon); return trayIcon; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Runnable leftClick = null;\r\n O[] menuItems = params_unpackList(_menuItems)..."; } }); } catch (Throwable __e) { return null; } } static public BufferedImage shootScreen2() { return shootScreen2(screenRectangle()); } static public BufferedImage shootScreen2(Rectangle area) { try { ping(); return new Robot().createScreenCapture(area); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedImage shootScreen2(Rect area) { return shootScreen2(area.getRectangle()); } static public BufferedImage shootScreen2(int x, int y, int w, int h) { return shootScreen2(new Rectangle(x, y, w, h)); } static public String toStringWithClass(Object o) { return o == null ? null : className(o) + " - " + o; } static public String hopeningTag(String tag, Map params) { return hopeningTag(tag, mapToParams(params)); } static public String hopeningTag(String tag, Object... params) { StringBuilder buf = new StringBuilder(); buf.append("<" + tag); params = unrollParams(params); for (int i = 0; i < l(params); i += 2) { String name = (String) get(params, i); Object val = get(params, i + 1); if (nempty(name) && val != null) { if (eqOneOf(val, html_valueLessParam(), true)) buf.append(" " + name); else { String s = str(val); if (!empty(s)) buf.append(" " + name + "=" + htmlQuote(s)); } } } buf.append(">"); return str(buf); } static public String dropNumberPrefix(String s) { return dropFirst(s, indexOfNonDigit(s)); } static public F0 fConst(A a) { return f0_const(a); } static public AutoCloseable tempSetField(Object o, String field, Object value) { final Object oldValue = get(o, field); set(o, field, value); return () -> set(o, field, oldValue); } static public AutoCloseable tempSetField(ISetAndGet gs, A value) { if (gs == null) return null; A oldValue = gs.get(); gs.set(value); return () -> gs.set(oldValue); } static public AutoCloseable tempSetField(A value, ISetAndGet gs) { return tempSetField(gs, value); } static public List filter(Iterable c, Object pred) { if (pred instanceof F1) return filter(c, (F1) pred); List x = new ArrayList(); if (c != null) for (Object o : c) if (isTrue(callF(pred, o))) x.add(o); return x; } static public List filter(Object pred, Iterable c) { return filter(c, pred); } static public List filter(Iterable c, F1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o)) x.add(o); return x; } static public List filter(F1 pred, Iterable c) { return filter(c, pred); } static public List filter(Iterable c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o)) x.add(o); return x; } static public List filter(B[] c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o)) x.add(o); return x; } static public List filter(IF1 pred, Iterable c) { return filter(c, pred); } static public A bindCheckBoxToLiveValue(A cb, SimpleLiveValue lv) { bindChangeListenerToComponent(cb, lv, new Runnable() { public void run() { try { setChecked(cb, isTrue(lv.get())); ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: ..."; } }); onChange(cb, new Runnable() { public void run() { try { lv.set(isChecked(cb)); ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: ..."; } }); return cb; } static public A bindCheckBoxToLiveValue(A cb, IVarWithNotify lv) { bindChangeListenerToComponent(cb, lv, new Runnable() { public void run() { try { setChecked(cb, isTrue(lv.get())); ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: ..."; } }); onChange(cb, new Runnable() { public void run() { try { lv.set(isChecked(cb)); ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: ..."; } }); return cb; } static public String fsIOpt(String s) { return formatSnippetIDOpt(s); } static public int deleteAllFilesInDirectory_minPathLength = 10; static public void deleteAllFilesInDirectory(File dir) { deleteAllFilesInDirectory(dir, false, false); } static public void deleteAllFilesInDirectory(File dir, boolean verbose, boolean testRun) { dir = getCanonicalFile(dir); assertTrue(f2s(dir), l(f2s(dir)) >= deleteAllFilesInDirectory_minPathLength); File[] files = dir.listFiles(); if (files == null) return; for (File f : files) { if (!isSymLink(f) && f.isDirectory()) deleteDirectory(f, verbose, testRun); else { if (verbose) print((testRun ? "Would delete " : "Deleting ") + f.getAbsolutePath()); if (!testRun) f.delete(); } } } static public void copyImagePart(BufferedImage src, int srcx, int srcy, BufferedImage dest, int destx, int desty, int w, int h) { Graphics2D g = dest.createGraphics(); BufferedImage sub = src.getSubimage(srcx, srcy, w, h); g.drawImage(sub, destx, desty, null); g.dispose(); } static public String appendWithNewLine(String a, String b) { if (empty(b)) return a; if (empty(a)) return b; return addSuffix(a, "\n") + b; } static public A assertEqualsVerbose(Object x, A y) { assertEqualsVerbose((String) null, x, y); return y; } static public A assertEqualsVerbose(String msg, Object x, A y) { if (!eq(x, y)) { throw fail((nempty(msg) ? msg + ": " : "") + "expected: " + x + ", got: " + y); } else print("OK" + (empty(msg) ? "" : " " + msg) + ": " + (x)); return y; } static public void assertEqualsVerbose(Scorer scorer, Object x, Object y) { assertEqualsVerbose(scorer, "", x, y); } static public void assertEqualsVerbose(Scorer scorer, String msg, Object x, Object y) { if (scorer == null) { assertEqualsVerbose(x, y); return; } if (!eq(x, y)) { print(appendColonIfNempty(msg) + y + " != " + x); scorer.add(false); } else { print("OK: " + appendColonIfNempty(msg) + x); scorer.add(true); } } static public boolean isOnPATH(String cmd) { return findCmdOnPATH(cmd) != null; } static public boolean isGeneralFileServerSnippet(long id) { return id >= 1400000 && id < 1500000; } static public Set syncLinkedHashSet() { return synchroLinkedHashSet(); } static public Throwable unwrapTrivialExceptionWraps(Throwable e) { if (e == null) return e; while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause(); return e; } static public int nfilter(Iterable c, IF1 pred) { return nfilter(pred, c); } static public int nfilter(IF1 pred, Iterable c) { int n = 0; if (c != null) for (A o : c) if (pred.get(o)) ++n; return n; } static public int nfilter(Iterable c, Object pred) { int n = 0; if (c != null) for (Object o : c) if (isTrue(callF(pred, o))) ++n; return n; } static public int nfilter(Object pred, Iterable c) { return nfilter(c, pred); } static public List sortFilesByName(List l) { sort(l, (a, b) -> stdcompare(a.getName(), b.getName())); return l; } static public double fracNonNeg(double d) { return frac_nonNeg(d); } static public String plusPrefixUnlessMinus(String s) { return startsWith(s, "-") ? s : "+" + s; } static public boolean tok_staticFunctionAlwaysReturnsVoid(List tok, String name) { Set types = tok_returnTypesOfStaticFunction_uncleaned(tok, name); if (empty(types)) return false; for (String type : types) if (!containsOneOf(javaTokC(type), javaxVoidAliases())) return false; return true; } static public boolean isKnownVoidFunction_uncached(String name) { return standardFunctionAlwaysReturnsVoid_uncached(name); } static public void addToContainer(Container a, Component... b) { if (a == null) return; { swing(() -> { for (Component c : unnullForIteration(b)) if (c != null) a.add(c); }); } } static public void mapPut(Map map, A key, B value) { if (map != null && key != null && value != null) map.put(key, value); } static public void mapPut(Map map, Pair p) { if (map != null && p != null) map.put(p.a, p.b); } static public String tag(String tag) { return htag(tag); } static public String tag(String tag, Object contents, Object... params) { return htag(tag, str(contents), params); } static public String tag(String tag, StringBuilder contents, Object... params) { return htag(tag, contents, params); } static public String tag(String tag, StringBuffer contents, Object... params) { return htag(tag, contents, params); } static public A printStructure(String prefix, A o) { if (endsWithLetter(prefix)) prefix += ": "; print(prefix + structureForUser(o)); return o; } static public A printStructure(A o) { print(structureForUser(o)); return o; } static public A onChange(A spinner, Object r) { return onChange(spinner, toRunnable(r)); } static public A onChange(A spinner, Runnable r) { if (r != null) { swing(() -> { spinner.addChangeListener(changeListener(r)); }); } return spinner; } static public A onChange(A b, Runnable r) { { swing(() -> { b.addItemListener(itemListener(r)); }); } return b; } static public void onChange(JTextComponent tc, Runnable r) { onUpdate(tc, r); } static public A onChange(A slider, Runnable r) { { swing(() -> { slider.addChangeListener(changeListener(r)); }); } return slider; } static public JComboBox onChange(JComboBox cb, ChangeTriggerable r) { return onChange(cb, new ChangeTrigger(r)); } static public JComboBox onChange(JComboBox cb, Updateable r) { return onChange(cb, new UpdateTrigger(r)); } static public JComboBox onChange(JComboBox cb, IVF1 f) { if (f != null) addActionListener(cb, () -> f.get(getSelectedItem_typed(cb))); return cb; } static public JComboBox onChange(JComboBox cb, Runnable r) { if (isEditableComboBox(cb)) onChange(textFieldFromComboBox(cb), r); else onSelectedItem(cb, runnableToIVF1(r)); return cb; } static public A onChange(A tabs, Runnable r) { { swing(() -> { tabs.addChangeListener(changeListener(r)); }); } return tabs; } static public A onChange(Runnable r, A cc) { if (cc != null && r != null) { swing(() -> { cc.getSelectionModel().addChangeListener(changeListener(r)); }); } return cc; } static public A onChange(A a, ChangeTriggerable b) { if (a != null && b != null) a.onChange(new ChangeTrigger(b)); return a; } static public A onChange(A a, Updateable b) { if (a != null && b != null) a.onChange(new UpdateTrigger(b)); return a; } static public A onChange(A a, Runnable r) { if (a != null && r != null) a.onChange(r); return a; } static public List splitCamelCase(String s) { return ai_splitCamelCase(s); } static public betterCIComparator_C betterCIComparator_instance; static public betterCIComparator_C betterCIComparator() { if (betterCIComparator_instance == null) betterCIComparator_instance = new betterCIComparator_C(); return betterCIComparator_instance; } final static public class betterCIComparator_C implements Comparator { public int compare(String s1, String s2) { if (s1 == null) return s2 == null ? 0 : -1; if (s2 == null) return 1; int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) { return c1 - c2; } } } } return n1 - n2; } } static public String appendColonIfNempty(String s) { return empty(s) ? "" : s + ": "; } static public PingSource pingSource() { return pingSource_tl().get(); } static public PingSource pingSource(Thread thread) { return pingSource_tl().get(thread); } static public Font loadFont(String snippetID) { try { return loadFont(snippetID, 12f); } catch (Exception __e) { throw rethrow(__e); } } static public Font loadFont(InputStream in) { try { return Font.createFont(Font.TRUETYPE_FONT, in); } catch (Exception __e) { throw rethrow(__e); } } static public Font loadFont(String snippetID, float fontSize) { return loadFont(loadLibrary(snippetID), fontSize); } static public Font loadFont(File f, float fontSize) { try { return Font.createFont(Font.TRUETYPE_FONT, f).deriveFont(fontSize); } catch (Exception __e) { throw rethrow(__e); } } static public Font loadFont(InputStream in, float fontSize) { try { return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(fontSize); } catch (Exception __e) { throw rethrow(__e); } } static public Class hotwireSharingLibraries_silently(String progID) { AutoCloseable __1 = temp_loadPage_silent(); try { return hotwireSharingLibraries(progID); } finally { _close(__1); } } static public String loadTextFileFromZipFile(File inZip, String fileName) { try { if (!fileExists(inZip)) return null; try { ZipFile zip = new ZipFile(inZip); try { return loadTextFileFromZipFile(zip, fileName); } finally { _close(zip); } } catch (Throwable e) { throw fail(f2s(inZip), e); } } catch (Exception __e) { throw rethrow(__e); } } static public String loadTextFileFromZipFile(ZipFile zip, String fileName) { try { ZipEntry entry = zip.getEntry(fileName); if (entry == null) return null; InputStream fin = zip.getInputStream(entry); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copyStream(fin, baos); return fromUTF8(baos.toByteArray()); } finally { _close(fin); } } catch (Exception __e) { throw rethrow(__e); } } static public void dm_popInModule(Object module) { dm_callOS("stefansOS_popInModule", dm_getStem(module)); } static public void dm_popInModule() { dm_popInModule(dm_current_generic_mandatory()); } static public String dropLeadingDots(String s) { int i = 0; while (charAt(s, i) == '.') ++i; return dropFirst(s, i); } static public Object[] mapToParams(Map map) { return mapToObjectArray(map); } static public String loadGZTextFile(File file) { try { if (!file.isFile()) return null; ping(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream fis = new FileInputStream(file); try { GZIPInputStream gis = newGZIPInputStream(fis); byte[] buffer = new byte[1024]; int len; while ((len = gis.read(buffer)) != -1) baos.write(buffer, 0, len); baos.close(); return fromUtf8(baos.toByteArray()); } finally { _close(fis); } } catch (Exception __e) { throw rethrow(__e); } } static public byte[] header = bytesFromHex("504B0304"); static public boolean isNonEmptySingleZip_byMagicHeader(byte[] data) { return byteArrayStartsWith(data, header); } static public boolean isNonEmptySingleZip_byMagicHeader(File f) { return isNonEmptySingleZip_byMagicHeader(loadBeginningOfBinaryFile(f, l(header))); } static public JComponent dm_vis(Object module) { return dm_getVisualization(module); } static public JComponent dm_vis() { return dm_getVisualization(); } static public void probabilisticForEach(IProbabilisticScheduler scheduler, double pStart, double pEnd, Collection l, IVF1 f) { if (scheduler == null || f == null) return; probabilisticForEach(scheduler, pStart, pEnd, iterator(l), 0, l(l), 1.0, f); } static public void probabilisticForEach(IProbabilisticScheduler scheduler, double pStart, double pEnd, Iterator it, int i, int n, double myProb, IVF1 f) { assertTrue(pEnd <= pStart); if (scheduler == null || f == null || !it.hasNext()) return; A a = it.next(); double p = blend(pStart, pEnd, doubleRatio(i, n - 1)); scheduler.at(new Runnable() { public void run() { try { f.get(a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return formatFunctionCall(f, a); } }); scheduler.atRelative(doubleRatio(p, myProb), () -> probabilisticForEach(scheduler, pStart, pEnd, it, i + 1, n, p, f)); } static public String utf8streamToString(InputStream in) { return readerToString(utf8bufferedReader(in)); } static public double frac_nonNeg(double d) { return mod(d, 1); } static public boolean isInQ(Q q) { return q != null && isCurrentThread(q.rst.thread); } static public String uniqueFileNameUsingMD5_80_v2(String fullName) { return uniqueFileNameUsingMD5_80_v2(fullName, md5(fullName)); } static public String uniqueFileNameUsingMD5_80_v2(String fullName, String md5) { return takeFirst(80 - 33, fileNameEncode(fullName)) + " - " + md5; } static public boolean isMenuSeparatorIndicator(Object o) { return eqOneOf(o, "***", "---", "===", ""); } static public A applyMargin(int top, int left, int bottom, int right, A c) { return addMargin(top, left, bottom, right, c); } static public A applyMargin(int w, A c) { return addMargin(w, c); } static public BufferedImage intMatrixToBufferedImage(Matrix m) { if (m == null) return null; int w = m.getWidth(), h = m.getHeight(); int[] pixels = matrixToIntArray(m); return newBufferedImage(w, h, pixels); } static public int withTopMargin_defaultWidth = 6; static public JPanel withTopMargin(Component c) { return withTopMargin(withTopMargin_defaultWidth, c); } static public JPanel withTopMargin(final int w, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0)); p.add(c); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat..."; } }); } static public Lock downloadLock_lock = fairLock(); static public Lock downloadLock() { return downloadLock_lock; } static public Boolean hasGlobalOption(String option) { String question = print(option + "?"); return askTripleBool(question); } static public void dm_inQ(Runnable r) { dm_q().add(r); } static public void dm_inQ(DynModule mod, Runnable r) { dm_q(mod, r); } static public File dirOfFile(File f) { return f == null ? null : f.getParentFile(); } static public A bindJLabelToLiveValue(final A label, final LiveValue lv) { bindLiveValueListenerToComponent(label, lv, new Runnable() { public void run() { try { setText(label, strOrNull(lv.get())); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setText(label, strOrNull(lv!))"; } }); return label; } static public RuntimeException error() { throw new RuntimeException("fail"); } static public RuntimeException error(String msg) { throw new RuntimeException(msg); } static public A setBackground(final Color color, final A a) { if (a != null) { swing(() -> { a.setBackground(color); }); } return a; } static public A setBackground(A a, Color color) { return setBackground(color, a); } static public Boolean dm_getFlag(String flagName) { Object mod = dm_current_generic(); Object stem = dm_stem(mod); Integer flagCode = (Integer) (getOpt(flagName, stem)); return flagCode == null ? null : (Boolean) call(stem, "hasFlag", flagCode); } static public String renderVars(Object... params) { return renderVars_str(params); } static public long sysNow() { ping(); return System.nanoTime() / 1000000; } static public Throwable innerException(Throwable e) { return getInnerException(e); } static public boolean isCurrentThread(Thread t) { return t != null && t == currentThread(); } static public String dropPrefixTrim(String prefix, String s) { return trim(dropPrefix(prefix, s)); } static public double elapsedSeconds(long time) { return toSeconds(sysNow() - time); } static public double elapsedSeconds(Timestamp ts) { return ts == null ? Double.NaN : toSeconds(now() - ts.date); } static public BigInteger bigint(String s) { return new BigInteger(s); } static public BigInteger bigint(long l) { return BigInteger.valueOf(l); } static public Class hotwire(String src) { return hotwire(src, __1 -> mainClassNameForClassLoader(__1)); } static public Class hotwire(String src, IF1 calculateMainClass) { assertFalse(_inCore()); Class j = getJavaX(); if (isAndroid()) { synchronized (j) { List libraries = new ArrayList(); File srcDir = (File) call(j, "transpileMain", src, libraries); if (srcDir == null) throw fail("transpileMain returned null (src=" + quote(src) + ")"); Object androidContext = get(j, "androidContext"); return (Class) call(j, "loadx2android", srcDir, src); } } else { return hotwire_overInternalBot(src, calculateMainClass); } } static public List wrapPrimitiveArrayAsImmutableList(Object array) { int n = Array.getLength(array); return new RandomAccessAbstractList() { public int size() { return n; } public Object get(int i) { return Array.get(array, i); } }; } static public List> matrixOfMatricesToListOfLists(Matrix> mm) { return map(__93 -> matrixToList(__93), matrixToList(mm)); } static public Object metaGet(IMeta o, Object key) { return metaMapGet(o, key); } static public Object metaGet(Object o, Object key) { return metaMapGet(o, key); } static public Object metaGet(String key, IMeta o) { return metaMapGet(o, key); } static public Object metaGet(String key, Object o) { return metaMapGet(o, key); } static public List newSubListOrSame(List l, int startIndex) { return newSubListOrSame(l, startIndex, l(l)); } static public List newSubListOrSame(List l, int startIndex, int endIndex) { if (l == null) return null; int n = l(l); startIndex = max(0, startIndex); endIndex = min(n, endIndex); if (startIndex >= endIndex) return ll(); if (startIndex == 0 && endIndex == n) return l; return cloneList(l.subList(startIndex, endIndex)); } static public List newSubListOrSame(List l, IntRange r) { return newSubListOrSame(l, r.start, r.end); } static public TreeSet caseInsensitiveSet_treeSet() { return new TreeSet(caseInsensitiveComparator()); } static public TreeSet caseInsensitiveSet_treeSet(Collection c) { return toCaseInsensitiveSet_treeSet(c); } static public A heldInstance(Class c) { List l = holdInstance_l.get(); for (int i = l(l) - 1; i >= 0; i--) { Object o = l.get(i); if (isInstanceOf(o, c)) return (A) o; } throw fail("No instance of " + className(c) + " held"); } static public Class veryQuickJava(CharSequence mainJava) { return veryQuickJava3(str(mainJava)); } static public String firstJavaToken(String s) { if (s == null) return null; int l = s.length(); int j = 0; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } if (j >= l) return null; int i = j; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else if (c == '[' && d == '[') { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') { do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]")); j = Math.min(j + 3, l); } else ++j; return quickSubstring(s, i, j); } static public String fromUTF8(byte[] bytes) { return fromUtf8(bytes); } static public List listCreateAndAdd(List l, A a) { return addDyn(l, a); } static public > IterableIterator nestedIterator(Iterable c, final F1 makeInnerIterator) { return nestedIterator(iterator(c), makeInnerIterator); } static public > IterableIterator nestedIterator(Iterable c, IF1 makeInnerIterator) { return nestedIterator(iterator(c), makeInnerIterator); } static public > IterableIterator nestedIterator(IterableIterator c, IF1 makeInnerIterator) { return nestedIterator((Iterator) c, makeInnerIterator); } static public > IterableIterator nestedIterator(Iterator it1, IF1 makeInnerIterator) { if (it1 == null || !it1.hasNext()) return emptyItIt(); return iff(new F0() { public A a; public Iterator innerIterator; { nextOuter(); } public void nextOuter() { a = it1.next(); innerIterator = makeInnerIterator.get(a); } public Object get() { while (true) { ping(); if (innerIterator != null && innerIterator.hasNext()) return innerIterator.next(); if (!it1.hasNext()) return endMarker(); nextOuter(); } } }); } static public > IterableIterator nestedIterator(final Iterator it1, F1 makeInnerIterator) { if (it1 == null || !it1.hasNext()) return emptyItIt(); return iff(new F0() { public A a; public Iterator innerIterator; { nextOuter(); } public void nextOuter() { a = it1.next(); innerIterator = makeInnerIterator.get(a); } public Object get() { while (true) { ping(); if (innerIterator != null && innerIterator.hasNext()) return innerIterator.next(); if (!it1.hasNext()) return endMarker(); nextOuter(); } } }); } static public > IterableIterator nestedIterator(IF1 makeInnerIterator, Iterator it1) { return nestedIterator(it1, makeInnerIterator); } static public > IterableIterator nestedIterator(IF1 makeInnerIterator, Collection l) { return nestedIterator(l, makeInnerIterator); } static public String tok_packageName(List tok) { int i = jfind(tok, "package"); if (i < 0) return ""; i += 2; int j = jfind(tok, i, ";"); if (j < 0) return ""; return join(codeTokensOnly(subList(tok, i - 1, j))); } static public String tok_packageName(String src) { Producer p = javaTokC_producer(src); String t = p.next(); if (!eq(t, "package")) return ""; StringBuilder buf = new StringBuilder(); while (!eqOneOf(t = p.next(), null, ";")) buf.append(t); return str(buf); } static public String getProgramName_cache; static public String getProgramName() { Lock __0 = downloadLock(); lock(__0); try { if (getProgramName_cache == null) getProgramName_cache = getSnippetTitleOpt(programID()); return getProgramName_cache; } finally { unlock(__0); } } static public void _onLoad_getProgramName() { { startThread(new Runnable() { public void run() { try { getProgramName(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getProgramName();"; } }); } } static public double twoPi() { return Math.PI * 2; } static public int defaultMargin() { return withMargin_defaultWidth; } static public List javaTokPlusPeriod(String s) { List tok = new ArrayList(); if (s == null) return tok; int l = s.length(); int i = 0; while (i < l) { int j = i; char c; String cc; while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j + 2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); cc = s.substring(i, Math.min(i + 2, l)); if (c == (char) 0x201C || c == (char) 0x201D) c = '"'; if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { char _c = s.charAt(j); if (_c == (char) 0x201C || _c == (char) 0x201D) _c = '"'; if (_c == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } if (j - 1 >= i + 1) { tok.add(opener + s.substring(i + 1, j - 1) + opener); i = j; continue; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); else if (Character.isDigit(c)) do ++j; while (j < l && Character.isDigit(s.charAt(j))); else if (cc.equals("[[")) { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (cc.equals("[=") && i + 2 < l && s.charAt(i + 2) == '[') { do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]")); j = Math.min(j + 3, l); } else if (s.substring(j, Math.min(j + 3, l)).equals("...")) j += 3; else if (c == '$' || c == '#') do ++j; while (j < l && Character.isDigit(s.charAt(j))); else ++j; tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static public String htmldecode(final String input) { if (input == null) return null; final int MIN_ESCAPE = 2; final int MAX_ESCAPE = 6; StringWriter writer = null; int len = input.length(); int i = 1; int st = 0; while (true) { while (i < len && input.charAt(i - 1) != '&') i++; if (i >= len) break; int j = i; while (j < len && j < i + MAX_ESCAPE + 1 && input.charAt(j) != ';') j++; if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) { i++; continue; } if (input.charAt(i) == '#') { int k = i + 1; int radix = 10; final char firstChar = input.charAt(k); if (firstChar == 'x' || firstChar == 'X') { k++; radix = 16; } try { int entityValue = Integer.parseInt(input.substring(k, j), radix); if (writer == null) writer = new StringWriter(input.length()); writer.append(input.substring(st, i - 1)); if (entityValue > 0xFFFF) { final char[] chrs = Character.toChars(entityValue); writer.write(chrs[0]); writer.write(chrs[1]); } else { writer.write(entityValue); } } catch (NumberFormatException ex) { i++; continue; } } else { CharSequence value = htmldecode_lookupMap().get(input.substring(i, j)); if (value == null) { i++; continue; } if (writer == null) writer = new StringWriter(input.length()); writer.append(input.substring(st, i - 1)); writer.append(value); } st = j + 1; i = st; } if (writer != null) { writer.append(input.substring(st, len)); return writer.toString(); } return input; } static public HashMap htmldecode_lookupMap_cache; static public HashMap htmldecode_lookupMap() { if (htmldecode_lookupMap_cache == null) htmldecode_lookupMap_cache = htmldecode_lookupMap_load(); return htmldecode_lookupMap_cache; } static public HashMap htmldecode_lookupMap_load() { var map = new HashMap(); for (CharSequence[] seq : htmldecode_escapes()) map.put(seq[1].toString(), seq[0]); return map; } static public boolean loadBufferedImageFixingGIFs_debug = false; static public ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal(); static public Image loadBufferedImageFixingGIFs(File file) { try { if (!file.exists()) return null; if (!isGIF(file)) return ImageIO.read(file); if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": checking gif"); ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next(); reader.setInput(ImageIO.createImageInputStream(file)); int numImages = reader.getNumImages(true); IIOMetadata imageMetaData = reader.getImageMetadata(0); String metaFormatName = imageMetaData.getNativeMetadataFormatName(); boolean foundBug = false; for (int i = 0; i < numImages && !foundBug; i++) { IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName); int nNodes = root.getLength(); for (int j = 0; j < nNodes; j++) { org.w3c.dom.Node node = root.item(j); if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) { String delay = ((IIOMetadataNode) node).getAttribute("delayTime"); if (Integer.parseInt(delay) == 0) { foundBug = true; } break; } } } if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug); Image image; if (!foundBug) { image = Toolkit.getDefaultToolkit().createImage(f2s(file)); } else { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); { ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream); try { ImageWriter writer = ImageIO.getImageWriter(reader); writer.setOutput(ios); writer.prepareWriteSequence(null); for (int i = 0; i < numImages; i++) { BufferedImage frameIn = reader.read(i); IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName); int nNodes = root.getLength(); for (int j = 0; j < nNodes; j++) { org.w3c.dom.Node node = root.item(j); if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) { String delay = ((IIOMetadataNode) node).getAttribute("delayTime"); if (Integer.parseInt(delay) == 0) { ((IIOMetadataNode) node).setAttribute("delayTime", "10"); } break; } } IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null); metadata.setFromTree(metadata.getNativeMetadataFormatName(), root); IIOImage frameOut = new IIOImage(frameIn, null, metadata); writer.writeToSequence(frameOut, writer.getDefaultWriteParam()); } writer.endWriteSequence(); } finally { _close(ios); } } byte[] data = baoStream.toByteArray(); setVar(loadBufferedImageFixingGIFs_output.get(), data); if (loadBufferedImageFixingGIFs_debug) print("Data size: " + l(data)); image = Toolkit.getDefaultToolkit().createImage(data); } return image; } catch (Exception __e) { throw rethrow(__e); } } static public List filesForNiceButtons(List l, IVF1 action) { return map(l, f -> { var tia = textImageActionToolTip(f.getName(), isImageFile(f) ? "#1101250" : "#1101231", new Runnable() { public void run() { try { pcallF(action, f); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, f)"; } }, f2s(f) + " (" + toK(fileSize(f)) + " K)"); tia.file = f; return tia; }); } static public List filesForNiceButtons(List l) { return filesForNiceButtons(l, f -> { { startThread(new Runnable() { public void run() { try { genericUI_openFile(f); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "genericUI_openFile(f);"; } }); } }); } static public A makeNiceButtons_usingStack(A stack, Object... params) { params = flattenArray2(params); for (int i = 0; i < l(params); ) { TextImageAction tia = null; if (params[i] instanceof TextImageAction) { tia = (TextImageAction) params[i]; i++; } else { tia = new TextImageAction(str(get(params, i)), str(get(params, i + 1)), get(params, i + 2)); i += 3; } final TextImageAction _tia = tia; Object action = tia.action; final String buttonDesc = action == null ? "actionless button " + sfu(_tia) : "button " + sfu(cloneWithoutField(_tia, "action")) + " with action " + trim(simpleSpaces(newLinesToSpaces(shorten(str(tia.action), 40)))); action = new Runnable() { public void run() { try { appendToLocalMechLog("User actions", "User clicked on " + buttonDesc); callF(_tia.action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "appendToLocalMechLog(\"User actions\", \"User clicked on \" + buttonDesc);\r\n ..."; } }; JButton b = jImageAndTextButton(tia.imageID, tia.text, action); if (nempty(tia.toolTip)) setToolTip(b, tia.toolTip); componentPopupMenu(b, tia.popupMenuMaker); resizeImageButtonToMax(b, niceButtons_maxImageSize()); setVerticalTextPosition(JButton.TOP, setFontSize(15, makeBold(b))); setVerticalAlignment(JButton.TOP, b); setMargin(10, b); onMouseEnter(b, new Runnable() { public void run() { try { appendToLocalMechLog("Mouse hovers", "Mouse hovered over " + buttonDesc); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "appendToLocalMechLog(\"Mouse hovers\", \"Mouse hovered over \" + buttonDesc)"; } }); onMouseExit(b, new Runnable() { public void run() { try { appendToLocalMechLog("Mouse hovers", "Mouse no longer hovers over " + buttonDesc); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "appendToLocalMechLog(\"Mouse hovers\", \"Mouse no longer hovers over \" + buttonD..."; } }); metaSet(b, TextImageAction.class, tia); stack.addComponent(b); } return stack; } static public DynamicHStack makeNiceButtons(Object... params) { return makeNiceButtons_usingStack((DynamicHStack) dynamicHStack().spacing(20), params); } static public String unquote(String s) { if (s == null) return null; if (startsWith(s, '[')) { int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; if (i < s.length() && s.charAt(i) == '[') { String m = s.substring(1, i); if (s.endsWith("]" + m + "]")) return s.substring(i + 1, s.length() - i - 1); } } return unquoteSingleOrDoubleQuotes(s); } static public boolean startsWithOneOf(String s, String... l) { for (String x : l) if (startsWith(s, x)) return true; return false; } static public boolean startsWithOneOf(String s, Matches m, String... l) { for (String x : l) if (startsWith(s, x, m)) return true; return false; } static public String aOrAn(String s) { return a(s); } static public AutoCloseable tempPingPrivileged() { return tempSetTL_noInit(pingSource_tl(), null); } static public A[] dropLast(A[] a) { return dropLast(a, 1); } static public A[] dropLast(A[] a, int n) { if (a == null) return null; n = Math.min(n, a.length); A[] b = arrayOfSameType(a, a.length - n); System.arraycopy(a, 0, b, 0, b.length); return b; } static public List dropLast(List l) { return subList(l, 0, l(l) - 1); } static public List dropLast(int n, List l) { return subList(l, 0, l(l) - n); } static public List dropLast(Iterable l) { return dropLast(asList(l)); } static public String dropLast(String s) { return substring(s, 0, l(s) - 1); } static public String dropLast(String s, int n) { return substring(s, 0, l(s) - n); } static public String dropLast(int n, String s) { return dropLast(s, n); } static public String getTabTitle(JTabbedPane tabs, int idx) { return tabs == null || idx < 0 ? null : swing(() -> idx < tabs.getTabCount() ? tabs.getTitleAt(idx) : null); } static public JTable tablePopupMenuItemsThreaded_top(final JTable table, Object... params) { params = reverseParams(params); for (int i = 0; i + 1 < l(params); i += 2) { final Object action = params[i + 1]; final Object threadInfo = _threadInfo(); tablePopupMenuItem_top(table, str(params[i]), new VF1() { public void get(final Integer row) { try { _threadInheritInfo(threadInfo); { startThread(new Runnable() { public void run() { try { try { callF(action, row); } catch (Throwable __e) { messageBox(__e); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n callF(action, row);\r\n } catch (Throwable __e) { messageBo..."; } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_threadInheritInfo(threadInfo);\r\n thread-messagebox {\r\n callF(act..."; } }); } return table; } static public 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 JLabel jImageLabel(Image img) { return swingNu(JLabel.class, imageIcon(img)); } static public JLabel jImageLabel(javax.swing.Icon icon) { return swingNu(JLabel.class, icon); } static public JLabel jImageLabel(String imageID) { return jImageLabel(imageIcon(imageID)); } static public JLabel jImageLabel(String text, String imageID) { final JLabel l = swingNu(JLabel.class, text, imageIcon(imageID), JLabel.CENTER); { swing(() -> { l.setVerticalTextPosition(SwingConstants.BOTTOM); l.setHorizontalTextPosition(SwingConstants.CENTER); }); } return l; } static public RuntimeException unimplemented() { throw fail("TODO"); } static public RuntimeException unimplemented(String msg) { throw fail("TODO: " + msg); } static public RuntimeException unimplemented(Object obj) { throw fail("TODO: implement method in " + className(obj)); } static public String appendParamsToURL(String url, Map params) { return appendQueryToURL(url, params); } static public String appendParamsToURL(String url, Object... data) { return appendQueryToURL(url, data); } static public Collection findConceptsWhere(Class c, Object... params) { return findConceptsWhere(db_mainConcepts(), c, params); } static public Collection findConceptsWhere(String c, Object... params) { return findConceptsWhere(db_mainConcepts(), c, params); } static public Collection findConceptsWhere(Concepts concepts, Class c, Object... params) { ping(); params = expandParams(c, params); if (concepts.fieldIndices != null) for (int i = 0; i < l(params); i += 2) { IFieldIndex index = concepts.getFieldIndex(c, (String) params[i]); if (index != null) { Collection rawList = index.getAll(params[i + 1]); params = dropEntryFromParams(params, i); if (params == null) return rawList; List l = new ArrayList(); for (A x : rawList) if (checkConceptFields(x, params)) l.add(x); return l; } } return filterConcepts(concepts.list(c), params); } static public Collection findConceptsWhere(Concepts concepts, String c, Object... params) { return filterConcepts(concepts.list(c), params); } static public A printStackTrace_gen(A e) { if (e instanceof Throwable) printStackTrace((Throwable) e); else print(e); return e; } static public HashSet litset(A... items) { return lithashset(items); } 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 Class veryQuickJava_finish_specialMainClass(String mainClassName, String src) { return veryQuickJava_finish_specialMainClass(mainClassName, src, null); } static public Class veryQuickJava_finish_specialMainClass(String mainClassName, String src, List libs) { src = findTranslators2(src, libs = cloneList(libs)); File bytecode = javaCompile_overInternalBot(src, join(" ", libs)); return hotwireCoreSpecialMainClass(mainClassName, concatLists(ll(bytecode), loadLibraries(libs))); } 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 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 String replacePrefix(String prefix, String replacement, String s) { if (!startsWith(s, prefix)) return s; return replacement + substring(s, l(prefix)); } static public AutoCloseable tempDBLock(Concepts concepts) { return tempLock(concepts.lock); } static public AutoCloseable tempDBLock() { return tempDBLock(db_mainConcepts()); } static public LinkedHashMap cloneLinkedHashMap(Map map) { return map == null ? new LinkedHashMap() : new LinkedHashMap(map); } static public String nLabels(long n) { return n2(n, "label"); } static public String nLabels(Collection l) { return nLabels(l(l)); } static public String nLabels(Map map) { return nLabels(l(map)); } 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 JComboBox jcombobox(String selectedItem, Collection items) { return jcombobox(items, selectedItem); } static public String toHex(byte[] bytes) { return bytesToHex(bytes); } static public String toHex(byte[] bytes, int ofs, int len) { return bytesToHex(bytes, ofs, len); } static public List showForm_arrange1(List> l) { int minW = showForm_leftWidth(l); List out = new ArrayList(); for (List row : l) out.add(westAndCenter(withRightMargin(showForm_gapBetweenColumns, jMinWidthAtLeast(minW, first(row))), second(row))); return out; } static public int selectedTableRow(final JTable t) { return t == null ? -1 : swing(new F0() { public Integer get() { try { return t.getSelectedRow(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return t.getSelectedRow();"; } }); } 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, jbuttonWithDisable("Medium transpile", 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 Map immutableEmptyMap() { return Collections.emptyMap(); } static public Rect preferredScreenBounds() { return screenBounds_safe(preferredScreen()); } static public String fileSep() { return File.separator; } static public List buttonsInGroup(ButtonGroup g) { if (g == null) return ll(); return asList(g.getElements()); } static public List characters(final String s) { return stringAsCharacterList(s); } 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 SimpleDateFormat simpleDateFormat_UTC(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf; } static public void swingEvery(JComponent component, long delay, Object r) { installTimer(component, delay, r); } static public void swingEvery(JComponent component, long delay, long firstDelay, Object r) { installTimer(component, r, delay, firstDelay); } static public void swingEvery(RootPaneContainer frame, long delay, Object r) { installTimer(frame, delay, r); } static public void swingEvery(RootPaneContainer frame, long delay, long firstDelay, Object r) { installTimer(frame, delay, firstDelay, r); } static public void setComponentID(Component c, String id) { if (c != null) componentID_map.put(c, id); } static public String a(String noun) { if (eq(noun, "")) return "?"; return ("aeiou".indexOf(noun.charAt(0)) >= 0 ? "an " : "a ") + noun; } static public String a(String contents, Object... params) { return hfulltag("a", contents, params); } static public Map synchronizedMap() { return synchroMap(); } static public Map synchronizedMap(Map map) { return synchroMap(map); } static volatile public boolean licensed_yes = true; static public boolean licensed() { if (!licensed_yes) return false; ping_okInCleanUp(); return true; } static public void licensed_off() { licensed_yes = false; } static public boolean oneIn(int n) { return random(n) == 0; } static public boolean oneIn(int n, Random random) { return random(random, n) == 0; } static public boolean oneIn(Random random, int n) { return oneIn(n, random); } static public BufferedImage resizeImageToHeight_bilinear(BufferedImage img, int newH) { return scaleImage_bilinear(doubleRatio(newH, img.getHeight()), img); } static public boolean haveMuricaPassword() { return nempty(muricaPassword()); } 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 Runnable addThreadInfoToRunnable(final Object r) { final Object info = _threadInfo(); return info == null ? asRunnable(r) : new Runnable() { public void run() { try { _inheritThreadInfo(info); callF(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_inheritThreadInfo(info); callF(r);"; } }; } static public 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(IMultiSet ms) { return ms == null ? 0 : ms.size(); } static public int l(IMultiMap mm) { return mm == null ? 0 : mm.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(ShortBuffer b) { return b == null ? 0 : b.size(); } static public int l(IntSize o) { return o == null ? 0 : o.size(); } static public JPanel jRaisedCenteredSection(Component c) { return jRaisedCenteredSection("", c); } static public JPanel jRaisedCenteredSection(String title, Component c) { return jCenteredRaisedSection(title, c); } static public Object vm_generalMap_set(Object key, Object value) { return vm_generalMap_put(key, value); } static public JPanel jcenteredbuttons(Object... params) { return jcenteredline(paramsToButtons(params)); } static public GlobalID asGlobalID(String id) { return id == null ? null : new GlobalID(id); } static public Pair uniq2(Class c, Object... params) { return uniq2(db_mainConcepts(), c, params); } static public Pair uniq2(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); return pair(x, true); } return pair(x, false); } finally { _close(__1); } } static public String copyTextToClipboard(Object _text) { String text = str(_text); StringSelection selection = new StringSelection(text); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection); vmBus_send("newClipboardContents", text); return text; } static public A findConceptWhere(Class c, Object... params) { return findConceptWhere(db_mainConcepts(), c, params); } static public A findConceptWhere(Concepts concepts, Class c, Object... params) { ping(); params = expandParams(c, params); if (concepts.fieldIndices != null) for (int i = 0; i < l(params); i += 2) { IFieldIndex index = concepts.getFieldIndex(c, (String) params[i]); if (index != null) { for (A x : index.getAll(params[i + 1])) if (checkConceptFields(x, params)) return x; return null; } } for (A x : concepts.list(c)) if (checkConceptFields(x, params)) return x; return null; } static public Concept findConceptWhere(Concepts concepts, String c, Object... params) { for (Concept x : concepts.list(c)) if (checkConceptFields(x, params)) return x; return null; } static public File muricaPasswordFile() { return new File(javaxSecretDir(), "murica/muricaPasswordFile"); } 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 boolean syncRemoveAll(Collection c, Collection b) { if (c == null || b == null) return false; synchronized (collectionMutex(c)) { return c.removeAll(b); } } static public boolean startsWithIgnoreCase(String a, String b) { return regionMatchesIC(a, 0, b, 0, b.length()); } 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 BufferedImage whiteImage(WidthAndHeight size) { return whiteImage(size.getWidth(), size.getHeight()); } static public Iterator emptyIterator() { return Collections.emptyIterator(); } 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(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(IMultiMap mm) { return mm == null || mm.size() == 0; } 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(SynchronizedLongBuffer b) { return b == null || b.isEmpty(); } static public boolean empty(DoubleBuffer b) { return b == null || b.isEmpty(); } static public boolean empty(SynchronizedDoubleBuffer b) { return b == null || b.isEmpty(); } static public boolean empty(SynchronizedFloatBufferPresentingAsDoubles b) { return b == null || b.isEmpty(); } static public boolean empty(IDoubleBuffer b) { return b == null || b.isEmpty(); } static public boolean empty(ILongBuffer 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(Chain c) { return c == null; } static public boolean empty(AppendableChain c) { return c == null; } static public boolean empty(IntSize l) { return l == null || l.size() == 0; } static public void minWindowWidth(Window window, int w) { if (window != null) { swing(() -> { if (window.getWidth() < w) window.setSize(w, window.getHeight()); }); } } static public A oneOf(List l) { if (empty(l)) return null; int n = l.size(); return n == 1 ? first(l) : l.get(defaultRandomizer().nextInt(n)); } static public char oneOf(String s) { return empty(s) ? '?' : s.charAt(random(l(s))); } static public A oneOf(A... l) { return oneOf(asList(l)); } static public void cancelAndInterruptThread(Thread t) { if (t == null) return; cancelThread(t); t.interrupt(); } static public Rect boundsAsRect(Component c) { return boundsRect(c); } static public IterableIterator singletonIterator(A a) { return new IterableIterator() { public boolean returned = false; public A next() { if (!returned) { returned = true; return a; } else throw fail(); } public boolean hasNext() { return !returned; } }; } static public void showPopupMenu(JPopupMenu menu, MouseEvent e) { if (menu != null && e != null) menu.show(e.getComponent(), e.getX(), e.getY()); } static public IterableIterator navigableMultiSetMapValuesIterator_concurrent(final MultiSetMap mm) { return navigableMultiSetMapValuesIterator_concurrent(mm, mm.data); } static public IterableIterator navigableMultiSetMapValuesIterator_concurrent(final MultiSetMap mm, Object mutex) { return iteratorFromFunction(new F0() { public Iterator> it = concurrentlyIterateValues((NavigableMap) mm.data, mutex); public Iterator it2; public B get() { while (it2 == null || !it2.hasNext()) { if (!it.hasNext()) return null; it2 = iterator(asList(it.next())); } return it2.next(); } }); } 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 List list(Concepts concepts) { return asList(concepts.allConcepts()); } 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 IVarWithNotify getterVarOnly(IVarWithNotify var) { if (var == null) return null; var var2 = new VirtualVar(() -> var.get(), null); addWeakChangeListener(var, var2); return var2; } static public void desktopOpen(File f) { try { if (f != null) { print("desktopOpen: " + f2s(f)); Desktop.getDesktop().open(f); } } catch (Exception __e) { throw rethrow(__e); } } static public JSpinner jSpinner() { return swing(() -> { JSpinner s = new JSpinner(); return jSpinnerCommitOnValidEdit(s); }); } static public JSpinner jSpinner(int value) { return swing(() -> { JSpinner s = new JSpinner(); s.setValue(value); return jSpinnerCommitOnValidEdit(s); }); } static public JSpinner jSpinner(int min, int max) { return jSpinner(min, min, max); } static public JSpinner jSpinner(int value, int min, int max) { return swing(() -> { return jSpinnerCommitOnValidEdit(new JSpinner(new SpinnerNumberModel(value, min, max, 1))); }); } static public String prependIfNempty(String prefix, String s) { return empty(s) ? unnull(s) : prefix + s; } static public JPanel makeForm2(Object... parts) { return makeForm_customLayout(formLayouter1(), parts); } static public A onFirstShow(A component, Runnable onShow) { return onFirstComponentShow(component, onShow); } static public A onFirstShow(Runnable onShow, A component) { return onFirstShow(component, onShow); } static public JComponent makeForm3(Object... parts) { return new JForm(parts).visualize(); } static public byte[] toUtf8(String s) { try { return s.getBytes(utf8charset()); } catch (Exception __e) { throw rethrow(__e); } } static public A nuInstance(Class c) { return nuEmptyObject(c); } static public Object[] dropEntryFromParams(Object[] params, int i) { int n = l(params); if (i < 0 || i >= n) return params; if (n == 2) return null; Object[] p = new Object[n - 2]; System.arraycopy(params, 0, p, 0, i); System.arraycopy(params, i + 2, p, i, n - i - 2); return p; } static public Rectangle maxWindowBounds() { return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); } static public boolean cic(Collection l, String s) { return containsIgnoreCase(l, s); } static public boolean cic(Collection l, Symbol s) { return contains(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 JLabel jCenteredLiveValueLabel(final LiveValue lv) { return centerLabel(jLiveValueLabel(lv)); } static public IterableIterator iteratorFromFunction_f0(final F0 f) { class IFF2 extends IterableIterator { public A a; public boolean done = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } public void getNext() { if (done || a != null) return; a = f.get(); done = a == null; } } ; return new IFF2(); } static public Set reflection_classesNotToScan_value = litset("jdk.internal.loader.URLClassPath"); static public Set reflection_classesNotToScan() { return reflection_classesNotToScan_value; } static public List flattenCollectionsAndArrays(Iterable a) { List l = new ArrayList(); for (Object x : a) if (x instanceof Collection) l.addAll(flattenCollectionsAndArrays((Collection) x)); else if (x instanceof Object[]) l.addAll(flattenCollectionsAndArrays(asList((Object[]) x))); else l.add(x); return l; } static public List flattenCollectionsAndArrays(Object... whatever) { return flattenCollectionsAndArrays(ll(whatever)); } static public JLabel jSimpleLabel() { return jSimpleLabel(""); } static public JLabel jSimpleLabel(String text) { return swing(() -> new JLabel(text)); } 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 JPanel centerAndSouthOrEast(boolean horizontal, Component c, Component s) { return horizontal ? centerAndEast(c, s) : centerAndSouth(c, s); } static public IF1 toIF1(final Object f) { if (f == null) return null; if (f instanceof IF1) return (IF1) f; if (isString(f)) { throw fail("callF_legacy"); } return new IF1() { public Object get(Object a) { return callF(f, a); } }; } public static byte[] saveBinaryFile(String fileName, byte[] contents) { try { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; try (FileOutputStream fileOutputStream = newFileOutputStream(tempFileName)) { fileOutputStream.write(contents); } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); vmBus_send("wroteFile", file); return contents; } catch (Exception __e) { throw rethrow(__e); } } static public byte[] saveBinaryFile(File fileName, byte[] contents) { return saveBinaryFile(fileName.getPath(), contents); } static public 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 void imageSurface_pixelated(ImageSurface imageSurface) { if (imageSurface == null) return; imageSurface.setDoubleBuffered(true); imageSurface.noAlpha = true; imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR; repaint(imageSurface); } static public void imageSurface_pixelated(ImageSurface imageSurface, boolean pixelated) { if (pixelated) imageSurface_pixelated(imageSurface); else imageSurface_unpixelated(imageSurface); } static public String renderRecordVars(String recordName, Object... params) { List l = new ArrayList(); int i = 0; for (; i + 1 < l(params); i += 2) l.add(params[i] + "=" + params[i + 1]); return formatFunctionCall(recordName, l); } static public String programID() { return getProgramID(); } static public String programID(Object o) { return getProgramID(o); } static public JFrame showPackedFrame(String title, Component contents) { return packFrame(showFrame(title, contents)); } static public JFrame showPackedFrame(Component contents) { return packFrame(showFrame(contents)); } 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 JPanel jpanel(LayoutManager layout, Object... components) { return jpanel(layout, asList(components)); } static public JPanel jpanel(LayoutManager layout, List components) { return smartAdd(jpanel(layout), components); } static public JPanel jpanel(LayoutManager layout) { return swing(() -> new JPanel(layout)); } static public JPanel jpanel() { return swing(() -> new JPanel()); } static public boolean isComponentOrSwingable(Object o) { if (o instanceof Swingable) return true; return o instanceof Component; } static public Rectangle maximumWindowBounds() { return maxWindowBounds(); } 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 TreeMap toCIMap(Map map) { return asCIMap(map); } static public A popLast(List l) { return liftLast(l); } static public List popLast(int n, List l) { return liftLast(n, l); } static public double popLast(DoubleBuffer l) { return l.popLast(); } static public int showForm_leftWidth_safetyMargin = 10; static public int showForm_leftWidth(List> l) { forEachLevel2(l, x -> vmBus_send("updateLayoutNow", x)); int minW = 0; for (List row : l) minW = max(minW, getMinimumSize(first(row)).width); return minW + or((Integer) vmBus_query("formSafetyMargin"), showForm_leftWidth_safetyMargin); } static public char charAt(String s, int i) { return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0'; } static public BufferedImage renderableToImage(Renderable r) { if (r == null) return null; return renderableToImage(r.preferredSize(), r); } static public BufferedImage renderableToImage(int w, int h, Renderable r) { return renderableToImage(w, h, white(), r); } static public BufferedImage renderableToImage(int w, int h, Color backgroundColor, Renderable r) { return renderableToImage(pt(w, h), backgroundColor, r); } static public BufferedImage renderableToImage(Pt size, Renderable r) { return renderableToImage(size, white(), r); } static public BufferedImage renderableToImage(Pt size, Color backgroundColor, Renderable r) { var img = newImage(size.x, size.y, backgroundColor); r.renderOn(imageGraphics(img), size.x, size.y); return img; } 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 A focus(final A a) { if (a != null) swingLater(new Runnable() { public void run() { try { a.requestFocus(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.requestFocus();"; } }); return a; } static public List tok_identifiersInOrder(String s) { return filter(__94 -> isIdentifier(__94), javaTokC(s)); } static public List tok_identifiersInOrder(List tok) { return filter(__95 -> isIdentifier(__95), codeTokens(tok)); } static public File fileAppendToName(File f, String suffix) { return newFile(f.getPath() + suffix); } static public int cores() { return numberOfCores(); } static public Object[] toArray(Collection c) { return toObjectArray(c); } static public A[] toArray(Class type, Iterable c) { return toArray(c, type); } static public A[] toArray(Class type, Collection c) { return toArray(c, type); } static public A[] toArray(Collection c, Class type) { A[] a = arrayOfType(l(c), type); if (a.length == 0) return a; asList(c).toArray(a); return a; } static public A[] toArray(Iterable c, Class type) { var c2 = asList(c); A[] a = arrayOfType(l(c2), type); if (a.length == 0) return a; c2.toArray(a); return a; } static public A[] toArray(A[] array, Collection c) { if (array == null || c == null) return null; asList(c).toArray(array); return array; } static public String[] asStringArray(Collection c) { return toStringArray(c); } static public String[] asStringArray(Object o) { return toStringArray(o); } static public A findConceptWhereCI(Class c, Object... params) { return findConceptWhereCI(db_mainConcepts(), c, params); } static public A findConceptWhereCI(Concepts concepts, Class c, Object... params) { params = expandParams(c, params); Lowest>> bestIndex = new Lowest(); if (concepts.ciFieldIndices != null) for (int i = 0; i < l(params); i += 2) { ping(); Object val = params[i + 1]; IFieldIndex index = concepts.getCIFieldIndex(c, (String) params[i]); if (index != null) { Collection l = index.getAll(val); bestIndex.put(() -> l, l(l)); } if (concepts.useBackRefsForSearches && val instanceof Concept) { bestIndex.put(() -> findBackRefs(((Concept) val), c), ((Concept) val)._backRefCount()); } } if (bestIndex.has()) { Collection l = bestIndex.get().get(); if (l(params) == 2) return first(l); for (A x : l) { ping(); if (checkConceptFieldsIC(x, params)) return x; } return null; } else { for (A x : concepts.list(c)) { ping(); if (checkConceptFieldsIC(x, params)) return x; } return null; } } static public Concept findConceptWhereCI(Concepts concepts, String c, Object... params) { for (Concept x : concepts.list(c)) { ping(); if (checkConceptFieldsIC(x, params)) return x; } return null; } static public void sleepInCleanUp(long ms) { try { if (ms < 0) return; Thread.sleep(ms); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedImageWithMeta intArrayToBufferedImage(int[] pixels, int w) { return intArrayToBufferedImage(pixels, w, pixels.length / w); } static public BufferedImageWithMeta intArrayToBufferedImage(int[] pixels, int w, int h) { if (w == 0 || h == 0) return null; int[] bitMasks = new int[] { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 }; SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, w, h, bitMasks); DataBufferInt db = new DataBufferInt(pixels, pixels.length); WritableRaster wr = Raster.createWritableRaster(sm, db, new Point()); return new BufferedImageWithMeta(ColorModel.getRGBdefault(), wr, false, null); } static public BufferedImageWithMeta intArrayToBufferedImage(int w, int... pixels) { return intArrayToBufferedImage(pixels, w); } static public String gtt(JTextComponent c) { return getTextTrim(c); } static public String gtt(JComboBox cb) { return getTextTrim(cb); } 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 Component jMinHeight(Swingable c, int h) { return jMinHeight(wrap(c), h); } static public Component jMinHeight(int h, Swingable c) { return jMinHeight(wrap(c), h); } static public A jMinHeight(A c, int h) { return jMinHeight(h, c); } static public A jMinHeight(int h, A c) { Dimension size = c.getMinimumSize(); c.setMinimumSize(new Dimension(size.width, max(h, size.height))); return jPreferHeight(h, c); } static public void printJavaVersion() { print("Java version: " + javaVersion()); } static public boolean stdEq2(Object a, Object b) { if (a == null) return b == null; if (b == null) return false; if (a.getClass() != b.getClass()) return false; for (String field : allFields(a)) if (neq(getOpt(a, field), getOpt(b, field))) return false; return true; } static public float clampZeroToOne(float x) { return x < 0 ? 0 : x > 1 ? 1 : x; } static public double clampZeroToOne(double x) { return x < 0 ? 0 : x > 1 ? 1 : x; } static public long toK(long l) { return (l + 1023) / 1024; } static public JPanel rightAlignedLine(Component... components) { return jrightAlignedLine(components); } static public JPanel rightAlignedLine(List components) { return jrightAlignedLine(components); } static public long toM(long l) { return (l + 1024 * 1024 - 1) / (1024 * 1024); } static public String toM(long l, int digits) { return formatDouble(toM_double(l), digits); } static public boolean even(int i) { return (i & 1) == 0; } static public boolean even(long i) { return (i & 1) == 0; } static public boolean even(BigInteger n) { return even(n.intValue()); } static public int linesOfCode_javaTok(String text) { List tok = javaTok(text); int lines = 0; boolean codeInCurrentLine = false; for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i)) { int lTok = l(t); for (int j = 0; j < lTok; j++) { char c = t.charAt(j); if (c == '\n') codeInCurrentLine = false; else if (!isSpaceEtc(c) && !codeInCurrentLine) { codeInCurrentLine = true; ++lines; } } } else { if (codeInCurrentLine && containsNewLine(t)) codeInCurrentLine = false; } } return lines; } static public double toS(long ms) { return toSeconds(ms); } static public String toS(long ms, int digits) { return toSeconds(ms, digits); } static public void swingNowOrLater(Runnable r) { if (isAWTThread()) r.run(); else swingLater(r); } static public byte[] scaledGrayBytesFromBWIntegralImage(int w, BWIntegralImage img) { return scaledGrayBytesFromBWIntegralImage(img, w); } static public byte[] scaledGrayBytesFromBWIntegralImage(BWIntegralImage img, int w) { return scaledGrayBytesFromBWIntegralImage(img, w, heightForWidth(img, w)); } static public byte[] scaledGrayBytesFromBWIntegralImage(BWIntegralImage img, int w, int h) { int w1 = img.getWidth(), h1 = img.getHeight(); double stepX = doubleRatio(w1, w), stepY = doubleRatio(h1, h); byte[] pixels = new byte[w * h]; int i = 0; double srcY = 0; if (stepX == 1 && stepY == 1) { for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { int pixel = img.getPixelBrightness(x, y); pixels[i++] = clampToUByte(pixel); } } else { for (int y = 0; y < h; y++) { double srcX = 0, nextSrcY = srcY + stepY; for (int x = 0; x < w; x++) { double nextSrcX = srcX + stepX; int pixel = iround(img.getPixelAverage(srcX, srcY, nextSrcX, nextSrcY)); pixels[i++] = clampToUByte(pixel); srcX = nextSrcX; } srcY = nextSrcY; } } return pixels; } static public byte[] scaledGrayBytesFromBWIntegralImage(int w, IBWIntegralImage img) { return scaledGrayBytesFromBWIntegralImage(img, w); } static public byte[] scaledGrayBytesFromBWIntegralImage(IBWIntegralImage img, int w) { return scaledGrayBytesFromBWIntegralImage(img, w, heightForWidth(img, w)); } static public byte[] scaledGrayBytesFromBWIntegralImage(IBWIntegralImage img, int w, int h) { int w1 = img.getWidth(), h1 = img.getHeight(); double stepX = doubleRatio(w1, w), stepY = doubleRatio(h1, h); byte[] pixels = new byte[w * h]; int i = 0; double srcY = 0; if (stepX == 1 && stepY == 1) { for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { int pixel = img.getPixelBrightness(x, y); pixels[i++] = clampToUByte(pixel); } } else { for (int y = 0; y < h; y++) { double srcX = 0, nextSrcY = srcY + stepY; for (int x = 0; x < w; x++) { double nextSrcX = srcX + stepX; int pixel = iround(img.getPixelAverage(srcX, srcY, nextSrcX, nextSrcY)); pixels[i++] = clampToUByte(pixel); srcX = nextSrcX; } srcY = nextSrcY; } } return pixels; } static public A jMaxWidth(int w, A c) { Dimension size = c.getMaximumSize(); c.setMaximumSize(new Dimension(w, size.height)); return jPreferWidth(w, c); } static public A jMaxWidth(A c, int w) { return jMaxWidth(w, c); } 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 void printNumberedLines(Map map) { printNumberedLines(mapToLines(map)); } static public void printNumberedLines(String prefix, Map map) { printNumberedLines(prefix, mapToLines(map)); } static public A printNumberedLines(A l) { int i = 0; if (l != null) for (Object a : cloneList(l)) print((++i) + ". " + str(a)); return l; } static public A printNumberedLines(String prefix, A l) { int i = 0; if (l != null) for (Object a : cloneList(l)) print(prefix + (++i) + ". " + str(a)); return l; } static public void printNumberedLines(Object[] l) { printNumberedLines("", l); } static public void printNumberedLines(String prefix, Object[] l) { printNumberedLines(prefix, wrapAsList(l)); } static public void printNumberedLines(Object o) { printNumberedLines(lines(str(o))); } static public int cmp(Number a, Number b) { return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue()); } static public int cmp(double a, double b) { return a < b ? -1 : a == b ? 0 : 1; } static public int cmp(int a, int b) { return a < b ? -1 : a == b ? 0 : 1; } static public int cmp(long a, long b) { return a < b ? -1 : a == b ? 0 : 1; } static public int cmp(Object a, Object b) { if (a == null) return b == null ? 0 : -1; if (b == null) return 1; return ((Comparable) a).compareTo(b); } static public ImageSurface pixelatedImageSurface() { var is = imageSurface(); imageSurface_pixelated(is); return is; } static public ImageSurface pixelatedImageSurface(MakesBufferedImage img) { return pixelatedImageSurface(toBufferedImage(img)); } static public ImageSurface pixelatedImageSurface(BufferedImage img) { var is = pixelatedImageSurface(); is.setImage(img); return is; } static public int getWidth(Component c) { return c == null ? 0 : (int) swingCall(c, "getWidth"); } static public void stepAllWithStats(Steppable s) { stepAllWithStats(s, null); } static public void stepAllWithStats(Steppable s, Long maxSteps) { if (s == null) return; long n = 0; long time = sysNow(); if (maxSteps == null) while (s.step()) { ping(); ++n; } else while (n < maxSteps && s.step()) { ping(); ++n; } time = sysNow() - time; print(n2(n, "step") + " in " + n2(time) + " ms"); } static public void setComboBoxItems_notifyListeners(JComboBox cb, Collection items) { if (cb != null) { swing(() -> { if (eq(getComboBoxItems(cb), items)) return; var sel = getSelectedItem_typed(cb); setComboBoxItems(cb, items); var item = getSelectedItem_typed(cb); if (!eq(sel, item)) { if (sel != null && contains(items, sel)) setSelectedItem(cb, sel); else { setSelectedItem(cb, (A) null); setSelectedItem(cb, item); } } }); } } static public String exceptionToStringShorter_dontDropOuterExceptions(Throwable e) { String msg = hideCredentials(unnull(e.getMessage())); String className = baseClassName(e); if (!eq(className, "RuntimeException") && (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)) return className + prependIfNempty(": ", msg); else return msg; } static public void scrollRowToVisible(JTable t, int rowIndex) { int colIndex = 0; if (!(t.getParent() instanceof JViewport)) return; JViewport viewport = (JViewport) t.getParent(); Rectangle rect = t.getCellRect(rowIndex, colIndex, true); Rectangle viewRect = viewport.getViewRect(); int x = viewRect.x; int y = viewRect.y; if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)) { } else if (rect.x < viewRect.x) { x = rect.x; } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) { x = rect.x - viewRect.width + rect.width; } if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)) { } else if (rect.y < viewRect.y) { y = rect.y; } else if (rect.y > (viewRect.y + viewRect.height - rect.height)) { y = rect.y - viewRect.height + rect.height; } viewport.setViewPosition(new Point(x, y)); } static public JWindow infoBoxForever(String message) { return infoBox(message, 0); } static public BufferedImage loadBufferedImageFile(File file) { try { if (!isFile(file)) return null; if (hasExtension(file, ".qoi")) return loadQOI(file); return ImageIO.read(file); } catch (Exception __e) { throw rethrow(__e); } } static public float bwImageSimilarityResized(BWImage a, BWImage b, float similarityRequired) { int aw = a.w(), ah = a.h(); int bw = b.w(), bh = b.h(); int wp = max(aw, bw), hp = max(ah, bh); float ratio1 = ((float) aw) / ah, ratio2 = ((float) bw) / bh; float mismatch = ratio1 / ratio2; if (mismatch < 1f) mismatch = 1f / mismatch; float factor = wp * hp / mismatch; float maxError = (1f - similarityRequired) * factor; float diff = 0; for (int y = 0; y < hp; y++) for (int x = 0; x < wp; x++) { diff += Math.abs(a.getPixel(x * aw / wp, y * ah / hp) - b.getPixel(x * bw / wp, y * bh / hp)); if (diff > maxError) return similarityRequired - 0.001f; } return 1f - diff / factor; } static public A dm_transientCalculatedToolTip(IF0 calc, A component) { return toolTipFromLiveValue(dm_transientCalculatedLiveValue(Object.class, calc), component); } static public void copyFileVerbose(File src, File dest) { copyFileToFileVerbose(src, dest); } static public Pair transpileOnBestServer(String snippetID, String mode) { try { return haveTranspilationPassword() ? print("shouldTranspileOnDedi", shouldTranspileOnDedi()) ? transpileOnDediServer(snippetID, mode) : transpileOnNewServer(snippetID, mode) : transpileOnServer(snippetID, mode); } catch (Exception __e) { throw rethrow(__e); } } static public Pair transpileOnBestServer(String snippetID) { return transpileOnBestServer(snippetID, "quick"); } static public List stringsSortedByLength(Iterable l) { return sortedByCalculatedField(l, new F1() { public Integer get(String s) { try { return l(s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "l(s)"; } }); } static public A leftAlignLabel(final A a) { return setHorizontalAlignment(JLabel.LEFT, a); } 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 String nFiles(long n) { return n2(n, "file"); } static public String nFiles(Collection l) { return nFiles(l(l)); } static public long parseLong(String s) { if (empty(s)) return 0; return Long.parseLong(dropSuffix("L", s)); } static public long parseLong(Object s) { return Long.parseLong((String) s); } static public void doPostBinaryToFile(Map urlParameters, String url, File file) { doPostBinaryToFile(makePostData(urlParameters), url, file); } static public void doPostBinaryToFile(String urlParameters, String url, File file) { try { URL _url = new URL(url); ping(); doPostBinaryToFile(urlParameters, _url.openConnection(), file); } catch (Exception __e) { throw rethrow(__e); } } static public void doPostBinaryToFile(String urlParameters, URLConnection conn, File file) throws IOException { setHeaders(conn); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); try { loadBinaryPageToFile_noHeaders(conn, file); } finally { writer.close(); } } static public String formatSeconds(long ms, int digits) { return formatDouble(toS(ms), digits); } static public String formatSeconds(Duration duration, int digits) { return formatSeconds(duration.toMillis(), digits); } static public GlobalID aGlobalIDObjUnlessLoading() { return dynamicObjectIsLoading() ? null : aGlobalIDObj(); } static public IterableIterator countIterator_inclusive_step(int a, int b, int step) { assertTrue("step > 0", step > 0); return new IterableIterator() { public int i = a; public boolean hasNext() { return i <= b; } public Integer next() { var j = i; i += step; return j; } }; } static public IterableIterator countIterator_inclusive_step(long a, long b, long step) { assertTrue("step > 0", step > 0); return new IterableIterator() { public long i = a; public boolean hasNext() { return i <= b; } public Long next() { var j = i; i += step; return j; } }; } static public IterableIterator countIterator_inclusive_step(double a, double b, double step) { assertTrue("step > 0", step > 0); return new IterableIterator() { public double i = a; public boolean hasNext() { return i <= b; } public Double next() { var j = i; i += step; return j; } }; } static public IterableIterator countIterator_inclusive_step(double a, double b, double step, IF1 f) { return mapI_if1(f, countIterator_inclusive_step(a, b, step)); } static public IterableIterator countIterator_inclusive_step(int a, int b, int step, IF1 f) { return mapI_if1(f, countIterator_inclusive_step(a, b, step)); } static public VF1 ivf1ToVF1(IVF1 f) { return f == null ? null : new VF1() { public void get(A a) { try { f.get(a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.get(a)"; } }; } static public int lCharSequence(CharSequence s) { return s == null ? 0 : s.length(); } 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(String imageID, String toolTip, Runnable action) { return jimageButton(imageIcon(imageID), toolTip, action); } 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 Dimension maxDimension(Dimension a, Dimension b) { return a == null ? b : b == null ? a : new Dimension(max(a.width, b.width), max(a.height, b.height)); } static public int formLayouter1_yPlus = 5; static public int formLayouter1_fixer2 = 0; static public F1 formLayouter1() { final int yplus = formLayouter1_yPlus, fixer2 = formLayouter1_fixer2; return new F1() { public Dimension get(Container parent) { try { List l = getComponents(parent); BitSet bigOnes = new BitSet(); for (int i = 0; i < l(l); i++) if (containsATextArea(l.get(i))) add(bigOnes, i); int nBigOnes = bigOnes.cardinality(); int mandatoryHeight = totalPreferredHeight(listWithoutIndicesInBitSet(l, bigOnes)); int gap = 4, outerSpacing = 5; Dimension size = parent.getSize(); int gapsAndMargins = outerSpacing * 2 - (l(l) - 1) * gap; int totalSpace = size.height - gapsAndMargins - fixer2; int liberalSpace = totalSpace - mandatoryHeight; double perBigOne = doubleRatio(liberalSpace, nBigOnes); double y = outerSpacing; for (int i = 0; i < l(l); i++) { Component c = l.get(i); boolean big = contains(bigOnes, i); double h = big ? perBigOne : c.getPreferredSize().height; int actualY = iround(y); c.setBounds(10, actualY, size.width - outerSpacing * 2, iround(y + h) - actualY); y += h + gap; } Dimension pref = componentsBoundingSize(parent, outerSpacing); if (parent.getHeight() <= 0) { int tph = totalPreferredHeight(l); pref.height = tph + gapsAndMargins + yplus; } return pref; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "L l = getComponents(parent);\r\n new BitSet bigOnes;\r\n for i o..."; } }; } static public ArrayList toList(A[] a) { return asList(a); } static public ArrayList toList(int[] a) { return asList(a); } static public ArrayList toList(short[] a) { return asList(a); } static public ArrayList toList(long[] a) { return asList(a); } static public ArrayList toList(double[] a) { return asList(a); } static public ArrayList toList(float[] a) { return asList(a); } static public ArrayList toList(Set s) { return asList(s); } static public ArrayList toList(Iterable s) { return asList(s); } static public RGB rgbFromGrayscale(int brightness) { float f = RGB.brightnessToFloat(brightness); return new RGB(f, f, f); } static public String joinStrings(String sep, Object... strings) { return joinStrings(sep, Arrays.asList(strings)); } static public String joinStrings(String sep, Iterable strings) { StringBuilder buf = new StringBuilder(); for (Object o : unnull(strings)) { String s = strOrNull(o); if (nempty(s)) { if (nempty(buf)) buf.append(sep); buf.append(s); } } return str(buf); } static public Object[] massageArgsForVarArgsCall(Executable m, Object[] args) { Class[] types = m.getParameterTypes(); int n = types.length - 1, nArgs = l(args); if (nArgs < n) return null; for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i])) return null; Class varArgType = types[n].getComponentType(); for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType)) return null; Object[] newArgs = new Object[n + 1]; arraycopy(args, 0, newArgs, 0, n); int nVarArgs = nArgs - n; Object varArgs = Array.newInstance(varArgType, nVarArgs); for (int i = 0; i < nVarArgs; i++) Array.set(varArgs, i, args[n + i]); newArgs[n] = varArgs; return newArgs; } static public void tableEnableTextDrag(final JTable table) { TransferHandler th = new TransferHandler() { @Override public int getSourceActions(JComponent c) { return COPY; } @Override public Transferable createTransferable(JComponent c) { Object o = selectedTableCell(table); return new StringSelection(str(o)); } }; tableEnableDrag(table, th); } static public IVF1 runnableToIVF1(Runnable r) { return r == null ? null : a -> r.run(); } static public boolean eqOneOf(Object o, Object... l) { if (l != null) for (Object x : l) if (eq(o, x)) return true; return false; } static public boolean containsClosingBracket(List l) { return any(__96 -> isClosingBracket(__96), l); } static public String roundBracket(String s) { return "(" + s + ")"; } static public String roundBracket(Object s) { return roundBracket(str(s)); } static public JToggleButton basicJToggleButton(String text) { return swing(() -> new JToggleButton(text)); } static public void listThreadLocalAdd(ThreadLocal> tl, A a) { List l = tl.get(); if (l == null) tl.set(l = new ArrayList()); l.add(a); } static public List virtualCountList(int n) { return new RandomAccessAbstractList() { public int size() { return n; } public Integer get(int i) { return i; } }; } static public List virtualCountList(int from, int to) { int n = max(to - from, 0); return new RandomAccessAbstractList() { public int size() { return n; } public Integer get(int i) { return from + i; } }; } static public String sfuIndent(Object o) { return sfuIndent(Integer.MAX_VALUE, o); } static public String sfuIndent(int levels, Object o) { return indentedStructureForUser(levels, o); } static public JPanel jCenteredLine(Component... components) { return jcenteredline(components); } static public JPanel jCenteredLine(List components) { return jcenteredline(components); } static public File computerIDFile() { return javaxDataDir("Basic Info/computer-id.txt"); } static public A onFirstShowing(A component, Runnable onShow) { return onFirstComponentShow(component, onShow); } static public void addAndValidate(Container c, Component x) { if (c != null && x != null) { swing(() -> { if (c instanceof DynamicStack) { ((DynamicStack) c).addComponent(x); return; } c.add(x); c.revalidate(); }); } } static public Pair mapEntryToPair(Map.Entry e) { return e == null ? null : pair(e.getKey(), e.getValue()); } static public void cancelThread(Thread t) { if (t == null) return; ping(); var ps = pingSource(t); if (ps == null) warn("No ping source for thread " + t + ", can't cancel"); else ps.cancel(); } static public Map castMapToMapO(Map map) { return map; } static public List endingWith_dropSuffix(Collection l, String suffix) { List out = new ArrayList(); for (String s : unnullForIteration(l)) if (endsWith(s, suffix)) out.add(dropLast(l(suffix), s)); return out; } static public List endingWith_dropSuffix(String suffix, Collection l) { return endingWith_dropSuffix(l, suffix); } static public IterableIterator iteratorFromFunction(final Object f) { class IFF extends IterableIterator { public A a; public boolean done = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } public void getNext() { if (done || a != null) return; a = (A) callF(f); done = a == null; } } ; return new IFF(); } static public IterableIterator iteratorFromFunction(F0 f) { return iteratorFromFunction_f0(f); } static public IterableIterator iteratorFromFunction(IF0 f) { return iteratorFromFunction_if0(f); } static public int secondIntFromLong(long l) { return (int) l; } static public List afterDelegatingToThread_operations = synchroList(); static public void afterDelegatingToThread(Thread t) { for (Object op : cloneList(afterDelegatingToThread_operations)) pcallF(op, t); } static public void afterDelegatingToThread_do(Object f) { setAdd(afterDelegatingToThread_operations, f); } static public void _registerIO(Object object, String path, boolean opened) { } static public boolean scrollAllTheWayDown_bruteForce = true; static public A scrollAllTheWayDown(A c) { if (c != null) { swing(() -> { int h = c.getHeight() - 1; if (scrollAllTheWayDown_bruteForce) h = max(h, 100000); c.scrollRectToVisible(new Rectangle(0, h, 1, 1)); }); } return c; } static public int stdHash2(Object a) { if (a == null) return 0; return stdHash(a, toStringArray(allFields(a))); } static public File javaxDataDir_dir; static public File javaxDataDir() { return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data"); } static public File javaxDataDir(String... subs) { return newFile(javaxDataDir(), subs); } static public 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 Pair jmenu_autoMnemonic(String s) { int i = indexOf(s, '&'); if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i + 1))) return pair(substring(s, 0, i) + substring(s, i + 1), (int) s.charAt(i + 1)); return pair(s, 0); } static public String substring(String s, int x) { return substring(s, x, strL(s)); } static public String substring(String s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; int n = s.length(); if (y < x) y = x; if (y > n) y = n; if (x >= y) return ""; return s.substring(x, y); } static public String substring(String s, IntRange r) { return r == null ? null : substring(s, r.start, r.end); } static public String substring(String s, CharSequence l) { return substring(s, lCharSequence(l)); } static public void clickButton(final JButton b) { if (b != null) { swing(() -> { if (b.isEnabled()) b.doClick(); }); } } static public Component horizontalStrut(int height) { return Box.createHorizontalStrut(height); } static public boolean setTextKeepCaret(String text, JTextComponent c) { if (c == null) return false; return swing(() -> { int caret = c.getCaretPosition(); if (eq(c.getText(), text)) return false; c.setText(text); setCaretPosition(c, caret); return true; }); } static public boolean setTextKeepCaret(JTextComponent c, String text) { return setTextKeepCaret(text, c); } static public AutoCloseable tempMapPut(Map map, A key, B value) { if (map != null && key != null && value != null) { B old = map.put(key, value); return () -> mapPutOrRemove(map, key, old); } return null; } static public ZipFile openZipFile(File f) { try { return new ZipFile(f); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedImage cloneBufferedImageWithMetaSrc(Object src, BufferedImage img) { if (img == null) return null; img = cloneBufferedImageWithMeta(img); setMetaSrc(img, src); assertSame("cloneBufferedImageWithMetaSrc", getMetaSrc(img), src); return img; } static public boolean isMD5(String s) { return l(s) == 32 && isLowerHexString(s); } 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 void drawLine(BufferedImage image, int x1, int y1, int x2, int y2, Color color) { drawLine(imageGraphics(image), x1, y1, x2, y2, color); } static public void drawLine(Graphics2D g, int x1, int y1, int x2, int y2, Color color) { g.setColor(color); g.drawLine(x1, y1, x2, y2); } static public void drawLine(BufferedImage image, Pt a, Pt b, Color color) { drawLine(imageGraphics(image), a, b, color); } static public void drawLine(Graphics2D g, Pt a, Pt b, Color color) { drawLine(g, a.x, a.y, b.x, b.y, color); } static public RuntimeException rethrowAndAppendToMessage(Throwable t, String msg) { String haveMsg = t.getMessage(); if (empty(msg) || endsWith(haveMsg, " " + msg)) throw rethrow(t); throw new RuntimeException(joinWithSpace(t.getMessage(), msg), t); } static public JLabel jimage(Image img) { return jImageLabel(img); } static public JLabel jimage(String imageID) { return jImageLabel(imageID); } static public List mapLL(Object f, Object... data) { return map(f, ll(data)); } static public List mapLL(IF1 f, A... data) { return map(f, ll(data)); } static public BufferedImage drawImage(BufferedImage canvas, Image img, Pt p) { return drawImageOnImage(img, canvas, p.x, p.y); } static public void drawImage(BufferedImage g, Image img) { drawImage(graphics(g), img); } static public void drawImage(Graphics2D g, Image img) { drawImage(g, img, 0, 0); } static public void drawImage(Graphics2D g, Image img, Pt p) { drawImage(g, img, p.x, p.y); } static public void drawImage(Graphics2D g, Image img, int x, int y) { { if (g != null) g.drawImage(img, x, y, null); } } static public File userDir_oneOf_createFirstIfNone(String... names) { return or(userDir_oneOf(names), userDir(first(names))); } static public Random getRandomizer(Random r) { return r != null ? r : defaultRandomGenerator(); } static public void imageSurface_unpixelated(ImageSurface imageSurface) { if (imageSurface == null) return; imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_BILINEAR; repaint(imageSurface); } static public Rect boundsRect(Component c) { return toRect(getBounds(c)); } static public Set allNonStaticFields(Object o) { TreeSet fields = new TreeSet(); Class _c = _getClass(o); do { for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & Modifier.STATIC) == 0) fields.add(f.getName()); _c = _c.getSuperclass(); } while (_c != null); return fields; } static public List cloneSubList(List l, int startIndex, int endIndex) { return newSubList(l, startIndex, endIndex); } static public List cloneSubList(List l, int startIndex) { return newSubList(l, startIndex); } static public void setCaretPosition(final JTextComponent c, final int pos) { if (c != null) { swing(() -> { try { int _pos = max(0, min(l(c.getText()), pos)); c.setCaretPosition(_pos); } catch (Throwable __e) { pcallFail(__e); } }); } } 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 File imageSnippetsCacheDir() { return javaxCachesDir("Image-Snippets"); } static public boolean syncAddAll(Collection c, Iterable b) { if (c == null || b == null) return false; synchronized (c) { return c.addAll(asCollection(b)); } } static public String fileName(File f) { return f == null ? null : f.getName(); } static public JComponent jErrorView(Throwable e) { return jSmallErrorView(e); } static public void removeSubList(List l, int from, int to) { if (l != null) subList(l, from, to).clear(); } static public void removeSubList(List l, int from) { if (l != null) subList(l, from).clear(); } static public Set listFields(Object c) { TreeSet fields = new TreeSet(); for (Field f : _getClass(c).getDeclaredFields()) fields.add(f.getName()); return fields; } static public List _stickyLibs_1013490 = ll("#1400553", "#1400552", "#1004016", "#1004015"); static public List listWebCams() { fixContextClassLoader(); return Webcam.getWebcams(); } static public JLabel jImage(Image img) { return jimage(img); } static public JLabel jImage(String imageID) { return jimage(imageID); } static public generalizedCIComparator_C generalizedCIComparator_cache; static public generalizedCIComparator_C generalizedCIComparator() { if (generalizedCIComparator_cache == null) generalizedCIComparator_cache = generalizedCIComparator_load(); return generalizedCIComparator_cache; } static public generalizedCIComparator_C generalizedCIComparator_load() { return new generalizedCIComparator_C(); } final static public class generalizedCIComparator_C implements Comparator { public int compare(Object o1, Object o2) { if (o1 instanceof String) if (o2 instanceof String) return betterCIComparator().compare(((String) o1), ((String) o2)); else return -1; else if (o2 instanceof String) return 1; else return cmp(o1, o2); } } static public Object callFunction(Object f, Object... args) { return callF(f, args); } 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 void disposeFrame(final Component c) { disposeWindow(c); } static public boolean sameFile(File a, File b) { try { return a == null ? b == null : b != null && eq(a.getCanonicalPath(), b.getCanonicalPath()); } catch (Exception __e) { throw rethrow(__e); } } static public int boostHashCombine(int a, int b) { return a ^ (b + 0x9e3779b9 + (a << 6) + (a >>> 2)); } static public List wrapArrayAsList(A[] a) { return a == null ? null : Arrays.asList(a); } static public List getSwingChildren(Component c) { if (c instanceof Container) return asList(((Container) c).getComponents()); return emptyList(); } static public IImageRegion g22_darkestRegion(IImageRegions regions) { return regions == null ? null : lowest(regions.regions(), r -> r.brightness()); } static public void printVars_shorten(Object... params) { print(renderVars_stringifier(o -> str_shorten(o), params)); } static public void sortIntRangesInPlace(List l) { sortInPlaceByCalculatedField(l, r -> r.start); } static public AutoCloseable tempSetTL(ThreadLocal tl, A a) { return tempSetThreadLocal(tl, a); } static public AutoCloseable tempSetTL(BetterThreadLocal tl, A a) { return tempSetThreadLocalIfNecessary(tl, a); } static public String renderVars_str(Object... params) { List l = new ArrayList(); int i = 0; if (odd(l(params))) { l.add(strOrNull(first(params))); ++i; } for (; i + 1 < l(params); i += 2) l.add(params[i] + "=" + params[i + 1]); return trim(joinWithComma(l)); } static public A pnl(A l) { return pnl("", l); } static public A pnl(String prefix, A l) { printNumberedLines(prefix, l); return l; } static public A[] pnl(A[] l) { return pnl("", l); } static public A[] pnl(String prefix, A[] l) { printNumberedLines(prefix, l); return l; } static public A pnl(A map) { printNumberedLines(map); return map; } static public A pnl(String prefix, A map) { printNumberedLines(prefix, map); return map; } static public String pnl(String s) { printNumberedLines(lines(s)); return s; } static public MultiSet pnl(MultiSet ms) { pnl(ms == null ? null : ms.asMap()); return ms; } static public MultiMap pnl(MultiMap mm) { pnl(mm == null ? null : mm.asMap()); return mm; } static public int parseDigit(char c) { return c >= '0' && c <= '9' ? c - '0' : 0; } static public int parseDigit(String s, int i) { return parseDigit(s.charAt(i)); } static public boolean dirOrZipContainsPath(File location, String subPath) { try { if (location.isDirectory()) { return new File(location, subPath).exists(); } else if (location.isFile()) { return zipFileContains_falseOnError(location, subPath); } return false; } catch (Exception __e) { throw rethrow(__e); } } static public AutoCloseable tempLock(Lock lock) { return tempLock("", lock); } static public AutoCloseable tempLock(String purpose, Lock lock) { if (lock == null) return null; lock(lock); return new AutoCloseable() { public String toString() { return "unlock(lock);"; } public void close() throws Exception { unlock(lock); } }; } static public ThreadLocal addInternalFrame_dontSelect = new ThreadLocal(); static public ThreadLocal addInternalFrame_layer = new ThreadLocal(); static public ThreadLocal addInternalFrame_toBack = new ThreadLocal(); static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h) { return addInternalFrame(desktop, title, x, y, w, h, null); } static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final int x, final int y, final int w, final int h, final Component contents) { return addInternalFrame(desktop, title, rect(x, y, w, h), contents); } static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Component contents) { return addInternalFrame(desktop, title, null, contents); } static public JInternalFrame addInternalFrame(final JDesktopPane desktop, final String title, final Rect r, final Component contents) { final boolean dontSelect = isTrue(optParam(addInternalFrame_dontSelect)); final boolean toBack = isTrue(optParam(addInternalFrame_toBack)); final Integer layer = optParam(addInternalFrame_layer); return swing(new F0() { public JInternalFrame get() { try { JInternalFrame frame; if (contents instanceof JInternalFrame) frame = (JInternalFrame) contents; else { frame = jInternalFrame(title); setInternalFrameContents(frame, contents); } frame.setVisible(true); desktop.add(frame, layer); if (r != null) setBounds(frame, r); else internalFrameDefaultPosition(frame); if (dontSelect) if (toBack) frame.toBack(); else frame.toFront(); else frame.setSelected(true); return fixInternalFrame(frame); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JInternalFrame frame;\r\n if (contents instanceof JInternalFrame)\r\n fra..."; } }); } static public JInternalFrame addInternalFrame(JDesktopPane desktop, String title) { return addInternalFrame(desktop, title, jpanel()); } static public int numberOfChildren(final Container c) { return c == null ? 0 : swing(new F0() { public Integer get() { try { return c.getComponentCount(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getComponentCount();"; } }); } static public void dm_watchFields(Collection fields, Runnable onChange) { for (String field : unnullForIteration(fields)) dm_watchField(field, onChange); } static public JPanel jcenteredline(final Component... components) { return swing(new F0() { public JPanel get() { try { return jFullCenter(hstackWithSpacing(components)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return jFullCenter(hstackWithSpacing(components));"; } }); } static public JPanel jcenteredline(List components) { return jcenteredline(asArray(Component.class, components)); } static public List cloneKeys(Map map) { return cloneList(keys(map)); } static public A liftLast(List l) { if (empty(l)) return null; int i = l(l) - 1; A a = l.get(i); l.remove(i); return a; } static public List liftLast(int n, List l) { int i = l(l) - n; List part = cloneSubList(l, i); removeSubList(l, i); return part; } static public 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 float[] unnull(float[] l) { return l == null ? emptyFloatArray() : l; } static public Map unnull(Map l) { return l == null ? emptyMap() : l; } static public Iterable unnull(Iterable i) { return i == null ? emptyList() : i; } static public A[] unnull(A[] a) { return a == null ? (A[]) emptyObjectArray() : a; } static public BitSet unnull(BitSet b) { return b == null ? new BitSet() : b; } static public Pt unnull(Pt p) { return p == null ? new Pt() : p; } static public Symbol unnull(Symbol s) { return s == null ? emptySymbol() : s; } static public Pair unnull(Pair p) { return p != null ? p : new Pair(null, null); } static public int unnull(Integer i) { return i == null ? 0 : i; } static public long unnull(Long l) { return l == null ? 0L : l; } static public double unnull(Double l) { return l == null ? 0.0 : l; } static public boolean 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 String joinWithComma(Iterable 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 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 void runInQAndWait(Q q, Runnable r) { if (r == null) return; if (isInQ(q)) { callF(r); return; } final Flag done = new Flag(); final Var error = new Var(); q.add(new Runnable() { public void run() { try { try { callF(r); } catch (Throwable e) { error.set(e); } finally { done.raise(); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n callF(r);\r\n } catch (Throwable e) {\r\n error.set(e);\r\n ..."; } }); done.waitUntilUp(); if (error.has()) throw rethrow(error.get()); } static public List allFrames() { return listAllFrames(); } static public String postPage(String url, Object... params) { return doPost(litmap(params), url); } static public Map vm_generalSubMap(Object name) { synchronized (vm_generalMap()) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = synchroMap()); return map; } } static public BufferedImage newBufferedImage(int w, int h) { return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); } static public BufferedImage newBufferedImage(int w, int h, RGB rgb) { return newBufferedImage(w, h, rgb.getColor()); } static public BufferedImage newBufferedImage(int w, int h, Color color) { BufferedImage img = newBufferedImage(w, h); Graphics2D g = img.createGraphics(); g.setColor(or(color, Color.white)); g.fillRect(0, 0, w, h); return img; } static public BufferedImage newBufferedImage(Pt p, Color color) { return newBufferedImage(p.x, p.y, color); } static public BufferedImage newBufferedImage(WidthAndHeight size, Color color) { return newBufferedImage(size.w(), size.h(), color); } static public BufferedImage newBufferedImage(int w, int h, int[] pixels) { return intArrayToBufferedImage(pixels, w, h); } static public A tabComponentClickFixer(A 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; } } }); return c; } 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 lessThan(Object a, Object b) { return cmp(a, b) < 0; } static public String or2_rev(String b, String a) { return or2(a, b); } static public SingleThread awtCalcEvery(JFrame f, int delay, int firstDelay, final Object runnable) { return awtCalcRegularly(f, delay, firstDelay, runnable); } static public SingleThread awtCalcEvery(JComponent c, int delay, int firstDelay, final Object runnable) { return awtCalcRegularly(c, delay, firstDelay, runnable); } static public SingleThread awtCalcEvery(JFrame f, int delay, final Object runnable) { return awtCalcRegularly(f, delay, delay, runnable); } static public SingleThread awtCalcEvery(int delay, JComponent c, Runnable runnable) { return awtCalcRegularly(c, delay, delay, runnable); } static public SingleThread awtCalcEvery(JComponent c, int delay, Runnable runnable) { return awtCalcRegularly(c, delay, delay, runnable); } static public SingleThread awtCalcEvery(JComponent c, int delay, final Object runnable) { return awtCalcRegularly(c, delay, delay, runnable); } static public SingleThread awtCalcEvery(JComponent c, double delay, Runnable runnable) { return awtCalcEvery(c, delay, (Object) runnable); } static public SingleThread awtCalcEvery(JComponent c, double delay, Object runnable) { return awtCalcEvery(c, toMS_int(delay), runnable); } static public SingleThread awtCalcEvery(JComponent c, double firstDelay, double delay, final Object runnable) { return awtCalcEvery(c, toMS_int(delay), toMS_int(firstDelay), runnable); } static public Rect scaleRect(Rect r, double factorX, double factorY) { return rectFromPoints(iround(r.x * factorX), iround(r.y * factorY), iround(r.x2() * factorX), iround(r.y2() * factorY)); } static public Rect scaleRect(Rect r, double factor) { return scaleRect(r, factor, factor); } static public Rect scaleRect(double factor, Rect r) { return scaleRect(r, factor); } static public DoubleRect scaleRect(DoubleRect r, double factorX, double factorY) { return doubleRect(r.x * factorX, r.y * factorY, r.w * factorX, r.h * factorY); } static public DoubleRect scaleRect(double factorX, double factorY, DoubleRect r) { return scaleRect(r, factorX, factorY); } static public List subList(List l, int startIndex) { return subList(l, startIndex, l(l)); } static public List subList(int startIndex, List l) { return subList(l, startIndex); } static public List subList(int startIndex, int endIndex, List l) { return subList(l, startIndex, endIndex); } static public List subList(List l, int startIndex, int endIndex) { if (l == null) return null; int n = l(l); startIndex = Math.max(0, startIndex); endIndex = Math.min(n, endIndex); if (startIndex > endIndex) return ll(); if (startIndex == 0 && endIndex == n) return l; return l.subList(startIndex, endIndex); } static public List subList(List l, IntRange r) { return subList(l, r.start, r.end); } static public BufferedImage copyImage(Image img) { if (img == null) return null; if (img instanceof BufferedImage) return copyImage((BufferedImage) img); int w = img.getWidth(null), h = img.getHeight(null); BufferedImage bi = newBufferedImage(w, h); drawImage(bi, img); return bi; } static public BufferedImage copyImage(BufferedImage bi) { if (bi == null) return null; ColorModel cm = bi.getColorModel(); boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); WritableRaster raster = bi.copyData(bi.getRaster().createCompatibleWritableRaster()); return new BufferedImage(cm, raster, isAlphaPremultiplied, null); } static public List sortConceptsByID(Collection l) { return sortedByCalculatedField(l, c -> c.id); } static public int withRightMargin_defaultWidth = 6; static public JPanel withRightMargin(Component c) { return withRightMargin(withRightMargin_defaultWidth, c); } static public JPanel withRightMargin(final int w, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel p = marginPanel(); p.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, w)); p.add(c); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel p = marginPanel();\r\n p.setBorder(BorderFactory.createEmptyBorder(0,..."; } }); } static public String[] toStringArray(Collection c) { String[] a = new String[l(c)]; Iterator it = c.iterator(); for (int i = 0; i < l(a); i++) a[i] = it.next(); return a; } static public String[] toStringArray(Object o) { if (o instanceof String[]) return (String[]) o; else if (o instanceof Collection) return toStringArray((Collection) o); else throw fail("Not a collection or array: " + getClassName(o)); } static public BWImage scaleAndPosterize(BufferedImage img, SnPSettings settings) { return scaleAndPosterize(new BWIntegralImage(img), settings); } static public BWImage scaleAndPosterize(IBWIntegralImage ii, SnPSettings settings) { return posterizeBWImage_withMeta(settings.colors, scaledBWImageFromBWIntegralImage_withMeta_height(settings.pixelRowsForImage(ii), ii)); } static public long intPairToLong(IntPair p) { return p == null ? 0 : (((long) p.a) << 32) | (((long) p.b) & 0xFFFFFFFF); } static public long intPairToLong(int a, int b) { return (((long) a) << 32) | (((long) b) & 0xFFFFFFFF); } static public A evalWithTimeoutOrFail(int timeoutMS, F0 f) { return evalWithTimeoutOrException(timeoutMS, f); } static public A evalWithTimeoutOrFail(double timeoutSeconds, F0 f) { return evalWithTimeoutOrException(timeoutSeconds, f); } static public A evalWithTimeoutOrFail(int timeoutMS, IF0 f) { return evalWithTimeoutOrException(timeoutMS, f); } static public A evalWithTimeoutOrFail(double timeoutSeconds, IF0 f) { return evalWithTimeoutOrException(timeoutSeconds, f); } static public void evalWithTimeoutOrFail(int timeoutMS, Runnable r) { evalWithTimeoutOrException(timeoutMS, runnableToF0(r)); } static public void evalWithTimeoutOrFail(double timeoutSeconds, Runnable r) { evalWithTimeoutOrException(timeoutSeconds, runnableToF0(r)); } static public void addAll(Collection c, Iterable b) { if (c != null && b != null) for (A a : b) c.add(a); } static public boolean addAll(Collection c, Collection b) { return c != null && b != null && c.addAll(b); } static public boolean addAll(Collection c, B... b) { return c != null && b != null && c.addAll(Arrays.asList(b)); } static public Map addAll(Map a, Map b) { if (a != null && b != null) a.putAll(b); return a; } static public A addAll(A c, Collection components) { return addComponents(c, components); } static public A addAll(A c, Component... components) { return addComponents(c, components); } static public DynamicObject dynamicObject(String className, Object... x) { DynamicObject d = new DynamicObject(className); for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null) setDyn(d, (String) x[i], x[i + 1]); return d; } static public A getVar(IF0 v) { return v == null ? null : v.get(); } static public A getVar(Optional v) { return v == null ? null : v.orElse(null); } static public LinkedHashMap mapSortedByValue(Map map) { return orderMapByValue(map); } static public boolean isAnonymousClassName(String s) { for (int i = 0; i < l(s); i++) if (s.charAt(i) == '$' && Character.isDigit(s.charAt(i + 1))) return true; return false; } static public Map putOrCreate(Map map, A key, B value) { if (map == null) map = new HashMap(); map.put(key, value); return map; } static public List selectedTableRows(final JTable table) { return table == null ? null : swing(new F0>() { public List get() { try { return asList(table.getSelectedRows()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return asList(table.getSelectedRows());"; } }); } static public boolean frameTooSmall(JFrame frame) { return frame.getWidth() < 100 || frame.getHeight() < 50; } static public boolean currentProgramHasLibrary(File f) { return contains(myLibraryFiles(), f); } 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 Object dm_callStem(Object moduleOrID, String method, Object... args) { return call_withVarargs(dm_getStem(moduleOrID), method, args); } static public JScrollPane borderlessScrollPane(JScrollPane sp) { return setBorder(null, withoutViewportBorder(sp)); } static public Map rsyntaxTextArea_fixNumPad_map = litmap(KeyEvent.VK_UP, KeyEvent.VK_KP_UP, KeyEvent.VK_DOWN, KeyEvent.VK_KP_DOWN, KeyEvent.VK_LEFT, KeyEvent.VK_KP_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_KP_RIGHT); static public boolean rsyntaxTextArea_fixNumPad_done = false; static public void rsyntaxTextArea_fixNumPad() { if (rsyntaxTextArea_fixNumPad_done) return; RSyntaxTextAreaDefaultInputMap inputMap = new RSyntaxTextAreaDefaultInputMap(); for (KeyStroke key : inputMap.keys()) { Integer code = rsyntaxTextArea_fixNumPad_map.get(key.getKeyCode()); if (code != null) inputMap.put(KeyStroke.getKeyStroke(code, key.getModifiers()), inputMap.get(key)); } UIManager.put("RSyntaxTextAreaUI.inputMap", inputMap); } static public String _computerID; static public Lock computerID_lock = lock(); public static String computerID() { if (_computerID == null) { Lock __0 = computerID_lock; lock(__0); try { if (_computerID != null) return _computerID; File file = computerIDFile(); _computerID = loadTextFile(file.getPath()); if (_computerID == null) { _computerID = loadTextFile(userDir(".tinybrain/computer-id")); if (_computerID == null) _computerID = makeRandomID(12, new SecureRandom()); saveTextFile(file, _computerID); } } finally { unlock(__0); } } return _computerID; } public static String bytesToHex(byte[] bytes) { return bytesToHex(bytes, 0, bytes.length); } public static String bytesToHex(byte[] bytes, int ofs, int len) { StringBuilder stringBuilder = new StringBuilder(len * 2); for (int i = 0; i < len; i++) { String s = "0" + Integer.toHexString(bytes[ofs + i]); stringBuilder.append(s.substring(s.length() - 2, s.length())); } return stringBuilder.toString(); } static public void _inheritThreadInfo(Object info) { _threadInheritInfo(info); } static public void printVars(Object... params) { printVars_str(params); } static public JSpinner dm_powersOfTwoSpinner(String field, int max) { SimpleLiveValue lv = dm_fieldLiveValue(field); return bindLiveValueToSpinner(lv, jPowersOfTwoSpinner(max, lv.get())); } static public String formatDoubleFull(double d, int digits) { String format = digits <= 0 ? "0" : "0." + rep(digits, '0'); return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d); } static public void unlock(Lock lock, String msg) { if (lock == null) return; lock.unlock(); vmBus_send("unlocked", lock, "thread", currentThread()); print("Unlocked: " + msg); } static public void unlock(Lock lock) { if (lock == null) return; lock.unlock(); vmBus_send("unlocked", lock, "thread", currentThread()); } static public String classNameToVM(String name) { return name.replace(".", "$"); } static public long psI(String snippetID) { return parseSnippetID(snippetID); } static public A _recordNewSwingComponent(A c) { if (c != null) callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c); return c; } static public URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) { if (con.getConnectTimeout() == 0) { con.setConnectTimeout(toInt(timeout)); if (con.getConnectTimeout() != timeout) print("Warning: URL connect timeout not set by JDK."); } if (con.getReadTimeout() == 0) { con.setReadTimeout(toInt(timeout)); if (con.getReadTimeout() != timeout) print("Warning: URL read timeout not set by JDK."); } return con; } static public void clearConceptsOf(String progID) { getProgramFile(progID, "concepts.structure").delete(); getProgramFile(progID, "concepts.structure.gz").delete(); getProgramFile(progID, "idCounter.structure").delete(); } static public String javaVersion() { return System.getProperty("java.version"); } static public JSpinner jListSpinner(List entries) { return jListSpinner(entries, first(entries)); } 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 ClassLoader getClassLoader(Object o) { return o == null ? null : _getClass(o).getClassLoader(); } 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 boolean bitMatrixRowEmpty(Matrix m, int y) { int w = m.getWidth(); for (int x = 0; x < w; x++) if (m.get(x, y)) return false; return true; } static public void catchError(DoneFlag doneFlag, Runnable r) { try { { if (r != null) r.run(); } } catch (Throwable e) { doneFlag.setError(e); } } 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 AutoCloseable tempSetButtonImage(JButton btn, ImageIcon img) { if (btn == null) return null; return swing(() -> { Icon oldIcon = btn.getIcon(); setButtonImage(btn, img); return new AutoCloseable() { public String toString() { return "setButtonImage(btn, oldIcon);"; } public void close() throws Exception { setButtonImage(btn, oldIcon); } }; }); } static public AutoCloseable _wrapIOCloseable(final AutoCloseable c) { return c == null ? null : new AutoCloseable() { public String toString() { return "c.close();\r\n _registerIO(c, null, false);"; } public void close() throws Exception { c.close(); _registerIO(c, null, false); } }; } static public String showFormSubmitButtonName() { return "Submit"; } static public Q startQ() { return new Q(); } static public Q startQ(String name) { return new Q(name); } static public double center(DoubleRange r) { return (r.start + r.end) / 2; } static public Pt center(Rect r) { return centerOfRect(r); } static public Pt center(int w, int h) { return pt(w / 2, h / 2); } static public > void forEachLevel2(Iterable l, IVF1 f) { if (l != null) for (B b : l) forEach(b, f); } static public > void forEachLevel2(IVF1 f, Iterable l) { forEachLevel2(f, l); } static public BufferedImage toBufferedImage(Object o) { return toBufferedImageOpt(o); } static public SimplyLinkedList toSimplyLinkedList(List l) { SimplyLinkedList sll = null; for (int i = l(l) - 1; i >= 0; i--) sll = SimplyLinkedList.cons(l.get(i), sll); return sll; } 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 Pair pair(A a, B b) { return new Pair(a, b); } static public Pair pair(A a) { return new Pair(a, a); } static public int parseInt(String s) { return emptyString(s) ? 0 : Integer.parseInt(s); } static public int parseInt(char c) { return Integer.parseInt(str(c)); } static public boolean headless() { return isHeadless(); } static public int lastIndexOf(String a, String b) { return a == null || b == null ? -1 : a.lastIndexOf(b); } static public int lastIndexOf(String a, char b) { return a == null ? -1 : a.lastIndexOf(b); } static public int lastIndexOf(List l, int i, A a) { if (l == null) return -1; for (i = min(l(l), i) - 1; i >= 0; i--) if (eq(l.get(i), a)) return i; return -1; } static public int lastIndexOf(List l, A a) { if (l == null) return -1; for (int i = l(l) - 1; i >= 0; i--) if (eq(l.get(i), a)) return i; return -1; } static public A getSelected(JList l) { return getSelectedItem_typed(l); } static public A getSelected(JComboBox cb) { return getSelectedItem_typed(cb); } static public String structureOrText(Object o) { return o instanceof String ? (String) o : structure(o); } static public File myJar() { return first(myLibraryFiles()); } static public boolean isOpeningBracket(String s) { return eqOneOf(s, "(", "{", "["); } static public A assertNempty(A a) { return assertNempty("", a); } static public A assertNempty(String msg, A a) { if (empty(a)) throw fail(joinNemptiesWithColon(msg, str(a))); return a; } static public A assertNempty(A a) { return assertNempty("", a); } static public A assertNempty(String msg, A a) { if (empty(a)) throw fail(joinNemptiesWithColon(msg, str(a))); return a; } static public A assertNempty(A a) { return assertNempty("", a); } static public A assertNempty(String msg, A a) { if (empty(a)) throw fail(joinNemptiesWithColon(msg, str(a))); return a; } static public A listGet(List l, int idx) { return l != null && idx >= 0 && idx < l.size() ? l.get(idx) : null; } static public void addAndRevalidate(Container c, Component x) { addAndValidate(c, x); } static public String toStringOpt(Object o) { return o instanceof String ? ((String) o) : null; } static public CleanExit cleanExit(String msg) { throw new CleanExit(msg); } static public CleanExit cleanExit() { throw new CleanExit(); } static public int csetAll(Concept c, Object... values) { return cset(c, values); } static public int csetAll(Iterable 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 __0 : _entrySet(values)) { String field = __0.getKey(); Object value = __0.getValue(); n += cset(c, field, value); } return n; } static public java.util.Timer doAfter(long delay, Object r) { return doLater(delay, r); } static public java.util.Timer doAfter(long delay, Runnable r) { return doLater(delay, (Object) r); } static public java.util.Timer doAfter(double delaySeconds, Object r) { return doLater(delaySeconds, r); } static public java.util.Timer doAfter(double delaySeconds, Runnable r) { return doLater(delaySeconds, r); } static public void put(Map map, A a, B b) { if (map != null) map.put(a, b); } static public void put(List l, int i, A a) { if (l != null && i >= 0 && i < l(l)) l.set(i, a); } static public JScrollPane borderless(JScrollPane sp) { return borderlessScrollPane(sp); } static public Dimension dimensionPlus(int w, int h, Dimension d) { return d == null ? null : new Dimension(d.width + w, d.height + h); } static public void caretToHome(JTextComponent c) { setCaret(c, 0); } static public List withoutNulls(Iterable l) { if (l instanceof List) if (!containsNulls((List) l)) return ((List) l); List l2 = new ArrayList(); for (A a : l) if (a != null) l2.add(a); return l2; } static public Map withoutNulls(Map map) { Map map2 = similarEmptyMap(map); for (A a : keys(map)) if (a != null) { B b = map.get(a); if (b != null) map2.put(a, b); } return map2; } static public List withoutNulls(A[] l) { List l2 = new ArrayList(); if (l != null) for (A a : l) if (a != null) l2.add(a); return l2; } static public JScrollPane enclosingScrollPane(Component c) { while (c.getParent() != null && !(c.getParent() instanceof JViewport) && c.getParent().getComponentCount() == 1) c = c.getParent(); if (!(c.getParent() instanceof JViewport)) return null; c = c.getParent().getParent(); return c instanceof JScrollPane ? (JScrollPane) c : null; } static public JWindow infoBox_noHide(String message) { return infoBoxForever(message); } static public List selectedTableRowsInModel(final JTable t) { return t == null ? emptyList() : swing(new F0>() { public List get() { try { return map(selectedTableRows(t), i -> t.convertRowIndexToModel(i)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return map(selectedTableRows(t), i -> t.convertRowIndexToModel(i));"; } }); } static public String nLines(long n) { return n2(n, "line"); } static public String nLines(Collection l) { return nLines(l(l)); } static public String nLines(String s) { return nLines(countLines(s)); } 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 double g22_regionFilledness(IImageRegion region) { return doubleRatio(region.numberOfPixels(), area(region.bounds())); } static public List powersOfTwoUpTo(int n) { return powersOfTwoUpTo(1, n); } static public List powersOfTwoUpTo(int firstPowerOfTwo, int n) { IntBuffer l = new IntBuffer(); int i = firstPowerOfTwo; while (i <= n && i > 0) { l.add(i); i *= 2; } return l.asVirtualList(); } static public int tableColumnCount(JTable table) { return tableNumColumns(table); } static public A jMinWidth(final int w, final A c) { if (c == null) return null; return swing(new F0() { public A get() { try { Dimension size = c.getMinimumSize(); c.setMinimumSize(new Dimension(w, size.height)); return jPreferWidth(w, c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Dimension size = c.getMinimumSize();\r\n c.setMinimumSize(new Dimension(/*ma..."; } }); } static public Object[] emptyObjectArray_a = new Object[0]; static public Object[] emptyObjectArray() { return emptyObjectArray_a; } 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 boolean isSubclassOf(Class a, Class b) { return isSubclass(a, b); } static public A repaint(A c) { if (c != null) c.repaint(); return c; } static public A onFirstComponentShow(final A component, final Runnable onShow) { { swing(() -> { component.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { component.removeAncestorListener(this); pcallF(onShow); } public void ancestorRemoved(AncestorEvent event) { } public void ancestorMoved(AncestorEvent event) { } }); }); } return component; } static public BufferedImage newImage(int w, int h) { return whiteImage(w, h); } static public BufferedImage newImage(int w, Color color) { return newImage(w, w, color); } 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(WidthAndHeight size) { return whiteImage(size.w(), size.h()); } static public BufferedImage newImage(Dimension size) { return whiteImage(size.width, size.height); } static public AutoCloseable tempDisableButton(final JButton b) { if (b == null) return null; boolean wasEnabled = swing(new F0() { public Boolean get() { try { boolean wasEnabled = isEnabled(b); if (wasEnabled) disableButton(b); return wasEnabled; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "bool wasEnabled = isEnabled(b);\r\n if (wasEnabled)\r\n disableButton(b);..."; } }); if (!wasEnabled) return null; return new AutoCloseable() { public String toString() { return "enableButton(b);"; } public void close() throws Exception { enableButton(b); } }; } static public int _hashCode(Object a) { return a == null ? 0 : a.hashCode(); } static public A toolTipFromLiveValue(LiveValue lv, A c) { return bindToolTipToLiveValue(lv, c); } static public String className(Object o) { return getClassName(o); } public static boolean isSnippetID(String s) { try { parseSnippetID(s); return true; } catch (RuntimeException e) { return false; } } static public boolean usingStarter(Object mainObject) { return endsWith(className(getClassLoader(mainObject)), "StartClassLoader"); } static public String baseClassName(String className) { return substring(className, className.lastIndexOf('.') + 1); } static public String baseClassName(Object o) { return baseClassName(getClassName(o)); } static public String tok_moveImportsUp(String src) { return join(tok_moveImportsUp(javaTok(src))); } static public List tok_moveImportsUp(List tok) { StringBuilder buf = new StringBuilder(); int i; Set have = new HashSet(); for (i = 1; i < l(tok); i += 2) if (eq(tok.get(i), "import")) { int j = indexOf(tok, i + 2, ";"); if (j < 0) break; String s = joinSubList(tok, i, j + 1); have.add(s); i = j; } else break; List reToks = new ArrayList(); for (; i < l(tok); i += 2) if (eq(tok.get(i), "import")) { int j = indexOf(tok, i + 2, ";"); if (j < 0) continue; String s = joinSubList(tok, i, j + 1); if (!have.contains(s)) { buf.append(s).append("\n"); have.add(s); } replaceTokens(tok, i, j + 1, ""); reToks.add(intRange(i, j + 1)); i -= 2; } if (nempty(buf)) { if (l(tok) == 1) addAll(tok, "", ""); tok.set(1, str(buf) + "\n" + tok.get(1)); reToks.add(intRange(1, 2)); } return reTok_multi(tok, reToks); } static public List sortedByCalculatedField(Iterable c, Object f) { return sortByCalculatedField(c, f); } static public List sortedByCalculatedField(Object f, Iterable c) { return sortedByCalculatedField(c, f); } static public List sortedByCalculatedField(IF1 f, Iterable c) { return sortedByCalculatedField(c, f); } static public List sortedByCalculatedField(Iterable c, IF1 f) { List l = cloneList(c); sort(l, new Comparator() { public int compare(A a, A b) { return stdcompare(f.get(a), f.get(b)); } }); return l; } static public List getClasses(Object[] array) { List l = emptyList(l(array)); for (Object o : array) l.add(_getClass(o)); return l; } static public int iround(double d) { return (int) Math.round(d); } static public int iround(Number n) { return iround(toDouble(n)); } static public List codeTokens(List tok) { return codeTokensOnly(tok); } static public List listDirs(File dir) { if (dir == null) return emptyList(); File[] files = dir.listFiles(); List l = new ArrayList(); if (files != null) for (File f : files) if (f.isDirectory()) l.add(f); return l; } static public List listDirs(String dir) { return listDirs(newFile(dir)); } static public List listPlus(Collection l, A... more) { return concatLists(l, asList(more)); } static public String snippetImageURL_http(String snippetID) { return snippetImageURL_http(snippetID, "png"); } static public String snippetImageURL_http(String snippetID, String contentType) { return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080"); } static public boolean sexyTable_drag = false; static public JTable sexyTable() { final JTable table = sexyTableWithoutDrag(); if (sexyTable_drag) tableEnableTextDrag(table); return table; } static public boolean isConceptFieldIndexed(Class c, String field) { return isConceptFieldIndexed(db_mainConcepts(), c, field); } static public boolean isConceptFieldIndexed(Concepts concepts, Class c, String field) { return concepts.getFieldIndex(c, field) != null; } static public Object pcallFunction(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable __e) { pcallFail(__e); } return null; } 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 BufferedImage toBufferedImageOpt(Object o) { if (o instanceof BufferedImage) return ((BufferedImage) o); if (o instanceof Image) return copyImage((Image) o); if (o instanceof MakesBufferedImage) return ((MakesBufferedImage) o).getBufferedImage(); String c = getClassName(o); if (eqOneOf(c, "main$BWImage", "main$RGBImage")) return (BufferedImage) call(o, "getBufferedImage"); return null; } 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) { pcallFail(__e); } return null; } static public B pcallF(F1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__e); } return null; } static public void pcallF(VF1 f, A a) { try { { if (f != null) f.get(a); } } catch (Throwable __e) { pcallFail(__e); } } static public Object pcallF(Runnable r) { try { { if (r != null) r.run(); } } catch (Throwable __e) { pcallFail(__e); } return null; } static public A pcallF(IF0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { pcallFail(__e); } return null; } static public B pcallF(IF1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__e); } return null; } static public List listSetIntersection(Iterable a, Collection b) { List l = new ArrayList(); Set bSet = asSet(b); for (A x : unnull(a)) if (bSet.contains(x)) l.add(x); return l; } static public ThreadLocal> holdInstance_l = new ThreadLocal(); static public AutoCloseable holdInstance(Object o) { if (o == null) return null; listThreadLocalAdd(holdInstance_l, o); return new AutoCloseable() { public void close() { listThreadLocalPopLast(holdInstance_l); } }; } static public void ownResource(AutoCloseable c) { _registerAutoCloseable(c); } static public float bwDistance(BWImage a, BWImage b, float maxDistance) { return 1f - bwImageSimilarityResized(a, b, 1f - maxDistance); } static public float bwDistance(BWImage a, BWImage b) { return bwDistance(a, b, 1f); } static public String tabsToSpaces(String s) { return tabsToSpaces(2, s); } static public String tabsToSpaces(int spacesPerTab, String s) { return replace(s, "\t", repSpace(spacesPerTab)); } static public String makePostData(Map map) { StringBuilder buf = new StringBuilder(); for (Map.Entry e : castMapToMapO(map).entrySet()) { String key = (String) (e.getKey()); Object val = e.getValue(); if (val != null) { String value = str(val); if (nempty(buf)) buf.append("&"); buf.append(urlencode(key)).append("=").append(urlencode((value))); } } return str(buf); } static public String makePostData(Object... params) { StringBuilder buf = new StringBuilder(); int n = l(params); for (int i = 0; i + 1 < n; i += 2) { String key = (String) (params[i]); Object val = params[i + 1]; if (val != null) { String value = str(val); if (nempty(buf)) buf.append("&"); buf.append(urlencode(key)).append("=").append(urlencode((value))); } } return str(buf); } static public String textOut_or(Collection l) { return textOut_or(l, "nothing"); } static public String textOut_or(Collection l, String emptyText) { if (empty(l)) return emptyText; List separators = rep(", ", l(l) - 2); separators.add(" or "); return join_flex(separators, l); } static public File loadLibrary(String snippetID) { return loadBinarySnippet(snippetID); } static public A packWindow(final A c) { { swing(() -> { Window w = getWindow(c); if (w != null) w.pack(); }); } return c; } static public boolean endsWithNewLine(String s) { return endsWith(s, "\n"); } static public IterableIterator> multiMapPairIterator_transformValueList(MultiMap mm, IF1, List> f) { return nestedIterator(iterator(keys(mm.data)), key -> (IterableIterator>) mapI(iterator(f.get(mm.data.get(key))), val -> pair(key, val))); } static public int done_minPrint = 10; static public long done(long startTime, String desc) { long time = now() - startTime; if (time >= done_minPrint) print(desc + " [" + time + " ms]"); return time; } static public long done(String desc, long startTime) { return done(startTime, desc); } static public long done(long startTime) { return done(startTime, ""); } static public JMenuItem jMenuItem(final String text) { return jmenuItem(text); } static public JMenuItem jMenuItem(String text, Object r) { return jmenuItem(text, r); } 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 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 String getClassName(Object o) { return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName(); } static public void savePNGVerbose(BufferedImage img, File file) { try { savePNG(img, file); print("Saved PNG: " + f2s(file)); } catch (Exception __e) { throw rethrow(__e); } } static public void savePNGVerbose(File file, BufferedImage img) { savePNGVerbose(img, file); } 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 int tableRows(JTable table) { return (int) swingCall(table, "getRowCount"); } static public void setAddAll(Collection a, Collection b) { for (A x : b) setAdd(a, x); } static public int indexOfIC_underscore(String a, String b) { int la = l(a), lb = l(b); if (la < lb) return -1; int n = la - lb; elsewhere: for (int i = 0; i <= n; i++) { for (int j = 0; j < lb; j++) { char c2 = b.charAt(j); if (c2 == '_' || eqic(c2, a.charAt(i + j))) { } else continue elsewhere; } return i; } return -1; } static public void sleepSeconds(double s) { if (s > 0) sleep(round(s * 1000)); } static public Object vmBus_wrapArgs(Object... args) { return empty(args) ? null : l(args) == 1 ? args[0] : args; } static public Map vm_generalMap_map; static public Map vm_generalMap() { if (vm_generalMap_map == null) vm_generalMap_map = (Map) get(javax(), "generalMap"); return vm_generalMap_map; } static public Collection values(Map map) { return map == null ? emptyList() : map.values(); } static public Collection values(Object map) { return values((Map) map); } static public Collection values(MultiMap mm) { return mm == null ? emptyList() : concatLists(values(mm.data)); } static public void tablePopupMenuItem_top(final JTable table, final String name, final Object action) { tablePopupMenuFirst(table, new VF2() { public void get(JPopupMenu menu, final Integer row) { try { addMenuItem(menu, name, new Runnable() { public void run() { try { pcallF(action, row); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, row)"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, name, r { pcallF(action, row) });"; } }); } 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 void setMeta(IMeta o, Object key, Object value) { metaMapPut(o, key, value); } static public void setMeta(Object o, Object key, Object value) { metaMapPut(o, key, value); } static public Pt ptMinus(Pt a, Pt b) { if (b == null) return a; return new Pt(a.x - b.x, a.y - b.y); } static public String formatSnippetIDOpt(String s) { return isSnippetID(s) ? formatSnippetID(s) : s; } static public List regexpGetGroups(Matcher matcher) { int n = matcher.groupCount(); List l = new ArrayList(); for (int i = 1; i <= n; i++) l.add(matcher.group(i)); return l; } static public List regexpGetGroups(String pat, String s) { Matcher m = regexpMatcher(pat, s); if (m.find()) return regexpGetGroups(m); return null; } static public String loadTextFile(String fileName) { return loadTextFile(fileName, null); } static public String loadTextFile(File f, String defaultContents) { return loadTextFile(f, defaultContents, "UTF-8"); } static public String loadTextFile(File f, String defaultContents, String encoding) { try { checkFileNotTooBigToRead(f); if (f == null || !f.exists()) return defaultContents; FileInputStream fileInputStream = new FileInputStream(f); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding); return loadTextFile(inputStreamReader); } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFile(File fileName) { return loadTextFile(fileName, null); } static public String loadTextFile(String fileName, String defaultContents) { return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents); } static public String loadTextFile(Reader reader) throws IOException { StringBuilder builder = new StringBuilder(); try { char[] buffer = new char[1024]; int n; while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n); } finally { reader.close(); } return str(builder); } static public 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 int menuItemCount(JMenu menu) { return menu == null ? 0 : swing(() -> menu.getItemCount()); } static public Map mapValues(Object func, Map map) { Map m = similarEmptyMap(map); for (Object key : keys(map)) m.put(key, callF(func, map.get(key))); return m; } static public Map mapValues(Map map, IF1 f) { return mapValues(f, map); } static public Map mapValues(IF1 f, Map map) { Map m = similarEmptyMap(map); for (Map.Entry __0 : _entrySet(map)) { A key = __0.getKey(); B val = __0.getValue(); m.put(key, f.get(val)); } return m; } static public Map mapValues(Map map, Object func) { return mapValues(func, map); } static public MultiMap mapValues(IF1 func, MultiMap mm) { return mapMultiMapValues(func, mm); } static public MultiMap mapValues(MultiMap mm, IF1 func) { return mapValues(func, mm); } static public void clear(Collection c) { if (c != null) c.clear(); } static public void clear(Map map) { if (map != null) map.clear(); } static public JProgressBar showProgressWindow(double maxValue) { return showProgressWindow(null, maxValue); } static public JProgressBar showProgressWindow(String text, double maxValue) { JProgressBar bar = jProgressBarWithText(iround(maxValue)); swingCall(bar, "setString", text); centerFrame(packFrameVertically(500, showFrame(text, bar))); return bar; } static public TreeMap revTreeMap() { return new TreeMap(reverseComparator()); } static public A rightAlignLabel(final A a) { return setHorizontalAlignment(JLabel.RIGHT, a); } static public Object call_withVarargs(Object o, String methodName, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findStaticMethod(methodName, args); if (me != null) return invokeMethod(me, null, args); List methods = cache.cache.get(methodName); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } { if (!(isStaticMethod(m))) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, null, newArgs); } throw fail("Method " + c.getName() + "." + methodName + "(" + formatArgumentClasses(args) + ") not found"); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me != null) return invokeMethod(me, o, args); List methods = cache.cache.get(methodName); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, o, newArgs); } throw fail("Method " + c.getName() + "." + methodName + "(" + formatArgumentClasses(args) + ") not found"); } } catch (Exception __e) { throw rethrow(__e); } } static public void replaceLastElement(List l, A a) { if (nempty(l)) l.set(l(l) - 1, a); } static public A third(List l) { return _get(l, 2); } static public A third(Iterable l) { if (l == null) return null; Iterator it = iterator(l); for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) { if (!it.hasNext()) return null; it.next(); } return it.hasNext() ? it.next() : null; } static public A third(Producer p) { if (p == null) return null; for (int _repeat_1 = 0; _repeat_1 < 2; _repeat_1++) { if (p.next() == null) return null; } return p.next(); } static public A third(A[] bla) { return bla == null || bla.length <= 2 ? null : bla[2]; } static public C third(T3 t) { return t == null ? null : t.c; } static public JScrollPane withoutViewportBorder(JScrollPane sp) { if (sp != null) { swing(() -> { sp.setViewportBorder(null); }); } return sp; } static public A setThreadLocal(ThreadLocal tl, A value) { if (tl == null) return null; A old = tl.get(); tl.set(value); return old; } static public Color getBackground(final Component c) { return c == null ? null : swing(new F0() { public Color get() { try { return c.getBackground(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getBackground();"; } }); } static public void addTab(JExtendedTabbedPane tabs, String title) { addTab(tabs, title, jpanel()); } static public void addTab(JExtendedTabbedPane tabs, String title, Component c) { if (tabs != null) { swing(() -> { tabs.add(title, wrap(c)); }); } } static public void addTab(JExtendedTabbedPane tabs, String title, Swingable c) { if (tabs != null) { swing(() -> { tabs.add(title, wrap(c)); }); } } static public void addTab(JTabbedPane tabs, String title) { addTab(tabs, title, jpanel()); } 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 void addTab(JTabbedPane tabs, WithToolTip title, Component c) { addTabWithToolTip(tabs, title.toolTip(), title == null ? null : title.get(), c); } static public void addTab(JTabbedPane tabs, WithToolTip title, Swingable c) { addTabWithToolTip(tabs, title.toolTip(), title == null ? null : title.get(), c); } static public boolean hasJPEGExtension(File f) { return ewicOneOf(fileName(f), ".jpg", ".jpeg"); } static public ConceptFieldIndexCI indexConceptFieldCI(Class c, String field) { return indexConceptFieldCI(db_mainConcepts(), c, field); } static public ConceptFieldIndexCI indexConceptFieldCI(Concepts concepts, Class c, String field) { ConceptFieldIndexCI idx = getConceptFieldCIIndex(concepts, c, field); return idx != null ? idx : new ConceptFieldIndexCI(concepts, c, field); } static public File javaxSecretDir_dir; static public File javaxSecretDir() { return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret"); } static public File javaxSecretDir(String sub) { return newFile(javaxSecretDir(), sub); } static public int lCommonPrefix(String a, String b) { int i = 0, n = Math.min(l(a), l(b)); while (i < n && a.charAt(i) == b.charAt(i)) ++i; return i; } static public JComponent showErrorFrame(Throwable e) { if (e == null) return null; return showTextWordWrapped("Error", renderStackTrace((e))); } static public void maximizeOrRestoreFrame(JFrame f) { if (f == null) return; if (!isExtendedStateNormal(f)) { swing(() -> { f.setExtendedState(JFrame.NORMAL); }); } else maximizeFrame(f); } 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 String trim(String s) { return s == null ? null : s.trim(); } static public String trim(StringBuilder buf) { return buf.toString().trim(); } static public String trim(StringBuffer buf) { return buf.toString().trim(); } static public A printWithTime(A a) { return printWithTime("", a); } static public A printWithTime(String s, A a) { print(hmsWithColons() + ": " + s, a); return a; } static public A lowestByScoreFunction(Iterable l, IF1 f) { Lowest lowest = new Lowest(); for (A a : unnull(l)) { Number score = callF(f, a); if (score != null) lowest.put(a, toDouble(score)); } return lowest.get(); } static public void saveImage(File f, BufferedImage img) { if (hasJPEGExtension(f)) saveJPG(f, img); else savePNG(f, img); } static public void saveImage(BufferedImage img, File f) { saveImage(f, img); } static public String shortenSnippetID(String snippetID) { if (snippetID.startsWith("#")) snippetID = snippetID.substring(1); String httpBlaBla = "http://tinybrain.de/"; if (snippetID.startsWith(httpBlaBla)) snippetID = snippetID.substring(httpBlaBla.length()); return "" + parseLong(snippetID); } static public JInternalFrame getInternalFrame(final Object _o) { return _o == null ? null : swing(new F0() { public JInternalFrame get() { try { Object o = _o; if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof JInternalFrame) return (JInternalFrame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; } }); } static public boolean syncAdd(Collection c, A b) { if (c == null) return false; synchronized (collectionMutex(c)) { return c.add(b); } } static public void syncAdd(List l, int idx, A b) { if (l != null) synchronized (collectionMutex(l)) { l.add(idx, b); } } static public BWImage toBW(RGBImage img) { return img == null ? null : new BWImage(img); } static public AutoCloseable tempSetThreadLocalIfNecessary(ThreadLocal tl, A a) { if (tl == null) return null; A prev = tl.get(); if (eq(prev, a)) return null; tl.set(a); return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); } }; } static public AutoCloseable tempSetThreadLocalIfNecessary(BetterThreadLocal tl, A a) { if (tl == null) return null; A prev = tl.get(); if (eq(prev, a)) return null; tl.set(a); return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); } }; } static public String formatRecordVars(String recordName, Object... params) { return renderRecordVars(recordName, params); } static public F0 runnableToF0(Runnable r) { return r == null ? null : new F0() { public Object get() { try { r.run(); return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "r.run(); null;"; } }; } static public boolean syncRemove(Collection c, A b) { if (c == null) return false; synchronized (collectionMutex(c)) { return c.remove(b); } } static public A syncRemove(List l, int idx) { if (l == null) return null; synchronized (collectionMutex(l)) { return l.remove(idx); } } static public B syncRemove(Map map, A key) { return map == null ? null : map.remove(key); } static public IterableIterator countIterator_inclusive(final int a, final int b) { return countIterator_exclusive(a, b + 1); } static public IterableIterator countIterator_inclusive(int a, int b, IF1 f) { return countIterator_inclusive(a, b, 1, f); } static public IterableIterator countIterator_inclusive(int a, int b, int step, IF1 f) { return countIterator_inclusive_step(a, b, 1, f); } static public IterableIterator countIterator_inclusive(double a, double b, double step, IF1 f) { return countIterator_inclusive_step(a, b, step, f); } static public JPanel vstack(Object... parts) { return vstack2(parts); } static public JPanel vstack(List parts) { return vstack(toObjectArray(parts)); } static public String formatWithThousands(long l) { return formatWithThousandsSeparator(l); } 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 void disposePossiblyInternalFrame(Component c) { Container f = (Container) (getPossiblyInternalFrame(c)); if (f instanceof JInternalFrame) disposeInternalFrame((JInternalFrame) f); else if (f instanceof Window) disposeWindow(f); } static public String exceptionType(Throwable e) { e = getInnerException(e); return shortClassName(e); } static public String rtrim_fromLines(Collection lines) { StringBuilder buf = new StringBuilder(); if (lines != null) { boolean first = true; for (Object line : lines) { if (first) first = false; else buf.append('\n'); buf.append(str(line)); } } return buf.toString(); } static public Map> setTableModel_after = weakHashMap(); static public Map> setTableModel_fixSorter = weakHashMap(); static public void setTableModel(final JTable table, final TableModel model) { { swing(() -> { Map widths = tableColumnWidthsByName(table); int[] i = table.getSelectedRows(); TableRowSorter sorter = model.getColumnCount() == tableColumnCount(table) ? (TableRowSorter) table.getRowSorter() : null; List sortKeys = sorter == null ? null : sorter.getSortKeys(); table.setModel(model); int n = model.getRowCount(); ListSelectionModel sel = table.getSelectionModel(); for (int j = 0; j < i.length; j++) if (i[j] < n) sel.addSelectionInterval(i[j], i[j]); tableSetColumnPreferredWidths(table, widths); if (sorter != null) { sorter.setModel(model); callF(setTableModel_fixSorter.get(table), table, sorter); if (sortKeys != null) sorter.setSortKeys(sortKeys); } table.setRowSorter(sorter); callF(setTableModel_after.get(table), table); }); } } static public List tabNames(JTabbedPane tabs) { return tabs == null ? null : swing(() -> countIteratorToList(tabs.getTabCount(), i -> tabs.getTitleAt(i))); } static public boolean isStaticMethod(Method m) { return methodIsStatic(m); } static public Object[] paramsPlus(Object[] a1, Object... a2) { if (a2 == null) return a1; if (a1 == null) return a2; if (l(a1) == 1 && a1[0] instanceof Map) return new Object[] { mapPlus((Map) a1[0], a2) }; assertEvenLength(a1); assertEvenLength(a2); Map map = paramsToOrderedMap(a1); int n = l(a2); for (int i = 0; i < n; i += 2) { Object key = a2[i]; if (key != null) map.put(key, a2[i + 1]); } return mapToParams(map); } static public Object[] paramsPlus(Map a1, Object... a2) { return paramsPlus(new Object[] { a1 }, a2); } static public ActionListener actionListener(final Object runnable) { return actionListener(runnable, null); } static public ActionListener actionListener(final Object runnable, final Object instanceToHold) { if (runnable instanceof ActionListener) return (ActionListener) runnable; final Object info = _threadInfo(); return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { _threadInheritInfo(info); AutoCloseable __1 = holdInstance(instanceToHold); try { pcallF(runnable); } finally { _close(__1); } } catch (Throwable __e) { messageBox(__e); } } }; } static public String str_shorten(Object o) { return shorten_str(o); } static public String str_shorten(Object o, int max) { return shorten_str(o, max); } static public String str_shorten(int max, Object o) { return shorten_str(max, o); } static public String formatUTCWithMS_24() { return formatUTCWithMS_24(now()); } static public String formatUTCWithMS_24(long time) { var sdf = new SimpleDateFormat("HH:mm:ss.SSSS"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf.format(time) + " UTC"; } static public Rectangle rectangleUnion(Rectangle a, Rectangle b) { return a == null ? b : b == null ? a : a.union(b); } static public JCheckBox liveValueCheckBox(String text, IVarWithNotify lv) { return jLiveValueCheckBox(text, lv); } static public JCheckBox liveValueCheckBox(IVarWithNotify lv, String text) { return jLiveValueCheckBox(text, lv); } 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 String conceptsDirName() { return conceptsDirName(db_mainConcepts()); } static public String conceptsDirName(Concepts cc) { return fileName(cc.conceptsDir()); } static public String fileInfo(File f) { return renderFileInfo(f); } static public String fileInfo(String f) { return renderFileInfo(newFile(f)); } static public Map synchroIdentityHashMap() { return synchroMap(new IdentityHashMap()); } static public String exceptionToStringShort(Throwable e) { try { 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; } catch (Throwable _e) { printStackTrace(_e); return "Error in exceptionToStringShort"; } } static public Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap(); static public Object nuObjectWithoutArguments(String className) { try { return nuObjectWithoutArguments(classForName(className)); } catch (Exception __e) { throw rethrow(__e); } } static public A nuObjectWithoutArguments(Class c) { try { if (nuObjectWithoutArguments_cache == null) return (A) nuObjectWithoutArguments_findConstructor(c).newInstance(); Constructor m = nuObjectWithoutArguments_cache.get(c); if (m == null) nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c)); return (A) m.newInstance(); } catch (Exception __e) { throw rethrow(__e); } } static public Constructor nuObjectWithoutArguments_findConstructor(Class c) { for (Constructor m : getDeclaredConstructors_cached(c)) if (empty(m.getParameterTypes())) { makeAccessible(m); return m; } throw fail("No default constructor found in " + c.getName()); } static public boolean isValidFileName(String s) { return nempty(s) && !eqOneOf(s, ".", "..") && all(characters(s), c -> isValidFileCharacter(c)); } static public A setToolTipText(final A c, final Object toolTip) { if (c == null) return null; { swing(() -> { String s = str_nullIfEmpty(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 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); g22_highlightRegion(pixels, itr, iHighlightedRegion, showRegionsAsOutline); } } static public void g22_highlightRegion(int[] pixels, Gazelle22_ImageToRegions itr, int iRegion, boolean showRegionsAsOutline) { g22_highlightRegion(pixels, itr, iRegion, 0xFF00C000, showRegionsAsOutline); } static public void g22_highlightRegion(int[] pixels, 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 JPanel makeForm_customLayout(final F1 layouter, final Object... parts) { return makeForm_customArrangement(new F1, JPanel>() { public JPanel get(List components) { try { return customLayoutPanel(layouter, components); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "customLayoutPanel(layouter, components)"; } }, parts); } static public A bindToolTipToTransformedLiveValue(IF1 f, LiveValue lv, A c) { bindLiveValueListenerToComponent(c, lv, new Runnable() { public void run() { try { setToolTipText(c, strOrNull(f.get(lv.get()))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setToolTipText(c, strOrNull(f.get(lv!)))"; } }); return c; } static public AutoCloseable tempAddToWindow(JWindow w, Component toAdd) { if (w == null || toAdd == null) return null; return swing(() -> { var oldContent = w.getContentPane(); setContentPane(w, centerAndSouth(oldContent, toAdd)); return () -> setContentPane(w, oldContent); }); } static public AutoCloseable tempAddToWindow(JFrame w, Component toAdd) { if (w == null || toAdd == null) return null; return swing(() -> { var oldContent = w.getContentPane(); setContentPane(w, centerAndSouth(oldContent, toAdd)); return () -> setContentPane(w, oldContent); }); } static public AutoCloseable tempEnter(Object o) { return o == null ? null : optCast(AutoCloseable.class, rcallOpt("enter", o)); } static public AutoCloseable tempEnter(Enterable o) { return o == null ? null : o.enter(); } static public Object[] arrayPlus(Object[] a1, Object... a2) { return concatArrays(a1, a2); } static public boolean sameSize(WidthAndHeight a, BufferedImage b) { return a != null && b != null && a.getWidth() == b.getWidth() && a.getHeight() == b.getHeight(); } static public boolean sameSize(BufferedImage b, WidthAndHeight a) { return sameSize(a, b); } static public IF1 f1ToIF1(F1 f) { return f == null ? null : a -> f.get(a); } static public Rect leftScreenBounds() { return first(allScreenBounds()); } static public AutoCloseable tempInfoBox(String msg) { return tempDisposeWindow(infoBox(msg)); } static public String joinNemptiesWithColon(String... strings) { return joinNempties(": ", strings); } static public String joinNemptiesWithColon(Collection strings) { return joinNempties(": ", strings); } static public void tableEnableDrag(final JTable table, TransferHandler th) { if (table.getDragEnabled()) { print("Table drag already enabled"); return; } table.setDragEnabled(true); table.setTransferHandler(th); table.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getButton() == 1 && e.getClickCount() == 1) table.getTransferHandler().exportAsDrag(table, e, TransferHandler.COPY); } }); } 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 HashSet lithashset(A... items) { HashSet set = new HashSet(); for (A a : items) set.add(a); return set; } static public List ciSorted(Collection c) { return sortedIgnoreCase(c); } static public A setDyn(A o, String key, Object value) { setDynObjectValue(o, key, value); return o; } static public void setDyn(IMeta o, String key, Object value) { metaMapPut(o, key, value); } static public Throwable innerException2(Throwable e) { if (e == null) return null; while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause(); return e; } static public B secondOfPair(Pair p) { return p == null ? null : p.b; } static public BWImage posterizeBWImage_withMeta(int brightnessLevels, BufferedImage img) { return posterizeBWImage_withMeta(brightnessLevels, toBWImage(img)); } static public BWImage posterizeBWImage_withMeta(int brightnessLevels, BWImage img) { PosterizeBWImage x = new PosterizeBWImage(brightnessLevels, img); x.run(); return setMetaSrcUnlessSame(img, x.result, x); } static public boolean containsPred(IF1 pred, Iterable l) { return any(pred, l); } static public boolean containsPred(Iterable l, IF1 pred) { return any(pred, l); } static public long saveGZStructureToFile(String file, Object o) { return saveGZStructureToFile(getProgramFile(file), o); } static public long saveGZStructureToFile(File file, Object o) { return saveGZStructureToFile(file, o, new structure_Data()); } static public long saveGZStructureToFile(File file, Object o, structure_Data data) { try { File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); File tempFile = tempFileFor(file); if (tempFile.exists()) try { String saveName = tempFile.getPath() + ".saved." + now(); copyFile(tempFile, new File(saveName)); } catch (Throwable e) { printStackTrace(e); } FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath()); CountingOutputStream cos; try { GZIPOutputStream gos = new GZIPOutputStream(fileOutputStream); cos = new CountingOutputStream(gos); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(cos, "UTF-8"); PrintWriter printWriter = new PrintWriter(outputStreamWriter); structureToPrintWriter(o, printWriter, data); printWriter.close(); gos.close(); fileOutputStream.close(); } catch (Throwable e) { fileOutputStream.close(); tempFile.delete(); throw rethrow(e); } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + file.getPath()); if (!tempFile.renameTo(file)) throw new IOException("Can't rename " + tempFile + " to " + file); return cos.getFilePointer(); } catch (Exception __e) { throw rethrow(__e); } } static public JTextField jLiveTextField(SimpleLiveValue lv) { return jLiveValueTextField_bothWays(lv); } 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 int cmpAlphanumIC(String a, String b) { return cmpAlphaNum(a, b); } static public A collectionGet(Collection c, int idx) { if (c == null || idx < 0 || idx >= l(c)) return null; if (c instanceof List) return listGet((List) c, idx); Iterator it = c.iterator(); for (int i = 0; i < idx; i++) if (it.hasNext()) it.next(); else return null; return it.hasNext() ? it.next() : null; } static public void frameStandardSize(JFrame frame) { frame.setBounds(300, 100, 500, 400); } static public JToggleButton jToggleButton(String text, Runnable action) { var btn = basicJToggleButton(text); addActionListener(btn, action); return btn; } static public int hashCode(Object a) { return a == null ? 0 : a.hashCode(); } static public int hashCode(long l) { return Long.hashCode(l); } static public int hashCode(double d) { return Double.hashCode(d); } static public FileOutputStream newFileOutputStream(File path) throws IOException { return newFileOutputStream(path.getPath()); } static public FileOutputStream newFileOutputStream(String path) throws IOException { return newFileOutputStream(path, false); } static public FileOutputStream newFileOutputStream(File path, boolean append) throws IOException { return newFileOutputStream(path.getPath(), append); } static public FileOutputStream newFileOutputStream(String path, boolean append) throws IOException { mkdirsForFile(path); FileOutputStream f = new FileOutputStream(path, append); _registerIO(f, path, true); return f; } static public String shortClassName(Object o) { if (o == null) return null; Class c = o instanceof Class ? (Class) o : o.getClass(); String name = c.getName(); return shortenClassName(name); } static public boolean checkConceptFields(Concept x, Object... data) { for (int i = 0; i < l(data); i += 2) if (neq(cget(x, (String) data[i]), deref(data[i + 1]))) return false; return true; } static public AutoCloseable tempInfoBoxNoHide(String msg) { return tempInfoBox_noHide(msg); } static public boolean rectContains(int x1, int y1, int w, int h, Pt p) { return p.x >= x1 && p.y >= y1 && p.x < x1 + w && p.y < y1 + h; } static public boolean rectContains(Rect a, Rect b) { return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2(); } static public boolean rectContains(Rect a, Rectangle b) { return rectContains(a, toRect(b)); } static public boolean rectContains(Rect a, int x, int y) { return a != null && a.contains(x, y); } static public boolean rectContains(Rect a, Pt p) { return a != null && p != null && a.contains(p); } static public CloseableIterableIterator linesFromReader(Reader r) { return linesFromReader(r, null); } static public CloseableIterableIterator linesFromReader(Reader r, IResourceHolder resourceHolder) { final BufferedReader br = bufferedReader(r); return holdResource(resourceHolder, iteratorFromFunction_f0_autoCloseable(new F0() { public String get() { try { return readLineFromReaderWithClose(br); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return readLineFromReaderWithClose(br);"; } }, _wrapIOCloseable(r))); } static public CloseableIterableIterator linesFromReader(InputStream in) { return linesFromReader(inputStreamReader(in)); } static public int length(Object[] array) { return array == null ? 0 : array.length; } static public int length(List list) { return list == null ? 0 : list.size(); } static public int length(String s) { return s == null ? 0 : s.length(); } 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) { pcallFail(__e); } } }); }); } return w; } static public JButton enableButton(JButton b) { return enableButton(b, true); } static public JButton enableButton(JButton b, boolean enable) { if (b != null) { swing(() -> { b.setEnabled(enable); }); } return b; } static public int clampToInt(long l) { return (int) clamp(l, Integer.MIN_VALUE, Integer.MAX_VALUE); } static public MultiSet multiSetMapToMultiSet(MultiSetMap mm) { MultiSet ms = new MultiSet(); for (A a : keys(mm)) ms.add(a, l(mm.get(a))); return ms; } static public GZIPInputStream newGZIPInputStream(File f) { return gzInputStream(f); } static public GZIPInputStream newGZIPInputStream(InputStream in) { return gzInputStream(in); } static public A setMetaSrc(A a, Object src) { setMetaAndVerify(a, "src", src); return a; } static public A setMetaSrc(A a, Object src) { setMetaAndVerify(a, "src", src); return a; } static public int totalPreferredHeight(List l) { int h = 0; for (Component c : unnull(l)) h += c.getPreferredSize().height; return h; } static public int indexOfTabName(JTabbedPane tabs, String name) { return tabs == null ? -1 : swing(() -> tabs.indexOfTab(name)); } static public Object[] assertEvenLength(Object[] a) { assertTrue(even(l(a))); return a; } static public A packWindowVertically(A c) { final Window win = getWindow(c); if (win == null) return c; final int w = win.getWidth(); packWindow(win); { swing(() -> { win.setSize(w, win.getHeight()); }); } return c; } static public Runnable _topLevelErrorHandling(Runnable r) { if (r == null) return null; Object info = _threadInfo(); Object mod = dm_current_generic(); Runnable r2 = r; if (info != null || mod == null) r2 = new Runnable() { public void run() { try { AutoCloseable __1 = (AutoCloseable) (rcall("enter", mod)); try { _threadInheritInfo(info); r.run(); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp (AutoCloseable) rcall enter(mod);\r\n _threadInheritInfo(info);\r\n ..."; } }; r2 = rPcall(r2); return r2; } static public void setSpinnerValue(JSpinner s, int value) { setSpinnerValue(s, (Integer) value); } static public void setSpinnerValue(JSpinner s, Object value) { try { if (s != null) { swing(() -> { s.setValue(value); }); } } catch (Throwable __e) { pcallFail(__e); } } static public RasterBars reproduceRasterBars(IBWIntegralImage ii) { var thinImage = scaledBWImageFromBWIntegralImage_withMeta(ii, 1, ii.getHeight()); var streaks = streaksOfRepeatingElements(listFromFunction(thinImage.getHeight(), y -> thinImage.getInt(0, y))); return new RasterBars(ii.getWidth(), ii.getHeight(), streaks); } static public void onUpdateAndNow(JComponent c, final Object r) { onUpdate(c, r); callF(r); } static public void onUpdateAndNow(JTextComponent c, IVF1 r) { swing(() -> { if (c == null) return; onUpdate(c, r); callF(r, c.getText()); }); } static public void onUpdateAndNow(List l, Object r) { for (JComponent c : l) onUpdate(c, r); callF(r); } static public void sleepUntilSysTime(long sysTime) { sleepUntilSys(sysTime); } static public void copyStreamWithPrints(InputStream in, OutputStream out, String pat) { try { byte[] buf = new byte[65536]; int total = 0; while (true) { int n = in.read(buf); if (n <= 0) return; out.write(buf, 0, n); if ((total + n) / 100000 > total / 100000) print(pat.replace("{*}", str(roundDownTo(100000, total)))); total += n; } } catch (Exception __e) { throw rethrow(__e); } } static public 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 JRootPane getRootPane(Component c) { Component f = (Component) getPossiblyInternalFrame(c); return f instanceof RootPaneContainer ? (JRootPane) swingCall(f, "getRootPane") : null; } static public String stackTraceForThread(Thread t) { return t == null ? null : lines(t.getStackTrace()); } static public List classNames(Collection l) { return getClassNames(l); } static public List classNames(Object[] l) { return getClassNames(asList(l)); } static public void waitWhileTrue(BoolVar var) { { if (var != null) var.waitUntilFalse(); } } 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 void lock(Lock lock) { try { ping(); if (lock == null) return; try { vmBus_send("locking", lock, "thread", currentThread()); lock.lockInterruptibly(); vmBus_send("locked", lock, "thread", currentThread()); } catch (InterruptedException e) { Object reason = vm_threadInterruptionReasonsMap().get(currentThread()); print("Locking interrupted! Reason: " + strOr(reason, "Unknown")); printStackTrace(e); rethrow(e); } } catch (Exception __e) { throw rethrow(__e); } } static public void lock(Lock lock, String msg) { print("Locking: " + msg); lock(lock); } static public void lock(Lock lock, String msg, long timeout) { print("Locking: " + msg); lockOrFail(lock, timeout); } static public ReentrantLock lock() { return fairLock(); } static public JLabel jboldLabel(String text) { return makeLabelBold(jlabel(text)); } static public WeakReference weakRef(A a) { return newWeakReference(a); } static public A swingNu(final Class c, final Object... args) { return swingConstruct(c, args); } static public void swingAndWait(Runnable r) { try { if (isAWTThread()) r.run(); else { r = addThreadInfoToRunnable(r); executingSwingCode(r); EventQueue.invokeAndWait(r); } } catch (Exception __e) { throw rethrow(__e); } } static public Object swingAndWait(Object f) { if (isAWTThread()) return callF(f); else { 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 firstToLower(String s) { if (empty(s)) return s; return Character.toLowerCase(s.charAt(0)) + s.substring(1); } static public void pcallFAll_minimalExceptionHandling(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) { ping(); pcallF_minimalExceptionHandling(f, args); } } static public void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) { while (it.hasNext()) { ping(); pcallF_minimalExceptionHandling(it.next(), args); } } static public IntRange intRangeWithLen(int start, int len) { return new IntRange(start, start + len); } static public File picturesDir() { return imagesDir(); } static public File picturesDir(String sub) { return newFile(picturesDir(), sub); } static public boolean isSubtypeOf(Class a, Class b) { return a != null && b != null && b.isAssignableFrom(a); } 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 boolean emptyString(String s) { return s == null || s.length() == 0; } static public int methodApplicabilityScore_onTypes(Method m, Class[] argTypes) { return methodApplicabilityScore_onTypes((Executable) m, argTypes); } static public int methodApplicabilityScore_onTypes(Executable m, Class[] argTypes) { Class[] types = m.getParameterTypes(); if (types.length != argTypes.length) return Integer.MAX_VALUE; int score = 0; for (int i = 0; i < types.length; i++) { Class a = argTypes[i]; Class c = types[i]; if (c == a) { } else if (isSubclassOf(a, c)) ++score; else return Integer.MAX_VALUE; } return score; } static public boolean endsWithIgnoreCase(String a, String b) { int la = l(a), lb = l(b); return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb); } static public boolean endsWithIgnoreCase(String a, String b, Matches m) { if (!endsWithIgnoreCase(a, b)) return false; if (m != null) m.m = new String[] { substring(a, 0, l(a) - l(b)) }; return true; } static public JLabel jcenteredLabel(String text) { return setHorizontalAlignment(JLabel.CENTER, jLabel(text)); } static public JLabel jcenteredLabel() { return jcenteredLabel(" "); } static public JTable dataToTable(Object data) { return dataToTable(showTable(), data); } static public JTable dataToTable(Object data, String title) { return dataToTable(showTable(title), data); } static public JTable dataToTable(JTable table, Object data) { return dataToTable(table, data, false); } static public JTable dataToTable(JTable table, Object data, boolean now) { List rows = new ArrayList(); List cols = new ContentsIndexedList(); if (data instanceof List) { for (Object x : (List) data) { try { rows.add(dataToTable_makeRow(x, cols)); } catch (Throwable __e) { pcallFail(__e); } } } else if (data instanceof Map) { Map map = (Map) data; for (Object key : map.keySet()) { Object value = map.get(key); rows.add(litlist(structureOrTextForUser(key), structureOrTextForUser(value))); } } else if (data != null) print("Unknown data type: " + data); fillTableWithData(table, rows, cols); return table; } static public JCheckBoxMenuItem jCheckBoxMenuItem_dyn(String text, IF0 checked, Object r) { JCheckBoxMenuItem mi = jCheckBoxMenuItem(text, false, r); if (checked != null) bindToComponent(mi, new Runnable() { public void run() { try { boolean b = isTrue(checked.get()); setChecked(mi, b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "boolean b = isTrue(checked!);\r\n ifdef jCheckBoxMenuItem_dyn_debug\r\n p..."; } }, new Runnable() { public void run() { try { ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef jCheckBoxMenuItem_dyn_debug\r\n print(\"jCheckBoxMenuItem_dyn: hiding..."; } }); return mi; } static public JCheckBoxMenuItem jCheckBoxMenuItem_dyn(String text, IF0 checked, IVF1 r) { return jCheckBoxMenuItem_dyn(text, checked, (Object) r); } static public int listL(Collection l) { return l == null ? 0 : l.size(); } static public A packInternalFrameVertically(A c) { return packInternalFrameVertically(-1, c); } static public A packInternalFrameVertically(int width, A c) { final JInternalFrame win = getInternalFrame(c); if (win == null) return c; final int w = width < 0 ? win.getWidth() : width; { swing(() -> { win.pack(); win.setSize(w, win.getHeight()); fixInternalFrame(win); }); } return c; } static public ThreadLocal threadLocalWithDefault(A defaultValue) { return new ThreadLocal() { public A initialValue() { return defaultValue; } }; } static public boolean isAGIBlueDomain(String domain) { return domainIsUnder(domain, theAGIBlueDomain()); } static public ArrayList litlist(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } static public String assertIsIdentifier(String s) { if (!isIdentifier(s)) throw fail("Not an identifier: " + quote(s)); return s; } static public String assertIsIdentifier(String msg, String s) { if (!isIdentifier(s)) throw fail(msg + " - Not an identifier: " + quote(s)); return s; } static public 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(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(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(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) { var it = l.iterator(); if (it.hasNext()) { var pingSource = pingSource(); do { ping(pingSource); x.add(f.get(it.next())); } while (it.hasNext()); } } 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(Map map, IF2 f) { List x = new ArrayList(); if (map != null) for (Map.Entry e : map.entrySet()) { ping(); x.add(f.get(e.getKey(), e.getValue())); } return x; } 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 int indexOfFirst(List l, Object pred) { return indexOfPred(l, pred); } static public int indexOfFirst(List l, IF1 pred) { return indexOfPred(l, pred); } static public boolean ewic(String a, String b) { return endsWithIgnoreCase(a, b); } static public boolean ewic(String a, String b, Matches m) { return endsWithIgnoreCase(a, b, m); } static public void disposeWindowOnClick(final Window window) { AWTEventListener l = new AWTEventListener() { public void eventDispatched(AWTEvent evt) { if (!window.isVisible()) { Toolkit.getDefaultToolkit().removeAWTEventListener(this); return; } if (!(evt instanceof MouseEvent)) return; Object source = evt.getSource(); if (source == window && evt.getID() == MouseEvent.MOUSE_PRESSED) { Toolkit.getDefaultToolkit().removeAWTEventListener(this); window.dispose(); } } }; Toolkit.getDefaultToolkit().addAWTEventListener(l, AWTEvent.MOUSE_EVENT_MASK); } 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 > A max(Iterable l) { A max = null; var it = iterator(l); if (it.hasNext()) { max = it.next(); while (it.hasNext()) { A a = it.next(); if (cmp(a, max) > 0) max = a; } } return max; } 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 fillJMenu(final JMenu m, Object... x) { if (x == null) return; for (int i = 0; i < l(x); i++) { Object o = x[i], y = get(x, i + 1); if (o instanceof List) fillJMenu(m, asArray((List) o)); else if (isMenuSeparatorIndicator(o)) { if (menuItemCount(m) != 0) m.addSeparator(); } else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) { final LiveValue lv = (LiveValue) o; final JMenuItem mi = jmenuItem(or2(unCurlyBracket(lv.get()), "..."), y); bindLiveValueListenerToComponent(mi, lv, new Runnable() { public void run() { try { String s = lv.get(); if (isCurlyBracketed(s)) { setEnabled(mi, false); s = unCurlyBracket(s); } else setEnabled(mi, true); setText(mi, s); revalidate(m); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = lv!;\r\n if (isCurlyBracketed(s)) {\r\n setEnabled(mi,..."; } }); print("bound live value " + lv + " to menu item " + mi); m.add(mi); ++i; } else if (o instanceof String && isRunnableX(y)) { m.add(jmenuItem((String) o, y)); ++i; } else if (o instanceof JMenuItem) m.add((JMenuItem) o); else if (o instanceof String || o instanceof Action || o instanceof Component) call(m, "add", o); else if (o == null && y instanceof Runnable) ++i; else if (o != null) print("Unknown menu item: " + o); } } 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 TreeMap asCIMap(Map map) { return asCaseInsensitiveMap(map); } static public boolean startsWithDigit(String s) { return nempty(s) && isDigit(s.charAt(0)); } 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 boolean canCallWithVarargs(Object o, String method, Object... args) { if (o == null) return false; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); if (cache.findStaticMethod(method, args) != null) return true; List methods = cache.cache.get(method); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs() && isStaticMethod(m))) continue; } if (massageArgsForVarArgsCall(m, args) != null) return true; } } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); if (cache.findMethod(method, args) != null) return true; List methods = cache.cache.get(method); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } if (massageArgsForVarArgsCall(m, args) != null) return true; } } return false; } static public double nsToMicroseconds(double ns) { return nanosToMicroseconds(ns); } static public A holdResource(IResourceHolder holder, A a) { { if (holder != null) holder.add(a); } return a; } static public int[] selectedTableRows_array(final JTable table) { return table == null ? null : swing(new F0() { public int[] get() { try { return table.getSelectedRows(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return table.getSelectedRows();"; } }); } static public List listWithoutIndicesInBitSet(List l, BitSet bs) { List out = new ArrayList(); for (int i = 0; i < l(l); i++) if (!bs.get(i)) out.add(l.get(i)); return out; } static public A waitUntilVarSet(Var v) { try { synchronized (v) { while (!v.has()) v.wait(); return v.get(); } } catch (Exception __e) { throw rethrow(__e); } } static public A waitUntilVarSet(Var v, int timeout) { try { synchronized (v) { long time = nanoTime(); while (!v.has() && (nanoTime() - time) < timeout * 900000) v.wait(timeout); return v.get(); } } catch (Exception __e) { throw rethrow(__e); } } static public Throwable _storeException_value; static public void _storeException(Throwable e) { _storeException_value = e; } static public void deleteFileVerbose_assertSuccess(File file) { if (!deleteFileVerbose(file)) throw fail("Couldn't delete " + file); } static public RGBImage loadImage(String snippetIDOrURL) { return new RGBImage(loadBufferedImage(snippetIDOrURL)); } static public RGBImage loadImage(File f) { return new RGBImage(loadBufferedImage(f)); } 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 A listThreadLocalPopLast(ThreadLocal> tl) { List l = tl.get(); if (l == null) return null; A a = popLast(l); if (empty(l)) tl.set(null); return a; } 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 List nullPlus(Collection l) { return itemPlusList(null, l); } static public String singleFieldName(Class c) { Set l = listFields(c); if (l(l) != 1) throw fail("No single field found in " + c + " (have " + n(l(l), "fields") + ")"); return first(l); } static public void sort(T[] a, Comparator c) { if (a != null) Arrays.sort(a, c); } static public void sort(T[] a) { if (a != null) Arrays.sort(a); } static public void sort(int[] a) { if (a != null) Arrays.sort(a); } static public void sort(List a, Comparator c) { if (a != null) Collections.sort(a, c); } static public void sort(List a) { if (a != null) Collections.sort(a); } static public float floatRatio(float x, float y) { return y == 0 ? 0 : x / y; } static public A listGetOrCreate(List l, int i, Class c) { return listGetOrCreate(l, i, () -> nuInstance(c)); } static public A listGetOrCreate(List l, int i, IF0 f) { if (l == null) return null; A a = get(l, i); if (a == null) listSet(l, i, a = f.get()); return a; } static public A listGetOrCreate(Class c, List l, int i) { return listGetOrCreate(l, i, c); } static public int tableColumnViewIndex(final JTable t, final String colName) { return swing(new F0() { public Integer get() { try { return t.convertColumnIndexToView(t.getColumn(colName).getModelIndex()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return t.convertColumnIndexToView(t.getColumn(colName).getModelIndex());"; } }); } static public List standardImports_fullyImportedPackages() { return endingWith_dropSuffix(standardImports(), ".*"); } static public A awtEveryAndNow(A component, long delay, Object r) { swingEvery(component, delay, 0, r); return component; } static public A awtEveryAndNow(A component, long delay, Runnable r) { return awtEveryAndNow(component, delay, (Object) r); } static public A awtEveryAndNow(A component, double delaySeconds, Object r) { return awtEveryAndNow(component, toMS(delaySeconds), r); } static public A awtEveryAndNow(A component, double delaySeconds, Runnable r) { return awtEveryAndNow(component, toMS(delaySeconds), r); } static public void awtEveryAndNow(RootPaneContainer frame, long delay, Object r) { swingEvery(frame, delay, 0, r); } static public Set> entries(Map map) { return _entrySet(map); } static public void disposeInternalFrame(Component c) { final JInternalFrame f = getInternalFrame(c); if (f != null) { swing(() -> { vmBus_send("disposingInternalFrame", f); f.dispose(); }); } } static public int indexOfLine(String text, String sub) { return indexOf(lines_iterator(text), sub); } static public String jextract(String pat, String s) { return jextract(pat, javaTok(s)); } static public String jextract(String pat, List tok) { List tokpat = javaTok(pat); jfind_preprocess(tokpat); int i = jfind(tok, tokpat); if (i < 0) return null; int j = i + l(tokpat) - 2; return joinSubList(tok, i, j); } static public Map synchroMap() { return synchroHashMap(); } static public Map synchroMap(Map map) { return new SynchronizedMap(map); } static public char firstChar(String s) { return s.charAt(0); } static public boolean tableSetColumnPreferredWidths_debug = false; static public void tableSetColumnPreferredWidths(final JTable table, final Map widths) { if (table == null || widths == null) return; { swing(() -> { try { TableColumnModel tcm = table.getColumnModel(); int n = tcm.getColumnCount(); for (int i = 0; i < n; i++) { TableColumn tc = tcm.getColumn(i); Integer w = widths.get(str(tc.getHeaderValue())); if (w != null) { tc.setPreferredWidth(w); if (tableSetColumnPreferredWidths_debug) print("Setting preferred width of column " + i + " to " + w); } } } catch (Throwable __e) { pcallFail(__e); } }); } } static public void tableSetColumnPreferredWidths(JTable table, Object... widths) { tableSetColumnPreferredWidths(table, litorderedmap(widths)); } static public Object deref(Object o) { if (o instanceof IRef) return ((IRef) o).get(); return o; } static public boolean addLibraryToCurrentProgram(String libID) { return addLibraryToCurrentProgram(loadLibrary(libID)); } static public boolean addLibraryToCurrentProgram(File f) { try { if (f == null || currentProgramHasLibrary(f)) return false; ClassLoader cl = myClassLoader(); return isTrue(call(cl, "addFile", f)); } catch (Exception __e) { throw rethrow(__e); } } static public JPanel centerAndEastWithMargins(Component c, Component e) { return applyDefaultMargin(centerAndEast(c, withLeftMargin(e))); } static public void setComboBoxItems(JComboBox cb, Collection items) { if (cb != null) { swing(() -> { cb.setModel(new DefaultComboBoxModel(new Vector(items))); }); } } static public A println(A a) { return print(a); } static public Map putAll(Map a, Map b) { if (a != null && b != null) a.putAll(b); return a; } static public MultiMap putAll(MultiMap a, Map b) { if (a != null) a.putAll((Map) b); return a; } static public Map putAll(Map a, Object... b) { if (a != null) litmap_impl(a, b); return a; } static public Object[] expandParams(Class c, Object[] params) { if (l(params) == 1) params = new Object[] { singleFieldName(c), params[0] }; else warnIfOddCount(params); return params; } static public List getMenuItems(JMenu menu) { if (menu == null) return null; return nonNulls(countIterator(menu.getItemCount(), i -> menu.getItem(i))); } static public List getMenuItems(JPopupMenu menu) { if (menu == null) return null; return instancesOf(JMenuItem.class, asList(menu.getSubElements())); } static public void cMigrateField(Concept c, String oldField, String newField) { if (c == null) return; Object oldValue = cget(c, oldField); Object newValue = cget(c, newField); if (oldValue != null && newValue == null) { try { String name = shortDynName(c); print("Migrating " + name + "." + oldField + " -> " + name + "." + newField + " [id " + c.id + "]"); cset(c, newField, oldValue); cset(c, oldField, null); } catch (Throwable __e) { pcallFail(__e); } } } static public void _onJavaXSet() { } static public String dropSuffix(String suffix, String s) { return nempty(suffix) && endsWith(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } static public Map syncHashMap() { return synchroHashMap(); } static public Pt toPt(Point p) { return p == null ? null : new Pt(p.x, p.y); } static public Pt toPt(Dimension d) { return d == null ? null : new Pt(d.width, d.width); } static public A evalWithTimeoutOrTypedException(int timeoutMS, IF0 f) { return evalWithTimeoutOrTypedException(toSeconds(timeoutMS), f); } static public A evalWithTimeoutOrTypedException(double timeoutSeconds, IF0 f) { Either e = evalWithTimeout(timeoutSeconds, f); if (e.isA()) return (A) e.a(); throw new TimeoutException_Inner(timeoutSeconds, f, e.b()); } static public MultiSetMap generalizedCIMultiSetMap() { MultiSetMap mm = new MultiSetMap(); mm.data = generalizedCIMap(); return mm; } static public int scoredSearch_score_single(String s, String query) { int i = indexOfIC_underscore(s, query); if (i < 0) return 0; if (i > 0) return 1; return l(s) == l(query) ? 3 : 2; } static public Set synchroHashSet() { return synchronizedSet(new HashSet()); } static public String stringify(IStringifier stringifier, Object o) { return stringifier == null ? str(o) : stringifier.toString(o); } static public TreeMap descTreeMap() { return revTreeMap(); } static public int getMinimumHeight(final Component c) { return getMinimumSize(c).height; } static public B syncGetOrCreate(Map map, A key, Class c) { try { synchronized (map) { return getOrCreate(map, key, c); } } catch (Exception __e) { throw rethrow(__e); } } static public B syncGetOrCreate(Map map, A key, Object f) { synchronized (map) { return getOrCreate(map, key, f); } } static public B syncGetOrCreate(Class c, Map map, A key) { return syncGetOrCreate(map, key, c); } static public B syncGetOrCreate(Map map, A key, IF0 f) { synchronized (map) { return getOrCreate(map, key, f); } } static public JComponent withCenteredBoldTitle(String title, Component c) { return withTitle(jCenteredBoldLabel(title), c); } static public JScrollPane jHigherScrollPane(final JComponent c) { return swing(() -> 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; } }); } 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 JScrollPane jBorderlessHigherScrollPane(JComponent c) { return borderlessScrollPane(jHigherScrollPane(c)); } 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 focusOnFirstShowVerbose(A a) { return onFirstComponentShow(a, () -> { print("Focusing on first show: " + a); focus(a); }); } static public B syncMapGetOrCreate(Map map, A key, Class c) { return syncGetOrCreate(map, key, c); } static public B syncMapGetOrCreate(Map map, A key, Object f) { return syncGetOrCreate(map, key, f); } static public B syncMapGetOrCreate(Class c, Map map, A key) { return syncGetOrCreate(c, map, key); } static public B syncMapGetOrCreate(Map map, A key, IF0 f) { return syncGetOrCreate(map, key, f); } static public JComponent withCenteredTitle(String title, Component c) { return withTitle(jCenteredLabel(title), c); } static public List syncListGetMulti(final List l, List indices) { synchronized (collectionMutex(l)) { return listGetMulti(l, indices); } } static public boolean removeAll(Collection a, Collection b) { return a != null && b != null && a.removeAll(b); } static public void removeAll(Map a, Collection b) { if (a != null && b != null) for (A x : b) a.remove(x); } static public boolean removeAll(Collection c, B... b) { return c != null && b != null && c.removeAll(Arrays.asList(b)); } static public void removeAll(Map a, A... b) { if (a != null && b != null) for (A x : b) a.remove(x); } static public String yesNo2(Boolean b) { return eq(b, true) ? "Yes" : eq(b, false) ? "No" : "Unknown"; } static public Dimension getMinimumSize(final Component c) { return c == null ? null : swing(new F0() { public Dimension get() { try { return c.getMinimumSize(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getMinimumSize();"; } }); } static public boolean isURL(String s) { return startsWithOneOf(s, "http://", "https://", "file:"); } static public void assertNotOnAWTThread() { assertFalse("Can't do this in AWT thread", isAWTThread()); } static public IterableIterator countIterator_inclusive_backwards(int a, int b) { return new IterableIterator() { public int i = a; public boolean hasNext() { return i >= b; } public Integer next() { return i--; } }; } static public IterableIterator countIterator_inclusive_backwards(int a, int b, IF1 f) { return mapI_if1(f, countIterator_inclusive_backwards(a, b)); } 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 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 Pt longToPt(long l) { return new Pt(firstIntFromLong(l), secondIntFromLong(l)); } static public JMenuItem disableMenuItem(final JMenuItem mi) { if (mi != null) { swing(() -> { mi.setEnabled(false); }); } return mi; } static public Object swingCall(final Object o, final String method, final Object... args) { return swing(new F0() { public Object get() { try { return call(o, method, args); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return call(o, method, args);"; } }); } static public Throwable getException(Runnable r) { try { callF(r); return null; } catch (Throwable e) { return e; } } 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 strOrNull(cb.getSelectedItem()); } static public Pt mouseLocationPt() { return mousePointer(); } static public > IterableIterator> outerProduct(List lists) { return outerProduct_faster(lists); } static public List pairsB(Collection> l) { return secondOfPairs(l); } static public List toLinesFullTrim(String s) { List l = new ArrayList(); for (String line : toLines(s)) if (nempty(line = trim(line))) l.add(line); return l; } static public List toLinesFullTrim(File f) { List l = new ArrayList(); for (String line : linesFromFile(f)) if (nempty(line = trim(line))) l.add(line); return l; } static public BufferedImage resizeImage(BufferedImage img, int newW, int newH) { return resizeImage(img, newW, newH, Image.SCALE_SMOOTH); } static public BufferedImage resizeImage(BufferedImage img, int newW, int newH, int scaleType) { if (newW == img.getWidth() && newH == img.getHeight()) return img; Image tmp = img.getScaledInstance(newW, newH, scaleType); BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = dimg.createGraphics(); g2d.drawImage(tmp, 0, 0, null); g2d.dispose(); return dimg; } static public BufferedImage resizeImage(BufferedImage img, int newW) { int newH = iround(img.getHeight() * (double) newW / img.getWidth()); return resizeImage(img, newW, newH); } static public BufferedImage resizeImage(int newW, BufferedImage img) { return resizeImage(img, newW); } static public MouseAdapter onMouseDown_anyButton(Component c, Runnable r) { return onMouseDown(c, runnableToIVF1(r)); } static public MouseAdapter onMouseDown_anyButton(Component c, IVF1 f) { return c == null || f == null ? null : swing(() -> { MouseAdapter ma = new MouseAdapter() { public void mousePressed(MouseEvent e) { f.get(e); } }; c.addMouseListener(ma); return ma; }); } static public TreeMap generalizedCIMap() { return new TreeMap(generalizedCIComparator()); } static volatile public String caseID_caseID; static public String caseID() { return caseID_caseID; } static public void caseID(String id) { caseID_caseID = id; } static public int dualLog(int i) { return 32 - Integer.numberOfLeadingZeros(max(0, i - 1)); } static public ThreadLocal customRandomizerForThisThread_tl = new ThreadLocal(); static public ThreadLocal customRandomizerForThisThread_tl() { return customRandomizerForThisThread_tl; } static public int incAtomicInt(AtomicInteger i) { return i.incrementAndGet(); } static public int incAtomicInt(AtomicInteger i, int delta) { return i.addAndGet(delta); } static public Thread newThread(Object runnable) { return new BetterThread(_topLevelErrorHandling(toRunnable(runnable))); } static public Thread newThread(Object runnable, String name) { if (name == null) name = defaultThreadName(); return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)), name); } static public Thread newThread(String name, Object runnable) { return newThread(runnable, name); } static public 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 boolean nemptyString(String s) { return s != null && s.length() > 0; } static public JTable onDoubleClickOrEnter(JTable table, Runnable runnable) { return onDoubleClickOrEnter(table, (Object) runnable); } static public JTable onDoubleClickOrEnter(final JTable table, Object runnable) { onDoubleClick(table, runnable); onEnter(table, runnable); return table; } static public JList onDoubleClickOrEnter(final JList list, final Object runnable) { onDoubleClick(list, runnable); onEnter(list, runnable); return list; } static public JTable onDoubleClickOrEnter(Object runnable, JTable table) { return onDoubleClickOrEnter(table, runnable); } static public TreeMap asCaseInsensitiveMap(Map map) { if (isCIMap(map)) return (TreeMap) map; TreeMap m = ciMap(); putAll(m, map); return m; } static public JList onDoubleClick(final JList list, final Object runnable) { { swing(() -> { list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { int idx = list.locationToIndex(evt.getPoint()); Object item = list.getModel().getElementAt(idx); list.setSelectedIndex(idx); callF(runnable, item); } } }); }); } return list; } static public JTable onDoubleClick(final JTable table, final Object runnable) { { swing(() -> { table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { int idx = table.rowAtPoint(evt.getPoint()); table.setRowSelectionInterval(idx, idx); callF(runnable, idx); } } }); }); } return table; } static public void onDoubleClick(final JComponent c, final Object runnable) { { swing(() -> { c.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getButton() == 1 && evt.getClickCount() == 2) callF(runnable, evt.getPoint()); } }); }); } } static public LookAndFeel currentLAF() { return UIManager.getLookAndFeel(); } static public void addWeakChangeListener(IHasChangeListeners src, ChangeTriggerable target) { addWeakChangeListener(src, target, o -> o.change()); } static public void addWeakChangeListener(IHasChangeListeners src, A target, IVF1 action) { if (src == null || action == null || target == null) return; var ref = weakRef(target); src.onChange(new Runnable() { public void run() { try { var target = ref.get(); if (target == null) src.removeChangeListener(this); else action.get(target); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var target = ref!;\r\n if (target == null)\r\n src.removeChangeListener(t..."; } }); } static public String lines_possiblyRTrim(String originalText, List lines) { return endsWithNewLine(originalText) ? lines(lines) : lines_rtrim(lines); } static public String lines_possiblyRTrim(List lines, String originalText) { return lines_possiblyRTrim(originalText, lines); } static public void hideTrayIcon(TrayIcon t) { removeTrayIcon(t); } 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 > A min(A a, A b) { return cmp(a, b) <= 0 ? a : b; } static public String fileExtension(File f) { if (f == null) return null; return fileExtension(f.getName()); } static public String fileExtension(String s) { return substring(s, smartLastIndexOf(s, '.')); } static public void arraycopy(Object[] a, Object[] b) { if (a != null && b != null) arraycopy(a, 0, b, 0, Math.min(a.length, b.length)); } static public void arraycopy(Object src, int srcPos, int destPos, int n) { arraycopy(src, srcPos, src, destPos, n); } static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) { if (n != 0) System.arraycopy(src, srcPos, dest, destPos, n); } static public int numberOfScreens() { return screenCount(); } static public int showForm_defaultGap = 4; static public int showForm_gapBetweenColumns = 10; static public JPanel showFormTitled(final String title, final Object... _parts) { JDesktopPane desktop = mainDesktopPane(); if (desktop != null) return showInternalFrameFormTitled(desktop, title, _parts); return swing(() -> { JPanel panel = showForm_makePanel(false, _parts); showForm_makeFrame(title, panel); return panel; }); } static public JPanel showForm_makePanel(Boolean internalFrame, Object... _parts) { List out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts)); return vstackWithSpacing(out, showForm_defaultGap); } static public List standardImports_cache; static public List standardImports() { if (standardImports_cache == null) standardImports_cache = standardImports_load(); return standardImports_cache; } static public List standardImports_load() { return ll("java.util.*", "java.util.zip.*", "java.util.List", "java.util.regex.*", "java.util.concurrent.*", "java.util.concurrent.atomic.*", "java.util.concurrent.locks.*", "java.util.function.*", "javax.swing.*", "javax.swing.event.*", "javax.swing.text.*", "javax.swing.table.*", "java.io.*", "java.net.*", "java.lang.reflect.*", "java.lang.ref.*", "java.lang.management.*", "java.security.*", "java.security.spec.*", "java.awt.*", "java.awt.event.*", "java.awt.image.*", "java.awt.geom.*", "javax.imageio.*", "java.math.*", "java.time.Duration", "java.lang.invoke.VarHandle", "java.lang.invoke.MethodHandles"); } static public String currentProcessCommand() { ProcessHandle processHandle = ProcessHandle.current(); return getVar(processHandle.info().command()); } static public class mapI_It extends IterableIterator { public Object f; public Iterator i; public mapI_It() { } public mapI_It(Object f, Iterator i) { this.i = i; this.f = f; } public boolean hasNext() { return i.hasNext(); } public Object next() { return callF(f, i.next()); } public String toString() { return formatFunctionCall("mapI", f, i); } } static public IterableIterator mapI(final Object f, final Iterator i) { return new mapI_It(f, i); } static public IterableIterator mapI(IterableIterator i, Object f) { return mapI((Iterator) i, f); } static public IterableIterator mapI(Object f, IterableIterator i) { return mapI((Iterator) i, f); } static public IterableIterator mapI(Iterator i, Object f) { return mapI(f, i); } static public IterableIterator mapI(Iterable i, IF1 f) { return new MapI(f, iterator(i)); } static public IterableIterator mapI(Iterator i, IF1 f) { return new MapI(f, i); } static public IterableIterator mapI(IterableIterator i, IF1 f) { return new MapI(f, i); } static public IterableIterator mapI(IF1 f, Iterable i) { return new MapI(f, iterator(i)); } static public IterableIterator mapI(Iterable i, Object f) { return mapI(f, i.iterator()); } static public IterableIterator mapI(Object f, Iterable i) { return mapI(i, f); } static public A addAndReturn(Collection c, A a) { if (c != null) c.add(a); return a; } static public A addAndReturn(List c, int idx, A a) { if (c != null) c.add(idx, a); return a; } static public boolean dirExists(String path) { return path != null && new File(path).isDirectory(); } static public boolean dirExists(File f) { return f != null && f.isDirectory(); } static public String hostNameFromURL(String url) { try { return empty(url) ? null : new URL(url).getHost(); } catch (Exception __e) { throw rethrow(__e); } } static public String mainClassNameForClassLoader(ClassLoader cl) { return or((String) callOpt(cl, "mainClassName"), "main"); } static public Map cloneMap(Map map) { if (map == null) return new HashMap(); synchronized (map) { return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map); } } static public List cloneMap(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : cloneList(l)) x.add(f.get(o)); return x; } static public List collectField(Iterable c, String field) { List l = new ArrayList(); if (c != null) for (Object a : c) l.add(getOpt(a, field)); return l; } static public List collectField(String field, Iterable c) { return collectField(c, field); } static public JSpinner rightAlignSpinner(JSpinner spinner) { setHorizontalAlignment(JTextField.RIGHT, getTextFieldFromSpinner(spinner)); return spinner; } static public boolean domainIsUnder(String domain, String mainDomain) { return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain); } static public int selectedTableRowInModel(final JTable t) { return t == null ? -1 : swing(new F0() { public Integer get() { try { int i = t.getSelectedRow(); return i < 0 ? i : t.convertRowIndexToModel(i); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "int i = t.getSelectedRow();\r\n ret i < 0 ? i : t.convertRowIndexToModel(i);"; } }); } static public double scaleToFitInside(BufferedImage image, Component c) { return scaleToFitInside(image, c.getWidth(), c.getHeight()); } static public double scaleToFitInside(BufferedImage image, int w) { return scaleToFitInside(image, w, w); } static public double scaleToFitInside(BufferedImage image, int w, int h) { int iw = image.getWidth(), ih = image.getHeight(); return min(doubleRatio(h, ih), doubleRatio(w, iw)); } static public File getGlobalCache() { File file = new File(javaxCachesDir(), "Binary Snippets"); file.mkdirs(); return file; } static public JProgressBar jProgressBarWithText() { return swing(() -> { JProgressBar bar = new JProgressBar(); bar.setStringPainted(true); return bar; }); } static public JProgressBar jProgressBarWithText(int maxValue) { JProgressBar bar = jProgressBarWithText(); { swing(() -> { bar.setMaximum(maxValue); }); } return bar; } static public JProgressBar jProgressBarWithText(int maxValue, String text) { var bar = jProgressBarWithText(maxValue); { swing(() -> { bar.setString(text); }); } return bar; } static public JProgressBar jProgressBarWithText(String text) { var bar = jProgressBarWithText(); { swing(() -> { bar.setString(text); }); } return bar; } static public File byteCodePathForClass(Class c) { if (c == null) return null; ClassLoader cl = getClassLoader(c); Collection files = (Collection) (getOpt(cl, "files")); if (files != null) { String name = c.getName().replace('.', '/') + ".class"; for (File location : files) if (dirOrZipContainsPath(location, name)) return location; throw fail(name + " not found in: " + files); } return null; } static public File byteCodePathForClass(Object o) { return byteCodePathForClass(_getClass(o)); } static public A fontSizePlus(final int delta, final A c) { if (c != null) { swing(() -> { Font font = c.getFont(); c.setFont(font.deriveFont(font.getSize2D() + delta)); }); } return c; } static public JLabel jCenteredLabel(String text) { return jcenteredLabel(text); } static public JLabel jCenteredLabel() { return jcenteredLabel(); } static public void renameFileVerbose_assertSuccess(File a, File b) { if (!renameFileVerbose(a, b)) throw fail("Couldn't rename " + a + " to " + b); } static public IMeta initMetaOfJComponent(JComponent c) { if (c == null) return null; IMeta meta = (IMeta) (c.getClientProperty(IMeta.class)); if (meta == null) c.putClientProperty(IMeta.class, meta = new Meta()); return meta; } static public String formatSnippetID(String id) { return "#" + parseSnippetID(id); } static public String formatSnippetID(long id) { return "#" + id; } static public boolean isScreenCoordinateInWindow(Pt p, Component c) { Window w = getWindow(c); return w != null && w.isShowing() && toRect(boundsOnScreen(w)).contains(p); } static public CloseableIterableIterator linesFromFile(File f) { return linesFromFile(f, null); } static public CloseableIterableIterator linesFromFile(File f, IResourceHolder resourceHolder) { try { if (!fileExists(f)) return emptyCloseableIterableIterator(); if (ewic(f.getName(), ".gz")) return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)), resourceHolder); return linesFromReader(utf8bufferedReader(f), resourceHolder); } catch (Exception __e) { throw rethrow(__e); } } static public CloseableIterableIterator linesFromFile(String path) { return linesFromFile(path, null); } static public CloseableIterableIterator linesFromFile(String path, IResourceHolder resourceHolder) { return linesFromFile(newFile(path), resourceHolder); } static public String snippetImageURL(long snippetID) { return snippetImageURL(fsI(snippetID)); } static public String snippetImageURL(String snippetID) { return snippetImageURL(snippetID, "png"); } static public String snippetImageURL(String snippetID, String contentType) { if (snippetID == null || isURL(snippetID)) return snippetID; long id = parseSnippetID(snippetID); String url; if (isImageServerSnippet(id)) url = imageServerLink(id); else url = "https://botcompany.de/img/" + id; return url; } static public List flattenToList(Object... l) { Flattener f = new Flattener(); f.add(l); return f.toList(); } static public List itemPlusList(A a, Collection l) { return concatLists(ll(a), l); } static public A revalidate(final A c) { if (c == null || !c.isShowing()) return c; { swing(() -> { c.revalidate(); c.repaint(); }); } return c; } static public void revalidate(JFrame f) { revalidate((Component) f); } static public void revalidate(JInternalFrame f) { revalidate((Component) f); } static public List stringAsCharacterList(final String s) { if (s == null) return null; return new RandomAccessAbstractList() { final public int l = l(s); public int size() { return l; } public Character get(int i) { return s.charAt(i); } }; } static public A unlisted(Class c, Object... args) { concepts_unlisted.set(true); try { return nuObject(c, args); } finally { concepts_unlisted.set(null); } } static public Concept unlisted(String name, Object... args) { Class cc = findClass(name); concepts_unlisted.set(true); try { return cc != null ? nuObject(cc) : new Concept(name); } finally { concepts_unlisted.set(null); } } static public Timestamp tsNowPlusMS(long ms) { return tsNow().plus(msToSeconds(ms)); } static public Timestamp tsNowPlusMS(double ms) { return tsNow().plus(msToSeconds(ms)); } static public GlobalID aGlobalIDObj() { return asGlobalID(randomID(16)); } static public GlobalID aGlobalIDObj(Random random) { return asGlobalID(randomID(random, 16)); } static public void replaceLast(List l, A a) { replaceLastElement(l, a); } static public JButton jbuttonWithDisable(String name, Runnable action) { return jbutton(name, disableButtonWhileCalcing3(action)); } static public int stdHash(Object a, String... fields) { if (a == null) return 0; int hash = getClassName(a).hashCode(); for (String field : fields) hash = boostHashCombine(hash, hashCode(getOpt(a, field))); return hash; } static public Map compileRegexp_cache = syncMRUCache(10); static public java.util.regex.Pattern compileRegexp(String pat) { java.util.regex.Pattern p = compileRegexp_cache.get(pat); if (p == null) { compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat)); } return p; } static public List immutableEmptyList() { return Collections.emptyList(); } static public Charset utf8charset_cache; static public Charset utf8charset() { if (utf8charset_cache == null) utf8charset_cache = utf8charset_load(); return utf8charset_cache; } static public Charset utf8charset_load() { return Charset.forName("UTF-8"); } static public Set evalWithTimeout_inTime = synchroSet(); static public Set evalWithTimeout_allThreads = newWeakHashSet(); static public ThreadLocal evalWithTimeout_threadName = new ThreadLocal(); static public Either evalWithTimeout(double timeoutSeconds, IF0 r) { return (Either) evalWithTimeout(timeoutSeconds, (Object) r); } static public Either evalWithTimeout(int timeoutMS, Object r) { return evalWithTimeout(toSeconds(timeoutMS), r); } static public Either evalWithTimeout(double timeoutSeconds, Object r) { final Flag done = new Flag(); final Flag doneWaiting = new Flag(); final Var var = new Var(); final Var error = new Var(); var printer = print_byThread().get(); Thread t = newThread(getAndClearThreadLocal(evalWithTimeout_threadName), new Runnable() { public void run() { try { try { AutoCloseable __1 = tempSetTL(print_byThread(), printer); try { try { var.set(callF(r)); } finally { evalWithTimeout_allThreads.remove(currentThread()); } } finally { _close(__1); } } catch (Throwable e) { error.set(e); if (doneWaiting.isUp()) printStackTrace_inPossiblyCancelledThread(e); } finally { done.raise(); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n temp tempSetTL(print_byThread(), printer);\r\n \r\n try {\r..."; } }); beforeDelegatingToThread(t); try { startThread(t); evalWithTimeout_inTime.add(t); evalWithTimeout_allThreads.add(t); try { done.waitUntilUp(timeoutSeconds); doneWaiting.raise(); } finally { evalWithTimeout_inTime.remove(t); } if (!done.isUp()) { print("Cancelling thread (timeout)"); cancelAndInterruptThread(t); return either2(t); } if (error.get() != null) rethrow(error.get()); return either1(var.get()); } finally { afterDelegatingToThread(t); } } static public ReentrantLock fairLock() { return new ReentrantLock(true); } static public IConceptIndex simpleConceptIndex(final Runnable r) { return new IConceptIndex() { public void update(Concept c) { pcallF(r); } public void remove(Concept c) { pcallF(r); } }; } static public A[] arrayOfType(Class type, int n) { return makeArray(type, n); } static public A[] arrayOfType(int n, Class type) { return arrayOfType(type, n); } static public void setComponent(SingleComponentPanel scp, Component c) { setSCPComponent(scp, c); } static public void setComponent(SingleComponentPanel scp, IF0 c) { if (scp != null) setComponent(scp, callF(c)); } static public MenuItem menuItem(String text, final Object r) { MenuItem mi = new MenuItem(text); mi.addActionListener(actionListener(r)); return mi; } static public MenuItem menuItem(String text, Runnable r) { MenuItem mi = new MenuItem(text); mi.addActionListener(actionListener(r)); return mi; } static public B mapPutOrRemove(Map map, A key, B value) { if (map != null && key != null) if (value != null) return map.put(key, value); else return map.remove(key); return null; } static public SimpleLiveValue varWithNotifyToLiveValue(Class type, IVarWithNotify var) { if (var == null) return null; var lv = new SimpleLiveValue(type); var lvRef = weakRef(lv); var.onChange(new Runnable() { public void run() { try { var lv = lvRef.get(); if (lv == null) var.removeChangeListener(this); else { var value = var.get(); lv.set(value); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var lv = lvRef!;\r\n print ifdef varWithNotifyToLiveValue_debug(\"varWithNoti..."; } }); lv.onChange(() -> var.set(lv.get())); lv.set(var.get()); return lv; } static public Comparator reverseComparator(Comparator c) { return (a, b) -> c.compare(b, a); } static public Comparator reverseComparator() { return (a, b) -> cmp(b, a); } static public void copyStream(InputStream in, OutputStream out) { try { byte[] buf = new byte[65536]; while (true) { int n = in.read(buf); if (n <= 0) return; out.write(buf, 0, n); } } catch (Exception __e) { throw rethrow(__e); } } static public 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 IterableIterator> multiMapPairIterator(MultiMap mm) { return nestedIterator(iterator(keys(mm.data)), key -> (IterableIterator>) mapI(iterator(mm.data.get(key)), val -> pair(key, val))); } static public List classNamesInJigsawModule(String moduleName) { return classNamesInJigsawModule(moduleName, javaHome()); } static public List classNamesInJigsawModule(String moduleName, File javaHome) { return classNamesInJarOrDir(jigsawModuleFile(moduleName, javaHome), "classes/"); } static public short[] emptyShortArray = new short[0]; static public short[] emptyShortArray() { return emptyShortArray; } static public JDesktopPane mainDesktopPane_value; static public JDesktopPane mainDesktopPane() { return mainDesktopPane_value; } static public boolean argumentCompatibleWithType(Object arg, Class type) { return arg == null ? !type.isPrimitive() : isInstanceX(type, arg); } static public void tableDependButtons(JTable table, List buttons) { for (Component c : buttons) if (c instanceof JButton) { JButton b = (JButton) c; onTableSelectionChangedAndNow(table, () -> b.setEnabled(table.getSelectedRow() >= 0)); } } static public File DiskSnippetCache_file(long snippetID) { return new File(getGlobalCache(), "data_" + snippetID + ".jar"); } public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException { File file = DiskSnippetCache_file(snippetID); return file.exists() ? file : null; } public static File DiskSnippetCache_getLibrary(String snippetID) { try { return DiskSnippetCache_getLibrary(psI(snippetID)); } catch (Exception __e) { throw rethrow(__e); } } public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { saveBinaryFile(DiskSnippetCache_file(snippetID), data); } static public byte[] loadDataSnippetImpl(String snippetID) throws IOException { byte[] data; try { URL url = new URL(dataSnippetLink(snippetID)); print("Loading library: " + hideCredentials(url)); try { data = loadBinaryPage(url.openConnection()); } catch (RuntimeException e) { data = null; } if (data == null || data.length == 0) { url = new URL(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID)); print("Loading library: " + hideCredentials(url)); data = loadBinaryPage(url.openConnection()); } print("Bytes loaded: " + data.length); } catch (FileNotFoundException e) { throw new IOException("Binary snippet #" + snippetID + " not found or not public"); } return data; } static public ZipFile zipFile(File f) { return openZipFile(f); } static public int iteratorCount_int_close(Iterator i) { try { int n = 0; if (i != null) while (i.hasNext()) { i.next(); ++n; } if (i instanceof AutoCloseable) ((AutoCloseable) i).close(); return n; } catch (Exception __e) { throw rethrow(__e); } } static public JButton tableDependentButton(JTable tbl, String text) { return tableDependentButton(tbl, text, null); } static public JButton tableDependentButton(JTable tbl, String text, Runnable action) { return tableDependButton(tbl, jbutton(text, action)); } static public String strOrNull(Object o) { return o == null ? null : str(o); } static public JComponent unwrapScrollPane(JScrollPane sp) { return sp == null ? null : (JComponent) sp.getViewport().getView(); } static public JComboBox jLiveValueComboBox(Collection values, IVarWithNotify lv) { final JComboBox cb = jComboBox(values); bindComboBoxToLiveValue(cb, lv); return cb; } static public JComboBox jLiveValueComboBox(IVarWithNotify lv, Collection values) { return jLiveValueComboBox(values, lv); } static public int packFrame_minw = 150, packFrame_minh = 50; static public A packFrame(final A c) { { swing(() -> { Window w = getWindow(c); if (w != null) { w.pack(); int maxW = getScreenWidth() - 50, maxH = getScreenHeight() - 50; w.setSize(min(maxW, max(w.getWidth(), packFrame_minw)), min(maxH, max(w.getHeight(), packFrame_minh))); } }); } return c; } static public JFrame packFrame(ButtonGroup g) { return packFrame(getFrame(g)); } static public String defaultThreadName_name; static public String defaultThreadName() { if (defaultThreadName_name == null) defaultThreadName_name = "A thread by " + programID(); return defaultThreadName_name; } static public int smartLastIndexOf(String s, char c) { if (s == null) return 0; int i = s.lastIndexOf(c); return i >= 0 ? i : l(s); } static public int smartLastIndexOf(List l, A sub) { int i = lastIndexOf(l, sub); return i < 0 ? l(l) : i; } static public List concatMap(Object f, Iterable l) { return concatLists(map(f, l)); } static public List concatMap(Iterable l, Object f) { return concatMap(f, l); } static public List concatMap(Object f, Object[] l) { return concatLists(map(f, l)); } static public List concatMap(Object[] l, Object f) { return concatMap(f, l); } static public > List concatMap(Iterable l, IF1 f) { return concatMap(l, (Object) f); } static public > List concatMap(IF1 f, Iterable l) { return concatMap(l, f); } static public > List concatMap(IF1 f, A[] l) { return concatMap((Object) f, l); } static public String printLog() { return getPrintLog(); } static public String shortenClassName(String name) { if (name == null) return null; int i = lastIndexOf(name, "$"); if (i < 0) i = lastIndexOf(name, "."); return i < 0 ? name : substring(name, i + 1); } static public List listGetMulti(final List l, List indices) { return map(indices, new F1() { public A get(Integer i) { try { return _get(l, i); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_get(l, i)"; } }); } static public int firstIntFromLong(long l) { return (int) (l >> 32); } static public IntRange intRangeWithLength(int start, int len) { return intRangeWithLen(start, len); } 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 DoubleRect doubleRect(double w, double h) { return new DoubleRect(0, 0, w, h); } static public DoubleRect doubleRect(double x, double y, double w, double h) { return new DoubleRect(x, y, w, h); } static public String joinNemptiesWithComma(Object... strings) { return joinNempties(", ", strings); } static public String joinNemptiesWithComma(Iterable strings) { return joinNempties(", ", strings); } static public Map paramsToMap(Object... params) { int n = l(params); if (l(params) == 1 && params[0] instanceof Map) return (Map) params[0]; LinkedHashMap map = new LinkedHashMap(); for (int i = 0; i + 1 < n; i += 2) mapPut(map, params[i], params[i + 1]); return map; } static public File copyFile(File src, File dest) { try { FileInputStream inputStream = new FileInputStream(src.getPath()); FileOutputStream outputStream = newFileOutputStream(dest.getPath()); try { copyStream(inputStream, outputStream); inputStream.close(); } finally { outputStream.close(); } return dest; } catch (Exception __e) { throw rethrow(__e); } } static public double g22_squareness(Rect r) { return doubleRatio(min(r.w, r.h), max(r.w, r.h)); } 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 void addDirectMenuItem(JMenuBar mb, String text, Object action) { if (mb != null) { swing(() -> { addDirectMenuItem(mb, directJMenuItem(text, action)); }); } } static public void addDirectMenuItem(Component c, String text, Object action) { addDirectMenuItem(addMenuBar(c), text, action); } static public void addDirectMenuItem(JMenuBar mb, JMenuItem menuItem) { if (mb != null) { swing(() -> { mb.add(menuItem); revalidate(mb); }); } } static public Map antiFilterKeys(Map map, Object f) { Map m2 = similarEmptyMap(map); for (A a : keys(map)) { if (!isTrue(callF(f, a))) m2.put(a, map.get(a)); } return m2; } static public Map antiFilterKeys(Object f, Map map) { return antiFilterKeys(map, f); } static public Map antiFilterKeys(IF1 f, Map map) { Map m2 = similarEmptyMap(map); for (A a : keys(map)) { if (!f.get(a)) m2.put(a, map.get(a)); } return m2; } static public String _userHome; static public String userHome() { if (_userHome == null) return actualUserHome(); return _userHome; } static public File userHome(String path) { return new File(userDir(), path); } static public int cmpAlphaNum(String a, String b) { return alphaNumComparator().compare(a, b); } static public List fromSimplyLinkedList(SimplyLinkedList sll) { List l = new ArrayList(); while (sll != null) { l.add(sll.head); sll = sll.tail; } return l; } static public Rect toRect_round(DoubleRect r) { if (r == null) return null; int x = iround(r.x), y = iround(r.y); return new Rect(x, y, iround(r.x2()) - x, iround(r.y2()) - y); } static public int indexOfIgnoreCase_manual(String a, String b) { return indexOfIgnoreCase_manual(a, b, 0); } static public int indexOfIgnoreCase_manual(String a, String b, int i) { int la = strL(a), lb = strL(b); if (la < lb) return -1; int n = la - lb; loop: for (; i <= n; i++) { for (int j = 0; j < lb; j++) { char c1 = a.charAt(i + j), c2 = b.charAt(j); if (!eqic(c1, c2)) continue loop; } return i; } return -1; } static public String join_flex(List glues, Iterable strings) { if (strings == null) return ""; StringBuilder buf = new StringBuilder(); Iterator i = strings.iterator(); Iterator iGlues = glues.iterator(); if (i.hasNext()) { buf.append(i.next()); while (i.hasNext()) buf.append(iGlues.next()).append(i.next()); } return buf.toString(); } static public String repSpace(int n) { return spaces(n); } static public double toM_double(long l) { return l / (1024 * 1024.0); } static public String shortDynName(Object o) { return shortDynamicClassName(o); } static public File getProgramDir() { return programDir(); } static public File getProgramDir(String snippetID) { return programDir(snippetID); } static public Map mapWithSingleValue(Iterable l, B b) { HashMap map = new HashMap(); if (l != null) for (A a : l) map.put(a, b); return map; } 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 Set> _entrySet(Map map) { return map == null ? Collections.EMPTY_SET : map.entrySet(); } static public Pair transpileOnServer(String snippetID) { return transpileOnServer(snippetID, "quick"); } static public Pair transpileOnServer(long snippetID) { return transpileOnServer(fsI(snippetID)); } static public Pair transpileOnServer(long snippetID, String mode) { return transpileOnServer(fsI(snippetID), mode); } static public Pair transpileOnServer(String snippetID, String mode) { try { print("Transpiling " + formatSnippetID(snippetID)); String url = tb_mainServer() + "/tb/transpile.php"; String modeStr = "&quick=1"; if (eq(mode, "medium")) modeStr += "&medium=1"; if (eq(mode, "fresh")) modeStr += "&fresh=1"; String query = "id=" + parseSnippetID(snippetID) + modeStr + standardCredentials(); String result = loadPage(url + "?" + query); print(result); Matcher m = regexp("URL=/(dexcompile\\.php.*?)'", result); if (!m.find()) return pair(false, result); url = tb_mainServer() + "/" + m.group(1) + standardCredentials(); result = loadPage(url); boolean ok = result.contains("SUCCESS"); return pair(ok, result); } catch (Exception __e) { throw rethrow(__e); } } static public class ListFromFunction extends RandomAccessAbstractList implements IFieldsToList { public int n; public IF1 f; public ListFromFunction() { } public ListFromFunction(int n, IF1 f) { this.f = f; this.n = n; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + n + ", " + f + ")"; } public Object[] _fieldsToList() { return new Object[] { n, f }; } public int size() { return n; } public A get(int i) { return f.get(i); } } static public List listFromFunction(int n, IF1 f) { return new ListFromFunction(n, f); } static public List listFromFunction(IF1 f, int n) { return new ListFromFunction(n, f); } 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 int absDiff(int a, int b) { return abs(a - b); } static public long absDiff(long a, long b) { return abs(a - b); } static public float absDiff(float a, float b) { return abs(a - b); } static public double absDiff(double a, double b) { return abs(a - b); } 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 Double first(double[] 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 first(IMultiSet a) { return a == null ? null : first(a.keySet()); } static public String nlLogic_text(Exp e) { return e == null ? null : e.text(); } static public String nlLogic_text(IfThen r) { return r == null ? null : r.text(); } static public LinkedHashMap litorderedmap(Object... x) { LinkedHashMap map = new LinkedHashMap(); litmap_impl(map, x); return map; } static public boolean networkAllowanceTest(String url) { return isAllowed("networkAllowanceTest", url); } static public void pnlQuoted(Collection l) { pnl(quoteAll(l)); } static public List allChildren(Component c) { return childrenOfType(c, Component.class); } static public A shallowClone(A o) { return (A) shallowClone_impl(o); } static public A shallowClone(A o, A emptyClone) { return copyFields(o, emptyClone); } static public Object shallowClone_impl(Object o) { if (o == null) return o; if (o instanceof List) return cloneList((List) o); if (o instanceof Map) return cloneMap((Map) o); if (o instanceof String || o instanceof Number || o instanceof Boolean) return o; if (o instanceof Object[]) { Object[] l = (Object[]) o; return l.clone(); } Object clone; if (o instanceof IMakeEmptyClone) clone = ((IMakeEmptyClone) o).makeEmptyClone(); else clone = nuEmptyObject(o.getClass()); copyFields(o, clone); return clone; } static public Map runnableThreadsWithRenderedStackTraces_withoutSystemThreads() { return mapValues(__97 -> stackTraceToString(__97), runnableThreadsWithStackTraces_withoutSystemThreads()); } static public A setMetaSrcUnlessSame(Object b, A a, Object src) { if (a != b) setMeta(a, "src", src); return a; } static public JComponent unwrap(JComponent c) { return c instanceof JScrollPane ? unwrapScrollPane((JScrollPane) c) : c; } 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 File oneOfTheFiles(String... paths) { if (paths != null) for (String path : paths) if (fileExists(path)) return newFile(path); return null; } static public File oneOfTheFiles(File... files) { return oneOfTheFiles(asList(files)); } static public File oneOfTheFiles(Iterable files) { if (files != null) for (File f : files) if (fileExists(f)) return f; return null; } static public 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 boolean isInstanceX(Class type, Object arg) { if (type == boolean.class) return arg instanceof Boolean; if (type == int.class) return arg instanceof Integer; if (type == long.class) return arg instanceof Long; if (type == float.class) return arg instanceof Float; if (type == short.class) return arg instanceof Short; if (type == char.class) return arg instanceof Character; if (type == byte.class) return arg instanceof Byte; if (type == double.class) return arg instanceof Double; return type.isInstance(arg); } static public Map objectToMap(Object o) { try { if (o instanceof Map) return (Map) o; if (o == null) return null; TreeMap map = new TreeMap(); Class c = o.getClass(); while (c != Object.class) { Field[] fields = c.getDeclaredFields(); for (final Field field : fields) { if ((field.getModifiers() & Modifier.STATIC) != 0) continue; field.setAccessible(true); final Object value = field.get(o); if (value != null) map.put(field.getName(), value); } c = c.getSuperclass(); } if (o instanceof DynamicObject) putAll(map, ((DynamicObject) o).fieldValues); return map; } catch (Exception __e) { throw rethrow(__e); } } static public List> objectToMap(Iterable l) { if (l == null) return null; List x = new ArrayList(); for (Object o : l) x.add(objectToMap(o)); return x; } static public Object rcall(String method, Object o, Object... args) { return call_withVarargs(o, method, args); } static public void onConceptChanges(Runnable r) { onConceptsChange(r); } static public void onConceptChanges(Concepts cc, Runnable r) { onConceptsChange(cc, r); } static public JLabel dm_transientCalculatedLabel(IF0 calc) { return jLiveValueLabel(dm_transientCalculatedLiveValue(Object.class, calc)); } 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 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 double calcFitScale(BufferedImage image, Component c) { return calcFitScale(image, c.getWidth(), c.getHeight()); } static public double calcFitScale(BufferedImage image, int w) { return calcFitScale(image, w, w); } static public double calcFitScale(BufferedImage image, int w, int h) { int iw = image.getWidth(), ih = image.getHeight(); return max(doubleRatio(h, ih), doubleRatio(w, iw)); } static public String strOrClassName(Object o) { if (o instanceof Class) return className((Class) o); return str(o); } static public Object nuObject(String className, Object... args) { try { return nuObject(classForName(className), args); } catch (Exception __e) { throw rethrow(__e); } } static public A nuObject(Class c, Object... args) { try { if (args == null || args.length == 0) return nuObjectWithoutArguments(c); Constructor m = nuObject_findConstructor(c, args); makeAccessible(m); return (A) m.newInstance(args); } catch (Exception __e) { throw rethrow(__e); } } static public Constructor nuObject_findConstructor(Class c, Object... args) { for (Constructor m : getDeclaredConstructors_cached(c)) { if (!nuObject_checkArgs(m.getParameterTypes(), args, false)) continue; return m; } throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : "")); } static public boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) { if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } static public File tempFileFor(File f) { return new File(f.getPath() + "_temp"); } static public int listRowCount(JList list) { return list == null ? 0 : swing(new F0() { public Integer get() { try { return list.getModel().getSize(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return list.getModel().getSize();"; } }); } static public JTextArea showWrappedText(final String title, final String text) { return (JTextArea) swingAndWait(new F0() { public Object get() { try { JTextArea textArea = wrappedTextArea(text); caretToHome(textArea); textArea.setFont(typeWriterFont()); makeFrame(title, new JScrollPane(textArea)); return textArea; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JTextArea textArea = wrappedTextArea(text);\r\n caretToHome(textArea);\r\n ..."; } }); } static public JTextArea showWrappedText(Object text) { return showWrappedText(autoFrameTitle(), str(text)); } static public File loadImageAsFile(String snippetIDOrURL) { try { if (isURL(snippetIDOrURL)) throw fail("not implemented"); if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL); String snippetID = "" + parseSnippetID(snippetIDOrURL); File file = imageSnippetCacheFile(snippetID); if (fileSize(file) > 0) return file; String imageURL = snippetImageURL_noHttps(snippetID); System.err.println("Loading image: " + imageURL); byte[] data = loadBinaryPage(imageURL); saveBinaryFile(file, data); return file; } catch (Exception __e) { throw rethrow(__e); } } static public Graphics2D antiAliasOn(Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); return g; } static public 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 long mul(long a, long b) { return a * b; } static public double mul(double a, double b) { return a * b; } static public AbstractAction abstractAction(String name, final Object runnable) { return new AbstractAction(name) { public void actionPerformed(ActionEvent evt) { pcallF(runnable); } }; } static public void assertFalse(Object o) { if (!(eq(o, false))) throw fail(str(o)); } static public boolean assertFalse(boolean b) { if (b) throw fail("oops"); return b; } static public boolean assertFalse(String msg, boolean b) { if (b) throw fail(msg); return b; } static public String mapEachLine(IF1 f, String text) { return lines_possiblyRTrim(text, mapLines(f, text)); } static public String mapEachLine(String text, IF1 f) { return mapEachLine(f, text); } static public boolean zipFileContains_falseOnError(File inZip, String fileName) { try { return zipFileContains(inZip, fileName); } catch (Throwable e) { return false; } } static public void printVars_str(Object... params) { print(renderVars_str(params)); } static public Object getMetaSrc(Object o) { return metaGet("src", o); } static public BufferedImage addBorderToImage(BufferedImage img, Color color, int border) { return img_addBorder(img, color, border); } static public BufferedImage addBorderToImage(Color color, BufferedImage img) { return addBorderToImage(1, color, img); } static public BufferedImage addBorderToImage(int border, Color color, BufferedImage img) { return img_addBorder(img, color, border); } static public BufferedImage addBorderToImage(Color color, int border, BufferedImage img) { return img_addBorder(img, color, border); } static public JPanel withTopRightAndBottomMargin(Component c) { return withTopRightAndBottomMargin(defaultMargin(), c); } static public JPanel withTopRightAndBottomMargin(int w, Component c) { return withMargins(w, 0, w, w, c); } static public File oneOfTheFilesInDir(File dir, String... names) { return oneOfTheFiles(map(names, name -> newFile(dir, name))); } static public A bindListenerToComponent(A component, IHasChangeListeners source, Runnable listener) { if (source != null && listener != null) bindToComponent(component, new Runnable() { public void run() { try { source.onChangeAndNow(listener); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "source.onChangeAndNow(listener);"; } }, new Runnable() { public void run() { try { source.removeChangeListener(listener); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "source.removeChangeListener(listener)"; } }); return component; } 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 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 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 Map objectToMap_inOrder_withoutFields(Object o, Collection withoutFields) { if (o == null) return null; if (o instanceof Map) return (Map) o; LinkedHashMap map = new LinkedHashMap(); for (String field : listWithoutSet(fieldsInOrder(o), withoutFields)) map.put(field, get(o, field)); return map; } static public Value value(A a) { return new Value(a); } static public int inc(AtomicInteger i) { return incAtomicInt(i); } static public int inc(AtomicInteger i, int delta) { return incAtomicInt(i, delta); } static public long inc(AtomicLong l) { return incAtomicLong(l); } static public long inc(AtomicLong l, long b) { return l.addAndGet(b); } static public int inc(IntVar v) { synchronized (v) { int val = v.get() + 1; v.set(val); return val; } } static public int inc(int i) { return i + 1; } static public long inc(long l) { return l + 1; } static public Set syncSet() { return synchroHashSet(); } static public Set syncSet(Collection l) { return addAllAndReturnCollection(synchroHashSet(), l); } static public class getOpt_Map extends WeakHashMap { public getOpt_Map() { if (getOpt_special == null) getOpt_special = new HashMap(); clear(); } public void clear() { super.clear(); put(Class.class, getOpt_special); put(String.class, getOpt_special); } } static final public Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map())); static public HashMap getOpt_special; static public Map getOpt_getFieldMap(Object o) { Class c = _getClass(o); HashMap map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); return map; } static public Object getOpt_cached(Object o, String field) { try { if (o == null) return null; Map map = getOpt_getFieldMap(o); if (map == getOpt_special) { if (o instanceof Class) return getOpt((Class) o, field); if (o instanceof Map) return ((Map) o).get(field); } Field f = map.get(field); if (f != null) return f.get(o); if (o instanceof DynamicObject) return syncMapGet2(((DynamicObject) o).fieldValues, field); return null; } catch (Exception __e) { throw rethrow(__e); } } static public HashMap getOpt_makeCache(Class c) { HashMap map; if (isSubtypeOf(c, Map.class)) map = getOpt_special; else { map = new HashMap(); if (!reflection_classesNotToScan().contains(c.getName())) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) { makeAccessible(f); String name = f.getName(); if (!map.containsKey(name)) map.put(name, f); } _c = _c.getSuperclass(); } while (_c != null); } } if (getOpt_cache != null) getOpt_cache.put(c, map); return map; } static public String formatWithThousandsSeparator(long l) { return NumberFormat.getInstance(new Locale("en_US")).format(l); } static public boolean eqicOrEq(Object a, Object b) { return a instanceof String && b instanceof String ? eqic((String) a, (String) b) : eq(a, b); } static public JPanel withRightAlignedButtons(JComponent center, Object... params) { return centerAndSouth(center, withMargin(jRightAlignedButtons(params))); } static public JPanel withRightAlignedButtons(Swingable center, Object... params) { return withRightAlignedButtons(wrap(center), params); } static public JPanel borderLayoutPanel() { return jpanel(new BorderLayout()); } static public int randomID_defaultLength = 12; static public String randomID(int length) { return makeRandomID(length); } static public String randomID(Random r, int length) { return makeRandomID(r, length); } static public String randomID() { return randomID(randomID_defaultLength); } static public String randomID(Random r) { return randomID(r, randomID_defaultLength); } static public long round(double d) { return Math.round(d); } static public String round(String s) { return roundBracket(s); } static public Complex round(Complex c) { return new Complex(round(c.re), round(c.im)); } static public Map weakHashMap() { return newWeakHashMap(); } static public char lastChar(String s) { return empty(s) ? '\0' : s.charAt(l(s) - 1); } static public Map runnableThreadsWithStackTraces_withoutSystemThreads() { return antiFilterKeys(__98 -> isSystemThread(__98), runnableThreadsWithStackTraces()); } static public void setTrayIconToolTip(TrayIcon trayIcon, String toolTip) { if (trayIcon != null) trayIcon.setToolTip(toolTip); } static public ScanlineBitMatrix toScanlineBitMatrix(Matrix m) { if (m == null) return null; if (m instanceof ScanlineBitMatrix) return ((ScanlineBitMatrix) m); return new ScanlineBitMatrix(m); } static public int strL(String s) { return s == null ? 0 : s.length(); } static public String quote(Object o) { if (o == null) return "null"; return quote(str(o)); } static public String quote(String s) { if (s == null) return "null"; StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2)); quote_impl(s, out); return out.toString(); } static public void quote_impl(String s, StringBuilder out) { out.append('"'); int l = s.length(); for (int i = 0; i < l; i++) { char c = s.charAt(i); if (c == '\\' || c == '"') out.append('\\').append(c); else if (c == '\r') out.append("\\r"); else if (c == '\n') out.append("\\n"); else if (c == '\t') out.append("\\t"); else if (c == '\0') out.append("\\0"); else out.append(c); } out.append('"'); } static public JLabel simpleTransformedLiveValueLabel(IF1 f, LiveValue lv) { return bindJLabelToTransformedLiveValue(f, swing(() -> new JLabel()), lv); } static public boolean isLowerHexString(String s) { for (int i = 0; i < l(s); i++) { char c = s.charAt(i); if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { } else return false; } return true; } static public JTextField jTextField() { return jTextField(""); } static public JTextField jTextField(final String text) { return swing(new F0() { public JTextField get() { try { JTextField tf = new JTextField(unnull(text)); standardTextFieldPopupMenu(tf); jenableUndoRedo(tf); tf.selectAll(); return tf; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JTextField tf = new JTextField(unnull(text));\r\n standardTextFieldPopupMenu..."; } }); } static public JTextField jTextField(Object o) { return jTextField(strOrEmpty(o)); } static public 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 String fileServerURL() { return "https://botcompany.de/files"; } static public Map> fieldsInOrder_cache = weakHashMap(); static public List fieldsInOrder(Object o) { return fieldsInOrder(_getClass(o)); } static public List fieldsInOrder(Class c) { if (c == null) return null; synchronized (fieldsInOrder_cache) { List fields = fieldsInOrder_cache.get(c); if (fields != null) return fields; String order = toStringOpt(getOpt(c, "_fieldOrder")); Set set = asTreeSet(allNonStaticFields(c)); if (order == null) return asList(set); fields = splitAtSpace(order); setAddAll(fields, set); fieldsInOrder_cache.put(c, fields); return fields; } } static public Set setWithNotify(final Runnable onChange) { return setWithNotify(new HashSet(), onChange); } static public Set setWithNotify(Set set, final Runnable onChange) { return new NotifyingSet(set) { public void change() { onChange.run(); } }; } 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 JTabbedPane jLeftTabs(Object... x) { JTabbedPane tabs = jtabs(x); tabs.setTabPlacement(JTabbedPane.LEFT); return tabs; } static public JTabbedPane jLeftTabs(Collection c) { return jLeftTabs(toObjectArray(c)); } static public Component addToWindow(final Component c, final Component toAdd) { if (toAdd != null) { swing(() -> { JFrame frame = getFrame(c); if (frame == null) return; setContentPane(frame, centerAndSouth(frame.getContentPane(), toAdd)); }); } return c; } static public void selectTableRows(final JTable table, int[] rows) { if (table != null) { swing(() -> { ListSelectionModel model = table.getSelectionModel(); int n = tableRows(table); model.clearSelection(); if (rows != null) for (int row : rows) if (row < n) model.addSelectionInterval(row, row); }); } } static public Pair transpileOnNewServer(String snippetID) { return transpileOnNewServer(snippetID, "quick"); } static public Pair transpileOnNewServer(long snippetID) { return transpileOnNewServer(fsI(snippetID)); } static public Pair transpileOnNewServer(long snippetID, String mode) { return transpileOnNewServer(fsI(snippetID), mode); } static public Pair transpileOnNewServer(String snippetID, String mode) { try { print("Transpiling " + formatSnippetID(snippetID)); String url = "https://botcompany.de/1018308/raw/" + psI(snippetID); url = appendParamsToURL(url, "medium", eq(mode, "medium") ? "1" : null, "fresh", eq(mode, "fresh") ? "1" : null); String result = postPage(url, transpilationCredentials()); print(result); boolean ok = cic(htmlDecode(result), "Transpiled & uploaded"); return pair(ok, result); } catch (Exception __e) { throw rethrow(__e); } } 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 boolean isRunnable(Object o) { return o instanceof Runnable || hasMethod(o, "get"); } static public void assertIsInstance(Class type, Object o) { if (!isInstance(type, o)) throw fail(_getClass(o) + " is not a subclass of " + type); } static public void assertIsInstance(Object o, Class type) { assertIsInstance(type, o); } static public A uniqCI(Class c, Object... params) { return uniqueConcept(db_mainConcepts(), c, params); } static public A uniqCI(Concepts cc, Class c, Object... params) { AutoCloseable __1 = tempDBLock(cc); try { params = expandParams(c, params); A x = findConceptWhereCI(cc, c, params); if (x == null) { x = unlisted(c); csetAll(x, params); cc.register(x); } return x; } finally { _close(__1); } } static public JPanel showInternalFrameFormTitled(final JDesktopPane desktop, final String title, final Object... _parts) { JPanel panel = showForm_makePanel(true, _parts); showForm_makeInternalFrame(desktop, title, panel); return panel; } static public Set emptySet() { return new HashSet(); } static public boolean isImageServerSnippet(long id) { return id >= 1100000 && id < 1200000; } static public Collection allConcepts() { return db_mainConcepts().allConcepts(); } static public Collection allConcepts(Concepts concepts) { return concepts.allConcepts(); } static volatile public boolean sleep_noSleep = false; static public void sleep(long ms) { ping(); if (ms < 0) return; if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread"); try { Thread.sleep(ms); } catch (Exception e) { throw new RuntimeException(e); } } static public void sleep() { try { if (sleep_noSleep) throw fail("nosleep"); print("Sleeping."); sleepQuietly(); } catch (Exception __e) { throw rethrow(__e); } } static public A centerFrame(A c) { Window w = getWindow(c); if (w != null) { swing(() -> { var r = preferredScreenBounds(); w.setLocation(r.x + (r.w - w.getWidth()) / 2, r.y + (r.h - w.getHeight()) / 2); }); } return c; } static public A centerFrame(int w, int h, A c) { return centerFrame(setFrameSize(w, h, c)); } static public Object[] reverseParams(Object[] params) { int n = l(params); if (params == null || odd(n)) return params; Object[] a = new Object[n]; for (int i = 0; i + 1 < n; i += 2) arraycopy(params, i, a, n - i - 2, 2); return a; } static public void indexConceptField(Class c, String field) { indexConceptField(db_mainConcepts(), c, field); } static public void indexConceptField(Concepts concepts, Class c, String field) { if (!isConceptFieldIndexed(concepts, c, field)) new ConceptFieldIndex(concepts, c, field); } static public int getHeight(Component c) { return c == null ? 0 : (int) swingCall(c, "getHeight"); } 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 int scoredSearch_score(Iterable l, List words) { int score = 0; if (l != null) for (String s : l) score += scoredSearch_score(s, words); return score; } static public int scoredSearch_score(String s, List words) { int score = 0; if (nempty(s)) for (String word : unnullForIteration(words)) score += scoredSearch_score_single(s, word); return score; } static public int scoredSearch_score(String s, String query) { return scoredSearch_score(s, scoredSearch_prepare(query)); } 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 jComboBox(String selectedItem, Collection items) { return jcombobox(items, selectedItem); } static public void close(AutoCloseable c) { _close(c); } static public void setHeaders(URLConnection con) throws IOException { String computerID = getComputerID_quick(); if (computerID != null) try { con.setRequestProperty("X-ComputerID", computerID); con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version")); } catch (Throwable e) { } } static public boolean isFile(File f) { return f != null && f.isFile(); } static public boolean isFile(String path) { return isFile(newFile(path)); } static public int indexOfPred(List l, Object pred) { for (int i = 0; i < l(l); i++) if (checkCondition(pred, l.get(i))) return i; return -1; } static public int indexOfPred(List l, IF1 pred) { return indexOfPred(l, (Object) pred); } static public JPanel northAndCenterWithMargins(Swingable n, Swingable c) { return northAndCenterWithMargins(n, toComponent(c)); } static public JPanel northAndCenterWithMargins(Swingable n, Component c) { return northAndCenterWithMargins(toComponent(n), c); } static public JPanel northAndCenterWithMargins(Component n, Swingable c) { return northAndCenterWithMargins(n, toComponent(c)); } static public JPanel northAndCenterWithMargins(Component n, Component c) { return applyDefaultMargin(northAndCenter(withBottomMargin(n), c)); } static public JPanel northAndCenterWithMargins(int margin, Swingable n, Swingable c) { return northAndCenterWithMargins(margin, n, toComponent(c)); } static public JPanel northAndCenterWithMargins(int margin, Swingable n, Component c) { return northAndCenterWithMargins(margin, toComponent(n), c); } static public JPanel northAndCenterWithMargins(int margin, Component n, Swingable c) { return northAndCenterWithMargins(margin, n, toComponent(c)); } static public JPanel northAndCenterWithMargins(int margin, Component n, Component c) { return applyMargin(margin, northAndCenter(withBottomMargin(margin, n), c)); } 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 assertSame(IF0 msg, Object a, Object b) { if (a != b) throw fail(joinNemptiesWithColon(msg.get(), a + " != " + b + " (" + identityHash(a) + "/" + identityHash(b) + ")")); } 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 RuntimeException todo() { throw new RuntimeException("TODO"); } static public RuntimeException todo(Object msg) { throw new RuntimeException("TODO: " + msg); } 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 byte[] bytesFromHex(String s) { return hexToBytes(s); } static public AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) { if (tl == null) return null; final A prev = setThreadLocal(tl, a); return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); } }; } static public A jMinSize(int w, int h, A c) { return jMinWidth(w, jMinHeight(h, c)); } static public A jMinSize(A c, int w, int h) { return jMinSize(w, h, c); } static public A jMinSize(A c, Dimension d) { return jMinSize(d.width, d.height, c); } static public String readLineFromReaderWithClose(BufferedReader r) { try { String s = r.readLine(); if (s == null) r.close(); return s; } catch (Exception __e) { throw rethrow(__e); } } static public A optParam(ThreadLocal tl, A defaultValue) { return optPar(tl, defaultValue); } static public A optParam(ThreadLocal tl) { return optPar(tl); } static public Object optParam(String name, Map params) { return mapGet(params, name); } static public A optParam(Object[] opt, String name, A defaultValue) { int n = l(opt); if (n == 1 && opt[0] instanceof Map) { Map map = (Map) (opt[0]); return map.containsKey(name) ? (A) map.get(name) : defaultValue; } if (!even(l(opt))) throw fail("Odd parameter length"); for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name)) return (A) opt[i + 1]; return defaultValue; } static public Object optParam(Object[] opt, String name) { return optParam(opt, name, null); } static public Object optParam(String name, Object[] params) { return optParam(params, name); } static public IProgressShower tempProgressBar(String text) { return tempProgressBar(text, 1); } static public IProgressShower tempProgressBar(String text, double total) { JProgressBar bar = showProgressWindow(text, total); 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() { disposePIFrame(bar); } }; } static public Pt centerOfRect(Rect r) { return r == null ? null : new Pt(r.x + r.w / 2, r.y + r.h / 2); } static public void register(Concept c) { registerConcept(c); } static public JLabel jCenteredBoldLabel(String text) { return jcenteredBoldLabel(text); } static public JLabel jCenteredBoldLabel() { return jcenteredBoldLabel(); } 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 Class _getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } static public Class _getClass(Object o) { return o == null ? null : o instanceof Class ? (Class) o : o.getClass(); } static public Class _getClass(Object realm, String name) { try { return classLoaderForObject(realm).loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } static public boolean instanceOf(Object o, String className) { if (o == null) return false; String c = o.getClass().getName(); return eq(c, className) || eq(c, "main$" + className); } static public boolean instanceOf(Object o, Class c) { if (c == null) return false; return c.isInstance(o); } static public boolean instanceOf(Class c, Object o) { return instanceOf(o, c); } static public JComponent wrapForSmartAdd_jComponent(Object o) { return componentToJComponent(wrapForSmartAdd(o)); } static public Pt mousePointer() { return new Pt(getMouseLocation()); } static public Either either2(B b) { return new Either(2, b); } static public Either either1(A a) { return new Either(1, a); } static public Component addToWindowAndGrow(final Component c, final Component toAdd) { { swing(() -> { int h = getMinimumHeight(toAdd); addToWindow(c, toAdd); growWindowSouth(c, h); }); } return c; } static public Object evalWithTimeoutOrException(final Object f, int timeoutMS) { return evalWithTimeoutOrException(timeoutMS, f); } static public Object evalWithTimeoutOrException(int timeoutMS, final Object f) { return eitherAOpt(evalWithTimeout(timeoutMS, f)); } static public Object evalWithTimeoutOrException(double timeoutSeconds, final Object f) { return eitherAOpt(evalWithTimeout(timeoutSeconds, f)); } static public A evalWithTimeoutOrException(int timeoutMS, F0 f) { Either e = evalWithTimeout(timeoutMS, f); if (e.isA()) return (A) e.a(); throw fail(trim("Timeout after " + timeoutMS + " ms. " + unnull(stackTraceForThread(e.b())))); } static public A evalWithTimeoutOrException(double timeoutSeconds, F0 f) { return evalWithTimeoutOrException(toMS_int(timeoutSeconds), f); } static public A evalWithTimeoutOrException(int timeoutMS, IF0 f) { return evalWithTimeoutOrException(timeoutMS, if0ToF0(f)); } static public A evalWithTimeoutOrException(double timeoutSeconds, IF0 f) { return evalWithTimeoutOrException(timeoutSeconds, if0ToF0(f)); } static public URLConnection openConnection(String url) { try { return openConnection(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } static public URLConnection openConnection(URL url) { try { ping(); callOpt(javax(), "recordOpenURLConnection", str(url)); return url.openConnection(); } catch (Exception __e) { throw rethrow(__e); } } static public int fixInternalFrame_borderTopLeft = 0; static public int fixInternalFrame_borderBottomRight = 40; static public JInternalFrame fixInternalFrame(final JInternalFrame f) { return swing(new F0() { public JInternalFrame get() { try { Container c = f.getParent(); if (c == null) return f; Rect r = toRect(f.getBounds()); int a = fixInternalFrame_borderTopLeft, b = fixInternalFrame_borderBottomRight; Rect outer = new Rect(a, a, c.getWidth() - b, c.getHeight() - b); if (!rectContains(outer, r)) f.setLocation(max(a, min(r.x, outer.x2())), max(a, min(r.y, outer.y2()))); if (r.w > c.getWidth() || r.h > c.getHeight()) f.setSize(c.getWidth() - a, c.getHeight() - a); return f; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Container c = f.getParent();\r\n if (c == null) ret f;\r\n Rect r = toRect(..."; } }); } static public Map mapKeys(Object func, Map map) { Map m = similarEmptyMap(map); for (Object key : keys(map)) m.put(callF(func, key), map.get(key)); return m; } static public Map mapKeys(Map map, Object func) { return mapKeys(func, map); } static public Map mapKeys(Map map, IF1 func) { return mapKeys(map, (Object) func); } static public Map mapKeys(IF1 func, Map map) { return mapKeys(map, func); } static public MultiMap mapKeys(IF1 f, MultiMap mm) { return mapMultiMapKeys(f, mm); } static public MultiSetMap mapKeys(IF1 f, MultiSetMap mm) { return mapMultiSetMapKeys(f, mm); } static public String snippetImageURL_noHttps(String snippetID) { return snippetImageURL_noHttps(snippetID, "png"); } static public String snippetImageURL_noHttps(String snippetID, String contentType) { return snippetImageURL(snippetID, contentType).replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/").replace("https://botcompany.de/", "http://botcompany.de/"); } static public JButton tableDependButton(JTable tbl, JButton b) { tableDependButtons(tbl, ll(b)); return b; } static public JButton tableDependButton(JTable tbl, String text, Object action) { return tableDependButton(tbl, jbutton(text, action)); } static public List getComboBoxItems(JComboBox cb) { return cb == null ? null : swing(() -> { ComboBoxModel model = cb.getModel(); int n = model.getSize(); List l = emptyList(n); for (int i = 0; i < n; i++) l.add(model.getElementAt(i)); return l; }); } 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 TreeSet asTreeSet(Collection set) { return set == null ? null : set instanceof TreeSet ? (TreeSet) set : new TreeSet(set); } static public File saveTextFile(String fileName, String contents) throws IOException { File file = new File(fileName); mkdirsForFile(file); String tempFileName = fileName + "_temp"; File tempFile = new File(tempFileName); if (contents != null) { if (tempFile.exists()) try { String saveName = tempFileName + ".saved." + now(); copyFile(tempFile, new File(saveName)); } catch (Throwable e) { printStackTrace(e); } FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath()); try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); } finally { _close(fileOutputStream); } } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (contents != null) if (!tempFile.renameTo(file)) throw new IOException("Can't rename " + tempFile + " to " + file); vmBus_send("wroteFile", file); return file; } static public File saveTextFile(File fileName, String contents) { try { saveTextFile(fileName.getPath(), contents); return fileName; } catch (Exception __e) { throw rethrow(__e); } } static public void setContentPane(JFrame frame, Container c) { swing(() -> { frame.setContentPane(c); revalidate(frame); }); } static public void setContentPane(JWindow w, Container c) { swing(() -> { w.setContentPane(c); revalidate(w); }); } static public TreeSet mapToTreeSet(Object f, Iterable l) { TreeSet x = new TreeSet(); if (l != null) for (Object o : l) x.add(callF(f, o)); return x; } static public TreeSet mapToTreeSet(IF1 f, Iterable l) { TreeSet x = new TreeSet(); if (l != null) for (var o : l) x.add(f.get(o)); return x; } static public TreeSet mapToTreeSet(Iterable l, IF1 f) { return mapToTreeSet(f, l); } static public Map> allFields_cache = weakHashMap(); static public Set allFields(Object o) { if (o == null) return emptySet(); Class _c = _getClass(o); Set fields = allFields_cache.get(_c); if (fields == null) allFields_cache.put(_c, fields = asTreeSet(keys(getOpt_getFieldMap(o)))); return fields; } 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 int ubyteToInt(byte b) { return b & 0x0FF; } static public int ubyteToInt(char c) { return c & 0x0FF; } static public CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; static public CloseableIterableIterator emptyCloseableIterableIterator() { return emptyCloseableIterableIterator_instance; } static public Map mapPlus(Map m, Object... data) { m = cloneMap(m); litmap_impl(m, data); return m; } static public void savePNG(BufferedImage img, File file) { try { File tempFile = new File(file.getPath() + "_temp"); CriticalAction ca = beginCriticalAction("Save " + f2s(file)); try { ImageIO.write(img, "png", mkdirsFor(tempFile)); file.delete(); tempFile.renameTo(file); } finally { ca.done(); } } catch (Exception __e) { throw rethrow(__e); } } static public void savePNG(String file, BufferedImage img) { savePNG(toFile(file), img); } static public void savePNG(File file, BufferedImage img) { savePNG(img, file); } static public void savePNG(File file, RGBImage img) { savePNG(file, img.getBufferedImage()); } static public boolean replaceNiceButtons(DynamicStack stack, Object... params) { boolean first = stack.isEmpty(); stack.setComponents(makeNiceButtons(params).components()); return first; } static public JButton disableButton(final JButton b) { if (b != null) { swing(() -> { b.setEnabled(false); }); } return b; } static public void disableButton() { disableButton(heldInstance(JButton.class)); } 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 __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, itr, region.indexInCreator(), color, false); } } isPosterized.setImage(bufferedImage(pixels, itr.posterized)); } 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 pnlToString(String prefix, Iterable l) { return hijackPrint(new Runnable() { public void run() { try { pnl(prefix, l); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pnl(prefix, l)"; } }); } static public String pnlToString(final Iterable l) { return hijackPrint(new Runnable() { public void run() { try { pnl(l); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pnl(l)"; } }); } static public String pnlToString(final A[] l) { return hijackPrint(new Runnable() { public void run() { try { pnl(l); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pnl(l)"; } }); } static public String pnlToString(final Map map) { return hijackPrint(new Runnable() { public void run() { try { pnl(map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pnl(map)"; } }); } static public String pnlToString(MultiMap map) { return pnlToString(multiMapToMap(map)); } static public double[] emptyDoubleArray = new double[0]; static public double[] emptyDoubleArray() { return emptyDoubleArray; } static public A[] makeArray(Class type, int n) { return (A[]) Array.newInstance(type, n); } 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 lines(File f) { return linesFromFile_list(f); } static public AutoCloseable tempSetTL_noInit(BetterThreadLocal tl, A a) { if (tl == null) return null; A prev = tl.isSet() ? tl.get() : null; if (eq(prev, a)) return null; tl.set(a); return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); } }; } static public JTabbedPane jtabs(Object... x) { return fillJTabs(swingNu(JTabbedPane.class), x); } static public void onTabSelected(JTabbedPane tabs, Runnable r) { if (tabs != null) { swing(() -> { tabs.getModel().addChangeListener(changeListener(r)); }); } } static public void onTabSelected(JTabbedPane tabs, IVF1 r) { if (tabs != null && r != null) onTabSelected(tabs, () -> r.get(tabs.getSelectedIndex())); } static public BWImage scaledBWImageFromBWIntegralImage(int w, IBWIntegralImage img) { return scaledBWImageFromBWIntegralImage(img, w); } static public BWImage scaledBWImageFromBWIntegralImage(IBWIntegralImage img, int w) { return scaledBWImageFromBWIntegralImage(img, w, heightForWidth(img, w)); } static public BWImage scaledBWImageFromBWIntegralImage(IBWIntegralImage img, int w, int h) { ScaledBWImageFromBWIntegralImage op = new ScaledBWImageFromBWIntegralImage(img, w, h); op.run(); return op.result; } static public BWImage scaledBWImageFromBWIntegralImage(int w, int h, IBWImage img) { return scaledBWImageFromBWIntegralImage(w, h, toIBWIntegralImage(img)); } 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 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(IMultiMap mm) { return mm != null && mm.size() != 0; } 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(CloseablesHolder ch) { return ch != null && !empty(ch.closeables); } static public boolean nempty(MultiSet ms) { return ms != null && !ms.isEmpty(); } static public boolean nempty(IntSize l) { return l != null && l.size() != 0; } static public boolean isEmpty(Collection c) { return c == null || c.isEmpty(); } static public boolean isEmpty(File f) { return f == null || f.length() == 0; } static public boolean isEmpty(CharSequence s) { return s == null || s.length() == 0; } static public boolean isEmpty(Object[] a) { return a == null || a.length == 0; } static public boolean isEmpty(byte[] a) { return a == null || a.length == 0; } static public boolean isEmpty(Map map) { return map == null || map.isEmpty(); } static public boolean isEmpty(DoubleRange r) { return r == null || r.isEmpty(); } static public boolean isEmpty(AppendableChain c) { return c == null; } static public boolean isEmpty(IntSize l) { return l == null || l.size() == 0; } static public String makeRandomID(int length) { return makeRandomID(length, defaultRandomGenerator()); } static public String makeRandomID(int length, Random random) { char[] id = new char[length]; for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26)); return new String(id); } static public String makeRandomID(Random r, int length) { return makeRandomID(length, r); } static public List allJFrames() { return allFrames(); } static public JComponent withTitle(String title, Swingable c) { return withTitle(title, toComponent(c)); } static public JComponent withTitle(String title, Component c) { return withTitle(withTitle_titlePanel(title), c); } static public JComponent withTitle_titlePanel(String title) { return jlabel(title); } static public JPanel withTitle(final JComponent titleComponent, final Component c) { return swing(new F0() { public JPanel get() { try { titleComponent.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, UIManager.getColor("Button.borderColor"))); JPanel panel = new JPanel(new BorderLayout()); panel.setBackground(Color.WHITE); panel.add(BorderLayout.NORTH, titleComponent); panel.add(BorderLayout.CENTER, wrap(c)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "titleComponent.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, UIManage..."; } }); } static public JComponent jSmallErrorView(Throwable e) { var btn = jimageButtonScaledToWidth(32, errorIconID(), "Show error details", () -> showErrorFrame(e)); String text = exceptionToStringShort(e); var label = jlabel_noAutoToolTip(text); return jline(btn, label); } static public int colorToIntOpaque(Color c) { return c.getRGB() | 0xFF000000; } static public Object dm_getStemByID(Object id) { return dm_callOS("getModuleByID", str(id)); } static public JToggleButton jImageToggleButton(Image image, String toolTip, Runnable action) { return jImageToggleButton(image, toolTip, action, false); } static public JToggleButton jImageToggleButton(Image image, String toolTip, Runnable action, boolean selected) { var btn = jToggleButton("", action); setSelected(btn, selected); toolTip(btn, toolTip); setButtonImage(btn, image); return btn; } static public JToggleButton jImageToggleButton(String image, String toolTip, Runnable action) { return jImageToggleButton(image, toolTip, action, false); } static public JToggleButton jImageToggleButton(String image, String toolTip, Runnable action, boolean selected) { var btn = jToggleButton("", action); setSelected(btn, selected); toolTip(btn, toolTip); setButtonImage(btn, image); return btn; } static public JPanel marginPanel() { return jtransparent(borderLayoutPanel()); } static public String showImage_defaultIcon = "#1004230"; static public ImageSurface showImage(String snippetIDOrURL, String title) { return showImage(loadImage(snippetIDOrURL), title); } static public ImageSurface showImage(String title, BufferedImage img) { return showImage(img, title); } static public ImageSurface showImage(final BufferedImage img, final String title) { return (ImageSurface) swing(new F0() { public Object get() { try { ImageSurface is = showImage(img); getFrame(is).setTitle(title); return is; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ImageSurface is = showImage(img);\r\n getFrame(is).setTitle(title);\r\n ret..."; } }); } static public ImageSurface showImage(final BufferedImage img) { return (ImageSurface) swing(new F0() { public Object get() { try { ImageSurface is = new ImageSurface(img); JFrame frame = showPackedFrame(new JScrollPane(is)); moveToTopRightCorner(frame); frameIcon(frame, showImage_defaultIcon); return is; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ImageSurface is = new ImageSurface(img);\r\n JFrame frame = showPackedFrame(..."; } }); } static public ImageSurface showImage(String imageID) { return showImage(loadImage2(imageID)); } static public ImageSurface showImage(ImageSurface surface, BufferedImage img) { return showImage(img, surface); } static public ImageSurface showImage(ImageSurface surface, String title, BufferedImage img) { return showImage(surface, img, title); } static public ImageSurface showImage(ImageSurface surface, BufferedImage img, String title) { return setFrameTitle(showImage(img, surface), title); } static public ImageSurface showImage(BufferedImage img, ImageSurface surface) { if (surface == null) return showImage(img); else { surface.setImage(img); return surface; } } static public ImageSurface showImage(String title, MakesBufferedImage img) { return showImage(title, img.getBufferedImage()); } static public ImageSurface showImage(ImageSurface is, MakesBufferedImage img) { return showImage(is, img.getBufferedImage()); } static public ImageSurface showImage(RGBImage img) { return showImage(img.getBufferedImage()); } static public ImageSurface showImage(RGBImage img, String title) { ImageSurface is = showImage(img.getBufferedImage()); getFrame(is).setTitle(title); return is; } static public ImageSurface showImage(ImageSurface surface, RGBImage img) { return showImage(img, surface); } static public ImageSurface showImage(RGBImage img, ImageSurface surface) { if (surface == null) return showImage(img); else { surface.setImage(img); return surface; } } static public ImageSurface showImage(ImageSurface surface, String title, RGBImage img) { return showImage(surface, img, title); } static public ImageSurface showImage(ImageSurface surface, RGBImage img, String title) { return setFrameTitle(showImage(img, surface), title); } static public ImageSurface showImage(MakesBufferedImage img) { return showImage(img.getBufferedImage()); } static public ImageSurface showImage() { return showImage(currentImage()); } static public ImageSurface showImage(File f) { return showImage(f2s(f), loadImage2(f)).setFile(f); } static public Pt scalePt(Pt p, double scaleX) { return scalePt(p, scaleX, scaleX); } static public Pt scalePt(Pt p, double scaleX, double scaleY) { return new Pt(iround(p.x * scaleX), iround(p.y * scaleY)); } static public Pt scalePt(double f, Pt p) { return scalePt(p, f); } static public Pt scalePt(int w, int h, double f) { return scalePt(new Pt(w, h), f); } static public IterableIterator iteratorFromFunction_if0(final IF0 f) { class IFF2 extends IterableIterator { public A a; public boolean done = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } public void getNext() { if (done || a != null) return; a = f.get(); done = a == null; } } ; return new IFF2(); } static public Map vm_busListenersByMessage_live_cache; static public Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache; } static public Map vm_busListenersByMessage_live_load() { return vm_generalHashMap("busListenersByMessage"); } static public Object selectedTableCell(JTable t, int col) { return getTableCell(t, selectedTableRow(t), col); } static public Object selectedTableCell(final JTable t) { return swing(new F0() { public Object get() { try { return selectedTableCell(t, t.getSelectedColumn()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return selectedTableCell(t, t.getSelectedColumn());"; } }); } static public Object selectedTableCell(final JTable t, final String colName) { return swing(new F0() { public Object get() { try { return selectedTableCell(t, tableColumnViewIndex(t, colName)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return selectedTableCell(t, tableColumnViewIndex(t, colName));"; } }); } static public long getFileSize(String path) { return path == null ? 0 : new File(path).length(); } static public long getFileSize(File f) { return f == null ? 0 : f.length(); } static public BufferedReader bufferedReader(Reader r) { return bufferedReader(r, 8192); } static public BufferedReader bufferedReader(Reader r, int bufSize) { if (r == null) return null; return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r, bufSize), r); } static public BufferedReader bufferedReader(File f) { return utf8bufferedReader(f); } static public A cDeref(Concept.Ref ref) { return ref == null ? null : ref.get(); } static public int shorten_default = 100; static public String shorten(CharSequence s) { return shorten(s, shorten_default); } static public String shorten(CharSequence s, int max) { return shorten(s, max, "..."); } static public String shorten(CharSequence s, int max, String shortener) { if (s == null) return ""; if (max < 0) return str(s); return s.length() <= max ? str(s) : subCharSequence(s, 0, min(s.length(), max - l(shortener))) + shortener; } static public String shorten(int max, CharSequence s) { return shorten(s, max); } static public List listWithout(Collection a, Object... b) { return minus(a, b); } static public Map vm_threadInterruptionReasonsMap() { return vm_generalWeakSubMap("Thread interruption reasons"); } static public int iceil(double d) { return (int) Math.ceil(d); } static public Point getMouseLocation() { return MouseInfo.getPointerInfo().getLocation(); } static public String asString(Object o) { return o == null ? null : o.toString(); } static public void ping_v3_setPingSourceMaker(IF0 pingMaker) { vm_generalMap_set("ping_v3_pingSourceMaker", pingMaker); } static public Object vm_generalMap_put(Object key, Object value) { return mapPutOrRemove(vm_generalMap(), key, value); } static public String nImages(long n) { return n2(n, "image"); } static public String nImages(Collection l) { return nImages(l(l)); } static public Color grayToColor(double f) { return toColor(brightnessToRGBA(iceil(f * 256))); } static public List lookupAllOpt(Map map, Collection l) { List out = new ArrayList(); if (l != null) for (A a : l) addIfNotNull(out, map.get(a)); return out; } static public List lookupAllOpt(Collection l, Map map) { return lookupAllOpt(map, l); } static public String str_toMB_oneDigit(long l) { return formatDouble1(toM(l)) + " MB"; } static public List newSubList(List l, int startIndex, int endIndex) { return cloneList(subList(l, startIndex, endIndex)); } static public List newSubList(List l, int startIndex) { return cloneList(subList(l, startIndex)); } 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 void addMenuItem(JPopupMenu menu, String text, Object action) { menu.add(jmenuItem(text, action)); } static public void addMenuItem(JPopupMenu menu, JMenuItem menuItem) { if (menu != null && menuItem != null) menu.add(menuItem); } static public void addMenuItem(JMenu menu, String text, Object action) { menu.add(jmenuItem(text, action)); } static public void addMenuItem(Menu menu, String text, Object action) { menu.add(menuItem(text, action)); } static public void addMenuItem(JMenu menu, JMenuItem menuItem) { menu.add(menuItem); } static public void addMenuItem(JMenuBar menuBar, String text, Runnable action) { addMenuItem(menuBar, jmenuItem(text, action)); } static public void addMenuItem(JMenuBar menuBar, JMenuItem menuItem) { addDirectMenuItem(menuBar, menuItem); } static public String longestPrefixInNavigableSet(String s, NavigableSet set) { if (set == null || s == null) return null; while (licensed()) { String key = set.floor(s); if (key == null) break; int n = lCommonPrefix(key, s); if (n == l(key)) return key; s = takeFirst(s, n); } return null; } static public void selectTab(JExtendedTabbedPane tabs, int idx) { if (tabs != null) { swing(() -> { tabs.setSelectedIndex(idx); }); } } static public void selectTab(JTabbedPane tabs, int idx) { if (tabs != null) { swing(() -> { tabs.setSelectedIndex(idx); }); } } static public B firstValue(Map map) { return first(values(map)); } static public B firstValue(MultiSetMap map) { return map == null ? null : first(firstValue(map.data)); } static public B firstValue(MultiMap map) { return map == null ? null : first(firstValue(map.data)); } static public boolean zipFileContains(File inZip, String fileName) { try { ZipFile zip = new ZipFile(inZip); try { return zipFileContains(zip, fileName); } finally { zip.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public boolean zipFileContains(ZipFile zip, String fileName) { try { return zip.getEntry(fileName) != null; } catch (Exception __e) { throw rethrow(__e); } } 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 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 boolean isImageFileName(String s) { return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif", ".qoi"); } static public boolean usingJTattoo() { return startsWith(className(currentLAF()), "com.jtattoo."); } static public Object[] arrayrep(Object a, int n) { Object[] array = new Object[n]; for (int i = 0; i < n; i++) array[i] = a; return array; } static public A[] arrayrep(Class type, A a, int n) { A[] array = newArray(type, n); for (int i = 0; i < n; i++) array[i] = a; return array; } static public File pathToJavaxJar() { return null; } static public File pathToJavaxJar_noResourceLoader() { try { return null; } catch (Exception __e) { throw rethrow(__e); } } static public String checkmarkIconID() { return "#1103071"; } static public JFrame showFrame() { return makeFrame(); } static public JFrame showFrame(Object content) { return makeFrame(content); } static public JFrame showFrame(String title) { return makeFrame(title); } static public JFrame showFrame(String title, Object content) { return makeFrame(title, content); } static public JFrame showFrame(final JFrame f) { if (f != null) { swing(() -> { if (frameTooSmall(f)) frameStandardSize(f); if (!f.isVisible()) f.setVisible(true); if (f.getState() == Frame.ICONIFIED) f.setState(Frame.NORMAL); }); } return f; } static public JFrame showFrame(String title, Object content, JFrame frame) { if (frame == null) return showFrame(title, content); else { frame.setTitle(title); setFrameContents(frame, content); return frame; } } static public Set synchronizedSet() { return synchroHashSet(); } static public Set synchronizedSet(Set set) { return new SynchronizedSet(set); } static public Object callConstructor(String className, Object... args) { return nuObject(className, args); } static public A callConstructor(Class c, Object... args) { return nuObject(c, args); } static public List identifiers(String s) { return tok_identifiersInOrder(s); } static public List identifiers(List tok) { return tok_identifiersInOrder(tok); } 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 JSpinner jSpinnerCommitOnValidEdit(JSpinner spinner) { var tf = getTextFieldFromSpinner(spinner); if (tf != null) { swing(() -> { DefaultFormatter formatter = (DefaultFormatter) (tf.getFormatter()); if (formatter != null) formatter.setCommitsOnValidEdit(true); }); } return spinner; } static public boolean isStringOrIntOrLong(Object o) { return o instanceof String || o instanceof Integer || o instanceof Long; } static public Set identityHashSet() { return Collections.newSetFromMap(new IdentityHashMap()); } static public String strOr(Object o, String ifNull) { return o == null ? ifNull : str(o); } static public void createEmptyConceptsFileInDir(File dir) { File f = newFile(dir, conceptsFileName()); if (!fileExists(f)) saveGZStructureToFile(f, litmap()); } static public JPanel jfullcenter(Component c) { return jFullCenter(c); } static public List regexpFirstGroups(String pat, String s) { if (s == null) return null; Matcher m = regexp(pat, s); return m.find() ? regexpGetGroups(m) : null; } static public WidthAndHeight sixteenToNine_p(int height) { return new WidthAndHeightImpl(iround(height * 16.0 / 9), height); } static public AutoCloseable tempSetRandomSeed(int seed) { return tempSetCustomRandomizerForThisThread(new Random(seed)); } static public JPanel northCenterAndSouthWithMargin(Component n, Component c, Component s) { return northCenterAndSouth(withBottomMargin(n), c, withTopMargin(s)); } static public JPanel northCenterAndSouthWithMargin(int margin, Component n, Component c, Component s) { return northCenterAndSouth(withBottomMargin(margin, n), c, withTopMargin(margin, s)); } static public SimpleLiveValue varWithNotifyToLiveValue_verbose(Class type, IVarWithNotify var) { if (var == null) return null; var lv = new SimpleLiveValue(type); var lvRef = weakRef(lv); var.onChange(new Runnable() { public void run() { try { var lv = lvRef.get(); if (lv == null) var.removeChangeListener(this); else { var value = var.get(); print("varChange " + value); lv.set(value); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var lv = lvRef!;\r\n if (lv == null)\r\n var.removeChangeListener(this);\r..."; } }); lv.onChange(() -> { var value = lv.get(); print("lvChange " + value); var.set(value); }); var value = var.get(); print("varToLvInit " + value); lv.set(value); return lv; } static public A _registerIOWrap(A wrapper, Object wrapped) { return wrapper; } static public void addMenuItems(JMenu m, Object... x) { fillJMenu(m, x); } static public void addMenuItems(JPopupMenu m, Object... x) { fillJPopupMenu(m, x); } static public JLabel jLabel(String text) { return jlabel(text); } static public JLabel jLabel() { return jlabel(); } static public AutoCloseable tempInfoBox_noHide(String msg) { return tempDisposeWindow(infoBox_noHide(msg)); } static public void callF_thread(final Object f, final Object... args) { if (f != null) { startThread(new Runnable() { public void run() { try { callF(f, args); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(f, args);"; } }); } } static public boolean neq(Object a, Object b) { return !eq(a, b); } static public SingleThread awtCalcRegularly(JComponent component, int delay, int firstDelay, Object runnable) { final SingleThread thread = new SingleThread(); final Runnable r2 = addThreadInfoToRunnable(runnable); final Object info = _threadInfo(); installTimer(component, delay, firstDelay, new Runnable() { public void run() { if (!licensed()) return; _threadInheritInfo(info); thread.go(r2); } }); return thread; } static public SingleThread awtCalcRegularly(JFrame frame, int delay, int firstDelay, final Object runnable) { return awtCalcRegularly(getRootPane(frame), delay, firstDelay, runnable); } static public JLabel centeredLiveValueLabel(LiveValue lv) { return jCenteredLiveValueLabel(lv); } static public int parseHexChar(char c) { if (c >= '0' && c <= '9') return charDiff(c, '0'); if (c >= 'a' && c <= 'f') return charDiff(c, 'a') + 10; if (c >= 'A' && c <= 'F') return charDiff(c, 'A') + 10; return -1; } static public boolean all(Object pred, Iterable l) { if (l != null) for (Object o : l) if (!isTrue(callF(pred, o))) return false; return true; } static public boolean all(Iterable l, IF1 f) { if (l != null) for (A a : l) if (!f.get(a)) return false; return true; } static public boolean all(IF1 f, Iterable l) { return all(l, f); } static public boolean all(int[] l, IIntPred f) { if (l != null) for (int i : l) if (!f.get(i)) return false; return true; } static public void setTabTitle(JExtendedTabbedPane tabs, int idx, String title) { if (tabs != null && idx >= 0) { swing(() -> { if (idx < tabs.getTabCount()) tabs.setTitleAt(idx, title); }); } } 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 List classNamesInLoadedJigsawModules() { return concatMap(loadedJigsawModuleNames(), moduleName -> classNamesInJigsawModule(moduleName)); } static public void systemExit(int code) { System.exit(code); } static public > A bindComboBoxToVar(IVarWithNotify var, A cb) { if (var != null) { bindListenerToComponent(cb, var, (Runnable) () -> selectItem(cb, var.get())); onChange(cb, (Runnable) () -> var.set(getSelected(cb))); } return cb; } static public > A bindComboBoxToVar(A cb, IVarWithNotify var) { return bindComboBoxToVar(var, cb); } static public boolean isDeepContainedInDir_canonical(File f, File dir) { return nempty(nameRelativeToPhysicalSubdirectory(f, dir)); } static public IBWImage iBWImageFromFunction(IF2_IntInt_Double f, int w, int h) { return new IBWImage() { public int getWidth() { return w; } public int getHeight() { return h; } public float getFloatPixel(int x, int y) { return (float) f.get(x, y); } }; } static public ThreadLocal bindComboBoxToLiveValue_debug = new ThreadLocal(); static public A bindComboBoxToLiveValue(final A cb, IVarWithNotify lv) { boolean debug = isTrue(bindComboBoxToLiveValue_debug.get()); bindLiveValueListenerToComponent(cb, lv, new Runnable() { public void run() { try { selectItem(cb, lv.get()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "selectItem(cb, lv!)"; } }); onChange(cb, new Runnable() { public void run() { try { String s = getText(cb); if (debug) print("ComboBox: " + s); lv.set(s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = getText(cb); // also works on editable combo boxes\r\n if (debug)..."; } }); return cb; } static public boolean isLetterOrDigit(char c) { return Character.isLetterOrDigit(c); } 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 void onEnterInAllTextFields(JComponent c, Runnable action) { if (action == null) return; for (Component tf : allChildren(c)) onEnterIfTextField(tf, action); } static public void onEnterInAllTextFields(List c, Runnable action) { for (Object o : unnull(c)) if (o instanceof JComponent) onEnterInAllTextFields(((JComponent) o), action); } 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 Pt addPts(Pt a, Pt b) { return a == null ? b : b == null ? a : new Pt(a.x + b.x, a.y + b.y); } static public int countTabs(JExtendedTabbedPane tabs) { return tabCount(tabs); } static public int countTabs(JTabbedPane tabs) { return tabCount(tabs); } static public void printStackTrace_inPossiblyCancelledThread(Throwable e) { AutoCloseable __1 = tempUncancelThread(); try { System.out.println(getStackTrace_noRecord(e)); } finally { _close(__1); } } static public List collect(Iterable c, String field) { return collectField(c, field); } static public List collect(String field, Iterable c) { return collectField(c, field); } static public 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 String nullIfEmpty(String s) { return isEmpty(s) ? null : s; } static public Map nullIfEmpty(Map map) { return isEmpty(map) ? null : map; } static public List nullIfEmpty(List l) { return isEmpty(l) ? null : l; } static public Vector toVector(A[] array) { return new Vector(toList(array)); } static public Vector toVector(Collection l) { return l == null ? null : new Vector(l); } static public void disposePIFrame(Component c) { disposePossiblyInternalFrame(c); } static public void setLocation(Component c, int p_x, int p_y) { setLocation(c, pt(p_x, p_y)); } static public void setLocation(Component c, Pt p) { if (c != null) { swing(() -> { c.setLocation(p.x, p.y); }); } } static public String joinNempties(String sep, Object... strings) { return joinStrings(sep, strings); } static public String joinNempties(String sep, Iterable strings) { return joinStrings(sep, strings); } public static File mkdirsFor(File file) { return mkdirsForFile(file); } static public Class _run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } static public String indentStructureString(String s) { return indentStructureString(100, s); } static public String indentStructureString(int levels, String s) { if (s == null) return null; return new StructureStringIndenter().levels(levels).get(s); } static public void callFInNewThread(Object f, Object... args) { callF_thread(f, args); } static public A optCast(Class c, Object o) { return isInstance(c, o) ? (A) o : null; } static public String replacePlusWithSpace(String s) { return replace(s, '+', ' '); } static public ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal(); static public ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal(); static public byte[] loadBinaryPage(String url) { try { print("Loading " + url); return loadBinaryPage(loadPage_openConnection(new URL(url))); } catch (Exception __e) { throw rethrow(__e); } } static public byte[] loadBinaryPage(URLConnection con) { try { Map extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders); setHeaders(con); for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key)); return loadBinaryPage_noHeaders(con); } catch (Exception __e) { throw rethrow(__e); } } static public byte[] loadBinaryPage_noHeaders(URLConnection con) { try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); InputStream inputStream = con.getInputStream(); loadBinaryPage_responseHeaders.set(con.getHeaderFields()); long len = 0; try { len = con.getContentLength(); } catch (Throwable e) { printStackTrace(e); } int n = 0; while (true) { int ch = inputStream.read(); if (ch < 0) break; buf.write(ch); if (++n % 100000 == 0) println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded."); } inputStream.close(); return buf.toByteArray(); } catch (Exception __e) { throw rethrow(__e); } } static public String tb_mainServer_default = "https://code.botcompany.de:9898"; static public Object tb_mainServer_override; static public String tb_mainServer() { if (tb_mainServer_override != null) return (String) callF(tb_mainServer_override); return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default)); } static public File tb_mainServer_file() { return getProgramFile("#1001638", "mainserver.txt"); } static public boolean tb_mainServer_isDefault() { return eq(tb_mainServer(), tb_mainServer_default); } static public 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 boolean any(Object pred, Iterable l) { if (l != null) for (A a : l) if (isTrue(callF(pred, a))) return true; return false; } static public boolean any(IF1 pred, Iterable l) { if (l != null) for (A a : l) if (pred.get(a)) return true; return false; } static public boolean any(Iterable l, IF1 pred) { return any(pred, l); } static public boolean any(A[] l, IF1 pred) { if (l != null) for (A a : l) if (pred.get(a)) return true; return false; } static public boolean any(Iterable l) { if (l != null) for (Boolean a : l) if (isTrue(a)) return true; return false; } static public String microSymbol() { return "\u00B5"; } static public List getMenus(JMenuBar mb) { if (mb == null) return null; return countIteratorAsList(mb.getMenuCount(), i -> mb.getMenu(i)); } static public int[] emptyIntArray_a = new int[0]; static public int[] emptyIntArray() { return emptyIntArray_a; } static public void addMouseListener(Container c, MouseListener l) { if (c != null && l != null) { swing(() -> { c.addMouseListener(l); }); } } static public void addMouseListener(JComponent c, MouseListener l) { addMouseListener((Container) c, l); } static public int screenNrContaining(Pt p) { if (p == null) return -1; return indexOfFirst(allScreenBounds(), screen -> contains(screen, p)); } static public Point mouseLocation() { return getMouseLocation(); } 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 LinkedHashMap paramsToOrderedMap(Object... params) { return asLinkedHashMap(paramsToMap(params)); } static public HashMap> callMC_cache = new HashMap(); static public String callMC_key; static public Method callMC_value; static public Object callMC(String method, String[] arg) { return callMC(method, new Object[] { arg }); } static public Object callMC(String method, Object... args) { try { Method me; if (callMC_cache == null) callMC_cache = new HashMap(); synchronized (callMC_cache) { me = method == callMC_key ? callMC_value : null; } if (me != null) try { return invokeMethod(me, null, args); } catch (IllegalArgumentException e) { throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e); } List m; synchronized (callMC_cache) { m = callMC_cache.get(method); } if (m == null) { if (callMC_cache.isEmpty()) { callMC_makeCache(); m = callMC_cache.get(method); } if (m == null) throw fail("Method named " + method + " not found in main"); } int n = m.size(); if (n == 1) { me = m.get(0); synchronized (callMC_cache) { callMC_key = method; callMC_value = me; } try { return invokeMethod(me, null, args); } catch (IllegalArgumentException e) { throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e); } } for (int i = 0; i < n; i++) { me = m.get(i); if (call_checkArgs(me, args, false)) return invokeMethod(me, null, args); } throw fail("No method called " + method + " with arguments (" + joinWithComma(getClasses(args)) + ") found in main"); } catch (Exception __e) { throw rethrow(__e); } } static public void callMC_makeCache() { synchronized (callMC_cache) { callMC_cache.clear(); Class _c = (Class) mc(), c = _c; while (c != null) { for (Method m : c.getDeclaredMethods()) if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) { makeAccessible(m); multiMapPut(callMC_cache, m.getName(), m); } c = c.getSuperclass(); } } } static public JTextArea showTextWordWrapped(final String title, final String text) { return showWrappedText(title, text); } static public JTextArea showTextWordWrapped(Object text) { return showWrappedText(text); } static public boolean isInstance(Class type, Object arg) { return type.isInstance(arg); } static public File programFile(String name) { return prepareProgramFile(name); } static public File programFile(String progID, String name) { return prepareProgramFile(progID, name); } 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 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 void setInternalFrameContents(final Component c, final Object contents) { { swing(() -> { JInternalFrame frame = getInternalFrame(c); if (frame == null) return; frame.getContentPane().removeAll(); frame.getContentPane().setLayout(new BorderLayout()); if (contents != null) frame.getContentPane().add(wrap(contents)); revalidate(frame); }); } } static public List quoteAll(String[] l) { return quoteAll(asList(l)); } static public List quoteAll(Collection l) { List x = new ArrayList(); for (String s : l) x.add(quote(s)); return x; } static public String renderVars_stringifier(IStringifier stringifier, Object... params) { List l = new ArrayList(); int i = 0; if (odd(l(params))) { l.add(stringifier.toString(first(params))); ++i; } for (; i + 1 < l(params); i += 2) l.add(params[i] + "=" + stringifier.toString(params[i + 1])); return trim(joinWithComma(l)); } static public A jMinWidthAtLeast(int w, final A c) { if (c == null) return null; return swing(new F0() { public A get() { try { Dimension size = c.getMinimumSize(); Dimension d = new Dimension(max(w, size.width), size.height); c.setMinimumSize(d); return jPreferWidth(d.width, c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Dimension size = c.getMinimumSize();\r\n Dimension d = new Dimension(max(w, ..."; } }); } static public List valuesList(Map map) { return cloneListSynchronizingOn(values(map), map); } static public List valuesList(MultiMap mm) { return mm == null ? emptyList() : concatLists(values(mm.data)); } static public int componentCount(Container c) { return numberOfChildren(c); } static public List nonNulls(Iterable l) { return withoutNulls(l); } static public List nonNulls(A[] l) { return withoutNulls(l); } static public Map nonNulls(Map map) { return withoutNulls(map); } static public List nonNulls(Iterable l, IF1 f) { return mapNonNulls(l, f); } static public void setProgressBarTotal(JProgressBar bar, int total) { swingCall(bar, "setMaximum", total); } static public JScrollPane setScrollPaneBackground(Color c, JScrollPane sp) { if (sp != null && c != null) { swing(() -> { sp.getViewport().setBackground(c); }); } return sp; } static public JPanel makeForm_customArrangement(F1, JPanel> arrange, final Object... _parts) { return makeForm_customArrangement(null, arrange, _parts); } static public JPanel makeForm_customArrangement(Boolean internalFrame, F1, JPanel> arrange, final Object... _parts) { return swing(new F0() { public JPanel get() { try { return callF(arrange, showForm_arrange1(showForm_makeComponents(internalFrame, _parts))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return callF(arrange,\r\n showForm_arrange1(showForm_makeComponents(intern..."; } }); } static public Object dm_getModule(Object moduleOrID) { if (moduleOrID == null || eq(moduleOrID, "")) return null; if (isString(moduleOrID) && isIdentifier(((String) moduleOrID))) return dm_getService(((String) moduleOrID)); if (isStringOrIntOrLong(moduleOrID)) return dm_callOS("getDynModuleByID", str(moduleOrID)); return dm_resolveModule(moduleOrID); } static public boolean containsInstance(Iterable i, Class c) { if (i != null) for (Object o : i) if (isInstanceX(c, o)) return true; return false; } static public void deleteConcept(long id) { db_mainConcepts().deleteConcept(id); } static public void deleteConcept(Concepts concepts, long id) { concepts.deleteConcept(id); } static public void deleteConcept(Concept c) { if (c != null) c.delete(); } static public void deleteConcept(Concept.Ref ref) { if (ref != null) deleteConcept(ref.get()); } static public void assertInstanceOf(Class type, Object o) { assertIsInstance(type, o); } static public void assertInstanceOf(Object o, Class type) { assertInstanceOf(type, o); } static public boolean deleteFileVerbose(File file) { if (file != null && file.delete()) { print("Deleted " + f2s(file)); return true; } return false; } static public void setEnclosingViewPosition(Component c, int p_x, int p_y) { setEnclosingViewPosition(c, pt(p_x, p_y)); } static public void setEnclosingViewPosition(Component c, Pt p) { setEnclosingViewPosition(c, toPoint(p)); } static public void setEnclosingViewPosition(Component c, Point p) { if (p == null) return; JScrollPane sp = enclosingScrollPane(c); if (sp != null) { swing(() -> { sp.getViewport().setViewPosition(p); }); } } static public boolean isCIMap(Map m) { return m instanceof TreeMap && ((TreeMap) m).comparator() == caseInsensitiveComparator(); } static public boolean hasMethodNamed(Object obj, String method) { if (obj == null) return false; if (obj instanceof Class) return hasMethodNamed((Class) obj, method); return hasMethodNamed(obj.getClass(), method); } static public boolean hasMethodNamed(Class c, String method) { if (c == null) return false; return getMethodCache(c).cache.containsKey(method); } static public String yesNo_short(boolean b) { return b ? "yes" : "no"; } static public boolean isGrandChildOf(Component a, Component b) { return swing(() -> { if (a == null || b == null) return false; if (a == b) return true; var _a_1 = a; while ((_a_1 = getParent(_a_1)) != null) if (_a_1 == b) return true; return false; }); } static public Component addToWindowWithMargin(final Component c, final Component toAdd) { if (toAdd != null) addToWindowAndGrow(c, withMargin(toAdd)); return c; } static public List scoredSearch_prepare(String query) { return map(__99 -> replacePlusWithSpace(__99), splitAtSpace(query)); } static public boolean loadBufferedImage_useImageCache = true; static public BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try { ping(); if (snippetIDOrURLOrFile == null) return null; if (isURL(snippetIDOrURLOrFile)) return imageIO_readURL(snippetIDOrURLOrFile); if (isSnippetID(snippetIDOrURLOrFile)) { String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile); IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return loadBufferedImage(rl.loadLibrary(snippetID)); File dir = imageSnippetsCacheDir(); if (loadBufferedImage_useImageCache) { dir.mkdirs(); File file = new File(dir, snippetID + ".png"); if (file.exists() && file.length() != 0) try { return ImageIO.read(file); } catch (Throwable e) { e.printStackTrace(); } } String imageURL = snippetImageURL_http(snippetID); print("Loading image: " + imageURL); BufferedImage image = imageIO_readURL(imageURL); if (loadBufferedImage_useImageCache) { File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis()); ImageIO.write(image, "png", tempFile); tempFile.renameTo(new File(dir, snippetID + ".png")); } return image; } else return loadBufferedImage(new File(snippetIDOrURLOrFile)); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedImage loadBufferedImage(File file) { return loadBufferedImageFile(file); } static public ThreadLocal imageGraphics_antiAlias = new ThreadLocal(); static public Graphics2D imageGraphics(BufferedImage img) { return !isFalse(imageGraphics_antiAlias.get()) ? antiAliasGraphics(img) : createGraphics(img); } static public JSplitPane jvsplit(Swingable n, Swingable s) { return jvsplit(n, toComponent(s)); } static public JSplitPane jvsplit(Swingable n, Component s) { return jvsplit(toComponent(n), s); } static public JSplitPane jvsplit(Component n, Swingable s) { return jvsplit(n, toComponent(s)); } static public JSplitPane jvsplit(Component n, Component s) { return jvsplit(n, s, 0.5); } static public JSplitPane jvsplit(Swingable n, Swingable s, double splitPoint) { return jvsplit(n, toComponent(s), splitPoint); } static public JSplitPane jvsplit(Swingable n, Component s, double splitPoint) { return jvsplit(toComponent(n), s, splitPoint); } static public JSplitPane jvsplit(Component n, Swingable s, double splitPoint) { return jvsplit(n, toComponent(s), splitPoint); } static public JSplitPane jvsplit(Component n, Component s, double splitPoint) { return jvsplit(n, s, splitPoint, 0); } static public JSplitPane jvsplit(Swingable n, Swingable s, double splitPoint, int delay) { return jvsplit(n, toComponent(s), splitPoint, delay); } static public JSplitPane jvsplit(Swingable n, Component s, double splitPoint, int delay) { return jvsplit(toComponent(n), s, splitPoint, delay); } static public JSplitPane jvsplit(Component n, Swingable s, double splitPoint, int delay) { return jvsplit(n, toComponent(s), splitPoint, delay); } static public JSplitPane jvsplit(Component n, Component s, double splitPoint, int delay) { return setSplitPaneOnFirstShowing(swing(() -> new JSplitPane(JSplitPane.VERTICAL_SPLIT, wrap(n), wrap(s))), splitPoint, delay); } static public JSplitPane jvsplit(double splitPoint, Swingable n, Swingable s) { return jvsplit(splitPoint, n, toComponent(s)); } static public JSplitPane jvsplit(double splitPoint, Swingable n, Component s) { return jvsplit(splitPoint, toComponent(n), s); } static public JSplitPane jvsplit(double splitPoint, Component n, Swingable s) { return jvsplit(splitPoint, n, toComponent(s)); } static public JSplitPane jvsplit(double splitPoint, Component n, Component s) { return jvsplit(splitPoint, 0, n, s); } static public JSplitPane jvsplit(double splitPoint, int delay, Swingable n, Swingable s) { return jvsplit(splitPoint, delay, n, toComponent(s)); } static public JSplitPane jvsplit(double splitPoint, int delay, Swingable n, Component s) { return jvsplit(splitPoint, delay, toComponent(n), s); } static public JSplitPane jvsplit(double splitPoint, int delay, Component n, Swingable s) { return jvsplit(splitPoint, delay, n, toComponent(s)); } static public JSplitPane jvsplit(double splitPoint, int delay, Component n, Component s) { return jvsplit(n, s, splitPoint, delay); } static public LayoutManager layoutManagerFromFunction(final Object layouter) { if (layouter instanceof LayoutManager) return ((LayoutManager) layouter); return new AbstractLayoutManager() { public void layoutContainer(Container parent) { Object size = pcallF(layouter, parent); if (size instanceof Dimension) preferredSize = (Dimension) size; else if (size instanceof Pair) { preferredSize = (Dimension) ((Pair) size).a; minimumSize = (Dimension) ((Pair) size).b; } } }; } static public int gzInputStream_defaultBufferSize = 65536; static public GZIPInputStream gzInputStream(File f) { try { return gzInputStream(new FileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } static public GZIPInputStream gzInputStream(File f, int bufferSize) { try { return gzInputStream(new FileInputStream(f), bufferSize); } catch (Exception __e) { throw rethrow(__e); } } static public GZIPInputStream gzInputStream(InputStream in) { return gzInputStream(in, gzInputStream_defaultBufferSize); } static public GZIPInputStream gzInputStream(InputStream in, int bufferSize) { try { return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in); } catch (Exception __e) { throw rethrow(__e); } } static public String yesNoShort(boolean b) { return yesNo_short(b); } static public Pair entryToPair(Map.Entry e) { return mapEntryToPair(e); } static public Map syncCIMap() { return (Map) synchroMap(caseInsensitiveMap()); } static public void lockOrFail(Lock lock, long timeout) { try { ping(); vmBus_send("locking", lock, "thread", currentThread()); if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) { String s = "Couldn't acquire lock after " + timeout + " ms."; if (lock instanceof ReentrantLock) { ReentrantLock l = (ReentrantLock) lock; s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner"); } throw fail(s); } vmBus_send("locked", lock, "thread", currentThread()); ping(); } catch (Exception __e) { throw rethrow(__e); } } static public CharSequence subCharSequence(CharSequence s, int x) { return subCharSequence(s, x, s == null ? 0 : s.length()); } static public CharSequence subCharSequence(CharSequence s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; if (x >= s.length()) return ""; if (y < x) y = x; if (y > s.length()) y = s.length(); return s.subSequence(x, y); } static public void centerWindowWithin(Window w, Rect r) { if (w != null) { swing(() -> { w.setLocation(r.x + (r.w - w.getWidth()) / 2, r.y + (r.h - w.getHeight()) / 2); }); } } static public Runnable toRunnable(final Object o) { if (o == null) return null; if (o instanceof Runnable) return (Runnable) o; if (o instanceof String) throw fail("callF_legacy"); return new Runnable() { public void run() { try { callF(o); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; } }; } static public Color colorWithAlpha(Color c, double alpha) { return new Color(c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, (float) clampZeroToOne(alpha)); } static public Color colorWithAlpha(double alpha, Color c) { return colorWithAlpha(c, alpha); } static public BWImage toBWImage(RGBImage img) { return toBW(img); } static public BWImage toBWImage(BufferedImage img) { return img == null ? null : new BWImage(img); } static public BWImage toBWImage(MakesBufferedImage img) { if (img == null) return null; if (img instanceof BWImage) return ((BWImage) img); return new BWImage(toBufferedImage(img)); } static public void setCaret(final JTextComponent c, final int pos) { if (c != null) { swing(() -> { c.setCaretPosition(pos); }); } } static public TitledBorder jRaisedSectionBorder(String title) { return swing(() -> { Border border = BorderFactory.createBevelBorder(BevelBorder.RAISED); return BorderFactory.createTitledBorder(border, title); }); } static public String structForUser(Object o) { return structureForUser(o); } static public String structForUser(Object o, structure_Data data) { return structureForUser(o, data); } static public boolean isInteger(String s) { int n = l(s); if (n == 0) return false; int i = 0; if (s.charAt(0) == '-') if (++i >= n) return false; while (i < n) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } static public void setSectionTitle(JComponent c, String title) { swing(() -> { var _c_1 = c; while (_c_1 != null) { var b = _c_1.getBorder(); if (b != null) { if (b instanceof javax.swing.border.TitledBorder) { ((javax.swing.border.TitledBorder) b).setTitle(title); revalidate(_c_1); return; } } if (_c_1.getParent() instanceof JComponent) _c_1 = (JComponent) _c_1.getParent(); else break; } }); } static public Color white() { return Color.white; } static public void makeTableUneditable(JTable table) { for (int c = 0; c < table.getColumnCount(); c++) { Class col_class = table.getColumnClass(c); table.setDefaultEditor(col_class, null); } } static public ThreadLocal dataToTable_useStruct = threadLocalWithDefault(true); static public void dataToTable_dynSet(List l, int i, Object s) { while (i >= l.size()) l.add(""); l.set(i, s); } static public List dataToTable_makeRow(Object x, List cols) { if (instanceOf(x, "DynamicObject")) x = get_raw(x, "fieldValues"); if (x instanceof Map) { Map m = (Map) x; List row = new ArrayList(); for (Object _field : keysWithoutHidden(m)) { String field = (String) _field; Object value = m.get(field); int col = cols.indexOf(field); if (col < 0) { cols.add(field); col = cols.size() - 1; } dataToTable_dynSet(row, col, dataToTable_wrapValue(value)); } return row; } if (x instanceof List) return allToString((List) x); return litlist(structureOrText(x)); } static public Object dataToTable_wrapValue(Object o) { if (o instanceof BufferedImage) return o; if (o instanceof MakesBufferedImage) return ((MakesBufferedImage) o).getBufferedImage(); if (o instanceof RGBImage) return o; if (o instanceof Boolean) return o; return dataToTable_useStruct.get() ? structureOrTextForUser(o) : strOrNull(o); } static public A syncGet(List l, int idx) { if (l == null || idx < 0) return null; synchronized (l) { return idx < l(l) ? l.get(idx) : null; } } static public B syncGet(Map map, A a) { if (map == null) return null; synchronized (map) { return map.get(a); } } static public List mapLines(String text, F1 f) { return mapLines(f, text); } static public List mapLines(F1 f, String text) { return mapLines(f1ToIF1(f), text); } static public List mapLines(String text, IF1 f) { return mapLines(f, text); } static public List mapLines(IF1 f, String text) { return map(f, lines(text)); } 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 void failIfOddCount(Object... list) { if (odd(l(list))) throw fail("Odd list size: " + list); } static public DoubleRect doubleRectFromPoints(double x1, double y1, double x2, double y2) { return new DoubleRect(x1, y1, x2 - x1, y2 - y1); } 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 void onFrameClose(Component c, final Runnable r) { JFrame f = getFrame(c); if (f != null) f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { try { r.run(); } catch (Throwable __e) { messageBox(__e); } } }); } static public RootPaneContainer getPossiblyInternalFrame(Component c) { JInternalFrame f = getInternalFrame(c); if (f != null) return f; return optCast(RootPaneContainer.class, getWindow(c)); } static public Class hotwireCoreSpecialMainClass(String mainClassName, List files) { try { JavaXClassLoader classLoader = hotwire_makeClassLoader(files); Class theClass = classLoader.loadClass(mainClassName); setOpt(theClass, "__javax", getJavaX()); if (getOpt(theClass, "programID") == null) setOpt(theClass, "programID", "#3999999"); if (!_inCore()) hotwire_copyOver(theClass); return theClass; } catch (Exception __e) { throw rethrow(__e); } } static public void scrollTableDownNow(final JTable table) { if (table != null) { swing(() -> { table.scrollRectToVisible(table.getCellRect(table.getRowCount() - 1, 0, true)); }); } } 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 TreeMap ciMap() { return caseInsensitiveMap(); } static public String spaces(int n) { return rep(' ', n); } static public boolean isExtendedStateNormal(JFrame f) { return f != null && swing(() -> f.getExtendedState() == JFrame.NORMAL); } static public List sortedIgnoreCase(Collection c) { List l = cloneList(c); Collections.sort(l, caseInsensitiveComparator()); return l; } static volatile public boolean muricaPassword_pretendNotAuthed = false; static public String muricaPassword() { if (muricaPassword_pretendNotAuthed) return null; return trim(loadTextFile(muricaPasswordFile())); } static public String formatDoubleX(double d, int digits) { return formatDoubleFull(d, digits); } static public long ptToLong(Pt p) { return p == null ? -1 : intPairToLong(p.x, p.y); } static public long ptToLong(int x, int y) { return intPairToLong(x, y); } static public long now_virtualTime; static public long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } static public BufferedImage img_addBorder(BufferedImage img, Color color, int border) { int top = border, bottom = border, left = border, right = border; int w = img.getWidth(), h = img.getHeight(); BufferedImage img2 = createBufferedImage(left + w + right, top + h + bottom, color); Graphics2D g = img2.createGraphics(); g.drawImage(img, left, top, null); g.dispose(); return img2; } static public File getProgramFile(String progID, String fileName) { if (new File(fileName).isAbsolute()) return new File(fileName); return new File(getProgramDir(progID), fileName); } static public File getProgramFile(String fileName) { return getProgramFile(getProgramID(), fileName); } static public void growWindowSouth(Component c, final int howMuch) { final Window w = getWindow(c); if (w != null) { swing(() -> { Rectangle r = w.getBounds(); w.setBounds(r.x, r.y, r.width, r.height + howMuch); }); } } static public A bindJLabelToTransformedLiveValue(IF1 f, A label, LiveValue lv) { bindLiveValueListenerToComponent(label, lv, () -> { setText(label, strOrNull(f.get(lv.get()))); }); return label; } static public void fillTableWithStrings(final JTable table, List> rows, List colNames) { fillTableWithStrings(table, rows, toStringArray(colNames)); } static public void fillTableWithStrings(final JTable table, List> rows, String... colNames) { final DefaultTableModel model = fillTableWithStrings_makeModel(rows, colNames); swingNowOrLater(new Runnable() { public void run() { try { setTableModel(table, model); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setTableModel(table, model);"; } }); } static public DefaultTableModel fillTableWithStrings_makeModel(List> rows, String... colNames) { Object[][] data = new Object[rows.size()][]; int w = 0; for (int i = 0; i < rows.size(); i++) { List l = rows.get(i); Object[] r = new Object[l.size()]; for (int j = 0; j < l.size(); j++) r[j] = l.get(j); data[i] = r; w = Math.max(w, l.size()); } Object[] columnNames = new Object[w]; for (int i = 0; i < w; i++) columnNames[i] = i < l(colNames) ? colNames[i] : "?"; return new DefaultTableModel(data, columnNames); } static public ActionListener actionListenerInNewThread(final Object runnable) { return actionListenerInNewThread(runnable, null); } static public ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) { if (runnable instanceof ActionListener) return (ActionListener) runnable; return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { startThread("Action Listener", new Runnable() { public void run() { try { AutoCloseable __1 = holdInstance(instanceToHold); try { callF(runnable); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __1 = holdInstance(instanceToHold); try {\r\n callF(runnable..."; } }); } catch (Throwable __e) { messageBox(__e); } } }; } static public IterableIterator> iterateWithIndex(Iterable l) { return iterateListWithIndex(l); } static public IterableIterator> iterateWithIndex(A[] l) { return iterateWithIndex(asVirtualList(l)); } static public boolean eqicOneOf(String s, String... l) { for (String x : l) if (eqic(s, x)) return true; return false; } static public boolean possibleMD5(String s) { return isMD5(s); } static public void _addAll(Collection c, Iterable b) { addAll(c, b); } static public boolean _addAll(Collection c, Collection b) { return addAll(c, b); } static public boolean _addAll(Collection c, B... b) { return addAll(c, b); } static public JTabbedPane scrollingTabs(JTabbedPane pane) { if (pane != null) { swing(() -> { pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); }); } return pane; } static volatile public PersistableThrowable lastException_lastException; static public PersistableThrowable lastException() { return lastException_lastException; } static public void lastException(Throwable e) { lastException_lastException = persistableThrowable(e); } static public JTabbedPane fillJTabs(final JTabbedPane tabs, final Object... _x) { if (tabs == null) return null; clearTabs(tabs); Object[] x = flattenArray2(_x); int idx = 0; if (get(x, 0) instanceof Integer) { idx = asInt(get(x, 0)); x = dropFirst(x); if (empty(x)) { x = arrayrep(null, idx); idx = 0; } } int n = 0; for (int i = 0; i < l(x); i++) { ++n; Object o = x[i]; if (isComponentOrSwingable(o)) addTab(tabs, "Tab " + n, wrap(o)); else { String toolTip = ""; if (o instanceof WithToolTip) { toolTip = ((WithToolTip) o).toolTip(); o = ((WithToolTip) o).get(); } String name = str(or(o, "Tab " + n)); Component c; if (isComponentOrSwingable(get(x, i + 1))) c = wrap(get(x, ++i)); else c = new JPanel(); addTabWithToolTip(tabs, name, toolTip, wrap(c)); } } if (idx != 0) tabs.setSelectedIndex(min(tabs.getTabCount() - 1, idx)); return tabs; } static public String getComputerID_quick() { return computerID(); } static public long sleepUntilSys(long sysTime) { long time = sysTime - sysNow(); sleep(time); return time; } static public void addButtonsToWindow(Component c, Object... buttonParams) { addToWindowWithMargin(c, jcenteredbuttons(buttonParams)); } static public boolean isStringStartingWith(Object o, String prefix) { return o instanceof String && ((String) o).startsWith(prefix); } static public IterableIterator lines_iterator(final String s) { if (s == null) return emptyIterableIterator(); return iteratorFromFunction(new F0() { public int start = 0; public String get() { int i = toLines_nextLineBreak(s, start); if (i < 0) { String toReturn = s.length() > start ? s.substring(start) : null; start = s.length(); return toReturn; } String toReturn = 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 toReturn; } }); } static public URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) { con.setConnectTimeout(toInt(timeout)); con.setReadTimeout(toInt(timeout)); if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout) print("Warning: Timeouts not set by JDK."); return con; } static public IResourceLoader vm_getResourceLoader() { return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader")); } static public JPanel westAndCenterWithMargin(Component w, Component c) { return westAndCenter(withRightMargin(w), c); } static public JPanel westAndCenterWithMargin(int margin, Component w, Component c) { return westAndCenter(withRightMargin(margin, w), c); } static public 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 A optPar(ThreadLocal tl, A defaultValue) { A a = tl.get(); if (a != null) { tl.set(null); return a; } return defaultValue; } static public A optPar(ThreadLocal tl) { return optPar(tl, null); } static public Object optPar(Object[] params, String name) { return optParam(params, name); } static public Object optPar(String name, Object[] params) { return optParam(params, name); } static public Object optPar(String name, Map params) { return optParam(name, params); } static public A optPar(Object[] params, String name, A defaultValue) { return optParam(params, name, defaultValue); } static public A optPar(String name, Object[] params, A defaultValue) { return optParam(params, name, defaultValue); } static public 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 ThreadLocal doPost_silently = new ThreadLocal(); static public ThreadLocal doPost_timeout = new ThreadLocal(); static public ThreadLocal> doPost_extraHeaders = new ThreadLocal(); static public String doPost(String url, Map urlParameters) { return doPost(urlParameters, url); } static public String doPost(Map urlParameters, String url) { return doPost(makePostData(urlParameters), url); } static public String doPost(String urlParameters, String url) { try { URL _url = new URL(url); ping(); return doPost(urlParameters, _url.openConnection(), _url); } catch (Exception __e) { throw rethrow(__e); } } static public String doPost(String urlParameters, URLConnection conn, URL url) { try { boolean silently = isTrue(optParam(doPost_silently)); Long timeout = optParam(doPost_timeout); Map extraHeaders = optPar(doPost_extraHeaders); setHeaders(conn); for (String key : keys(extraHeaders)) { conn.setRequestProperty(key, extraHeaders.get(key)); } int l = lUtf8(urlParameters); if (!silently) print("Sending POST request: " + hideCredentials(url) + " (" + l + " bytes)"); if (timeout != null) setURLConnectionTimeouts(conn, timeout); ((HttpURLConnection) conn).setRequestMethod("POST"); ((HttpURLConnection) conn).setDoOutput(true); ((HttpURLConnection) conn).setFixedLengthStreamingMode(l); OutputStreamWriter writer = new OutputStreamWriter(((HttpURLConnection) conn).getOutputStream(), "UTF-8"); writer.write(urlParameters); writer.flush(); String contents = loadPage_utf8(((HttpURLConnection) conn), url, false); writer.close(); return contents; } catch (Exception __e) { throw rethrow(__e); } } static public BWIntegralImage bwIntegralImage_withMeta(BufferedImage img) { return bwIntegralImage_withMeta(img, null); } static public BWIntegralImage bwIntegralImage_withMeta(BufferedImage img, Decolorizer decolorizer) { return setMetaSrc(bwIntegralImage(img, decolorizer), img); } static public BWIntegralImage bwIntegralImage_withMeta(BWImage img) { return setMetaSrc(bwIntegralImage(img), img); } static public List colorPaletteByBits(int bits) { return map(outerProduct(rep(3, countIteratorAsList(0, 1 << bits, i -> iround(i * 255.0 / (1 << bits - 1))))), rgb -> new Color(first(rgb), second(rgb), third(rgb))); } static public boolean showTable_searcher = true; static public JTable showTable(Object data) { return dataToTable_uneditable(data); } static public JTable showTable(String title, Object data) { return showTable(data, title); } static public JTable showTable(Object data, String title) { return dataToTable_uneditable(data, title); } static public JTable showTable(JTable table, Object data) { return showTable(table, data, autoFrameTitle()); } static public JTable showTable(Object data, JTable table) { return showTable(table, data); } static public JTable showTable(JTable table, Object data, String title) { if (table == null) table = showTable(data, title); else { setFrameTitle(table, title); dataToTable_uneditable(table, data); } return table; } static public JTable showTable() { return showTable(new ArrayList>(), new ArrayList()); } static public JTable showTable(String title) { return showTable(new ArrayList>(), new ArrayList(), title); } static public JTable showTable(List> rows, List cols) { return showTable(rows, cols, autoFrameTitle()); } static public JTable showTable(List> rows, List cols, String title) { JTable tbl = sexyTable(); fillTableWithStrings(tbl, rows, cols); showFrame(title, tbl); return tbl; } static public File userDir_oneOf(String... names) { return oneOfTheFilesInDir(userDir(), names); } static public boolean showTitledForm_blocking(String title, Object... _parts) { assertNotOnAWTThread(); final Var var = new Var(); onFrameClose(showFormTitled(title, arrayPlus(_parts, new Runnable() { public void run() { try { var.set(true); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var.set(true)"; } })), new Runnable() { public void run() { try { if (!var.has()) var.set(false); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!var.has()) var.set(false)"; } }); waitUntilVarSet(var); return var.get(); } static public InputStream urlConnection_getInputStream(URLConnection con) throws IOException { return con.getInputStream(); } static public String stackTraceToString(StackTraceElement[] st) { return lines(st); } static public String stackTraceToString(Throwable e) { return getStackTrace_noRecord(e); } static public Object getTableCell(JTable tbl, int row, int col) { if (row >= 0 && row < tbl.getModel().getRowCount()) return tbl.getModel().getValueAt(row, col); return null; } static public BWIntegralImage bwIntegralImage(BufferedImage img) { return bwIntegralImage(img, null); } static public BWIntegralImage bwIntegralImage(BufferedImage img, Decolorizer decolorizer) { return img == null ? null : new BWIntegralImage(img, decolorizer); } static public BWIntegralImage bwIntegralImage(BWImage img) { return img == null ? null : new BWIntegralImage(img); } static public BWIntegralImage bwIntegralImage(IBWImage img) { return img == null ? null : new BWIntegralImage(img); } 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 byte clampToUByte(long l) { return (byte) clamp(l, 0, 255); } static public String theAGIBlueDomain() { return "agi.blue"; } static public void clearTabs(final JTabbedPane tabs) { if (tabs != null) { swing(() -> { tabs.removeAll(); }); } } static public File javaxCachesDir_dir; static public File javaxCachesDir() { return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches"); } static public File javaxCachesDir(String sub) { return newFile(javaxCachesDir(), sub); } static public List getClassNames(Collection l) { List out = new ArrayList(); if (l != null) for (Object o : l) out.add(o == null ? null : getClassName(o)); return out; } static public CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) { class IFF2 extends CloseableIterableIterator { public A a; public boolean done = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } public void getNext() { if (done || a != null) return; a = f.get(); done = a == null; } public void close() throws Exception { if (closeable != null) closeable.close(); } } ; return new IFF2(); } static public Font deriveFont(Font font, float size) { return font == null ? null : font.deriveFont(size); } 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 WeakReference newWeakReference(A a) { return a == null ? null : new WeakReference(a); } static public A setMargin(final int w, final int h, final A a) { if (a != null) { swing(() -> { a.setBorder(BorderFactory.createEmptyBorder(h, w, h, w)); }); } return a; } static public A setMargin(int w, A a) { return setMargin(w, w, a); } static public int boolToInt(boolean b) { return b ? 1 : 0; } static public Map humanizeKeys(Map map) { return mapKeys(__100 -> humanizeFormLabel(__100), map); } static public boolean sameSnippetID(String a, String b) { if (!isSnippetID(a) || !isSnippetID(b)) return false; return parseSnippetID(a) == parseSnippetID(b); } static public int indexOfIgnoreCase(List a, String b) { return indexOfIgnoreCase(a, b, 0); } static public int indexOfIgnoreCase(List a, String b, int i) { int n = a == null ? 0 : a.size(); for (; i < n; i++) if (eqic(a.get(i), b)) return i; return -1; } static public int indexOfIgnoreCase(String[] a, String b) { return indexOfIgnoreCase(a, b, 0); } static public int indexOfIgnoreCase(String[] a, String b, int i) { int n = a == null ? 0 : a.length; for (; i < n; i++) if (eqic(a[i], b)) return i; return -1; } static public int indexOfIgnoreCase(String a, String b) { return indexOfIgnoreCase_manual(a, b); } static public int indexOfIgnoreCase(String a, String b, int i) { return indexOfIgnoreCase_manual(a, b, i); } static public Class getClass(String name) { return _getClass(name); } static public Class getClass(Object o) { return _getClass(o); } static public Class getClass(Object realm, String name) { return _getClass(realm, name); } static public void fillTableWithData(final JTable table, List rows, List colNames) { fillTableWithData(table, rows, toStringArray(colNames)); } static public void fillTableWithData(final JTable table, List rows, String... colNames) { final DefaultTableModel model = fillTableWithData_makeModel(rows, colNames); setTableModel(table, model); } static public DefaultTableModel fillTableWithData_makeModel(List rows, String... colNames) { Pair p = fillTableWithData_makeData(rows, colNames); return new DefaultTableModel(p.a, p.b) { public Class getColumnClass(int column) { return or(_getClass(getValueAt(0, column)), String.class); } public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } }; } 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 void printRunningThreads() { List threads = valuesList(runnableThreadsWithRenderedStackTraces_withoutSystemThreads()); for (int i = 0; i < l(threads); i++) print("\n[Thread " + (i + 1) + "/" + l(threads) + "] " + threads.get(i)); } static public double scoredSearch_scoreWeighted2(Collection> l, List words) { double score = 0; if (l != null) for (Pair __0 : l) { String s = pairA(__0); double weight = pairB(__0); score += scoredSearch_score(s, words) * weight; } return score; } static public Random defaultRandomizer() { return defaultRandomGenerator(); } static public JLabel jcenteredlabel(String text) { return jcenteredLabel(text); } static public JLabel jcenteredlabel() { return jcenteredLabel(); } static public boolean anyValueContainsIgnoreCase(Map map, String pat) { for (Object val : values(map)) if (val instanceof String && containsIgnoreCase((String) val, pat)) return true; return false; } 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 List> rawTableData(JTable t) { int n = tableRows(t); List l = new ArrayList(); for (int i = 0; i < n; i++) l.add(rawTableLineAsMap(t, i)); return l; } static public TreeMap caseInsensitiveMap() { return new TreeMap(caseInsensitiveComparator()); } 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 List filterConcepts(List list, Object... params) { if (empty(params)) return list; List l = new ArrayList(); for (A x : list) if (checkConceptFields(x, params)) l.add(x); return l; } static public Set syncIdentityHashSet() { return (Set) synchronizedSet(identityHashSet()); } static public void mapPut2(Map map, A key, B value) { if (map != null && key != null) if (value != null) map.put(key, value); else map.remove(key); } static public int screenNrOfWindow(Window w) { if (w == null) return -1; Rect bounds = boundsAsRect(w); return indexOfMax(allScreenBounds(), screen -> area(intersectRects(bounds, screen))); } static public Object dm_resolveModule(Object moduleOrStem) { return dm_callOS("resolveModule", moduleOrStem); } static public boolean isMain() { return isMainProgram(); } static public boolean containsKey(Map map, A key) { return map != null && map.containsKey(key); } static public String addFileSep(String path) { return addSuffix(path, fileSep()); } static public boolean containsATextArea(Component c) { return childOfType(c, JTextArea.class) != null; } 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 Matcher regexpMatcher(String pat, String s) { return compileRegexp(pat).matcher(unnull(s)); } static public Matcher regexpMatcher(java.util.regex.Pattern pat, String s) { return pat.matcher(unnull(s)); } static public Component verticalStrut(int height) { return Box.createVerticalStrut(height); } static public boolean containsTabNameWithoutTrailingCount(JTabbedPane tabs, String name) { return indexOfTabNameWithoutTrailingCount(tabs, name) >= 0; } static public String errorIconID() { return "#1101390"; } static public Object collectionMutex(List l) { return l; } static public Object collectionMutex(Object o) { if (o instanceof List) return o; String c = className(o); return o; } static public boolean confirmOKCancel(final Component owner, final String msg) { return isTrue(swingAndWait(new F0() { public Object get() { try { return JOptionPane.showConfirmDialog(owner, msg, "JavaX", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return JOptionPane.showConfirmDialog(owner,\r\n msg, \"JavaX\", JOptionPane...."; } })); } static public boolean confirmOKCancel(String msg) { return confirmOKCancel(null, msg); } 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 String structureOrTextForUser(Object o) { return o == null ? "" : o instanceof String ? (String) o : structureForUser(o); } static public JTable dataToTable_uneditable(Object data, final JTable table) { return dataToTable_uneditable(table, data); } static public JTable dataToTable_uneditable(final JTable table, final Object data) { if (table != null) { swing(() -> { dataToTable(table, data, true); makeTableUneditable(table); }); } return table; } static public JTable dataToTable_uneditable(final Object data) { return dataToTable_uneditable(showTable(), data); } static public JTable dataToTable_uneditable(Object data, String title) { return dataToTable_uneditable(showTable(title), data); } static public BufferedImageWithMeta cloneBufferedImageWithMeta(BufferedImage img) { if (img == null) return null; if (img instanceof BufferedImageWithMeta) return ((BufferedImageWithMeta) img); Hashtable properties = new Hashtable(); var names = img.getPropertyNames(); if (names != null) for (var key : names) properties.put(key, img.getProperty(key)); if (!properties.containsKey("meta")) properties.put("meta", new Meta()); var cm = img.getColorModel(); var img2 = new BufferedImageWithMeta(cm, img.getRaster(), cm.hasAlpha() && cm.isAlphaPremultiplied(), properties); assertNotNull(toIMeta(img2)); return img2; } static public int asInt(Object o) { return toInt(o); } static public B mapGet(Map map, A a) { return map == null || a == null ? null : map.get(a); } static public B mapGet(A a, Map map) { return map == null || a == null ? null : map.get(a); } public static long parseSnippetID(String snippetID) { long id = Long.parseLong(shortenSnippetID(snippetID)); if (id == 0) throw fail("0 is not a snippet ID"); return id; } static public Rect rightScreenBounds() { return second(allScreenBounds()); } 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 Object[] mapToArray(Map map) { return mapToObjectArray(map); } static public Object[] mapToArray(Object f, Collection l) { return mapToObjectArray(f, l); } static public Object[] mapToArray(Object f, Object[] l) { return mapToObjectArray(f, l); } static public Object[] mapToArray(Collection l, IF1 f) { return mapToObjectArray(l, f); } static public Object[] mapToArray(A[] l, IF1 f) { return mapToObjectArray(f, l); } static public Object[] mapToArray(IF1 f, A[] l) { return mapToObjectArray(f, l); } static public boolean containsNulls(Collection c) { return contains(c, null); } static public String htmlDecode(String input) { return htmldecode(input); } static public A setAll(A o, Map fields) { if (fields == null) return o; for (String field : keys(fields)) set(o, field, fields.get(field)); return o; } static public A setAll(A o, Object... values) { failIfOddCount(values); for (int i = 0; i + 1 < l(values); i += 2) { String field = (String) values[i]; Object value = values[i + 1]; set(o, field, value); } return o; } static public int lUtf8(String s) { return l(utf8(s)); } static public JPanel centerSection(JPanel section) { if (section != null) { swing(() -> { Border border = section.getBorder(); if (border instanceof TitledBorder) ((TitledBorder) border).setTitleJustification(TitledBorder.CENTER); }); } return section; } static public > B addAllAndReturnCollection(B c, Collection b) { if (c != null && b != null) c.addAll(b); return c; } static public > B addAllAndReturnCollection(B c, A... b) { addAll(c, b); return c; } static public A awtEvery(A component, long delay, Object r) { swingEvery(component, delay, r); return component; } static public A awtEvery(long delay, A component, Runnable r) { return awtEvery(component, delay, delay, (Object) r); } static public A awtEvery(A component, long delay, Runnable r) { return awtEvery(component, delay, delay, r); } static public A awtEvery(A component, long delay, long firstDelay, Runnable r) { return awtEvery(component, delay, firstDelay, (Object) r); } static public A awtEvery(A component, long delay, long firstDelay, Object r) { swingEvery(component, delay, firstDelay, r); return component; } static public void awtEvery(RootPaneContainer frame, long delay, Object r) { swingEvery(frame, delay, r); } static public A awtEvery(A component, double firstDelaySeconds, double delaySeconds, Object r) { return awtEvery(component, toMS(firstDelaySeconds), toMS(delaySeconds), r); } static public A awtEvery(A component, double delaySeconds, Object r) { return awtEvery(component, toMS(delaySeconds), r); } static public Comparator mapComparator(final Map map) { return new Comparator() { public int compare(A a, A b) { return cmp(map.get(a), map.get(b)); } }; } static public String firstIntAsString(String s) { return jextract("", s); } 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 = clampZeroToOne(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 Component frameIcon(Component c, String imageID) { setFrameIconLater(c, imageID); return c; } static public Component frameIcon(String imageID, Component c) { setFrameIconLater(c, imageID); return c; } 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 List beginCriticalAction_inFlight = synchroList(); static public class CriticalAction implements AutoCloseable { public String description; public CriticalAction() { } public CriticalAction(String description) { this.description = description; } final public void close() { done(); } public void done() { beginCriticalAction_inFlight.remove(this); } } static public CriticalAction beginCriticalAction(String description) { ping(); CriticalAction c = new CriticalAction(description); beginCriticalAction_inFlight.add(c); return c; } static public void cleanMeUp_beginCriticalAction() { int n = 0; while (nempty(beginCriticalAction_inFlight)) { int m = l(beginCriticalAction_inFlight); if (m != n) { n = m; try { print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description"))); } catch (Throwable __e) { pcallFail(__e); } } sleepInCleanUp(10); } } static public JScrollPane jscrollHorizontal(final Component c) { return swing(new F0() { public JScrollPane get() { try { return new JScrollPane(c, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return new JScrollPane(c,\r\n ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,\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 Color toColor(RGB rgb) { return rgb == null ? null : rgb.getColor(); } static public Color toColor(int rgb) { return new Color(rgb); } static public Color toColor(String hex) { return awtColor(hex); } static public Color toColor(int[] rgb) { return new Color(rgb[0], rgb[1], rgb[2]); } static public ArrayList asList(A[] a) { return a == null ? new ArrayList() : new ArrayList(Arrays.asList(a)); } static public ArrayList asList(char[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (var i : a) l.add(i); return l; } static public ArrayList asList(byte[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (var i : a) l.add(i); return l; } 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 ArrayList asList(ReverseChain c) { return c == null ? emptyList() : c.toList(); } static public List asList(Pair p) { return p == null ? null : ll(p.a, p.b); } static public void setDynObjectValue(DynamicObject o, String field, Object value) { dynamicObject_setRawFieldValue(o, field, value); } static public Runnable wrapAsActivity(Object r) { if (r == null) return null; Runnable r2 = toRunnable(r); Object mod = dm_current_generic(); if (mod == null) return r2; return new Runnable() { public void run() { try { AutoCloseable c = (AutoCloseable) (rcall("enter", mod)); AutoCloseable __1 = c; try { r2.run(); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable c = (AutoCloseable) (rcall enter(mod));\r\n temp c;\r\n r2.r..."; } }; } static public String str_toKB(long l) { return n2(toK(l)) + " KB"; } static public String str_toKB(File f) { return str_toKB(fileSize(f)); } static public class ECJError { public String file, error; public int lineNr; public String codeLine; public IntRange colRange; public String toString() { return "Error on line " + lineNr + ": " + error; } } static public List parseECJOutputForErrors(String text) { List errors = new ArrayList(); List lines = lines(text); for (int i = 0; i < l(lines); i++) { if (startsWith(lines.get(i), "---")) { String line = get(lines, i + 1); List groups = regexpFirstGroups("^\\d+\\. ERROR in (.*?) \\(at line (\\d+)\\)$", line); if (groups != null) { String codeLine = get(lines, i + 2); String markLine = get(lines, i + 3); String errorLine = get(lines, i + 4); List markGroups = regexpFirstGroups("^( *)(\\^+)", markLine); ECJError e = new ECJError(); e.file = groups.get(0); e.error = errorLine; e.lineNr = parseInt(groups.get(1)); e.codeLine = codeLine; int col1 = l(first(markGroups)); int cols = l(second(markGroups)); e.colRange = intRangeWithLength(col1 + 1, cols); errors.add(e); } } } return errors; } static public SingleComponentPanel jOnDemand(IF0 makeComponent) { SingleComponentPanel scp = singleComponentPanel(); bindToComponent(scp, () -> { if (!scp.isEmpty()) return; 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 String singleDigitBytesToString(ByteBuffer l) { if (l == null) return null; int n = l.size(); char[] data = new char[n]; for (int i = 0; i < n; i++) data[i] = (char) ('0' + ubyteToInt(l.get(i)) % 10); return str(data); } static public String dropPrefixFromLines(String prefix, String s) { return mapEachLine(s, line -> dropPrefix(prefix, line)); } static public String indentedStructureForUser(Object o) { return indentedStructureForUser(Integer.MAX_VALUE, o); } static public String indentedStructureForUser(int levels, Object o) { return indentStructureString(levels, structForUser(o)); } static public String indentedStructureForUser(Object o, structure_Data data) { return indentedStructureForUser(Integer.MAX_VALUE, o, data); } static public String indentedStructureForUser(int levels, Object o, structure_Data data) { return indentStructureString(levels, structForUser(o, data)); } static public byte[] hexToBytes(String s) { if (odd(l(s))) throw fail("Hex string has odd length: " + quote(shorten(10, s))); int n = l(s) / 2; byte[] bytes = new byte[n]; for (int i = 0; i < n; i++) { int a = parseHexChar(s.charAt(i * 2)); int b = parseHexChar(s.charAt(i * 2 + 1)); if (a < 0 || b < 0) throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s)); bytes[i] = (byte) ((a << 4) | b); } return bytes; } static public List listAllFrames() { List l = new ArrayList(); for (Frame f : Frame.getFrames()) if (f instanceof JFrame) l.add((JFrame) f); return l; } static public A proxy(Class intrface, final Object target) { if (target == null) return null; if (isInstance(intrface, target)) return (A) target; return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new proxy_InvocationHandler(target)); } static public A proxy(Object target, Class intrface) { return proxy(intrface, target); } static public JMenuBar addMenuBar(final Component c) { return swing(new F0() { public JMenuBar get() { try { RootPaneContainer f = getPossiblyInternalFrame(c); if (f == null) return null; JMenuBar bar = (JMenuBar) (call(f, "getJMenuBar")); if (bar == null) { setMenuBar(f, bar = new JMenuBar()); revalidate((Component) f); } return bar; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "RootPaneContainer f = getPossiblyInternalFrame(c);\r\n if (f == null) null;\r..."; } }); } static public Map nuEmptyObject_cache = newDangerousWeakHashMap(); static public A nuEmptyObject(Class c) { try { Constructor ctr; synchronized (nuEmptyObject_cache) { ctr = nuEmptyObject_cache.get(c); if (ctr == null) { nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c)); makeAccessible(ctr); } } try { return (A) ctr.newInstance(); } catch (InstantiationException e) { if (empty(e.getMessage())) if ((c.getModifiers() & Modifier.ABSTRACT) != 0) throw fail("Can't instantiate abstract class " + className(c), e); else throw fail("Can't instantiate " + className(c), e); else throw rethrow(e); } } catch (Exception __e) { throw rethrow(__e); } } static public Constructor nuEmptyObject_findConstructor(Class c) { for (Constructor m : getDeclaredConstructors_cached(c)) if (m.getParameterTypes().length == 0) return m; throw fail("No default constructor declared in " + c.getName()); } static public List lambdaMap(IF1 f, Iterable l) { return map(l, f); } static public List lambdaMap(IF1 f, A[] l) { return map(l, f); } static public String getType(Object o) { return getClassName(o); } 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 boolean endsWith(String a, String b) { return a != null && a.endsWith(b); } static public boolean endsWith(String a, char c) { return nempty(a) && lastChar(a) == c; } static public boolean endsWith(String a, String b, Matches m) { if (!endsWith(a, b)) return false; m.m = new String[] { dropLast(l(b), a) }; return true; } static public String nameRelativeToPhysicalSubdirectory(File inner, File outer) { try { if (inner == null || outer == null) return null; String path1 = inner.getCanonicalPath(); String path2a = outer.getCanonicalPath(); if (eq(path1, path2a)) return ""; String path2 = addFileSep(path2a); Matches m = new Matches(); if (startsWith(path1, path2, m)) return m.rest(); else return null; } catch (Exception __e) { throw rethrow(__e); } } static public A enableScaffolding(A o) { return enableScaffolding(o, true); } static public A enableScaffolding(A o, boolean b) { if (o instanceof IMeta) ((IMeta) o).metaPut("scaffolding", trueOrNull(b)); return o; } static public void ping_okInCleanUp() { } static public LinkedHashMap asLinkedHashMap(Map map) { if (map instanceof LinkedHashMap) return (LinkedHashMap) map; LinkedHashMap m = new LinkedHashMap(); if (map != null) synchronized (collectionMutex(map)) { m.putAll(map); } return m; } static public Object callOptWithEnter(Object o, String method, String[] arg) { return callOptWithEnter(o, method, new Object[] { arg }); } static public Object callOptWithEnter(Object o, String method, Object... args) { if (o == null) return null; AutoCloseable __1 = tempEnter(o); try { return callOpt_withVarargs(o, method, args); } finally { _close(__1); } } static public void vmBus_send(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg); pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg); } static public void vmBus_send(String msg) { vmBus_send(msg, (Object) null); } static public > IterableIterator> outerProduct_faster(List lists) { return mapI(__101 -> fromSimplyLinkedList(__101), outerProduct_faster(toSimplyLinkedList(lists))); } static public > IterableIterator> outerProduct_faster(SimplyLinkedList lists) { if (lists == null) return singletonIterator(null); SimplyLinkedList lists2 = lists.tail; return nestedIterator(lists.head, new F1>>() { public Iterator> get(A a) { try { return mapI(outerProduct_faster(lists2), l -> SimplyLinkedList.cons(a, l)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "mapI(outerProduct_faster(lists2), l -> SimplyLinkedList.cons(a, l))"; } }); } static public File envJavaHome() { return newFile(System.getProperty("java.home")); } static public long incAtomicLong(AtomicLong l) { return l.incrementAndGet(); } static public A copyFields(Object x, A y, String... fields) { if (empty(fields)) { Map map = objectToMap(x); for (String field : map.keySet()) setOpt(y, field, map.get(field)); } else for (String field : fields) { Object o = getOpt(x, field); if (o != null) setOpt(y, field, o); } return y; } static public A copyFields(Object x, A y, Collection fields) { return copyFields(x, y, asStringArray(fields)); } static public void onChangeAndNow(JComponent c, Object r) { onUpdateAndNow(c, r); } static public void onChangeAndNow(List l, Object r) { onUpdateAndNow(l, r); } static public void onChangeAndNow(JTextComponent c, IVF1 r) { onUpdateAndNow(c, 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 JSlider onChangeAndNow(JSlider s, Runnable f) { if (s != null && f != null) { onChange(s, f); f.run(); } return s; } static public Object dm_getStem(Object moduleOrID) { if (isString(moduleOrID) && isIdentifier(((String) moduleOrID))) moduleOrID = dm_getService(((String) moduleOrID)); if (isStringOrIntOrLong(moduleOrID)) return dm_getStemByID(moduleOrID); return or(getOpt(dm_getModule(moduleOrID), "_host"), moduleOrID); } static public Collection asCollection(Iterable l) { return l == null ? null : l instanceof Collection ? ((Collection) l) : asList(l); } static public double msToSeconds(long ms) { return toSeconds(ms); } static public double msToSeconds(double ms) { return toSeconds(ms); } static public Map _registerThread_threads; static public Object _onRegisterThread; static public Thread _registerThread(Thread t) { if (_registerThread_threads == null) _registerThread_threads = newWeakHashMap(); _registerThread_threads.put(t, true); vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc())); callF(_onRegisterThread, t); return t; } static public void _registerThread() { _registerThread(Thread.currentThread()); } static public Graphics2D antiAliasGraphics(BufferedImage img) { return antiAliasOn(createGraphics(img)); } 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 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 DynamicObject dO(String className, Object... x) { return dynamicObject(className, x); } static public Throwable getInnerException(Throwable e) { if (e == null) return null; while (e.getCause() != null) e = e.getCause(); return e; } static public Throwable getInnerException(Runnable r) { return getInnerException(getException(r)); } static public String getTextTrim(JTextComponent c) { return trim(getText(c)); } static public String getTextTrim(JComboBox cb) { return trim(getText(cb)); } static public String getTextTrim(JComponent c) { if (c instanceof JLabel) return trim(((JLabel) c).getText()); if (c instanceof JComboBox) return getTextTrim((JComboBox) c); return getTextTrim((JTextComponent) c); } 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 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 final public Map callOpt_cache = newDangerousWeakHashMap(); static public Object callOpt_cached(Object o, String methodName, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me == null || (me.getModifiers() & Modifier.STATIC) == 0) return null; return invokeMethod(me, null, args); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me == null) return null; return invokeMethod(me, o, args); } } catch (Exception __e) { throw rethrow(__e); } } static public _MethodCache callOpt_getCache(Class c) { _MethodCache cache = callOpt_cache.get(c); if (cache == null) callOpt_cache.put(c, cache = new _MethodCache(c)); return cache; } static public void setSelected(AbstractButton btn, boolean selected) { if (btn != null) { swing(() -> { btn.setSelected(selected); }); } } static public A getAndClearThreadLocal(ThreadLocal tl) { A a = tl.get(); tl.set(null); return a; } static public Map> multiMapToMap(MultiMap m) { return m == null ? null : m.data; } static public Graphics2D graphics(BufferedImage img) { return imageGraphics(img); } static public int getCaretPosition(final JTextComponent c) { return c == null ? 0 : swing(new F0() { public Integer get() { try { return c.getCaretPosition(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getCaretPosition();"; } }); } static public boolean jInternalFrame_iconifiable = true; static public JInternalFrame jInternalFrame() { return jInternalFrame(""); } static public JInternalFrame jInternalFrame(final String title) { return swing(new F0() { public JInternalFrame get() { try { JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame_iconifiable); f.setVisible(true); return f; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JInternalFrame f = new JInternalFrame(title, true, true, true, jInternalFrame..."; } }); } 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 Class javax() { return getJavaX(); } 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 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 char[] emptyCharArray = new char[0]; static public char[] emptyCharArray() { return emptyCharArray; } 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 void removeTrayIcon(final TrayIcon t) { if (t != null) { swing(() -> { SystemTray.getSystemTray().remove(t); }); } } static public A packFrameVertically(A c) { return packWindowVertically(c); } static public A packFrameVertically(int width, A c) { return packWindowVertically(setFrameWidth(width, c)); } static public boolean isFalse(Object o) { return eq(false, o); } static public String imageServerURL() { return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/"); } static public RSyntaxTextAreaWithSearch rSyntaxTextAreaWithSearch() { return new RSyntaxTextAreaWithSearch(); } static public RSyntaxTextAreaWithSearch rSyntaxTextAreaWithSearch(String text) { var ta = rSyntaxTextAreaWithSearch(); ta.setText(text); return ta; } static public boolean eq(Object a, Object b) { return a == b || a != null && b != null && a.equals(b); } static public boolean eq(Symbol a, String b) { return eq(str(a), b); } static public AutoCloseable tempDisableButtons(Collection buttons) { return combineAutoCloseables(map(__102 -> tempDisableButton(__102), buttons)); } static public Object callOpt_withVarargs(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(method, args); if (me == null) { return null; } if ((me.getModifiers() & Modifier.STATIC) == 0) return null; return invokeMethod(me, null, args); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(method, args); if (me != null) return invokeMethod(me, o, args); List methods = cache.cache.get(method); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, o, newArgs); } return null; } } catch (Exception __e) { throw rethrow(__e); } } static public 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 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 Pt origin() { return pt(0, 0); } static public JFastLogView_noWrap jFastLogView_noWrap() { return jFastLogView_noWrap(""); } static public JFastLogView_noWrap jFastLogView_noWrap(String text) { return withTypeWriterFont(swingNu(JFastLogView_noWrap.class, text)); } static public String nResults(int n) { return n2(n, "result"); } static public String nResults(Collection l) { return nResults(l(l)); } static public Point enclosingViewPosition(Component c) { JScrollPane sp = enclosingScrollPane(c); return sp == null ? null : swing(new F0() { public Point get() { try { return sp.getViewport().getViewPosition(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return sp.getViewport().getViewPosition();"; } }); } static public int random(int n) { return random(n, defaultRandomGenerator()); } static public int random(int n, Random r) { return random(r, n); } static public long random(long n) { return random(n, defaultRandomGenerator()); } static public long random(long 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 long random(Random r, long n) { return n <= 0 ? 0 : getRandomizer(r).nextLong(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 long random(long min, long 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 double random(DoubleRange r) { return random(r.start, r.end); } static public Timestamp random(TimestampRange r) { return r == null ? null : new Timestamp(random(r.startTime().unixDate(), r.endTime().unixDate())); } static public Pair random(Map map) { return entryToPair(random(entries(map))); } static public Map mapKeyAndFunction(Iterable l, Object f) { return mapKeyAndFunction(f, l); } static public Map mapKeyAndFunction(Object f, Iterable l) { HashMap map = new HashMap(); if (l != null) for (Object o : l) map.put(o, callF(f, o)); return map; } static public Map mapKeyAndFunction(Map map, IF2 f) { HashMap map2 = new HashMap(); if (map != null) for (Map.Entry __0 : _entrySet(map)) { A key = __0.getKey(); B value = __0.getValue(); map2.put(key, callF(f, key, value)); } return map2; } static public Map mapKeyAndFunction(Iterable l, IF1 f) { return mapKeyAndFunction(f, l); } static public JPanel centerAndSouthWithMargin(Swingable c, Swingable s) { return centerAndSouthWithMargin(c, toComponent(s)); } static public JPanel centerAndSouthWithMargin(Swingable c, Component s) { return centerAndSouthWithMargin(toComponent(c), s); } static public JPanel centerAndSouthWithMargin(Component c, Swingable s) { return centerAndSouthWithMargin(c, toComponent(s)); } static public JPanel centerAndSouthWithMargin(Component c, Component s) { return centerAndSouth(c, withTopMargin(s)); } static public JPanel centerAndSouthWithMargin(int margin, Swingable c, Swingable s) { return centerAndSouthWithMargin(margin, c, toComponent(s)); } static public JPanel centerAndSouthWithMargin(int margin, Swingable c, Component s) { return centerAndSouthWithMargin(margin, toComponent(c), s); } static public JPanel centerAndSouthWithMargin(int margin, Component c, Swingable s) { return centerAndSouthWithMargin(margin, c, toComponent(s)); } static public JPanel centerAndSouthWithMargin(int margin, Component c, Component s) { return centerAndSouth(c, withTopMargin(margin, s)); } static public List> streaksOfRepeatingElements(List l) { List> out = new ArrayList(); int i = 0, n = l(l); while (i < n) { A a = l.get(i); int j = i + 1; while (j < n && eq(a, l.get(j))) ++j; out.add(pair(intRange(i, j), a)); i = j; } return out; } static public List listMinusSet(Iterable l, Collection stuff) { if (l == null) return null; if (empty(stuff)) return asList(l); Set set = asSet(stuff); List l2 = new ArrayList(); for (A a : l) if (!set.contains(a)) l2.add(a); return l2; } static public List listMinusSet(Iterable l, Collection stuff, Collection stuff2) { return listMinusSet(listMinusSet(l, stuff), stuff2); } 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 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 String platformName() { if (isWindows()) return "Windows"; if (isMac()) return "Mac OS"; return "Linux"; } static public List allImageFiles(File dir) { return filter(__103 -> isImageFile(__103), findAllFiles_noDirs(dir)); } static public JPanel jRightAlignedLine(Component... components) { return jrightAlignedLine(components); } static public JPanel jRightAlignedLine(List components) { return jrightAlignedLine(components); } static public List reTok_multi(List tok, List places) { if (empty(places)) return tok; if (l(places) == 1) return reTok(tok, first(places)); List orig = cloneList(tok); sortIntRangesInPlace(places); List places2 = new ArrayList(); for (IntRange p : places) { p = intRange(p.start & ~1, p.end | 1); if (nempty(places2) && p.start <= last(places2).end) last(places2).end = p.end; else places2.add(p); } int iPlace = 0, n = l(orig); IntRange p = get(places2, iPlace); int next = p.start, i = next; tok.subList(next, tok.size()).clear(); while (i < n) if (i < next) tok.add(orig.get(i++)); else { int j = p.end; String s = joinSubList(orig, i, j); tok.addAll(javaTok(s)); i = j; p = get(places2, ++iPlace); if (p == null) break; next = p.start; } while (i < n) tok.add(orig.get(i++)); return tok; } static public JInternalFrame minInternalFrameWidth(final JInternalFrame frame, final int w) { { swing(() -> { if (frame != null && frame.getWidth() < w) frame.setSize(w, frame.getHeight()); }); } return frame; } static public JInternalFrame minInternalFrameWidth(int w, JInternalFrame frame) { return minInternalFrameWidth(frame, w); } static public boolean comboBoxContainsItem(JComboBox cb, A item) { return contains(getComboBoxItems(cb), item); } static public Container getContentPane(Object o) { JFrame f = getFrame(o); return f == null ? null : f.getContentPane(); } 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 JSpinner bindLiveValueToSpinner(IVarWithNotify lv, JSpinner spinner) { onChange(spinner, () -> lv.set(intFromSpinner(spinner))); lv.onChange(() -> setSpinnerValue(spinner, lv.get())); return spinner; } static public boolean containsIgnoreCase(Collection l, String s) { if (l != null) for (String x : l) if (eqic(x, s)) return true; return false; } static public boolean containsIgnoreCase(String[] l, String s) { if (l != null) for (String x : l) if (eqic(x, s)) return true; return false; } static public boolean containsIgnoreCase(String s, char c) { return indexOfIgnoreCase(s, String.valueOf(c)) >= 0; } static public boolean containsIgnoreCase(String a, String b) { return indexOfIgnoreCase(a, b) >= 0; } static public JScrollPane jscroll_center_borderless(Component c) { return jscroll_centered_borderless(c); } static public Set vm_busListeners_live_cache; static public Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache; } static public Set vm_busListeners_live_load() { return vm_generalIdentityHashSet("busListeners"); } static public A setFrameSize(A c, int w, int h) { JFrame f = getFrame(c); if (f != null) f.setSize(w, h); return c; } static public A setFrameSize(int w, int h, A c) { return setFrameSize(c, w, h); } static public String ffmpegLibraryIDForPlatform() { if (isLinux()) return "#1400557"; else if (isWindows()) return "#1400558"; else return null; } static public AutoCloseable tempUncancelThread() { return tempPingPrivileged(); } static public Map synchroHashMap() { return synchronizedMap(new HashMap()); } static public JPanel withMargins(Component c) { return withMargin(c); } static public JPanel withMargins(int w, Component c) { return withMargin(w, c); } static public JPanel withMargins(int w, int h, Component c) { return withMargin(w, h, c); } static public JPanel withMargins(int top, int left, int bottom, int right, Component c) { return withMargin(top, left, bottom, right, c); } static public String dataSnippetLink(String snippetID) { long id = parseSnippetID(snippetID); if (id >= 1100000 && id < 1200000) return imageServerURL() + id; if (id >= 1200000 && id < 1300000) { String pw = muricaPassword(); if (empty(pw)) throw fail("Please set 'murica password by running #1008829"); return "https://botcompany.de/files/" + id + "?_pass=" + pw; } return fileServerURL() + "/" + id; } static public String urlencode(String x) { try { return URLEncoder.encode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } static public int selectedTabIndex(JExtendedTabbedPane tabs) { return tabs == null ? -1 : swing(() -> tabs.getSelectedIndex()); } static public int selectedTabIndex(JTabbedPane tabs) { return tabs == null ? -1 : swing(() -> tabs.getSelectedIndex()); } static public void removeAllComponents(final Container c) { if (c != null) { swing(() -> { c.removeAll(); revalidate(c); }); } } static public String appendQueryToURL(String url, Map params) { if (url == null) return null; String data = makePostData(params); if (empty(data)) return url; int idx = smartIndexOf(url, '#'); String url2 = takeFirst(url, idx); return url2 + (url2.contains("?") ? "&" : "?") + data + substring(url, idx); } static public String appendQueryToURL(String url, Object... data) { return appendQueryToURL(url, paramsToMap(data)); } static public String selectedTabName(JTabbedPane tabs) { return tabs == null ? null : swing(() -> getTabTitle(tabs, tabs.getSelectedIndex())); } static public ThreadLocal saveTiming_last = new ThreadLocal(); static public void saveTiming(long ms) { print(ms + " ms"); saveTiming_noPrint(ms); } static public void saveTiming_noPrint(long ms) { saveTiming_last.set(ms); } static public ThreadLocal saveTiming_tl() { return saveTiming_last; } static public String fsI(String id) { return formatSnippetID(id); } static public String fsI(long id) { return formatSnippetID(id); } static public float clamp(float x, float a, float b) { return x < a ? a : x > b ? b : x; } static public double clamp(double x, double a, double b) { return x < a ? a : x > b ? b : x; } static public int clamp(int x, int a, int b) { return x < a ? a : x > b ? b : x; } static public long clamp(long x, long a, long b) { return x < a ? a : x > b ? b : x; } static public void dynamicObject_setRawFieldValue(DynamicObject o, Object key, Object value) { if (o == null) return; synchronized (o) { o.fieldValues = syncMapPut2_createLinkedHashMap((LinkedHashMap) o.fieldValues, key, value); } } static public List methodNames(Object o) { return allMethodNames(o); } static public List countIteratorAsList(int b) { return countIteratorAsList(0, b); } static public List countIteratorAsList(int a, int b) { return countIteratorToList(a, b); } static public List countIteratorAsList(int b, IF1 f) { return countIteratorAsList(0, b, f); } static public List countIteratorAsList(int a, int b, IF1 f) { return countIteratorToList(a, b, f); } static public List countIteratorAsList(int a, int b, int step) { return countIteratorToList(a, b, step); } static public List countIteratorAsList(double a, double b, double step, IF1 f) { return countIteratorToList(a, b, step, f); } static public List countIteratorAsList(double a, double b, double step) { return countIteratorToList(a, b, step); } static public List countIteratorAsList(IF1 f, double a, double b, double step) { return countIteratorToList(f, a, b, step); } static public List countIteratorAsList(IF1 f, int b) { return countIteratorAsList(f, 0, b); } static public List countIteratorAsList(IF1 f, int a, int b) { return countIteratorToList(f, a, b); } static public > List getVars(Iterable l) { return lambdaMap(__104 -> getVar(__104), l); } static public boolean is(String a, String b) { return false; } static public boolean isVisibleWindow(Window w) { return w != null && swing(() -> w.isVisible()); } static public boolean odd(int i) { return (i & 1) != 0; } static public boolean odd(long i) { return (i & 1) != 0; } static public boolean odd(BigInteger i) { return odd(toInt(i)); } static public Object dm_getService(String serviceName) { return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName))); } static public IterableIterator> iterateListWithIndex(Iterable l) { return iterateListWithIndex(l, 0); } static public IterableIterator> iterateListWithIndex(Iterable l, int startAt) { return iff(new Object() { public Iterator it = iterator(l); public int i = startAt; public Object get() { if (!it.hasNext()) return endMarker(); return pair(i++, it.next()); } }); } static public List sortInPlaceByCalculatedField(List l, final F1 f) { sort(l, new Comparator() { public int compare(A a, A b) { return stdcompare(f.get(a), f.get(b)); } }); return l; } static public List sortInPlaceByCalculatedField(List l, final IF1 f) { sort(l, new Comparator() { public int compare(A a, A b) { return stdcompare(f.get(a), f.get(b)); } }); return l; } static public Dimension componentsBoundingSize(Container container, int insetBottomRight) { Rectangle r = new Rectangle(0, 0, 0, 0); for (Component c : container.getComponents()) r = rectangleUnion(r, c.getBounds()); return new Dimension(r.x + r.width + insetBottomRight, r.y + r.height + insetBottomRight); } static public JTextField standardTextFieldPopupMenu(final JTextField tf) { final WeakReference ref = weakRef(tf); componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() { public void run() { try { copyTextToClipboard(ref.get().getText()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(ref.get().getText())"; } }); componentPopupMenuItem(tf, "Paste", new Runnable() { public void run() { try { ref.get().paste(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ref.get().paste()"; } }); return tf; } static public File imagesDir() { return userDir_oneOf_createFirstIfNone("Pictures", "OneDrive/Pictures", "OneDrive/Bilder", "Bilder"); } static public File imagesDir(String sub) { return newFile(imagesDir(), sub); } static public ClassLoader classLoader(Object o) { return classLoaderForObject(o); } static public File loadDataSnippetToFile(String snippetID) { try { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadLibrary(snippetID); return loadDataSnippetToFile_noResourceLoader(snippetID); } catch (Exception __e) { throw rethrow(__e); } } static public File loadDataSnippetToFile_noResourceLoader(String snippetID) { try { snippetID = fsI(snippetID); File f = DiskSnippetCache_file(parseSnippetID(snippetID)); List urlsTried = new ArrayList(); List errors = new ArrayList(); try { URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID))); print("Loading library: " + hideCredentials(url)); try { loadBinaryPageToFile(openConnection(url), f); if (fileSize(f) == 0) throw fail(); } catch (Throwable e) { errors.add(e); url = addAndReturn(urlsTried, new URL(tb_mainServer() + "/blobs/" + psI(snippetID))); print(e); print("Trying other server: " + hideCredentials(url)); loadBinaryPageToFile(openConnection(url), f); print("Got bytes: " + fileSize(f)); } if (fileSize(f) == 0) throw fail(); System.err.println("Bytes loaded: " + fileSize(f)); } catch (Throwable e) { errors.add(e); throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors)); } return f; } catch (Exception __e) { throw rethrow(__e); } } static public ScreenShotMeta shootScreenWithMeta(Rect bounds) { var timeRange = new TimestampRange().start(tsNow()); ScreenShotMeta result = new ScreenShotMeta(timeRange, bounds, shootScreen2(bounds)); timeRange.end(tsNow()); result.image = cloneBufferedImageWithMetaSrc(result, result.image); return result; } 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 PersistableThrowable persistableThrowable(Throwable e) { return e == null ? null : new PersistableThrowable(e); } static public File renameFile_assertTrue(File a, File b) { try { if (a.equals(b)) return b; if (!a.exists()) throw fail("Source file not found: " + f2s(a)); if (b.exists()) throw fail("Target file exists: " + f2s(b)); mkdirsForFile(b); if (!a.renameTo(b)) throw fail("Can't rename " + f2s(a) + " to " + f2s(b)); return b; } catch (Exception __e) { throw rethrow(__e); } } static public List itemPlus(A a, Collection l) { return itemPlusList(a, l); } static public RSyntaxTextArea javaxSyntaxTextArea() { return swing(new F0() { public RSyntaxTextArea get() { try { RSyntaxTextArea textArea = new RSyntaxTextArea(1, 10); initSyntaxTextArea(textArea); textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); return textArea; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "RSyntaxTextArea textArea = new RSyntaxTextArea(1, 10);\r\n initSyntaxTextAre..."; } }); } static public List cloneKeys_noSync(Map map) { return cloneList_noSync(keys(map)); } static public Object safeUnstruct(String s) { return unstructure(s, true); } static public boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) { return a != null && a.regionMatches(true, offsetA, b, offsetB, len); } static public List tlft(String s) { return toLinesFullTrim(s); } static public List tlft(File f) { return toLinesFullTrim(f); } static public BufferedImage scaleImage_bilinear(BufferedImage before, double scaleX) { return scaleImage_bilinear(before, scaleX, scaleX); } static public BufferedImage scaleImage_bilinear(BufferedImage before, double scaleX, double scaleY) { return scaleImageWithOp(before, scaleX, scaleY, AffineTransformOp.TYPE_BILINEAR); } static public BufferedImage scaleImage_bilinear(double scale, BufferedImage before) { return scaleImage_bilinear(before, scale); } static public 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 DynamicHStack dynamicHStack(Component... components) { DynamicHStack stack = swingNu(DynamicHStack.class); stack.addComponents(asList(components)); return stack; } static public JTable tablePopupMenuItemsThreaded(final JTable table, Object... params) { for (int i = 0; i + 1 < l(params); i += 2) { final Object action = params[i + 1]; final Object threadInfo = _threadInfo(); tablePopupMenuItem(table, str(params[i]), new VF1() { public void get(final Integer row) { try { _threadInheritInfo(threadInfo); { startThread(new Runnable() { public void run() { try { try { callF(action, row); } catch (Throwable __e) { messageBox(__e); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n callF(action, row);\r\n } catch (Throwable __e) { messageBo..."; } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_threadInheritInfo(threadInfo);\r\n thread-messagebox {\r\n callF(act..."; } }); } return table; } static public String md5OfStream(InputStream in) { try { if (in == null) return "-"; AutoCloseable __1 = in; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] buf = new byte[65536]; int l; while (true) { l = in.read(buf); if (l <= 0) break; md5.update(buf, 0, l); } return bytesToHex(md5.digest()); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } static public Object vm_generalMap_get(Object key) { return vm_generalMap().get(key); } static public JLabel jcenteredBoldLabel(String text) { JLabel l = jboldLabel(text); l.setHorizontalAlignment(JLabel.CENTER); return l; } static public JLabel jcenteredBoldLabel() { return jcenteredBoldLabel(""); } static public A focusOnFirstShow(A a) { return focusOnShow(a); } 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 class TableSearcher { public JTable table; public JTextField tfInput; public JComponent searchPanel, panel; public F2 rowTester; public List rowIndices; public SingleComponentPanel scpRightOfSearchPanel = scp(); public List lastFiltered, lastOriginal; public String input() { return gtt(tfInput); } public void clearSearchField() { setText(tfInput, ""); } } static public TableSearcher tableWithSearcher2(JTable t, Object... __) { TableSearcher s = new TableSearcher(); boolean precise = true; s.table = t; s.tfInput = jtextfield(); s.rowTester = new F2() { public Boolean get(String pat, Map row) { try { return anyValueContainsIgnoreCase(row, pat); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "anyValueContainsIgnoreCase(row, pat)"; } }; onUpdate(s.tfInput, new Runnable() { public void run() { String pat = s.input(); List> data = rawTableData(t); if (eq(s.lastFiltered, data)) data = s.lastOriginal; List data2 = new ArrayList(); List rowIndices = new ArrayList(); for (int i = 0; i < l(data); i++) { Map map = data.get(i); if (isTrue(callF(s.rowTester, pat, map))) { data2.add(map); rowIndices.add(i); } } s.lastFiltered = data2; s.lastOriginal = data; dataToTable(t, data2); if (precise) s.lastFiltered = rawTableData(t); s.rowIndices = rowIndices; } }); s.searchPanel = centerAndEast(withLabel(" Search:", s.tfInput), s.scpRightOfSearchPanel); JComponent top = s.searchPanel; s.panel = boolOptPar(__, "withMargin") ? northAndCenterWithMargin(top, t) : northAndCenter(top, t); return s; } static public List loadedJigsawModuleNames() { var moduleLayer = ModuleLayer.boot(); var modules = moduleLayer.modules(); return map(modules, mod -> mod.getName()); } static public Object[] concatArrays(Object[]... arrays) { int l = 0; for (Object[] a : arrays) l += l(a); Object[] x = new Object[l]; int i = 0; for (Object[] a : arrays) if (a != null) { System.arraycopy(a, 0, x, i, l(a)); i += l(a); } return x; } 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_getPlural(String singular) { return plural(singular); } static public String n2(double l, String singular) { return empty(singular) ? str(l) : n2(l, singular, n2_getPlural(singular)); } 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, n2_getPlural(singular)); } 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) { return n2(ms, singular, n2_getPlural(singular)); } static public String n2(MultiSet ms, String singular, String plural) { return n_fancy2(ms, singular, plural); } static public String n2(IMultiMap mm, String singular) { return n2(mm, singular, n2_getPlural(singular)); } static public String n2(IMultiMap mm, String singular, String plural) { return n_fancy2(l(mm), singular, plural); } static public void closeAutoCloseables(Collection l) { if (l != null) for (AutoCloseable c : l) { try { c.close(); } catch (Throwable __e) { pcallFail(__e); } } } static public String lines_rtrim(Collection lines) { return rtrim_fromLines(lines); } 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 BufferedImage drawImageOnImage(Image img, BufferedImage canvas, int x, int y) { createGraphics(canvas).drawImage(img, x, y, null); return canvas; } static public BufferedImage drawImageOnImage(Image img, BufferedImage canvas) { return drawImageOnImage(img, canvas, 0, 0); } static public A setFrameWidth(int w, A c) { return setFrameWidth(c, w); } static public A setFrameWidth(A c, int w) { JFrame f = getFrame(c); if (f != null) f.setSize(w, f.getHeight()); return c; } static public Class mc() { return utils.class; } static public void replaceTokens(List tok, IntRange r, String s) { replaceTokens(tok, r.start, r.end, s); } static public void replaceTokens(List tok, int i, int j, String s) { clearAllTokens(tok, i + 1, j); tok.set(i, s); } static public void replaceTokens(List tok, String s) { clearAllTokens(tok, 1, l(tok)); tok.set(0, s); } static public JButton setButtonImage(Icon img, JButton btn) { btn.setIcon(img); return btn; } static public JButton setButtonImage(Image img, JButton btn) { btn.setIcon(imageIcon(img)); return btn; } static public A setButtonImage(Image img, A btn) { btn.setIcon(imageIcon(img)); return btn; } static public A setButtonImage(A btn, Image img) { return setButtonImage(img, btn); } static public A setButtonImage(A btn, String imageID) { btn.setIcon(imageIcon(imageID)); return btn; } static public JButton setButtonImage(JButton btn, Image img) { return setButtonImage(img, btn); } static public JButton setButtonImage(JButton btn, Icon img) { return setButtonImage(img, btn); } static public Set> entrySet(Map map) { return _entrySet(map); } static public String actualUserHome_value; static public String actualUserHome() { if (actualUserHome_value == null) { if (isAndroid()) actualUserHome_value = "/storage/emulated/0/"; else actualUserHome_value = System.getProperty("user.home"); } return actualUserHome_value; } static public File actualUserHome(String sub) { return newFile(new File(actualUserHome()), sub); } static public RSyntaxTextAreaWithSearch liveValueRSyntaxTextArea_bothWays(SimpleLiveValue lv) { RSyntaxTextAreaWithSearch ta = rSyntaxTextAreaWithSearch(); bindTextComponentToLiveValue_bothWays(ta.textArea(), lv); return ta; } 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 boolean renameFileVerbose(File a, File b) { if (a == null || b == null) return false; boolean result = renameFile(a, 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 IMeta toIMeta(Object o) { return initIMeta(o); } static public java.awt.Color colorFromHex(String hex) { return awtColor(hex); } static public Pt translatePt(Pt a, Pt b) { return addPts(a, b); } static public Pt translatePt(int x, int y, Pt a) { return addPts(a, pt(x, y)); } static public Pt translatePt(Pt a, int x, int y) { return translatePt(x, y, a); } static public BWImage scaledBWImageFromBWIntegralImage_withMeta(int w, IBWIntegralImage img) { return scaledBWImageFromBWIntegralImage_withMeta(img, w); } static public BWImage scaledBWImageFromBWIntegralImage_withMeta_height(int h, IBWIntegralImage img) { return scaledBWImageFromBWIntegralImage_withMeta(img, widthForHeight(img, h), h); } static public BWImage scaledBWImageFromBWIntegralImage_withMeta(IBWIntegralImage img, int w) { return scaledBWImageFromBWIntegralImage_withMeta(img, w, heightForWidth(img, w)); } static public BWImage scaledBWImageFromBWIntegralImage_withMeta(IBWIntegralImage img, int w, int h) { ScaledBWImageFromBWIntegralImage x = new ScaledBWImageFromBWIntegralImage(img, w, h); x.run(); return setMetaSrc(x.result, x); } static public String hijackPrint(Runnable r) { StringBuilder buf = new StringBuilder(); Object old = interceptPrintInThisThread(new F1() { public Boolean get(String s) { buf.append(s); return false; } }); try { { if (r != null) r.run(); } return str(buf); } finally { interceptPrintInThisThread(old); } } static public JPanel comboBoxAndButton(JComboBox cb, String buttonText, IVF1 onEnter) { Runnable r = new Runnable() { public void run() { try { callF(onEnter, getText(cb)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onEnter, getText(cb))"; } }; return centerAndEastWithMargin(onEnter(cb, r), jbutton(buttonText, r)); } static public Set keys(Map map) { return map == null ? new HashSet() : map.keySet(); } static public Set keys(Object map) { return keys((Map) map); } static public Set keys(MultiSet ms) { return ms == null ? null : ms.keySet(); } static public Set keys(IMultiMap mm) { return mm == null ? null : mm.keySet(); } static public A nu(Class c, Object... values) { A a = nuObject(c); setAll(a, values); return a; } static public char stringToChar(String s) { if (l(s) != 1) throw fail("bad stringToChar: " + s); return firstChar(s); } static public String assertIdentifier(String s) { return assertIsIdentifier(s); } static public String assertIdentifier(String msg, String s) { return assertIsIdentifier(msg, s); } static public double parseDouble(String s) { return empty(s) ? 0.0 : Double.parseDouble(s); } static public ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal(); static public void checkFileNotTooBigToRead(File f) { callF(checkFileNotTooBigToRead_tl.get(), f); } static public void setTab(JExtendedTabbedPane tabs, int iTab, Component c) { if (tabs != null) { swing(() -> { if (iTab >= 0 && iTab < countTabs(tabs)) tabs.setComponentAt(iTab, wrap(c)); }); } } static public void setTab(JTabbedPane tabs, int iTab, Component c) { if (tabs != null) { swing(() -> { if (iTab >= 0 && iTab < countTabs(tabs)) tabs.setComponentAt(iTab, wrap(c)); }); } } static public Object sleepQuietly_monitor = new Object(); static public void sleepQuietly() { try { assertFalse(isAWTThread()); synchronized (sleepQuietly_monitor) { sleepQuietly_monitor.wait(); } } catch (Exception __e) { throw rethrow(__e); } } static public Map rawTableLineAsMap(JTable tbl, int row) { if (row >= 0 && row < tbl.getModel().getRowCount()) { Map map = litorderedmap(); for (int i = 0; i < tbl.getModel().getColumnCount(); i++) mapPut(map, tbl.getModel().getColumnName(i), tbl.getModel().getValueAt(row, i)); return map; } return null; } static public AutoCloseable tempMapPutAll(Map map, Map toAdd) { if (map != null && nempty(toAdd)) { List> toRestore = new ArrayList(); for (var __0 : _entrySet(toAdd)) { var key = __0.getKey(); var value = __0.getValue(); if (key != null && value != null) { B old = map.put(key, value); if (!eq(old, value)) toRestore.add(pair(key, old)); } } return () -> { for (var p : toRestore) mapPutOrRemove(map, p.a, p.b); }; } return null; } static public String dirPath(File f) { return f == null ? null : f.getParent(); } static public SimpleLiveValue liveValue_hasChangeListeners(A object, IF0 getter) { return liveValue_hasChangeListeners(object, null, getter); } static public SimpleLiveValue liveValue_hasChangeListeners(A object, Class type, IF0 getter) { return liveValue_hasChangeListeners(object, type, getter, null); } static public SimpleLiveValue liveValue_hasChangeListeners(A object, IF0 getter, IVF1 setter) { return liveValue_hasChangeListeners(object, null, getter, setter); } static public SimpleLiveValue liveValue_hasChangeListeners(A object, Class type, IF0 getter, IVF1 setter) { SimpleLiveValue value = new SimpleLiveValue<>(type, getter.get()); addWeakChangeListener(object, value, val -> val.set(getter.get())); value.onChange(() -> { { if (setter != null) setter.get(value.get()); } }); return value; } static public String commaCombine(Object... l) { return joinNemptiesWithComma(flattenCollectionsAndArrays(l)); } static public Map mapToValues(Iterable l, Object f) { return mapKeyAndFunction(l, f); } static public Map mapToValues(Object f, Iterable l) { return mapKeyAndFunction(f, l); } static public Map mapToValues(Iterable l, IF1 f) { return mapKeyAndFunction(f, l); } static public Map mapToValues(IF1 f, Iterable l) { return mapKeyAndFunction(f, l); } static public Map mapToValues(Map map, IF2 f) { return mapKeyAndFunction(map, f); } static public int toInt(Object o) { if (o == null) return 0; if (o instanceof Number) return ((Number) o).intValue(); if (o instanceof String) return parseInt((String) o); if (o instanceof Boolean) return boolToInt((Boolean) o); throw fail("woot not int: " + getClassName(o)); } static public int toInt(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } static public A or(A a, A b) { return a != null ? a : b; } static public ClassLoader classLoaderForObject(Object o) { if (o instanceof ClassLoader) return ((ClassLoader) o); if (o == null) return null; return _getClass(o).getClassLoader(); } static public Map syncMRUCache(int size) { return synchroMap(new MRUCache(size)); } 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 void setProgressBarValue(JProgressBar bar, int value) { swingCall(bar, "setValue", value); } static public void setProgressBarValue(JProgressBar bar, int value, int total) { setProgressBarTotal(bar, total); setProgressBarValue(bar, value); } static public int roundDownTo(int n, int x) { return x / n * n; } static public long roundDownTo(long n, long x) { return x / n * n; } static public double roundDownTo(double n, double x) { return floor(x / n) * n; } static public SimpleLiveValue stringLiveValue() { return new SimpleLiveValue(String.class); } static public SimpleLiveValue stringLiveValue(String value) { return new SimpleLiveValue(String.class, value); } static public int charDiff(char a, char b) { return (int) a - (int) b; } static public int charDiff(String a, char b) { return charDiff(stringToChar(a), b); } static public int indexOfMax(List l, IF1 f) { Best_comparable best = new Best_comparable(); for (int i = 0; i < l(l); i++) best.put(i, f.get(l.get(i))); return or(best.get(), -1); } static public Map tableColumnWidthsByName(JTable table) { TableColumnModel tcm = table.getColumnModel(); if (tcm == null) return null; int n = tcm.getColumnCount(); TreeMap map = new TreeMap(); for (int i = 0; i < n; i++) { TableColumn tc = tcm.getColumn(i); map.put(str(tc.getHeaderValue()), tc.getWidth()); } return map; } static public A swingConstruct(final Class c, final Object... args) { return swing(new F0() { public A get() { try { return nuObject(c, args); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return nuObject(c, args);"; } }); } static volatile public Object isAllowed_function; static volatile public boolean isAllowed_all = true; static public boolean isAllowed(String askingMethod, Object... args) { Object f = vm_generalMap_get("isAllowed_function"); if (f != null && !isTrue(callF(f, askingMethod, args))) return false; return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args)); } static public A jtransparent(final A a) { { swing(() -> { a.setOpaque(false); }); } return a; } static public LinkedHashMap orderMapByValue(final Map map) { List l = new ArrayList(map.keySet()); sort(l, mapComparator(map)); LinkedHashMap map2 = litorderedmap(); for (A a : l) map2.put(a, map.get(a)); return map2; } static public A jPreferWidth(int w, A c) { { swing(() -> { Dimension size = c.getPreferredSize(); c.setPreferredSize(new Dimension(w, size.height)); }); } return c; } static public A jPreferWidth(A c, int w) { return jPreferWidth(w, c); } 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) { pcallFail(__e); } sleep(1); } } return c; } static public Iterator iterator(Iterable c) { return c == null ? emptyIterator() : c.iterator(); } static public JPanel northCenterAndSouth(Component n, Component c, Component s) { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.NORTH, wrap(n)); panel.add(BorderLayout.CENTER, wrap(c)); panel.add(BorderLayout.SOUTH, wrap(s)); return panel; } static public A withToolTip(A c, final Object toolTip) { return setToolTipText(c, toolTip); } static public A withToolTip(Object toolTip, A c) { return setToolTipText(toolTip, c); } static public A assertNotNull(A a) { assertTrue(a != null); return a; } static public A assertNotNull(String msg, A a) { assertTrue(msg, a != null); return a; } static public A assertNotNull(Scorer scorer, String msg, A a) { if (scorer == null) return assertNotNull(msg, a); if (a == null) { print("BAD - " + msg + " is null: " + a); scorer.add(false); } else { print("OK, " + msg + " not null: " + a); scorer.add(true); } return a; } static public Pair fillTableWithData_makeData(List rows, List colNames) { return fillTableWithData_makeData(rows, asStringArray(colNames)); } static public Pair fillTableWithData_makeData(List rows, String... colNames) { Object[][] data = new Object[rows.size()][]; int w = 0; for (int i = 0; i < rows.size(); i++) { List l = rows.get(i); Object[] r = new Object[l.size()]; for (int j = 0; j < l.size(); j++) { Object o = l.get(j); if (o instanceof BufferedImage) o = imageIcon((BufferedImage) o); if (o instanceof RGBImage) o = imageIcon((RGBImage) o); r[j] = o; } data[i] = r; w = Math.max(w, l.size()); } Object[] columnNames = new Object[w]; for (int i = 0; i < w; i++) columnNames[i] = i < l(colNames) ? colNames[i] : "?"; return pair(data, columnNames); } 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 int tabCount(JExtendedTabbedPane tabs) { return tabs == null ? 0 : swing(() -> tabs.getTabCount()); } static public int tabCount(JTabbedPane tabs) { return tabs == null ? 0 : swing(() -> tabs.getTabCount()); } static public String shortDynamicClassName(Object o) { if (o instanceof DynamicObject && ((DynamicObject) o).className != null) return ((DynamicObject) o).className; return shortClassName(o); } static public Map cgetAll(Concept c, Collection fields) { return mapToValues(fields, f -> cget(c, f)); } static public Thread currentThread() { return Thread.currentThread(); } static public int identityHash(Object o) { return identityHashCode(o); } static public java.awt.Color awtColor(String hex) { byte[] b = bytesFromHex(dropPrefix("#", hex)); return new Color(ubyteToInt(b[0]), ubyteToInt(b[1]), ubyteToInt(b[2])); } static public JTextField jtextfield() { return jTextField(); } static public JTextField jtextfield(String text) { return jTextField(text); } static public JTextField jtextfield(Object o) { return jTextField(o); } static public String str(Object o) { return o == null ? "null" : o.toString(); } static public String str(char[] c) { return c == null ? "null" : new String(c); } static public String str(char[] c, int offset, int count) { return new String(c, offset, count); } static public void disposeWindows(final Collection l) { for (Window w : unnull(l)) disposeWindow(w); } static public A jPreferHeight(int h, A c) { Dimension size = c.getPreferredSize(); c.setPreferredSize(new Dimension(size.width, max(h, size.height))); return c; } static public JPanel westAndCenter(final Component w, final Component c) { return swing(new F0() { public JPanel get() { try { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.WEST, wrap(w)); panel.add(BorderLayout.CENTER, wrap(c)); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST..."; } }); } static public LineAndColumn tokenToLineAndColumn(ListAndIndex ptr) { return ptr == null ? null : tokenToLineAndColumn(ptr.list(), ptr.idx()); } static public LineAndColumn tokenToLineAndColumn(List tok, int tokenIndex) { int line = 1, col = 1; tokenIndex = min(tokenIndex, l(tok)); for (int i = 0; i < tokenIndex; i++) { String t = tok.get(i); int n = l(t); for (int j = 0; j < n; j++) if (t.charAt(j) == '\n') { ++line; col = 1; } else ++col; } return new LineAndColumn(line, col); } static public File loadBinarySnippet(String snippetID) { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadLibrary(snippetID); return loadBinarySnippet_noResourceLoader(snippetID); } static public File loadBinarySnippet_noResourceLoader(String snippetID) { try { long id = parseSnippetID(snippetID); if (isImageServerSnippet(id)) return loadImageAsFile(snippetID); File f = DiskSnippetCache_getLibrary(id); if (fileSize(f) == 0) f = loadDataSnippetToFile_noResourceLoader(snippetID); return f; } catch (Exception __e) { throw rethrow(__e); } } static public IterableIterator concurrentlyIterateValues(NavigableMap map) { return concurrentlyIterateValues(map, map); } static public IterableIterator concurrentlyIterateValues(final NavigableMap map, Object mutex) { return iteratorFromFunction(new F0() { public Iterator it = keys(map).iterator(); public A key; public B get() { synchronized (mutex) { try { if (!it.hasNext()) return null; return map.get(key = it.next()); } catch (ConcurrentModificationException e) { print("Re-iterating"); it = map.tailMap(key, false).keySet().iterator(); if (!it.hasNext()) return null; return map.get(key = it.next()); } } } }); } 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 JPanel jCenteredRaisedSection(Swingable c) { return jCenteredRaisedSection("", c); } static public JPanel jCenteredRaisedSection(String title, Swingable c) { return jCenteredRaisedSection(title, wrap(c)); } static public JPanel jCenteredRaisedSection(Component c) { return jCenteredRaisedSection("", c); } static public JPanel jCenteredRaisedSection(String title, Component c) { return centerSection(jRaisedSection(title, c)); } static public BufferedImage createBufferedImage(int w, int h, Color color) { return newBufferedImage(w, h, color); } static public String longestPrefixInTreeSet(String s, TreeSet set) { return longestPrefixInNavigableSet(s, set); } static public List beforeDelegatingToThread_operations = synchroList(); static public void beforeDelegatingToThread(Thread t) { for (Object op : cloneList(beforeDelegatingToThread_operations)) pcallF(op, t); } static public void beforeDelegatingToThread_do(Object f) { setAdd(beforeDelegatingToThread_operations, f); } static public String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); } static public String hideCredentials(String url) { try { if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url))) return url; } catch (Throwable e) { print("HideCredentials", e); } return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2="); } static public String hideCredentials(Object o) { return hideCredentials(str(o)); } static public CharInToken charIndexToCharInToken(List tok, int charIndex) { int i = 0, idx = 0, lTok; while (i < l(tok) && idx + (lTok = l(tok.get(i))) <= charIndex) { idx += lTok; i++; } return new CharInToken(tok, i, charIndex - idx); } static public JComponent withLabelToTheRight(Swingable component, String label) { return withLabelToTheRight(toJComponent(component), label); } static public JComponent withLabelToTheRight(JComponent component, String label) { return centerAndEast(component, jlabel(" " + label)); } static public JComponent withLabelToTheRight(String label, Swingable component) { return withLabelToTheRight(label, toJComponent(component)); } static public JComponent withLabelToTheRight(String label, JComponent component) { return withLabelToTheRight(component, label); } 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 Class getMainClass() { return mc(); } static public Class getMainClass(Object o) { try { if (o == null) return null; if (o instanceof Class && eq(((Class) o).getName(), "x30")) return (Class) o; ClassLoader cl = (o instanceof Class ? (Class) o : o.getClass()).getClassLoader(); if (cl == null) return null; String name = mainClassNameForClassLoader(cl); return loadClassFromClassLoader_orNull(cl, name); } catch (Exception __e) { throw rethrow(__e); } } static public 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 internalFrameDefaultPosition(JInternalFrame f) { f.setSize(500, 300); centerInternalFrame(f); } static public A bindToolTipToLiveValue(LiveValue lv, A c) { bindLiveValueListenerToComponent(c, lv, new Runnable() { public void run() { try { setToolTipText(c, strOrNull(lv.get())); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setToolTipText(c, strOrNull(lv!))"; } }); return c; } static public String exceptionToStringShorter(Throwable e) { e = getInnerException(e); return exceptionToStringShorter_dontDropOuterExceptions(e); } static public int jlist_indexOf(JList list, A item) { return swing(new F0() { public Integer get() { try { ListModel model = list.getModel(); int n = model.getSize(); for (int i = 0; i < n; i++) if (eq(model.getElementAt(i), item)) return i; return -1; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ListModel model = list.getModel();\r\n int n = model.getSize();\r\n for ..."; } }); } static public LinkedHashMap syncMapPut2_createLinkedHashMap(LinkedHashMap map, A key, B value) { if (key != null) if (value != null) { if (map == null) map = new LinkedHashMap(); synchronized (collectionMutex(map)) { map.put(key, value); } } else if (map != null) synchronized (collectionMutex(map)) { map.remove(key); } return map; } static public boolean isValidFileCharacter(char c) { return isLetterOrDigit(c) || contains(".-_ %", c); } 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 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 void setProgressBarText(JProgressBar bar, String text) { swingCall(bar, "setString", text); } static public void dm_watchFieldAndNow(String field, Runnable onChange) { dm_watchField(field, onChange); dm_q(onChange); } static public boolean isSubclass(Class a, Class b) { return a != null && b != null && b.isAssignableFrom(a); } static public A[] arrayOfSameType(A[] a, int n) { return newObjectArrayOfSameType(a, n); } 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 Method findMethod_precise_onTypes(Object o, String method, Class... argTypes) { try { if (o instanceof Class) { _MethodCache cache = callOpt_getCache((Class) o); List methods = cache.cache.get(method); Lowest best = new Lowest(); if (methods != null) for (Method m : methods) { { if (!(isStaticMethod(m))) continue; } int score = methodApplicabilityScore_onTypes(m, argTypes); if (score < Integer.MAX_VALUE) best.put(m, score); } return best.get(); } if (o == null) return null; _MethodCache cache = callOpt_getCache(o.getClass()); List methods = cache.cache.get(method); Lowest best = new Lowest(); if (methods != null) for (Method m : methods) { int score = methodApplicabilityScore_onTypes(m, argTypes); if (score < Integer.MAX_VALUE) best.put(m, score); } return best.get(); } catch (Exception __e) { throw rethrow(__e); } } static public void saveJPG(BufferedImage img, File file) { try { if (!ImageIO.write(img, "jpeg", mkdirsFor(file))) { print("Reconstructing image for saving JPEG"); img = reconstructBufferedImage(img); if (!ImageIO.write(img, "jpeg", file)) throw fail("Couldn't write JPEG: " + file + " (" + img + ")"); } vmBus_send("wroteFile", file); } catch (Exception __e) { throw rethrow(__e); } } static public void saveJPG(File file, BufferedImage img) { try { saveJPG(img, file); } catch (Exception __e) { throw rethrow(__e); } } static public int vstackWithSpacing_fixed_default = 10; static public JPanel vstackWithSpacing_fixed(List parts) { return vstackWithSpacing_fixed(parts, vstackWithSpacing_fixed_default); } static public JPanel vstackWithSpacing_fixed(List parts, int spacing) { return swing(() -> { 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(0, 0, spacing, 0); smartAddWithLayout(panel, gbc, flattenToArray(parts)); gbc.weighty = 1; gbc.insets = new Insets(0, 0, 0, 0); panel.add(jrigid(), gbc); return panel; }); } static public JPanel vstackWithSpacing_fixed(Component... parts) { return vstackWithSpacing_fixed(vstackWithSpacing_fixed_default, parts); } static public JPanel vstackWithSpacing_fixed(int spacing, Component... parts) { return vstackWithSpacing_fixed(asList(parts), spacing); } static public boolean checkConceptFieldsIC(Concept x, Object... data) { for (int i = 0; i < l(data); i += 2) if (!eqicOrEq(cget(x, (String) data[i]), deref(data[i + 1]))) return false; return true; } static public Class loadClassFromClassLoader_orNull(ClassLoader cl, String name) { try { return cl == null ? null : cl.loadClass(name); } catch (ClassNotFoundException e) { return null; } } static public JSpinner dm_spinner(String field, int min, int max) { return liveValueSpinner(dm_fieldLiveValue(field), min, max); } static public String unnullForIteration(String s) { return s == null ? "" : s; } static public Collection unnullForIteration(Collection l) { return l == null ? immutableEmptyList() : l; } static public List unnullForIteration(List l) { return l == null ? immutableEmptyList() : l; } static public byte[] unnullForIteration(byte[] l) { return l == null ? emptyByteArray() : l; } static public int[] unnullForIteration(int[] l) { return l == null ? emptyIntArray() : l; } static public char[] unnullForIteration(char[] l) { return l == null ? emptyCharArray() : l; } static public double[] unnullForIteration(double[] l) { return l == null ? emptyDoubleArray() : l; } static public short[] unnullForIteration(short[] l) { return l == null ? emptyShortArray() : l; } static public Map unnullForIteration(Map l) { return l == null ? immutableEmptyMap() : l; } static public Iterable unnullForIteration(Iterable i) { return i == null ? immutableEmptyList() : i; } static public A[] unnullForIteration(A[] a) { return a == null ? (A[]) emptyObjectArray() : a; } static public BitSet unnullForIteration(BitSet b) { return b == null ? new BitSet() : b; } static public Pt unnullForIteration(Pt p) { return p == null ? new Pt() : p; } static public Symbol unnullForIteration(Symbol s) { return s == null ? emptySymbol() : s; } static public Pair unnullForIteration(Pair p) { return p != null ? p : new Pair(null, null); } static public long unnullForIteration(Long l) { return l == null ? 0L : l; } static public JScrollPane jscroll(Component c) { return swing(() -> { return c instanceof JScrollPane ? ((JScrollPane) c) : new JScrollPane(c); }); } static public AutoCloseable tempSetButtonImages(Collection buttons, ImageIcon img) { return combineAutoCloseables(map(buttons, b -> tempSetButtonImage(b, img))); } static public void setMenuBar(final JMenuBar mb, final RootPaneContainer f) { { swing(() -> { call(f, "setJMenuBar", mb); revalidate((Component) f); }); } } static public void setMenuBar(RootPaneContainer f, JMenuBar mb) { setMenuBar(mb, f); } static public JLabel makeLabelBold(JLabel l) { if (l != null) { swing(() -> { l.setFont(l.getFont().deriveFont(Font.BOLD)); }); } return l; } static public MultiMap descTreeMultiMap() { return new MultiMap(descTreeMap()); } 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 double normalizeTo0to1(double x) { return Math.min(Math.max(x, 0), 1); } static public File execFileChooser(JFileChooser fileChooser) { return fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ? fileChooser.getSelectedFile() : null; } static public List> showForm_makeComponents(Boolean internalFrame, Object... _parts) { IVF1 closeFrame = isTrue(internalFrame) ? __1 -> disposeInternalFrame(__1) : isFalse(internalFrame) ? __2 -> disposeFrame(__2) : null; return showForm_makeComponents(closeFrame, _parts); } static public List> showForm_makeComponents(IVF1 closeFrame, Object... _parts) { List> l = new ArrayList(); List parts = asList(_parts); JButton submitButton = null; for (int i = 0; i < l(parts); i++) if (parts.get(i) instanceof Swingable) parts.set(i, ((Swingable) parts.get(i)).visualize()); for (int i = 0; i < l(parts); i++) { Object o = parts.get(i), next = get(parts, i + 1); if (o instanceof String && next instanceof Component) setComponentID((Component) next, (String) o); if (o instanceof Component || o instanceof String || next instanceof Component) { l.add(mapLL(__105 -> wrapForSmartAdd_jComponent(__105), o == null ? new JPanel() : o instanceof String ? humanizeFormLabel((String) o) : o, next)); if (next instanceof JButton && submitButton == null) submitButton = (JButton) next; i++; } else if (isRunnable(o)) l.add(mapLL(__106 -> wrapForSmartAdd_jComponent(__106), null, submitButton = jbutton(showFormSubmitButtonName(), new Runnable() { public void run() { try { Object result = call(o); print("Result of form runnable: " + result + ". Button: " + heldInstance(JButton.class)); if (neq(Boolean.FALSE, result)) { if (closeFrame != null) closeFrame.get(heldInstance(JButton.class)); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object result = call(o);\r\n print(\"Result of form runnable: \" + result ..."; } }))); else print("showForm: Unknown element type: " + getClassName(o)); } if (submitButton != null) { final JButton _submitButton = submitButton; onEnterInAllTextFields(concatLists(l), new Runnable() { public void run() { try { clickButton(_submitButton); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "clickButton(_submitButton)"; } }); } for (List row : l) { JComponent left = first(row); if (left instanceof JLabel) makeBold((JLabel) left).setVerticalAlignment(JLabel.TOP); } return l; } static public JInternalFrame centerInternalFrame(final JInternalFrame f) { { swing(() -> { Container c = f.getParent(); if (c != null) { f.setLocation((c.getWidth() - f.getWidth()) / 2, (c.getHeight() - f.getHeight()) / 2); } }); } return f; } static public JInternalFrame centerInternalFrame(final int w, final int h, final JInternalFrame f) { { swing(() -> { f.setSize(w, h); }); } return centerInternalFrame(f); } static public Object[] flattenToArray(Object... a) { return flattenArray2(a); } static public Rect screenBounds_safe(int iScreen) { return screenBounds(min(iScreen, screenCount() - 1)); } 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 BufferedImage imageIO_readURL(String url) { try { return ImageIO.read(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } static public boolean isImageFile(File f) { return isImageFileName(fileName(f)) && isFile(f); } static public Runnable asRunnable(Object o) { return toRunnable(o); } static public A bindTextComponentToLiveValue_bothWays(A tc, SimpleLiveValue lv) { bindLiveValueListenerToComponent(tc, lv, new Runnable() { public void run() { try { setTextKeepCaret(tc, lv.get()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setTextKeepCaret(tc, lv!)"; } }); onChange(tc, new Runnable() { public void run() { try { lv.set(getText(tc)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lv.set(getText(tc))"; } }); return tc; } static public A _get(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } static public Object _get(Object o, String field) { return get(o, field); } static public Object _get(String field, Object o) { return get(o, field); } static public A _get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } static public File jigsawModuleFile(String moduleName) { return jigsawModuleFile(moduleName, javaHome()); } static public File jigsawModuleFile(String moduleName, File javaHome) { return new File(javaHome, "jmods/" + moduleName + ".jmod"); } static public boolean boolOptPar(ThreadLocal tl) { return boolOptParam(tl); } static public boolean boolOptPar(Object[] __, String name) { return boolOptParam(__, name); } static public boolean boolOptPar(String name, Object[] __) { return boolOptParam(__, name); } public static File mkdirsForFile(File file) { File dir = file.getParentFile(); if (dir != null) { dir.mkdirs(); if (!dir.isDirectory()) if (dir.isFile()) throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!"); else throw fail("Unknown IO exception during mkdirs of " + f2s(file)); } return file; } public static String mkdirsForFile(String path) { mkdirsForFile(new File(path)); return path; } static public VF1 runnableToVF1(final Runnable r) { return r == null ? null : new VF1() { public void get(A a) { try { r.run(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "r.run()"; } }; } static public Set createOrAddToSyncLinkedHashSet(Set set, A a) { if (set == null) set = syncLinkedHashSet(); set.add(a); return set; } 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 ConceptFieldIndexCI getConceptFieldCIIndex(Class c, String field) { return getConceptFieldCIIndex(db_mainConcepts(), c, field); } static public ConceptFieldIndexCI getConceptFieldCIIndex(Concepts concepts, Class c, String field) { return (ConceptFieldIndexCI) concepts.getCIFieldIndex(c, field); } static public JSpinner liveValueSpinner(IVarWithNotify lv, int min, int max) { JSpinner spinner = jSpinner(lv.get(), min, max); return bindLiveValueToSpinner(lv, spinner); } static public List listDirsContainingFileNamed(File dir, String fileName) { return filter(listDirs(dir), d -> isFile(newFile(d, fileName))); } static public List synchroList() { return synchroList(new ArrayList()); } static public List synchroList(List l) { return new SynchronizedList(l); } static public JComponent componentToJComponent(Component c) { if (c instanceof JComponent) return (JComponent) c; if (c instanceof JFrame) return ((JFrame) c).getRootPane(); if (c == null) return null; throw fail("boohoo " + getClassName(c)); } static public BufferedImage inputImage_image; static public BufferedImage inputImage() { if (inputImage_image != null) return inputImage_image; final ImageChooser ic = new ImageChooser(); if (!showTitledForm_blocking("Please Choose Image To Work On", "", ic)) throw fail("No input image selected"); return ic.getImage(); } static public AlphanumComparator alphaNumComparator_instance; static public Comparator alphaNumComparator() { if (alphaNumComparator_instance == null) alphaNumComparator_instance = new AlphanumComparator(); return alphaNumComparator_instance; } static public Object pcallF_minimalExceptionHandling(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable e) { System.out.println(getStackTrace(e)); _storeException(e); } return null; } static public boolean eqic(String a, String b) { if ((a == null) != (b == null)) return false; if (a == null) return true; return a.equalsIgnoreCase(b); } static public boolean eqic(Symbol a, Symbol b) { return eq(a, b); } static public boolean eqic(Symbol a, String b) { return eqic(asString(a), b); } static public boolean eqic(char a, char b) { if (a == b) return true; char u1 = Character.toUpperCase(a); char u2 = Character.toUpperCase(b); if (u1 == u2) return true; return Character.toLowerCase(u1) == Character.toLowerCase(u2); } static public String pnlToLines(String prefix, Iterable l) { return pnlToString(prefix, l); } static public String pnlToLines(Iterable l) { return pnlToString(l); } static public String pnlToLines(A[] l) { return pnlToString(l); } static public String pnlToLines(Map map) { return pnlToString(map); } static public String pnlToLines(MultiMap map) { return pnlToString(map); } static public void appendToTextFile(File file, String s) { appendToFile(file, s); } static public void appendToTextFile(String file, String s) { appendToTextFile(programFile(file), s); } static public Image resizeImage_raw(Image img, int newW, int newH) { return resizeImage_raw(img, newW, newH, Image.SCALE_SMOOTH); } static public Image resizeImage_raw(Image img, int newW, int newH, int scaleType) { if (newW == img.getWidth(null) && newH == img.getHeight(null)) return img; return img.getScaledInstance(newW, newH, scaleType); } static public Image resizeImage_raw(Image img, int newW) { int newH = iround(img.getHeight(null) * (double) newW / img.getWidth(null)); return resizeImage_raw(img, newW, newH); } static public Image resizeImage_raw(int newW, Image img) { return resizeImage_raw(img, newW); } 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 int indexOfIC(List a, String b) { return indexOfIgnoreCase(a, b); } static public int indexOfIC(List a, String b, int i) { return indexOfIgnoreCase(a, b, i); } static public int indexOfIC(String[] a, String b) { return indexOfIC(a, b, 0); } static public int indexOfIC(String[] a, String b, int i) { return indexOfIgnoreCase(a, b, i); } static public int indexOfIC(String a, String b) { return indexOfIgnoreCase(a, b); } static public int indexOfIC(String a, String b, int i) { return indexOfIgnoreCase(a, b, i); } static public String conceptsFileName() { return "concepts.structure.gz"; } static public B pairB(Pair p) { return p == null ? null : p.b; } 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 JButton jdisabledButton(String text, Object action) { JButton b = newButton(text, action); setEnabled(b, false); return b; } static public JButton jdisabledButton(String text) { return jdisabledButton(text, null); } 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 A addAllComponents(A c, List components) { if (nempty(components)) { swing(() -> { for (Component x : components) c.add(x); revalidate(c); }); } return c; } static public A addAllComponents(A c, Component... components) { return addAllComponents(c, asList(components)); } static public A[] toTypedArray(Class type, Iterable c) { return toArray(c, type); } static public A addToButtonGroup(ButtonGroup group, A btn) { { swing(() -> { group.add(btn); }); } return btn; } static public FileInputStream newFileInputStream(File path) throws IOException { return newFileInputStream(path.getPath()); } static public FileInputStream newFileInputStream(String path) throws IOException { FileInputStream f = new FileInputStream(path); _registerIO(f, path, true); return f; } static public List listZipEntries(File inZip) { try { if (inZip == null) return null; ZipFile zipFile = new ZipFile(inZip); try { return listZipEntries(zipFile); } finally { _close(zipFile); } } catch (Exception __e) { throw rethrow(__e); } } static public List listZipEntries(ZipFile zipFile) { try { List list = new ArrayList(); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) (entries.nextElement()); if (!entry.isDirectory()) list.add(entry); } return list; } catch (Exception __e) { throw rethrow(__e); } } static public BufferedImage loadImage2(String snippetIDOrURL) { return loadBufferedImage(snippetIDOrURL); } static public BufferedImage loadImage2(File file) { return loadBufferedImage(file); } static public void stepMaxWithStats(Steppable s, long maxSteps) { stepAllWithStats(s, maxSteps); } static public void stepMaxWithStats(long maxSteps, Steppable s) { stepMaxWithStats(s, maxSteps); } static public Field makeAccessible(Field f) { try { f.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error", e, f); } return f; } static public Method makeAccessible(Method m) { try { m.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error", e, m); } return m; } static public Constructor makeAccessible(Constructor c) { try { c.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error", e, c); } return c; } static public JScrollPane jscroll_centered_borderless(Component c) { return borderlessScrollPane(jscroll_centered(c)); } static public String dropPrefix(String prefix, String s) { return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s; } static public String imageServerLink(String md5OrID) { if (possibleMD5(md5OrID)) return "https://botcompany.de/images/md5/" + md5OrID; return imageServerLink(parseSnippetID(md5OrID)); } static public String imageServerLink(long id) { return "https://botcompany.de/images/" + id; } static public JButton jDisabledButton(String text, Object action) { return jdisabledButton(text, action); } static public JButton jDisabledButton(String text) { return jdisabledButton(text); } static public JScrollPane jscroll_copyBackground(Component c) { return setScrollPaneBackground(getBackground(c), jscroll(c)); } 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 JFormattedTextField getTextFieldFromSpinner(JSpinner spinner) { return spinner == null ? null : swing(() -> ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField()); } static public List _registerDangerousWeakMap_preList; static public A _registerDangerousWeakMap(A map) { return _registerDangerousWeakMap(map, null); } static public A _registerDangerousWeakMap(A map, Object init) { callF(init, map); if (init instanceof String) { final String f = (String) init; init = new VF1() { public void get(Map map) { try { callMC(f, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callMC(f, map)"; } }; } if (javax() == null) { if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList(); _registerDangerousWeakMap_preList.add(pair(map, init)); return map; } call(javax(), "_registerDangerousWeakMap", map, init); return map; } static public void _onLoad_registerDangerousWeakMap() { assertNotNull(javax()); if (_registerDangerousWeakMap_preList == null) return; for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b); _registerDangerousWeakMap_preList = null; } static public boolean isEnabled(final JComponent c) { return c != null && swing(new F0() { public Boolean get() { try { return c.isEnabled(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.isEnabled();"; } }); } static public byte[] utf8(String s) { return toUtf8(s); } static public Random customRandomizerForThisThread() { return customRandomizerForThisThread_tl().get(); } static public BufferedImage shootWindow(Window w) { w.toFront(); sleep(50); return shootScreen2(w.getBounds()); } static public JTextArea jTextArea_noUndo() { return jTextArea_noUndo(""); } static public JTextArea jTextArea_noUndo(final String text) { return swingNu(JTextArea.class, text); } static public Component jrigid() { return javax.swing.Box.createRigidArea(new Dimension(0, 0)); } static public Map emptyMap() { return new HashMap(); } 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 Map createGraphics_modulators = synchroIdentityHashMap(); static public Graphics2D createGraphics(BufferedImage img) { Graphics2D g = img.createGraphics(); Object mod = createGraphics_modulators.get(img); if (mod != null) callF(mod, g); return g; } static public void createGraphics_modulate(BufferedImage img, Object mod) { mapPut2(createGraphics_modulators, img, mod); } static public List allToString(Iterable c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } static public List allToString(Object[] c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } static public List paramsToButtons(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 l; } static public A[] newObjectArrayOfSameType(A[] a) { return newObjectArrayOfSameType(a, a.length); } static public A[] newObjectArrayOfSameType(A[] a, int n) { return (A[]) Array.newInstance(a.getClass().getComponentType(), n); } static public BufferedReader utf8bufferedReader(InputStream in) { try { return in == null ? null : bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in)); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedReader utf8bufferedReader(File f) { try { return utf8bufferedReader(newFileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } static public List secondOfPairs(Collection> l) { return lambdaMap(__107 -> secondOfPair(__107), l); } static public void loadBinaryPageToFile(String url, File file) { try { print("Loading " + url); loadBinaryPageToFile(openConnection(new URL(url)), file); } catch (Exception __e) { throw rethrow(__e); } } static public void loadBinaryPageToFile(URLConnection con, File file) { try { setHeaders(con); loadBinaryPageToFile_noHeaders(con, file); } catch (Exception __e) { throw rethrow(__e); } } static public void loadBinaryPageToFile_noHeaders(URLConnection con, File file) { try { assertNotNull(file); File ftemp = new File(f2s(file) + "_temp"); FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp)); try { InputStream inputStream = con.getInputStream(); long len = 0; try { len = con.getContentLength(); } catch (Throwable e) { printStackTrace(e); } String pat = " {*}" + (len != 0 ? "/" + len : "") + " bytes loaded."; copyStreamWithPrints(inputStream, buf, pat); inputStream.close(); buf.close(); file.delete(); renameFile_assertTrue(ftemp, file); } finally { if (buf != null) buf.close(); } } catch (Exception __e) { throw rethrow(__e); } } public static void copyFileToFileVerbose(File src, File dest) { print("Copying " + f2s(src) + " to " + f2s(dest)); copyFile(src, dest); } static public void centerDialogOverOwner(JDialog dialog) { if (dialog != null) { swing(() -> { var owner = dialog.getOwner(); if (owner != null) setLocation(dialog, center(boundsRect(owner))); }); } } static public BufferedImage reconstructBufferedImage(BufferedImage img) { if (img == null) return null; RGBImage rgb = new RGBImage(img); rgb.uncacheBufferedImage(); return rgb.getBufferedImage(); } static public double fraction(double d) { return d % 1; } static public File javaHome() { return envJavaHome(); } static public File javaHome(String sub) { return newFile(envJavaHome(), sub); } static public void tablePopupMenuItem(JTable table, String name, Object action) { tablePopupMenu(table, new VF2() { public void get(JPopupMenu menu, final Integer row) { try { addMenuItem(menu, name, new Runnable() { public void run() { try { pcallF(action, row); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, row)"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, name, r { pcallF(action, row) });"; } }); } static public void tablePopupMenuItem(JTable table, String name, IVF1 action) { tablePopupMenuItem(table, name, (Object) action); } static public void assertSameSize(BufferedImage a, BufferedImage b) { int w1 = a.getWidth(), w2 = b.getWidth(); int h1 = a.getHeight(), h2 = b.getHeight(); if (w1 != w2 || h1 != h2) throw fail("Different sizes: " + w1 + "*" + h1 + " vs " + w2 + "*" + h2); } static public void assertSameSize(WidthAndHeight a, WidthAndHeight b) { int w1 = a.getWidth(), w2 = b.getWidth(); int h1 = a.getHeight(), h2 = b.getHeight(); if (w1 != w2 || h1 != h2) throw fail("Different sizes: " + w1 + "*" + h1 + " vs " + w2 + "*" + h2); } static public void showDialogOnSameScreen(JDialog dialog, Component c) { swing(() -> { if (dialog == null) return; Window w = getWindow(c); if (w != null) centerWindowWithin(dialog, screenBounds_safe(screenNrOfWindow(w))); dialog.setVisible(true); }); } static public void messageBox(final String msg) { print(msg); { swing(() -> { JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE); }); } } static public void messageBox(Throwable e) { printStackTrace(e); messageBox(hideCredentials(innerException2(e))); } static public double nanosToMicroseconds(double ns) { return ns / 1000; } static public List sortByCalculatedField(Iterable c, final Object f) { List l = cloneList(c); sort(l, new Comparator() { public int compare(A a, A b) { return stdcompare(callF(f, a), callF(f, b)); } }); return l; } static public List findBackRefs(Collection concepts, Class type) { IdentityHashMap l = new IdentityHashMap(); for (Concept c : concepts) if (c.backRefs != null) for (Concept.Ref r : c.backRefs) if (instanceOf(r.concept(), type)) l.put((A) r.concept(), true); return asList(keys(l)); } static public List findBackRefs(Concept c, Class type) { IdentityHashMap l = new IdentityHashMap(); if (c != null && c.backRefs != null) for (Concept.Ref r : c.backRefs) if (instanceOf(r.concept(), type)) l.put((A) r.concept(), true); return asList(keys(l)); } static public List findBackRefs(Class type, Concept c) { return findBackRefs(c, type); } static public Collection findBackRefs(Concept c) { return findBackRefs(c, Concept.class); } static public List keysWithoutHidden(Map map) { return filter(keys(map), new F1() { public Boolean get(Object o) { try { return !eq(o, "[hidden]") && !isStringStartingWith(o, "[hidden] "); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "!eq(o, \"[hidden]\") && !isStringStartingWith(o, \"[hidden] \")"; } }); } static public JLabel jlabel_noAutoToolTip() { return jlabel_noAutoToolTip(" "); } static public JLabel jlabel_noAutoToolTip(String text) { var lbl = swingConstruct(BetterLabel.class, text); lbl.autoToolTip = false; return lbl; } 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 A componentPopupMenuItem(A c, String name, Runnable action) { componentPopupMenu(c, new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, name, action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, name, action);"; } }); return c; } static public void componentPopupMenuItem(JComponent c, JMenuItem menuItem) { componentPopupMenu(c, new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, menuItem); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, menuItem);"; } }); } static public JInternalFrame showForm_makeInternalFrame(JDesktopPane desktop, String title, JPanel panel) { JInternalFrame f = addInternalFrame(desktop, title, withMargin(panel)); minInternalFrameWidth(f, 400); packInternalFrameVertically(f); centerInternalFrame(f); return f; } static public boolean isShowing(Component c) { return isComponentShowing(c); } static public File imageSnippetCacheFile(String snippetID) { File dir = imageSnippetsCacheDir(); if (!loadBufferedImage_useImageCache) return null; return new File(dir, parseSnippetID(snippetID) + ".png"); } static public String dropTrailingBracketedCount(String s) { return replaceAll(s, "\\s?\\([0-9,]+\\)$", ""); } static public ArrayList cloneList_noSync(Iterable l) { return l instanceof Collection ? cloneList_noSync((Collection) l) : asList(l); } static public ArrayList cloneList_noSync(Collection l) { if (l == null) return new ArrayList(); return new ArrayList(l); } static public JPanel customLayoutPanel(final Object layouter) { return jpanel(layoutManagerFromFunction(layouter)); } static public JPanel customLayoutPanel(final Object layouter, final List components) { return addAllComponents(customLayoutPanel(layouter), components); } static public JPanel customLayoutPanel(LayoutManager layouter, Component... components) { return addAllComponents(customLayoutPanel(layouter), components); } static public int syncL(Collection l) { if (l == null) return 0; synchronized (collectionMutex(l)) { return l.size(); } } static public int syncL(Map map) { if (map == null) return 0; synchronized (collectionMutex(map)) { return map.size(); } } static public List syncL() { return syncList(); } static public void syncClear(Collection c) { if (c != null) synchronized (collectionMutex(c)) { c.clear(); } } static public void syncClear(Map map) { if (map != null) synchronized (collectionMutex(map)) { map.clear(); } } static public 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 long toLong(Object o) { if (o instanceof Number) return ((Number) o).longValue(); if (o instanceof String) return parseLong((String) o); return 0; } static public long toLong(Timestamp ts) { return ts == null ? 0 : ts.unixDate(); } static public long toLong(Date d) { return d == null ? 0 : d.getTime(); } static public File copyFileToClipboard(File f) { if (f == null) return null; Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new FileTransferable(f), null); vmBus_send("newClipboardContents", f); return f; } 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 long fileSize(String path) { return getFileSize(path); } static public long fileSize(File f) { return getFileSize(f); } static public List concatLists(Iterable... lists) { List l = new ArrayList(); if (lists != null) for (Iterable list : lists) addAll(l, list); return l; } static public List concatLists(Collection> lists) { List l = new ArrayList(); if (lists != null) for (Iterable list : lists) addAll(l, list); return l; } static public Object invokeMethod(Method m, Object o, Object... args) { try { try { return m.invoke(o, args); } catch (InvocationTargetException e) { throw rethrow(getExceptionCause(e)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args))); } } catch (Exception __e) { throw rethrow(__e); } } static public int tableNumColumns(JTable table) { return table == null ? 0 : swing(new F0() { public Integer get() { try { return table.getColumnCount(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return table.getColumnCount();"; } }); } static public boolean isMainProgram() { return creator() == null; } static public Random defaultRandomGenerator() { { Random r = customRandomizerForThisThread(); if (r != null) return r; } return ThreadLocalRandom.current(); } static public boolean swingConfirm(Component owner, String msg) { return confirmOKCancel(owner, msg); } static public boolean swingConfirm(String msg) { return confirmOKCancel(msg); } static public JMenuItem directJMenuItem(Action a) { return new JMenuItem(a) { public Dimension getMaximumSize() { return new Dimension(super.getPreferredSize().width, super.getMaximumSize().height); } }; } static public JMenuItem directJMenuItem(String text, Object action) { return directJMenuItem(abstractAction(text, action)); } static public boolean methodIsStatic(Method m) { return (m.getModifiers() & Modifier.STATIC) != 0; } static public BufferedImage scaleImageWithOp(BufferedImage before, double scaleX, int affineTransformOpType) { return scaleImageWithOp(before, scaleX, scaleX, affineTransformOpType); } static public BufferedImage scaleImageWithOp(BufferedImage before, double scaleX, double scaleY, int affineTransformOpType) { if (scaleX == 1 && scaleY == 1) return before; int w = before.getWidth(); int h = before.getHeight(); int neww = max(1, iround(w * scaleX)), newh = max(1, iround(h * scaleY)); BufferedImage after = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_ARGB); AffineTransform at = new AffineTransform(); at.scale(scaleX, scaleY); AffineTransformOp scaleOp = new AffineTransformOp(at, affineTransformOpType); return scaleOp.filter(before, after); } static public JPanel withSideAndBottomMargin(Component c) { return withSideAndBottomMargin(defaultMargin(), c); } static public JPanel withSideAndBottomMargin(int w, Component c) { return swing(() -> { JPanel p = marginPanel(); p.setBorder(BorderFactory.createEmptyBorder(0, w, w, w)); p.add(c); return p; }); } static public File conceptsDir() { return conceptsDir(db_mainConcepts()); } static public File conceptsDir(Concepts cc) { return cc.conceptsDir(); } static public File conceptsDir(String subName) { return conceptsDir(db_mainConcepts(), subName); } static public File conceptsDir(Concepts cc, String subName) { return newFile(conceptsDir(cc), subName); } static public List wrapAsList(A[] a) { return wrapArrayAsList(a); } 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); 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 img == null ? null : new ImageIcon(img); } static public ImageIcon imageIcon(RGBImage img) { return imageIcon(img.getBufferedImage()); } 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 String hmsWithColons() { return hmsWithColons(now()); } static public String hmsWithColons(long time) { return new SimpleDateFormat("HH:mm:ss").format(time); } static public List listWithoutSet(Collection l, Collection stuff) { return listMinusSet(l, stuff); } static public int screenCount() { return l(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()); } static public Map componentID_map = weakHashMap(); static public String componentID(Component c) { return c == null ? null : componentID_map.get(c); } static public List getAll(Map map, Collection l) { return lookupAllOpt(map, l); } static public List getAll(Collection l, Map map) { return lookupAllOpt(map, l); } static public > List getAll(Iterable l) { return getVars(l); } static public void onEnterIfTextField(Component c, Runnable action) { if (action == null) return; if (c instanceof JTextField) onEnter(((JTextField) c), action); else if (c instanceof JComboBox) onEnter(((JComboBox) c), action); } static public Runnable disableButtonWhileCalcing3(final Runnable r) { return new Runnable() { public void run() { try { disableButtonWhileCalcing2(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disableButtonWhileCalcing2(r)"; } }; } static public void disableButtonWhileCalcing2(final Object f) { final JButton button = heldInstance(JButton.class); disableButton(button); { startThread(new Runnable() { public void run() { try { try { boolean ok = isTrue(callF(f)); if (ok) disposePossiblyInternalFrame(button); } finally { enableButton(button); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n boolean ok = isTrue(callF(f));\r\n if (ok) disposePossiblyInt..."; } }); } } static public int intFromSpinner(JSpinner s) { return toInt(s.getValue()); } static public Map classForName_cache = synchroHashMap(); static public Class classForName(String name) { return classForName(name, null); } static public Class classForName(String name, Object classFinder) { if (classForName_cache == null || classFinder != null) return classForName_uncached(name, classFinder); Class c = classForName_cache.get(name); if (c == null) classForName_cache.put(name, c = classForName_uncached(name, null)); return c; } static public Class classForName_uncached(String name, Object classFinder) { try { if (classFinder != null) return (Class) callF(classFinder, name); return Class.forName(name); } catch (Exception __e) { throw rethrow(__e); } } static public String dateWithMSUTC() { return dateWithMSUTC(now()); } static public String dateWithMSUTC(long time) { var format = simpleDateFormat_UTC("yyyy/MM/dd"); return format.format(time) + " " + formatUTCWithMS_24(time); } static public JTextField jLiveValueTextField_bothWays(final SimpleLiveValue lv) { final JTextField ta = jTextField(); bindTextComponentToLiveValue_bothWays(ta, lv); return ta; } static public A makeBold(final A c) { if (c != null) { swing(() -> { c.setFont(c.getFont().deriveFont(java.awt.Font.BOLD)); }); } return c; } static public AutoCloseable tempSetCustomRandomizerForThisThread(Random random) { return tempSetTL(customRandomizerForThisThread_tl(), random); } static public File userDir() { return new File(userHome()); } static public File userDir(String path) { return new File(userHome(), path); } static public B getOrCreate(Map map, A key, Class c) { try { B b = map.get(key); if (b == null) map.put(key, b = c.newInstance()); return b; } catch (Exception __e) { throw rethrow(__e); } } static public B getOrCreate(Map map, A key, Object f) { try { B b = map.get(key); if (b == null) map.put(key, b = (B) callF(f)); return b; } catch (Exception __e) { throw rethrow(__e); } } static public B getOrCreate(IF0 f, Map map, A key) { return getOrCreate(map, key, f); } static public B getOrCreate(Map map, A key, IF0 f) { B b = map.get(key); if (b == null) map.put(key, b = f.get()); return b; } static public B getOrCreate(Class c, Map map, A key) { return getOrCreate(map, key, c); } static public A setAlwaysOnTop(A c) { return alwaysOnTop(c); } static public B syncMapGet2(Map map, A a) { if (map == null) return null; synchronized (collectionMutex(map)) { return map.get(a); } } static public B syncMapGet2(A a, Map map) { return syncMapGet2(map, a); } static public boolean isClosingBracket(String s) { return eqOneOf(s, ")", "}", "]"); } 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 int roundedRatio(double a, double b) { return iround(ratio(a, b)); } static public int roundedRatio(int a, int b) { return (a + b / 2 - 1) / b; } static public BufferedImage bufferedImageWithoutAlpha(int[] pixels, int w, int h) { return intArrayToBufferedImageWithoutAlpha(pixels, w, h); } static public BufferedImage bufferedImageWithoutAlpha(int w, int h, int[] pixels) { return intArrayToBufferedImageWithoutAlpha(pixels, w, h); } static public BufferedImage bufferedImageWithoutAlpha(int w, int h, Color color) { return bufferedImageWithoutAlpha(w, h, repIntAsArray(w * h, colorToInt(color))); } static public String str_px(int w, int h) { return n2(w) + "*" + n2(h) + "px"; } static public String str_px(WidthAndHeight image) { return image == null ? null : str_px(image.getWidth(), image.getHeight()); } static public > Set concatMapToSet(Iterable l, IF1 f) { Set set = new HashSet(); if (l != null) for (var a : l) addAll(set, f.get(a)); return set; } static public > Set concatMapToSet(IF1 f, Iterable l) { return concatMapToSet(l, f); } static public > Set concatMapToSet(IF1 f, A[] l) { Set set = new HashSet(); if (l != null) for (var a : l) addAll(set, f.get(a)); return set; } static public A markVisualizer(Object visualizer, A a) { return setMetaSrc(a, visualizer); } static public String lambdaArgsToString_pureJava(String[] args) { return l(args) == 1 ? first(args) : roundBracketed(joinWithComma(args)); } static public String lambdaArgsToString_pureJava(List args) { return lambdaArgsToString_pureJava(toStringArray(args)); } static public String multiLineQuote(String s) { for (int i = 0; ; i++) { String closer = "]" + rep('=', i) + "]"; if (!contains(s, closer)) return "[" + rep('=', i) + "[" + s + closer; } } static public void rgbFillRect(RGBImage img, int x1, int y1, int w, int h, Color color) { rgbFill(img, x1, y1, w, h, colorToInt(color)); } static public void rgbFillRect(RGBImage img, int x1, int y1, int w, int h, int color) { rgbFill(img, x1, y1, w, h, color); } static public void rgbFillRect(BufferedImage img, int x1, int y1, int w, int h, Color color) { fillRect(img, x1, y1, w, h, color); } static public A printIndentedStruct(A a) { return printIndentedStruct("", a); } static public A printIndentedStruct(String prefix, A a) { print(prefix, indentedStructureForUser(a)); return a; } static public A printIndentedStruct(A a, structure_Data data) { return printIndentedStruct("", a, data); } static public A printIndentedStruct(String prefix, A a, structure_Data data) { print(prefix, indentedStructureForUser(a, data)); return a; } static public String reverseString(String s) { return empty(s) ? s : new StringBuilder(s).reverse().toString(); } static public void setText_neverEmpty(JLabel c, Object text) { String s = spaceIfEmpty(strUnnull(text)); setText(c, s); } static public List> listToOverlappingPairs(List l) { List> out = new ArrayList(); Iterator it = iterator(l); if (!it.hasNext()) return out; A a = it.next(); while (it.hasNext()) { A b = it.next(); addPair(out, a, b); a = b; } return out; } static public Pt ptPlus(Pt a, Pt b) { return addPts(a, b); } static public List llNonNulls(A... a) { List l = new ArrayList(); if (a != null) for (A x : a) if (x != null) l.add(x); return l; } static public JComponent jGazelleLogo() { return setOpaqueBackground(Color.white, jimage(gazelleLogoImageID())); } static public int toInt_checked(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } static public int[] reverseIntArrayInPlace(int[] a) { if (a == null) return null; for (int i = 0; i < a.length / 2; i++) { int temp = a[i]; a[i] = a[a.length - 1 - i]; a[a.length - 1 - i] = temp; } return a; } static public void removeAndValidate(Component c) { if (c != null) { swing(() -> { Container cc = c.getParent(); if (cc != null) { cc.remove(c); cc.revalidate(); cc.repaint(); } }); } } static public void removeAndValidate(Container container, Component c) { if (c != null) { swing(() -> { if (c.getParent() == container) removeAndValidate(c); }); } } static public Object[] litObjectArray(Object... l) { return l; } static public NavigableMap synchroNavigableMap(NavigableMap map) { return new SynchronizedNavigableMap(map); } static public MultiMap reverseMultiMap(MultiMap map) { MultiMap mm = new MultiMap(); for (A key : keys(map)) for (B value : map.get(key)) mm.put(value, key); return mm; } static public void rgbFill(RGBImage img, int x1, int y1, int w, int h, int color) { for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) img.setPixel(x1 + x, y1 + y, color); } static public void rgbFill(RGBImage img, Rect r, RGB color) { rgbFill(img, r.x, r.y, r.w, r.h, color.getInt()); } static public String codePointToString(int codePoint) { return new String(Character.toChars(codePoint)); } static public A replaceIfEqual(A a, A b, A c) { return eq(a, b) ? c : a; } static public JWindow showCenterPackedWindow(Component c) { return swing(() -> { JWindow w = new JWindow(); w.add(c); w.pack(); centerWindow(w); w.setVisible(true); return w; }); } static public void assertSetEquals(Collection l1, Collection l2) { assertSetEquals("", l1, l2); } static public void assertSetEquals(String msg, Collection l1, Collection l2) { assertSetsEqual(msg, l1, l2); } static public A lookupOrKeep(Map map, A key) { return map != null && map.containsKey(key) ? map.get(key) : key; } static public Font deriveBoldItalic(boolean bold, boolean italic, Font font) { return font == null ? null : font.deriveFont((bold ? Font.BOLD : 0) | (italic ? Font.ITALIC : 0)); } static public Concept getConcept(long id) { return db_mainConcepts().getConcept(id); } static public Concept getConcept(Concepts concepts, long id) { return concepts.getConcept(id); } static public A getConcept(Class cc, long id) { return getConcept(db_mainConcepts(), cc, id); } static public A getConcept(Concepts concepts, Class cc, long id) { Concept c = concepts.getConcept(id); if (c == null) return null; if (!isInstance(cc, c)) throw fail("Can't convert concept: " + getClassName(c) + " -> " + getClassName(cc) + " (" + id + ")"); return (A) c; } static public List javaTokSnippet(String snippetID) { return javaTok(loadSnippet(snippetID)); } static public boolean structure_isMarker(String s, int i, int j) { if (i >= j) return false; if (s.charAt(i) != 'm') return false; ++i; while (i < j) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } static public double blend2D(double val, double val2, double val3, double val4, double xFrac, double yFrac) { double upper = blend(val, val2, xFrac); double lower = blend(val3, val4, xFrac); return blend(upper, lower, yFrac); } static public BufferedImage renderShape_antiAlias(Shape shape, int w, int h) { return renderShape_antiAlias(Color.white, shape, w, h); } static public BufferedImage renderShape_antiAlias(Color bg, Shape shape, int w, int h) { BufferedImage img = newBufferedImage(w, h, bg); Graphics2D g = antiAliasOn(img.createGraphics()); g.setColor(Color.black); g.fill(shape); return img; } static public BufferedImage renderShape_antiAlias(Shape shape) { return renderShape_antiAlias(Color.white, shape); } static public BufferedImage renderShape_antiAlias(Color bg, Shape shape) { if (shape == null) return null; Rect r = toRect(shape.getBounds()); BufferedImage img = newBufferedImage(max(1, r.w), max(1, r.h), bg); Graphics2D g = antiAliasOn(img.createGraphics()); g.translate(-r.x, -r.y); g.setColor(Color.black); g.fill(shape); return img; } static public void addSeparator(JMenu menu) { menu.addSeparator(); } static public void addSeparator(JPopupMenu menu) { menu.addSeparator(); } static public Object f2s_opt(Object o) { if (o instanceof File) return f2s((File) o); return o; } static public Color repeatingGradient(double position, double gradientLength, Color color1, Color color2) { return blendColor(color1, color2, frac(doubleRatio(position, gradientLength))); } static public boolean hasAlpha(BufferedImage img) { return hasTransparency(img); } static public boolean hasAlpha(Color color) { return color.getAlpha() != 0xFF; } static public boolean getBit(byte[] b, int bit) { int idx = bit >> 3; if (idx < 0 || idx > l(b)) return false; byte mask = (byte) (1 << (bit & 7)); return (b[idx] & mask) != 0; } static public double getProjectionDistance2(DoublePt a, DoublePt b, DoublePt c) { return getProjectionDistance2(a.x, a.y, b.x, b.y, c.x, c.y); } static public double getProjectionDistance2(double ax, double ay, double bx, double by, double cx, double cy) { var k2 = bx * bx - bx * ax + by * by - by * ay; var k1 = ax * ax - bx * ax + ay * ay - by * ay; var ab2 = (ax - bx) * (ax - bx) + (ay - by) * (ay - by); var kcom = (cx * (ax - bx) + cy * (ay - by)); var d2 = (k2 + kcom) / ab2; return d2; } static public boolean containsFile(File dir, String name) { return new File(dir, name).exists(); } static public boolean containsFile(Iterable l, File f) { return any(l, file -> sameFile(f, file)); } static public Collection copyList(Collection a, Collection b) { if (a != null && b != null && a != b) { b.clear(); b.addAll(a); } return a; } static public Map standardClassesMap() { return standardClassesMap_uncached(); } static public String firstWord2(String s) { s = xltrim(s); if (empty(s)) return ""; if (isLetterOrDigit(first(s))) return takeCharsWhile(__108 -> isLetterOrDigit(__108), s); else return "" + first(s); } static public List reverseInPlace(List l) { return reverseList(l); } static public String starFormat(String pat, Object... args) { int n = l(pat), iArg = 0, iChar = 0; StringBuilder buf = new StringBuilder(); while (true) { int jChar = smartIndexOf(pat, iChar, '*'); buf.append(substring(pat, iChar, jChar)); if (jChar >= n) break; buf.append(str(get(args, iArg++))); iChar = jChar + 1; } return str(buf); } static public double[] iDoublePtsToDoubleArray(List l) { int n = l(l); double[] array = new double[n * 2]; for (int i = 0; i < l(l); i++) { var p = l.get(i); array[i * 2] = p.x_double(); array[i * 2 + 1] = p.y_double(); } return array; } static public List sortByMap_inPlace(List l, Map map) { sort(l, mapComparator(map)); return l; } static public boolean isNull(Object o) { return o == null; } static public int intRatio_ceil(int a, int b) { return idiv_ceil(a, b); } static public double infinity() { return positiveInfinity(); } static public String editImageID() { return "#1103068"; } static public String[] match2(List pat, List tok) { int i = pat.indexOf("..."); if (i < 0) return match2_match(pat, tok); pat = new ArrayList(pat); pat.set(i, "*"); while (pat.size() < tok.size()) { pat.add(i, "*"); pat.add(i + 1, ""); } return match2_match(pat, tok); } static public String[] match2_match(List pat, List tok) { List result = new ArrayList(); if (pat.size() != tok.size()) { return null; } for (int i = 1; i < pat.size(); i += 2) { String p = pat.get(i), t = tok.get(i); if (eq(p, "*")) result.add(t); else if (!equalsIgnoreCase(unquote(p), unquote(t))) return null; } return result.toArray(new String[result.size()]); } static public String str_pcall(Object o) { try { return str(o); } catch (Throwable e) { printStackTrace(e); return "[error in toString of " + className(o) + "]"; } } static public Color withAlpha(Color c, double alpha) { return colorWithAlpha(c, alpha); } static public Color withAlpha(double alpha, Color c) { return colorWithAlpha(alpha, c); } static public int withAlpha(double alpha, int rgb) { return rgb & 0xFFFFFF | (iround(clampToZeroOne(alpha) * 255) << 24); } static public String resolve(String host) { return hostToIP(host); } static public List memoryPoolMXBeans() { return ManagementFactory.getMemoryPoolMXBeans(); } static public Rect rectFromPointsOrNull(int x1, int y1, int x2, int y2) { return nullIfEmptyRect(pointsRect(x1, y1, x2, y2)); } static public Map.Entry higherEntry(NavigableMap map, A key) { return map == null ? null : map.higherEntry(key); } static public Iterator iterator_gen(Object o) { if (o == null) return emptyItIt(); if (o instanceof Iterator) return ((Iterator) o); if (o instanceof Iterable) return ((Iterable) o).iterator(); if (o instanceof Object[]) return arrayIterator((Object[]) o); throw fail("Not iterable: " + className(o)); } static public Rect scaleRect_imageToImage(Rect r, BufferedImage imgSrc, BufferedImage imgDest) { return rescaleRect_imageToImage(r, imgSrc, imgDest); } static public Rect scaleRect_imageToImage(Rect r, WidthAndHeight imgSrc, WidthAndHeight imgDest) { return rescaleRect_imageToImage(r, imgSrc, imgDest); } static public boolean jmatch(String pat, String s) { return jmatch(pat, s, null); } static public boolean jmatch(String pat, String s, Matches matches) { if (s == null) return false; return jmatch(pat, javaTok(s), matches); } static public boolean jmatch(String pat, List toks) { return jmatch(pat, toks, null); } static public boolean jmatch(String pat, List toks, Matches matches) { List tokpat = javaTok(pat); String[] m = match2(tokpat, toks); if (m == null) return false; else { if (matches != null) matches.m = m; return true; } } static public String lpad(String s, int l) { return lpad(s, l, ' '); } static public String lpad(String s, int l, char c) { if (s == null) s = ""; return s.length() >= l ? s : rep(c, l - s.length()) + s; } static public String lpad(int l, String s) { return lpad(s, l); } static public int lengthOfLine(String text, int lineNr) { return l(getFromIterator(linesIterator(text), lineNr)); } static public List splitAtComma_trim(String s) { return nempties(trimAll(splitAtComma(s))); } static public int typeConversionScore(Class a, Class b) { if (a == b) return 0; if (b.isPrimitive()) { if (a.isPrimitive()) { if (b == boolean.class) return Integer.MAX_VALUE; if (b == byte.class) return Integer.MAX_VALUE; if (b == char.class) return a == byte.class ? -2 : Integer.MAX_VALUE; if (b == short.class) return a == byte.class ? -2 : Integer.MAX_VALUE; if (b == int.class) return a == byte.class || a == char.class || a == short.class ? -2 : Integer.MAX_VALUE; if (b == long.class) return a == byte.class || a == char.class || a == short.class || a == int.class ? -2 : Integer.MAX_VALUE; if (b == float.class) return a == byte.class || a == char.class || a == short.class || a == int.class ? -2 : Integer.MAX_VALUE; return a != boolean.class ? -2 : Integer.MAX_VALUE; } else { return primitiveToBoxedType(b) == a ? 1 : Integer.MAX_VALUE; } } else { if (a.isPrimitive()) return primitiveToBoxedType(a) == b ? 1 : Integer.MAX_VALUE; if (!b.isAssignableFrom(a)) return Integer.MAX_VALUE; if (a.isInterface() || b.isInterface()) return 1; if (a.isArray() && b.isArray()) return typeConversionScore(a.getComponentType(), b.getComponentType()) / 2; return subclassDistance(a, b) * 2; } } static public List isYes_yesses = litlist("y", "yes", "yeah", "y", "yup", "yo", "corect", "sure", "ok", "afirmative"); static public boolean isYes(String s) { return isYes_yesses.contains(collapseWord(toLowerCase(firstWord2(s)))); } static public Pt maxPt(Pt a, Pt b) { return a == null ? b : b == null ? a : new Pt(max(a.x, b.x), max(a.y, b.y)); } static public Pt maxPt(Iterable l) { Pt max = null; for (var p : unnullForIteration(l)) max = maxPt(max, p); return max; } static public A cnewUnlisted(Class c, Object... params) { return unlistedWithValues(c, params); } static public Set nonStaticFields(Object o) { return allNonStaticFields(o); } static public BufferedImage integralImageToBufferedImage(IntegralImage img) { if (img == null) return null; int w = img.w, h = img.h; BufferedImage out = newBufferedImage(w, h); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) out.setRGB(x, y, ii_getPixel(img, x, y)); return out; } static public BufferedImage integralImageToBufferedImage(IIntegralImage img) { return img == null ? null : img.getBufferedImage(); } static public String autoUnindent(String s) { int n = getIndent(s); if (n == 0) return s; List l = toLines(s); for (int i = 0; i < l(l); i++) l.set(i, substring(l.get(i), n)); return fromLines(l); } static public Rect shrinkRect(Rect r) { return shrinkRect(r, 1); } static public Rect shrinkRect(Rect r, int pixels) { return shrinkRect(pixels, pixels, r); } static public Rect shrinkRect(int x, int y, Rect r) { return new Rect(r.x + x, r.y + y, r.w - x * 2, r.h - y * 2); } static public Rect shrinkRect(int x, int y, int w, int h, int pixels) { return shrinkRect(new Rect(x, y, w, h), pixels); } static public PtInComponent ptInComponentFromEvent(MouseEvent evt) { return new PtInComponent(evt.getComponent(), pt(evt.getX(), evt.getY())); } static public A bindChangeListenerToComponent(A component, IHasChangeListeners hcl, Runnable listener) { return bindHasChangeListenersToComponent(component, hcl, listener); } static public A bindChangeListenerToComponent(IHasChangeListeners hcl, A component, Runnable listener) { return bindChangeListenerToComponent(component, hcl, listener); } static public JPanel rightAlignedLineWithSpacing(int spacing, Component... components) { return swing(() -> { return new RightAlignedLine(spacing, components); }); } static public String regexpReplace_direct(String s, String pat, String replacement) { Matcher m = regexp(pat, s); return regexpReplace_direct(m, replacement); } static public String regexpReplace_direct(Matcher m, String replacement) { StringBuffer buf = new StringBuffer(); while (m.find()) m.appendReplacement(buf, replacement); m.appendTail(buf); return str(buf); } static public BufferedImage shapeToImage(Shape shape, int w, int h) { return shapeToImage(Color.white, shape, w, h); } static public BufferedImage shapeToImage(Color bg, Shape shape, int w, int h) { return renderShape_antiAlias(bg, shape, w, h); } static public BufferedImage shapeToImage(Shape shape) { return shapeToImage(Color.white, shape); } static public BufferedImage shapeToImage(Color bg, Shape shape) { return renderShape_antiAlias(bg, shape); } static public String addFunctionNameToInclude(String snippetID, String functionName) { List tok = javaTokSnippet(snippetID); var pif = tok_nextPleaseIncludeFunctionsStatement(tok); if (pif == null) return "PIF statement not found in snippet"; if (pif.containsFunction(functionName)) return functionName + " already included"; int i = pif.iFirstIdentifier; tokPrepend(tok, i, functionName + or2(javaDropComments(tok.get(i + 1)), " ")); return editSnippet(snippetID, join(tok)); } static public MultiSet cloneMultiSet(MultiSet ms) { if (ms == null) return new MultiSet(); MultiSet ms2 = similarEmptyMultiSet(ms); ms2.addAll(ms); return ms2; } static public void setPixel(BufferedImage img, int p_x, int p_y, Color color) { setPixel(img, pt(p_x, p_y), color); } static public void setPixel(BufferedImage img, Pt p, Color color) { { if (img != null) img.setRGB(p.x, p.y, colorToIntOpaque(color)); } } static public void setPixel(Graphics2D g, int p_x, int p_y, Color color) { setPixel(g, pt(p_x, p_y), color); } static public void setPixel(Graphics2D g, Pt p, Color color) { g.setColor(color); g.drawRect(p.x, p.y, 1, 1); } static public Rect rescaleRect_imageToImage(Rect r, BufferedImage imgSrc, BufferedImage imgDest) { return rescaleRect(r, imgSrc.getWidth(), imgSrc.getHeight(), imgDest.getWidth(), imgDest.getHeight()); } static public Rect rescaleRect_imageToImage(Rect r, WidthAndHeight imgSrc, WidthAndHeight imgDest) { return rescaleRect(r, imgSrc.getWidth(), imgSrc.getHeight(), imgDest.getWidth(), imgDest.getHeight()); } static public void setPixels(BufferedImage img, Iterable points, Color color) { if (img == null) return; for (var p : unnullForIteration(points)) img.setRGB(p.x, p.y, colorToIntOpaque(color)); } static public MultiSet multiMapToMultiSet(MultiMap mm) { return multiMapAsMultiSet(mm); } static public B floorValue(NavigableMap map, A key) { if (map == null) return null; var e = map.floorEntry(key); return e == null ? null : e.getValue(); } static public MultiSet multiMapAsMultiSet(MultiMap mm) { MultiSet ms = new MultiSet(); for (A a : keys(mm)) ms.add(a, l(mm.get(a))); return ms; } static public boolean divides(long a, long b) { return b != 0 && (a % b) == 0; } static public Object invokeMethodWithWidening(Method m, Object o, Object... args) { try { try { Class[] types = m.getParameterTypes(); int n = types.length; Object[] args2 = new Object[n]; for (int i = 0; i < n; i++) args2[i] = convertPrimitiveIfNecessary(args[i], types[i]); return m.invoke(o, args2); } catch (InvocationTargetException e) { throw rethrow(getExceptionCause(e)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args))); } } catch (Exception __e) { throw rethrow(__e); } } static public int randomIndex(List l) { return random(l(l)); } static public A firstInstanceOf(Iterable i, Class c) { if (i == null) return null; c = primitiveToBoxedTypeOpt(c); for (Object o : i) if (isInstance(c, o)) return (A) o; return null; } static public A firstInstanceOf(Class c, Iterable i) { return firstInstanceOf(i, c); } static public A firstInstanceOf(Object[] a, Class c) { if (a == null) return null; c = primitiveToBoxedTypeOpt(c); for (Object o : a) if (isInstance(c, o)) return (A) o; return null; } static public void showDirChooser(File defaultDir, IVF1 action) { showDirChooser(null, defaultDir, action); } static public void showDirChooser(Component parent, File defaultDir, IVF1 action) { JFileChooser fileChooser = new JFileChooser(defaultDir); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setAcceptAllFileFilterUsed(false); if (fileChooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) { if (action != null) action.get(fileChooser.getSelectedFile()); } } static public Set joinSets(Collection... l) { Set set = similarEmptySet(first(l)); for (Collection o : l) if (o != null) set.addAll(o); return set; } static public _MethodCache getMethodCache(Class c) { return callOpt_getCache(c); } static public String n2OrStrOrNull(Object o) { if (o == null) return null; if (o instanceof Number) return n2(((Number) o).longValue()); return str(o); } static public A jMinWidth_pure(int w, A c) { if (c != null) { swing(() -> { Dimension size = c.getMinimumSize(); c.setMinimumSize(new Dimension(w, size.height)); }); } return c; } static public A jMinWidth_pure(A c, int w) { return jMinWidth_pure(w, c); } static public Producer javaTokC_noMLS_onReader(final BufferedReader r) { final class X implements Producer { public StringBuilder buf = new StringBuilder(); public char c, d, e = 'x'; public X() { nc(); nc(); nc(); } public void nc() { try { c = d; d = e; if (e == '\0') return; int i = r.read(); e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i; } catch (Exception __e) { throw rethrow(__e); } } public void ncSave() { if (c != '\0') { buf.append(c); nc(); } } public String next() { while (c != '\0') { if (c == ' ' || c == '\t' || c == '\r' || c == '\n') nc(); else if (c == '/' && d == '*') { do nc(); while (c != '\0' && !(c == '*' && d == '/')); nc(); nc(); } else if (c == '/' && d == '/') { do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0); } else break; } if (c == '\0') return null; if (c == '\'' || c == '"') { char opener = c; ncSave(); while (c != '\0') { if (c == opener || c == '\n') { ncSave(); break; } else if (c == '\\') { ncSave(); ncSave(); } else ncSave(); } } else if (Character.isJavaIdentifierStart(c)) do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\''); else if (Character.isDigit(c)) { do ncSave(); while (Character.isDigit(c)); if (c == 'L') ncSave(); } else ncSave(); String t = buf.toString(); buf.setLength(0); return t; } } return new X(); } static public Component jVerticalStrut(int height) { return verticalStrut(height); } static public BufferedImage imageFromFunction(int w, IF2_Int f) { return imageFromFunction(w, w, f); } static public BufferedImage imageFromFunction(int w, int h, IF2_Int f) { int[] pixels = new int[w * h]; int i = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) pixels[i++] = f.get(x, y); return intArrayToBufferedImage(pixels, w, h); } static public boolean isAnonymousClass(Class c) { return isAnonymousClassName(className(c)); } static public JPanel withCenteredButtons(JComponent center, Object... params) { return centerAndSouth(center, withMargin(jcenteredbuttons(params))); } static public A conceptWhere(Class c, Object... params) { return findConceptWhere(c, params); } static public A conceptWhere(Concepts cc, Class c, Object... params) { return findConceptWhere(cc, c, params); } static public JLabel jnarrowLabel() { return jnarrowLabel(50); } static public JLabel jnarrowLabel(int width) { return jnarrowLabel(width, ""); } static public JLabel jnarrowLabel(String text) { return jnarrowLabel(50, text); } static public JLabel jnarrowLabel(int width, String text) { return jMinWidth_pure(width, jlabel(text)); } static public JLabel jnarrowLabel(JLabel lbl) { return jnarrowLabel(50, lbl); } static public JLabel jnarrowLabel(int width, JLabel lbl) { return jMinWidth_pure(width, lbl); } static public Method findSingleInterfaceMethodOrFail(Class intrface) { Method m = findSingleInterfaceMethod(intrface); if (m == null) throw fail(intrface + " is not a single method interface"); return m; } static public int rgbIntFromDoubles_fullAlpha(double r, double g, double b) { return 0xFF000000 | limitToUByte(iround(r)) << 16 | limitToUByte(iround(g)) << 8 | limitToUByte(iround(b)); } static public boolean isDeepContainedInDir_absolute(File f, File dir) { return nempty(nameRelativeToPhysicalSubdirectory_nonCanonical(f, dir)); } static public boolean reflection_isForbiddenMethod(Method m) { return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives"); } static public A clearMetaSrc(A a) { return setMetaSrc(a, null); } static public Class getOuterClass(Class c) { return getOuterClass(c, null); } static public Class getOuterClass(Class c, Object classFinder) { try { String s = c.getName(); int i = s.lastIndexOf('$'); String name = substring(s, 0, i); return classForName(name, classFinder); } catch (Exception __e) { throw rethrow(__e); } } static public Class getOuterClass(Object o) { return getOuterClass(o, null); } static public Class getOuterClass(Object o, Object classFinder) { return getOuterClass(_getClass(o), classFinder); } static public double atan2(double x, double y) { return Math.atan2(x, y); } static public JLabel jcenterNarrowLabel() { return jcenterNarrowLabel(50); } static public JLabel jcenterNarrowLabel(int width) { return jcenterNarrowLabel(width, ""); } static public JLabel jcenterNarrowLabel(String text) { return jcenterNarrowLabel(50, text); } static public JLabel jcenterNarrowLabel(int width, String text) { return centerLabel(jnarrowLabel(width, text)); } static public Field findFieldOfClass(Class c, String field) { return c == null || field == null ? null : getOpt_getFieldMap(c).get(field); } static public A pcallF_typed(F0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { pcallFail(__e); } return null; } static public B pcallF_typed(F1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__e); } return null; } static public void pcallF_typed(VF1 f, A a) { try { { if (f != null) f.get(a); } } catch (Throwable __e) { pcallFail(__e); } } static public void pcallF_typed(IVF1 f, A a) { try { { if (f != null) f.get(a); } } catch (Throwable __e) { pcallFail(__e); } } static public void pcallF_typed(IVF2 f, A a, B b) { try { { if (f != null) f.get(a, b); } } catch (Throwable __e) { pcallFail(__e); } } static public Object pcallF_typed(Runnable r) { try { { if (r != null) r.run(); } } catch (Throwable __e) { pcallFail(__e); } return null; } static public A pcallF_typed(IF0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { pcallFail(__e); } return null; } static public B pcallF_typed(IF1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__e); } return null; } static public void fixFieldValues(DynamicObject o) { if (o == null) return; mapRemove(o.fieldValues, "ping_anyActions"); mapRemove(o.fieldValues, "ping_pauseAll"); mapRemove(o.fieldValues, "cleaningUp_flag"); if (o instanceof ChangeTriggerable) ((ChangeTriggerable) o).change(); } static public JTextArea showLinesWithCount(Collection lines) { return showLinesWithCount(autoFrameTitle(), lines); } static public JTextArea showLinesWithCount(String title, Collection lines) { return showLines(appendBracketedCount(l(lines), title), lines); } static public BufferedImage cloneBufferedImage(BufferedImage image) { return copyImage(image); } static public void addOrReplaceTab(JTabbedPane tabs, String tabName, Swingable c) { addOrReplaceTab(tabs, tabName, wrap(c)); } static public void addOrReplaceTab(JTabbedPane tabs, String tabName, Component c) { swing(() -> { if (tabs == null) return; int idx = indexOfTabName(tabs, tabName); if (idx >= 0) setTab(tabs, idx, c); else addTabs(tabs, tabName, c); }); } static public byte[] isJPEG_magic = bytesFromHex("FFD8FF"); static public boolean isJPEG(byte[] data) { return byteArrayStartsWith(data, isJPEG_magic); } static public boolean isJPEG(File f) { return isJPEG(loadBeginningOfBinaryFile(f, l(isJPEG_magic))); } static public String appendSquareBracketed(String b) { return empty(b) ? "" : "" + " [" + b + "]"; } static public String appendSquareBracketed(String a, String b) { return empty(b) ? a : a + appendSquareBracketed(b); } static public int hash(Object... l) { return hashAboutObjects(l); } static public A instaToolTip(A c, String toolTip) { return instaToolTip(toolTip, c); } static public A instaToolTip(IF0 toolTip, A c) { new InstantNeverHideToolTip(toolTip, c); return c; } static public A instaToolTip(String toolTip, A c) { new InstantNeverHideToolTip(toolTip, c); return c; } static public String actualMCDollar() { return actualMC().getName() + "$"; } static public Field fieldObject(Object o, String field) { return findField2(o, field); } static public JScrollPane jscroll_vertical(JComponent c) { return jscroll_trackWidth(c); } static public JScrollPane jscroll_vertical(Swingable c) { return jscroll_trackWidth(c); } static public boolean preciseNuObject_debug = false; static public A preciseNuObject(Class c, Object... args) { try { Constructor[] methods = getDeclaredConstructors_cached(c); if (methods.length == 0) throw fail(c + " doesn't define any constructors"); return preciseNuObject(methods, args); } catch (Exception __e) { throw rethrow(__e); } } static public A preciseNuObject(Constructor[] methods, Object... args) { try { Constructor best = null; int bestScore = Integer.MAX_VALUE; boolean widening = false; if (preciseNuObject_debug) printVars("preciseNuObject", "c", first(methods).getDeclaringClass(), "methods", l(methods)); for (var m : methods) { int score = methodApplicabilityScore_withPrimitiveWidening(m, args); if (score == 0) return (A) m.newInstance(args); if (preciseNuObject_debug) print("Method score: " + m + " " + score); if (abs(score) < bestScore) { best = m; bestScore = abs(score); widening = score < 0; } } if (best != null) if (widening) return (A) invokeConstructorWithWidening(best, args); else return (A) best.newInstance(args); methodSearch: for (var m : methods) { { if (!(m.isVarArgs())) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return (A) m.newInstance(newArgs); } var c = first(methods).getDeclaringClass(); throw fail("No matching constructor found: " + formatFunctionCall(c, map(__109 -> _getClass(__109), args))); } catch (Exception __e) { throw rethrow(__e); } } static public boolean defaultAgeBasedBackupRetentionStrategy_shouldKeep(double age, double lastAge) { if (age <= 1 / 12.0) return true; if (age <= 0.5 && age >= lastAge + 1 / 12.0) return true; if (age <= 7 && age >= lastAge + 1) return true; if (age <= 28 && age >= lastAge + 7) return true; if (age >= lastAge + 365.0 / 12) return true; return false; } static public String stringIfTrue(boolean b, String s) { return b ? s : ""; } static public int typeConversionScoreWithUnboxing(Class a, Class b) { int score = typeConversionScore(a, b); if (score == 0 || score == 1) return score; Class aPrim = boxedToPrimitiveType(a); if (aPrim != null) { int score2 = typeConversionScore(aPrim, b); if (score2 == 0) return 1; else if (score2 != Integer.MAX_VALUE) return score2; } return score; } static public boolean removeFile(File file) { return deleteFile(file); } static public List toLinesTrim2(String s) { return map(__110 -> trim(__110), toLinesTrim(s)); } static public A onEnabledChanged(A c, Runnable r) { if (c != null && c != null) { swing(() -> { c.getAccessibleContext().addPropertyChangeListener(evt -> r.run()); }); } return c; } static public List listFilesNotDirs(String dir) { return listFilesOnly(dir); } static public List listFilesNotDirs(File... dirs) { return listFilesOnly(dirs); } static public Object preciseGetOrCallMethod(Object object, String name) { if (object == null) return null; if (canCallWithVarargs(object, name)) return call(object, name); return _get(object, name); } static public double pointDistance(Pt a, Pt b) { return sqrt(sqr(a.x - b.x) + sqr(a.y - b.y)); } static public double pointDistance(double x1, double y1, double x2, double y2) { return sqrt(sqr(x1 - x2) + sqr(y1 - y2)); } static public double pointDistance(DoublePt a, DoublePt b) { return pointDistance(a.x, a.y, b.x, b.y); } static public boolean inImage(int p_x, int p_y, BufferedImage img) { return inImage(pt(p_x, p_y), img); } static public boolean inImage(Pt p, BufferedImage img) { return p != null && img != null && p.x >= 0 && p.y >= 0 && p.x < img.getWidth() && p.y < img.getHeight(); } static public JTextArea uneditableTextArea() { return uneditableTextArea(""); } static public JTextArea uneditableTextArea(String text) { return uneditableBlackTextArea_noUndo(text); } static public int numberOfBitsNeededToRepresentNOptions(int i) { return 32 - Integer.numberOfLeadingZeros(max(0, i - 1)); } static public boolean startsWithSpaceEtc(String s) { return isSpaceEtc(charAt(s, 0)); } static public long rawBufferedImageDistance_sameSize(MakesBufferedImage img1, MakesBufferedImage img2) { return rawBufferedImageDistance_sameSize(img1, toBufferedImage(img2)); } static public long rawBufferedImageDistance_sameSize(MakesBufferedImage img1, BufferedImage img2) { return rawBufferedImageDistance_sameSize(toBufferedImage(img1), img2); } static public long rawBufferedImageDistance_sameSize(BufferedImage img1, MakesBufferedImage img2) { return rawBufferedImageDistance_sameSize(img1, toBufferedImage(img2)); } static public long rawBufferedImageDistance_sameSize(BufferedImage img1, BufferedImage img2) { return new RawBufferedImageDistance_sameSize(img1, img2).get(); } static public long rawBufferedImageDistance_sameSize(BufferedImage img1, BufferedImage img2, long stoppingValue) { return new RawBufferedImageDistance_sameSize(img1, img2).stoppingValue(stoppingValue).get(); } static public int toCodePoint(String s) { return unicodeToCodePoint(s); } static public double cos(double x) { return Math.cos(x); } static public List synchroLinkedList() { return synchroList(new LinkedList()); } static public Pt ptDiff(Pt a, Pt b) { return a == null ? b : b == null ? a : pt(a.x - b.x, a.y - b.y); } static public BufferedImage markPointInImageWithAlpha(BufferedImage img, int p_x, int p_y, Color color, double alpha) { return markPointInImageWithAlpha(img, pt(p_x, p_y), color, alpha); } static public BufferedImage markPointInImageWithAlpha(BufferedImage img, Pt p, Color color, double alpha) { return markPointInImageWithAlpha(img, p, color, alpha, 3); } static public BufferedImage markPointInImageWithAlpha(BufferedImage img, int p_x, int p_y, Color color, double alpha, int size) { return markPointInImageWithAlpha(img, pt(p_x, p_y), color, alpha, size); } static public BufferedImage markPointInImageWithAlpha(BufferedImage img, Pt p, Color color, double alpha, int size) { if (img != null && p != null) rgbFillRect(img, p.x - size / 2, p.y - size / 2, size, size, colorWithAlpha(color, alpha)); return img; } static public A getAndClear(IVar v) { A a = v.get(); v.set(null); return a; } static public Point toPoint(Pt p) { return p == null ? null : new Point(p.x, p.y); } static public A awtCalcContinuously(A component, Runnable runnable) { if (runnable == null) return component; SingleThread thread = new SingleThread(); BoolVar visible = new BoolVar(); var info = _threadInfo(); Runnable theLoop = new Runnable() { public void run() { try { _threadInheritInfo(info); while (visible.get()) { ping(); try { runnable.run(); } catch (Throwable e) { printStackTrace(e); sleepSeconds(1); } } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_threadInheritInfo(info);\r\n while (visible!) { ping(); \r\n try {\r\n ..."; } }; bindToComponent(component, () -> { visible.set(); thread.go(theLoop); }, () -> visible.clear()); return component; } static public JScrollPane jscrollVertical(final Component c) { return swing(new F0() { public JScrollPane get() { try { return new JScrollPane(c, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return new JScrollPane(c,\r\n ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEED..."; } }); } static public Pt neg(Pt p) { return p == null ? null : new Pt(-p.x, -p.y); } static public int neg(int i) { return -i; } static public double neg(double i) { return -i; } static public JPopupMenu currentPopupMenu() { return firstInstanceOf(JPopupMenu.class, allAWTComponents()); } static public int[] toIntArray(Collection l) { int[] a = new int[l(l)]; int i = 0; if (a.length != 0) for (int x : l) a[i++] = x; return a; } static public void setSpinnerMax(JSpinner s, int max) { if (s != null) { swing(() -> { s.setModel(new SpinnerNumberModel(0, 0, max, 1)); }); } } static public TreeSet toTreeSet(Collection set) { return asTreeSet(set); } static public List paragraphsFromText(String text) { List lines = toLinesTrim2(text); List> paragraphs = paragraphsFromText_groupParagraphs(lines); return lmap(__111 -> fromLines(__111), paragraphs); } static public List> paragraphsFromText_groupParagraphs(List lines) { return groupNonEmpty(lines, new F1() { public Object get(String line) { try { return empty(line); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "empty(line)"; } }); } static public List parseHexRanges(String s) { return map(__112 -> parseHexRange(__112), splitAtComma_trim(s)); } static public List toLowerCase(List strings) { List x = new ArrayList(); for (String s : strings) x.add(s.toLowerCase()); return x; } static public String[] toLowerCase(String[] strings) { String[] x = new String[l(strings)]; for (int i = 0; i < l(strings); i++) x[i] = strings[i].toLowerCase(); return x; } static public String toLowerCase(String s) { return s == null ? "" : s.toLowerCase(); } static public void inputText(String msg, String defaultText, IVF1 action) { inputText(msg, defaultText, (Object) action); } static public void inputText(String msg, IVF1 action) { inputText(msg, (Object) action); } static public void inputText(String msg, Object action) { inputText(msg, "", action); } static public void inputText(String msg, String defaultText, Object action) { final Object threadInfo = _threadInfo(); swingLater(new Runnable() { public void run() { try { final JTextField tf = jtextfield(defaultText); String title = joinNemptiesWithVBar(msg, programNameOrNull()); JComponent form = showFormTitled(title, unnull(msg), tf, new Runnable() { public void run() { try { vmBus_send("inputtingText_OK", threadInfo, msg, tf); callF_thread(action, getTextTrim(tf)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "vmBus_send(\"inputtingText_OK\", threadInfo, msg, tf);\r\n callF_thread(ac..."; } }); renameSubmitButton(form, "OK"); vmBus_send("inputtingText", threadInfo, msg, tf); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tf = jtextfield(defaultText);\r\n String title = joinNempti..."; } }); } static public A newInstance(Class c, Object... args) { return nuObject(c, args); } static public Object newInstance(String className, Object... args) { return nuObject(className, args); } static public void closeAll(Iterable l) { if (l == null) return; for (AutoCloseable c : l) { try { close(c); } catch (Throwable __e) { pcallFail(__e); } } } static public void closeAll(AutoCloseable... l) { if (l == null) return; for (AutoCloseable c : l) { try { close(c); } catch (Throwable __e) { pcallFail(__e); } } } static public int reverseBits(int i) { return reverseBits(i, 32); } static public int reverseBits(int i, int bits) { int j = 0; for (int _repeat_0 = 0; _repeat_0 < bits; _repeat_0++) { j = (j << 1) | (i & 1); i >>>= 1; } return j; } static public void fixContextClassLoader() { Thread.currentThread().setContextClassLoader(myClassLoader()); } static public VF1 toVF1(IVF1 f) { return ivf1ToVF1(f); } static public String joinWithColon(Iterable l) { return join(": ", l); } static public String joinWithColon(Object... l) { return join(": ", l); } static public Steppable combineSteppables(Iterable steppables) { return iteratorToSteppable(roundRobinCombinedIterator(map(__113 -> steppableToIterator(__113), steppables))); } static public Steppable combineSteppables(A... steppables) { return combineSteppables(asList(steppables)); } static public JCheckBoxMenuItem jLiveValueCheckBoxMenuItem(String text, IVarWithNotify lv) { return swing(() -> { JCheckBoxMenuItem cb = new JCheckBoxMenuItem(text); bindCheckBoxMenuItemToVar(cb, lv); return cb; }); } static public List> reversePairs(Iterable> l) { return map(__114 -> reversedPair(__114), l); } static public Pt onePathDirection(int index) { return onePathDirections()[index]; } static public Pt onePathDirection(Pt p, int index) { return ptPlus(p, onePathDirections()[index]); } static public String nPixels(long n) { return n2(n, "pixel"); } static public String nPixels(Collection l) { return nPixels(l(l)); } static public boolean inRange(int x, int n) { return x >= 0 && x < n; } static public boolean inRange(int x, List l) { return inRange(x, l(l)); } static public boolean inRange(int x, int a, int b) { return x >= a && x < b; } static public List> listToSquareishChunks(List l) { int chunkSize = max(1, iround(sqrt(l(l)))); return listToChunks(l, chunkSize); } static public IterableIterator steppableToIterator(Steppable s) { return s == null ? emptyItIt() : iff(() -> s.step() ? null : endMarker()); } static public WidthAndHeight widthAndHeight(BufferedImage image) { return image == null ? null : widthAndHeight(image.getWidth(), image.getHeight()); } static public WidthAndHeight widthAndHeight(int w) { return widthAndHeight(w, w); } static public WidthAndHeight widthAndHeight(int w, int h) { return new WidthAndHeightFinal(w, h); } static public Graphics2D getGraphics(BufferedImage img) { return imageGraphics(img); } static public double floor(double d) { return Math.floor(d); } static public File[] listFiles(File dir) { File[] files = dir == null ? null : dir.listFiles(); return files == null ? new File[0] : files; } static public File[] listFiles(String dir) { return listFiles(new File(dir)); } static public Set keySet(Map map) { return map == null ? new HashSet() : map.keySet(); } static public Set keySet(Object map) { return keys((Map) map); } static public Set keySet(MultiSet ms) { return ms.keySet(); } static public Set keySet(MultiMap mm) { return mm.keySet(); } static public HashSet mapToSet(Object f, Iterable l) { return mapToHashSet(f, l); } static public HashSet mapToSet(IF1 f, Iterable l) { return mapToHashSet(f, l); } static public HashSet mapToSet(IF1 f, A[] l) { return mapToSet(f, asList(l)); } static public HashSet mapToSet(Iterable l, IF1 f) { return mapToSet(f, l); } static public Color getColor(BufferedImage img, int x, int y) { return colorFromRGBA(img.getRGB(x, y)); } static public Color getColor(BufferedImage img, Pt p) { return colorFromRGBA(img.getRGB(p.x, p.y)); } static public void smartSet(Field f, Object o, Object value) throws Exception { try { f.set(o, value); } catch (Exception e) { Class type = f.getType(); if (type == int.class && value instanceof Long) { f.set(o, ((Long) value).intValue()); return; } if (type == boolean.class && value instanceof String) { f.set(o, isTrueOrYes(((String) value))); return; } if (type == LinkedHashMap.class && value instanceof Map) { f.set(o, asLinkedHashMap((Map) value)); return; } try { if (f.getType() == Concept.Ref.class) { f.set(o, ((Concept) o).new Ref((Concept) value)); return; } if (o instanceof Concept.Ref) { f.set(o, ((Concept.Ref) o).get()); return; } } catch (Throwable _e) { } throw e; } } static public int indexOfSelectedTab(JExtendedTabbedPane tabs) { return selectedTabIndex(tabs); } static public int indexOfSelectedTab(JTabbedPane tabs) { return selectedTabIndex(tabs); } static public List countIteratorToList_incl(int b) { return countIteratorToList_incl(0, b); } static public List countIteratorToList_incl(int a, int b) { return countIteratorToList_inclusive(a, b); } static public List countIteratorToList_incl(int b, IF1 f) { return countIteratorToList_incl(0, b, f); } static public List countIteratorToList_incl(int a, int b, IF1 f) { return countIteratorToList_inclusive(a, b, f); } static public List countIteratorToList_incl(int a, int b, int step) { return countIteratorToList_inclusive(a, b, step); } static public List countIteratorToList_incl(double a, double b, double step, IF1 f) { return countIteratorToList_inclusive(a, b, step, f); } static public List countIteratorToList_incl(double a, double b, double step) { return countIteratorToList_inclusive(a, b, step); } static public List countIteratorToList_incl(IF1 f, double a, double b, double step) { return countIteratorToList_inclusive(f, a, b, step); } static public List countIteratorToList_incl(IF1 f, int a, int b) { return countIteratorToList_incl(f, a, b, 1); } static public List countIteratorToList_incl(IF1 f, int a, int b, int step) { return countIteratorToList_inclusive(f, a, b, step); } static public String str_toK(long l) { return n2(toK(l)) + " K"; } static public A proxyFromInvocationHandler(Class intrface, InvocationHandler handler) { return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, handler); } static public String str_toM(long l) { return n2(toM(l)) + " MB"; } static public List> transpose(List> l) { List> cols = new ArrayList(); for (int i = 0; i < l(l); i++) { List row = l.get(i); for (int j = 0; j < l(row); j++) { while (j >= l(cols)) cols.add(new ArrayList()); listPut(cols.get(j), i, row.get(j)); } } return cols; } static public IterableIterator emptyItIt() { return emptyIterableIterator(); } static public String collapse(String s) { return collapseWord(s); } static public List reversed(Iterable l) { return reversedList(l); } static public List reversed(A[] l) { return reversedList(asList(l)); } static public String reversed(String s) { return reversedString(s); } static public JScrollPane jscroll_trackWidth(JComponent c) { return jscroll(scrollable_trackWidth(c)); } static public JScrollPane jscroll_trackWidth(Swingable c) { return jscroll_trackWidth(c.visualize()); } static public JList jlist(final List l) { return (JList) swing(new F0() { public Object get() { try { JList list = new JList(); final WeakReference ref = weakRef(list); listPopupMenuItem(list, "Copy text to clipboard", new Runnable() { public void run() { try { copyTextToClipboardIfNotNull(selectedItem(ref.get())); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboardIfNotNull(selectedItem(ref!))"; } }); fillListWithStrings(list, l); return list; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new JList list;\r\n final WeakReference ref = weakRef(list);\r\n lis..."; } }); } static public JList jlist(String... l) { return jlist(asList(l)); } static public A bindJLabelToVar(A label, IF0WithChangeListeners var) { bindListenerToComponent(label, var, () -> { try { setText(label, strOrNull(var.get())); } catch (Throwable e) { printStackTrace(e); setText(label, "Error"); } }); return label; } static public long nanos() { return nanoTime(); } static public Pt rotatePtLeft(Pt p) { return pt(p.y, -p.x); } static public int uploadToImageServerIfNotThere_tries = 3; static public String uploadToImageServerIfNotThere(BufferedImage img, String name) { return uploadToImageServerIfNotThere(null, img, name); } static public String uploadToImageServerIfNotThere(File f, BufferedImage img, String name) { String md5 = md5OfRGBImage(new RGBImage(img)); Throwable lastException = null; for (int tries = 0; tries < uploadToImageServerIfNotThere_tries; tries++) try { long id = imageServerCheckMD5(md5); if (id == 0) return uploadToImageServer_new(f, img, name); else return snippetImgLink(fsI(id)); } catch (Throwable e) { lastException = printException(e); } throw fail(lastException); } static public String uploadToImageServerIfNotThere(File f) { return uploadToImageServerIfNotThere(f, loadImage2(f), fileName(f)); } static public DoublePt addDoublePts(DoublePt a, DoublePt b) { return a == null ? b : b == null ? a : doublePt(a.x_double() + b.x_double(), a.y_double() + b.y_double()); } static public IDoublePt addDoublePts(IDoublePt a, IDoublePt b) { return a == null ? b : b == null ? a : doublePt(a.x_double() + b.x_double(), a.y_double() + b.y_double()); } static public JButton jThreadedButton(String text, Object action) { return swing(new F0() { public JButton get() { try { String text2 = dropPrefix("[disabled] ", text); JButton btn = basicJButton(text2); if (l(text2) < l(text)) btn.setEnabled(false); btn.setToolTipText(btn.getText()); if (action != null) btn.addActionListener(actionListenerInNewThread(action, btn)); return btn; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "S text2 = dropPrefix(\"[disabled] \", text);\r\n JButton btn = basicJButton(te..."; } }); } static public JButton jThreadedButton(String text, Runnable action) { return jThreadedButton(text, (Object) action); } static public Rect nullIfEmptyRect(Rect r) { return rectEmpty(r) ? null : r; } static public String uploadToImageServer_rawBytes(byte[] imgData, String name) { String page = postPage(imageServerURL() + "upload/" + randomID(), "data", bytesToHex(imgData), "name", name); print(page); Matcher m = Pattern.compile("/images/([0-9]+)").matcher(page); if (!m.find()) return null; return snippetImgLink(m.group(1)); } static public JButton jImageButton(String imageID, Object action) { return jimageButton(imageID, action); } static public JButton jImageButton(String imageID) { return jimageButton(imageID); } static public JButton jImageButton(Image image, String toolTip, Runnable action) { return jimageButton(image, toolTip, action); } static public JButton jImageButton(String imageID, String toolTip, Runnable action) { return jimageButton(imageID, toolTip, action); } static public String javaDropAllComments(String s) { return join(javaDropAllComments(javaTok(s))); } static public List javaDropAllComments(List tok) { for (int i = 0; i < l(tok); i += 2) tok.set(i, tok_javaDropCommentsFromWhitespace(tok.get(i))); return tok; } static public String regexpReplace(String s, String pat, IF1 f) { return regexReplace(s, pat, f); } static public String regexpReplace(String s, String pat, String replacement) { return regexpReplace_direct(s, pat, replacement); } static public A makeUneditableWithTextColor(A a, Color color) { if (a != null) { swing(() -> { a.setEditable(false); DefaultCaret caret = (DefaultCaret) (a.getCaret()); caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE); a.setDisabledTextColor(color); }); } return a; } static public A makeUneditableWithTextColor(Color color, A a) { return makeUneditableWithTextColor(a, color); } static public String copyTextToClipboardIfNotNull(String text) { if (text != null) copyTextToClipboard(text); return text; } static public boolean equalsIgnoreCase(String a, String b) { return eqic(a, b); } static public boolean equalsIgnoreCase(char a, char b) { return eqic(a, b); } static public void thinAProgramsBackups(String progID, boolean doIt) { File dir = programDir(progID); thinAProgramsBackups(dir, doIt); } static public void thinAProgramsBackups(File dir, boolean doIt) { List files = new ArrayList(); Map ageMap = new HashMap(); java.util.regex.Pattern pat = regexp("^(.*)\\.backup(20\\d\\d)(\\d\\d)(\\d\\d)-(\\d\\d)(\\d*)$"); print("Processing backups in " + dir); for (File f : listFilesNotDirs(dir, newFile(dir, "backups"))) { String s = f.getName(); java.util.regex.Matcher matcher = pat.matcher(s); { if (!(matcher.find())) continue; } String originalName = matcher.group(1); { if (!(eq(originalName, "concepts.structure.gz"))) continue; } int year = matcherInt(matcher, 2); int month = matcherInt(matcher, 3); int day = matcherInt(matcher, 4); int hour = matcherInt(matcher, 5); int minute = matcherInt(matcher, 6); long time = timestampFromYMDHM(year, month, day, hour, minute); double age = ((now() - time) / 1000.0 / 60 / 60 / 24); ageMap.put(f, age); files.add(f); } int numDeleted = 0; sortByMap_inPlace(files, ageMap); double lastAge = -1; for (File f : files) { double age = ageMap.get(f); if (!thinAProgramsBackups_shouldKeep(age, lastAge)) { ++numDeleted; if (doIt) { print("Deleting: " + f); f.delete(); } } else { lastAge = age; } } if (numDeleted != 0) print((doIt ? "Deleted: " : "Would delete: ") + n(numDeleted, "file")); } static public boolean thinAProgramsBackups_shouldKeep(double age, double lastAge) { return defaultAgeBasedBackupRetentionStrategy_shouldKeep(age, lastAge); } static public IterableIterator iota(final int n) { return new IterableIterator() { public int i = 0; public boolean hasNext() { return i < n; } public Integer next() { return ++i; } }; } static public List cloneValues(Map map) { return cloneList(values(map)); } static public boolean isStandardFunction(String name) { return isIdentifier(name) && stdFunctions_cached().containsKey(name); } static public void setOptAllDyn_pcall(DynamicObject o, Map fields) { if (fields == null || o == null) return; HashMap fieldMap = instanceFieldsMap(o); for (Map.Entry e : fields.entrySet()) { try { String field = e.getKey(); Object val = e.getValue(); Field f = fieldMap.get(field); if (f != null) smartSet(f, o, val); else { dynamicObject_setRawFieldValue(o, intern(field), val); } } catch (Throwable __e) { pcallFail(__e); } } } static public BufferedImage shootRightScreen() { var screens = allScreenBounds(); return shootScreen2(l(screens) >= 2 ? second(screens) : last(screens)); } static public A uneditableBlack(A a) { return makeUneditableWithTextColor(Color.black, a); } static public BufferedImage pointsToImage(Iterable points) { var pointsList = asList(points); if (empty(pointsList)) return whiteImage(1); Rect bounds = boundsOfPts(pointsList); var img = whiteImage(bounds.w + 2, bounds.h + 2); for (var p : pointsList) { ping(); setPixel(img, p.x - bounds.x + 1, p.y - bounds.y + 1, Color.black); } return img; } static public BufferedImage pointsToImage_fromOrigin(Iterable points) { var pointsList = asList(points); if (empty(pointsList)) return whiteImage(1); Pt size = maxPt(pointsList); var img = whiteImage(size.x + 2, size.y + 2); for (var p : pointsList) setPixel(img, p, Color.black); return img; } static public double radianToDegree(double rad) { return rad * (180 / pi()); } static public ReliableSingleThread rstWithDelay(final int delay, final Runnable r) { return new ReliableSingleThread(new Runnable() { public void run() { try { sleep(delay); callF(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "sleep(delay);\r\n callF(r);"; } }); } static public ReliableSingleThread rstWithDelay(double seconds, Runnable r) { return rstWithDelay(toMS_int(seconds), r); } static public int bitOr(int a, int b) { return a | b; } static public Object[] litobjectarray(Object... l) { return litObjectArray(l); } static public Object invokeConstructorWithWidening(Constructor m, Object... args) { try { try { Class[] types = m.getParameterTypes(); int n = types.length; Object[] args2 = new Object[n]; for (int i = 0; i < n; i++) args2[i] = convertPrimitiveIfNecessary(args[i], types[i]); return m.newInstance(args2); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args))); } } catch (Exception __e) { throw rethrow(__e); } } static public A getFromIterator(Iterator it, int idx) { if (idx < 0) return null; while (true) { ping(); if (!it.hasNext()) return null; else { A a = it.next(); if (idx-- == 0) return a; } } } static public Class actualMC() { return or((Class) realMC(), mc()); } static public int unicodeToCodePoint(String s) { return s.codePointAt(0); } static public ReliableSingleThread rst(Runnable r) { return new ReliableSingleThread(r); } static public List> multiMapToPairs(MultiMap mm) { List> out = new ArrayList(); for (A key : keys(mm)) for (B value : mm.get(key)) out.add(pair(key, value)); return out; } static public List localFontFamilies() { return wrapAsList(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()); } static public double pow(double a, double b) { return Math.pow(a, b); } static public float pow(float a, float b) { return (float) Math.pow(a, b); } static public BigInteger pow(BigInteger a, int b) { return a.pow(b); } static public List>> multiSetMapToMapPairs(MultiSetMap mm) { List>> out = new ArrayList(); for (A key : keys(mm)) out.add(pair(key, mm.get(key))); return out; } static public ReliableSingleThread rstWithPreDelay(int delay, Runnable r) { return rstWithDelay(delay, r); } static public ReliableSingleThread rstWithPreDelay(double seconds, Runnable r) { return rstWithDelay(seconds, r); } static public RSTOverQ rstWithPreDelay(double seconds, Q q, Runnable r) { return new RSTOverQ(q, new Runnable() { public void run() { try { sleepSeconds(seconds); callF(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Sleep " + seconds + "s, then: " + r; } }); } static public String cnfp(Object o, Class c, String className) { return classNameForPrinting(o, c, className); } static public String curly(String s) { return optionalCurlyBrace(s); } static public int idiv_ceil(int a, int b) { return (a + b - 1) / b; } static public int idiv_ceil(long a, long b) { return toInt_checked((a + b - 1) / b); } static public boolean isArrayType(Class type) { return type != null && type.isArray(); } static public void linkVars(IVarWithNotify var1, IVarWithNotify var2) { if (var1 == null || var2 == null) return; var2.onChange(value -> var1.set(value)); var1.onChangeAndNow(value -> var2.set(value)); } static public NESWDirection getNESWDirection(int index) { return NESWDirection.values[index & 3]; } static public String reversedString(String s) { return reverseString(s); } static public Rect imageRect() { return imageRect(currentImage()); } static public Rect imageRect(BufferedImage img) { return img == null ? null : new Rect(0, 0, img.getWidth(), img.getHeight()); } static public Rect imageRect(MakesBufferedImage img) { return img == null ? null : new Rect(0, 0, img.getWidth(), img.getHeight()); } static public JTextArea jVarTextArea(IVarWithNotify var) { return bindTextComponentToVarWithNotify(jTextArea(), var); } static public Font localFont(String fontFamily) { return localFont(fontFamily, defaultFontSize()); } static public Font localFont(String fontFamily, int size) { return new Font(fontFamily, Font.PLAIN, size); } static public int lineNrToCharIndex(String s, int lineNr) { int i = 0; while (--lineNr > 0) i = smartIndexOf(s, '\n', i) + 1; return i; } static public void addFirst(List c, A a) { if (c != null) c.add(0, a); } static public IterableIterator filterIterator(final Iterator it, final F1 f) { if (it == null) return null; return iff(new F0() { public Object get() { try { while (it.hasNext()) { A a = it.next(); if (callF(f, a)) return a; } return endMarker(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "while (it.hasNext()) {\r\n A a = it.next();\r\n if (callF(f, a))\r\n ..."; } }); } static public IterableIterator filterIterator(final Iterator it, final IF1 f) { if (it == null) return null; return iff(new F0() { public Object get() { try { while (it.hasNext()) { A a = it.next(); if (callF(f, a)) return a; } return endMarker(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "while (it.hasNext()) {\r\n A a = it.next();\r\n if (callF(f, a))\r\n ..."; } }); } static public IterableIterator filterIterator(final F1 f, final Iterator it) { return filterIterator(it, f); } static public IterableIterator filterIterator(Collection l, IF1 f) { if (l == null) return null; Iterator it = iterator(l); return iff(new F0() { public Object get() { try { while (it.hasNext()) { A a = it.next(); if (f.get(a)) return a; } return endMarker(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "while (it.hasNext()) {\r\n A a = it.next();\r\n if (f.get(a))\r\n ..."; } }); } static public IterableIterator filterIterator(IF1 f, Iterator it) { return filterIterator(it, f); } static public int methodApplicabilityScore_withPrimitiveWidening(Executable m, Object[] args) { Class[] types = m.getParameterTypes(); if (types.length != l(args)) return Integer.MAX_VALUE; int score = 0; boolean widenings = false; for (int i = 0; i < types.length; i++) { Object a = args[i]; Class c = types[i]; if (a == null) { if (c.isPrimitive()) return Integer.MAX_VALUE; } else { Class t = a.getClass(); int s = typeConversionScoreWithUnboxing(t, c); if (s == Integer.MAX_VALUE) return Integer.MAX_VALUE; if (s < 0) widenings = true; score += abs(s); } } return widenings ? -score : score; } static public File dbDir() { return programDir(dbProgramID()); } static public String longToHex(long l) { return bytesToHex(longToBytes(l)); } static public DoublePt toDoublePt(Pt p) { return p == null ? null : new DoublePt(p.x, p.y); } static public DoublePt toDoublePt(IDoublePt p) { if (p == null) return null; if (p instanceof DoublePt) return ((DoublePt) p); return new DoublePt(p.x_double(), p.y_double()); } static public void deleteAllConceptsOfProgram(String progID) { deleteFile(getProgramFile(progID, "concepts.structure")); deleteFile(getProgramFile(progID, "concepts.structure.gz")); } static public int countComponents(Container c) { return numberOfChildren(c); } static public A renameSubmitButton(A form, String newName) { renameButton(form, showFormSubmitButtonName(), newName); return form; } static public A renameSubmitButton(String newName, A form) { return renameSubmitButton(form, newName); } static public String joinLines(List lines) { return fromLines(lines); } static public String joinLines(String glue, String text) { return join(glue, toLines(text)); } static public File conceptsFileIn(File dir) { return newFile(dir, conceptsFileName()); } static public JTextField jVarTextField(IVarWithNotify var) { return bindTextComponentToVarWithNotify(jTextField(), var); } static public BufferedImage scaleBufferedImageToFit(int w, BufferedImage img) { return scaleBufferedImageToFit(w, w, img); } static public BufferedImage scaleBufferedImageToFit(int w, int h, BufferedImage img) { int iw = img.getWidth(), ih = img.getHeight(); double imgScale = max(doubleRatio(h, ih), doubleRatio(w, iw)); return scaleImage(img, imgScale); } static public BufferedImage scaleBufferedImageToFit(BufferedImage img, int w) { return scaleBufferedImageToFit(img, w, w); } static public BufferedImage scaleBufferedImageToFit(BufferedImage img, int w, int h) { return scaleBufferedImageToFit(w, h, img); } static public Font fontForName(String name) { if (isSnippetID(name)) return loadFont_cached(name); if (isLocalFontFamily(name)) return new Font(name, Font.PLAIN, defaultFontSize()); throw fail("No font for name " + name); } static public List getList(Map map, Object key) { return map == null ? null : (List) map.get(key); } static public List getList(List l, int idx) { return (List) get(l, idx); } static public List getList(Object o, Object key) { if (o instanceof Map) return getList((Map) o, key); if (key instanceof String) return (List) getOpt(o, (String) key); throw fail("Not a string key: " + getClassName(key)); } static public List getList(String name, Object o) { return getList(o, name); } static public A bindHasChangeListenersToComponent(A component, IHasChangeListeners hcl, Runnable listener) { if (hcl != null) bindToComponent(component, () -> hcl.onChangeAndNow(listener), () -> hcl.removeChangeListener(listener)); return component; } static public IVF1 vf1ToIVF1(VF1 f) { return f == null ? null : a -> f.get(a); } static public double degreeToRadian(double deg) { return deg * (pi() / 180); } static public IterableIterator boolIter(boolean includeTrue) { return itIt(includeTrue ? ll(false, true) : ll(false)); } static public Set allAWTComponents_extraList = weakHashSet(); static public List allAWTComponents() { if (headless()) return emptyList(); return swing(new F0>() { public List get() { try { return flattenList2(map(__115 -> allChildren(__115), allWindows()), cloneList(allAWTComponents_extraList)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return flattenList2(\r\n map allChildren(allWindows()),\r\n cloneList(a..."; } }); } static public void drawPixelStripes(BufferedImage image) { int w = image.getWidth(), h = image.getHeight(); var g = getGraphics(image); for (int y = 0; y < h; y++) drawLine(g, 0, y, w - 1, y, even(y) ? Color.lightGray : Color.white); } static public A printException(A e) { printStackTrace(e); return e; } static public long benchFor5Seconds(String desc, Runnable r) { return benchForNSeconds(desc, r, 5); } static public long benchFor5Seconds(Runnable r) { return benchFor5Seconds(str(r), r); } static public A benchFor5Seconds(IF0 f) { return benchFor5Seconds(str(f), f); } static public A benchFor5Seconds(String desc, IF0 f) { benchFor5Seconds(desc, new Runnable() { public void run() { try { f.get(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f!"; } }); return f.get(); } static final public Pt[] onePathDirections_directions = { pt(0, 0), pt(-1, -1), pt(0, -1), pt(1, -1), pt(1, 0), pt(1, 1), pt(0, 1), pt(-1, 1), pt(-1, 0) }; static public Pt[] onePathDirections() { return onePathDirections_directions; } static public JExtendedTabbedPane jExtendedTabs(Object... x) { return swing(() -> new JExtendedTabbedPane(jtabs(x))); } static public double randomZeroToOneExclusive() { return random(100000) / 100000.0; } static public String nLetters(long n) { return n2(n, "letter"); } static public String nLetters(Collection l) { return nLetters(l(l)); } static public String nLetters(Map map) { return nLetters(l(map)); } static public int parseIntN2(String s) { return parseInt(replace(s, ",", "")); } static public int blendMultipleColorsToInt(List> colors) { double sum = doubleSum(pairsB(colors)); double r = 0, g = 0, b = 0; for (var __0 : colors) { var color = pairA(__0); var weight = pairB(__0); r += color.getRed() * weight; g += color.getGreen() * weight; b += color.getBlue() * weight; } return rgbInt(roundedRatio(r, sum), roundedRatio(g, sum), roundedRatio(b, sum)); } static public int blendMultipleColorsToInt(Color[] colors, double[] weights) { double sum = doubleSum(weights); double r = 0, g = 0, b = 0; for (int i = 0; i < l(colors); i++) { Color color = colors[i]; double weight = weights[i]; r += color.getRed() * weight; g += color.getGreen() * weight; b += color.getBlue() * weight; } return rgbInt(roundedRatio(r, sum), roundedRatio(g, sum), roundedRatio(b, sum)); } static public A firstKey(Map map) { return first(keys(map)); } static public A firstKey(IMultiMap map) { return map == null ? null : first(map.keySet()); } static public AutoCloseable tempProfileSingleThreadToConsole() { SingleThreadProfiler profiler = new SingleThreadProfiler(); profiler.start(); return () -> { profiler.stop(); print(profiler.renderFullResults(true)); profiler.close(); }; } static public List constructorsWithNumberOfArguments(Class c, int n) { return filter(getDeclaredConstructors_cached(c), con -> l(con.getParameterTypes()) == n); } static public List flattenList2(Object... a) { List l = new ArrayList(); if (a != null) for (Object x : a) if (x instanceof Collection) for (Object sub : (Collection) x) l.addAll(flattenList2(sub)); else if (x != null) l.add(x); return l; } static public List> groupNonEmpty(List l, Object isSep) { List> out = new ArrayList(); int j = 0; for (int i = 0; i < l(l); i++) { boolean sep = isTrue(callF(isSep, l.get(i))); if (sep) { if (i > j) out.add(newSubList(l, j, i)); j = i + 1; } } if (l(l) > j) out.add(newSubList(l, j)); return out; } static public long boostHashCombine64(long a, long b) { return a ^ (b + 0x9e3779b97f4a7c15L + (a << 6) + (a >>> 2)); } static public int getIndentOfLine(String s) { int i = 0, n = l(s); while (i < n && s.charAt(i) == ' ') ++i; return i; } static public long timestampFromYMDHM(int y, int m, int d, int h, int minutes) { return new GregorianCalendar(y, m - 1, d, h, minutes).getTimeInMillis(); } static public List trimAll(String... l) { return trimAll(asList(l)); } static public List trimAll(Collection l) { List l2 = new ArrayList(); if (l != null) for (String s : l) l2.add(trim(s)); return l2; } static public String regexpN2() { return "\\d+(?:,\\d+)*"; } static public Object componentMetaSrc(Component c) { return swing(() -> { var _c_2 = c; do { var __1 = getMetaSrc(_c_2); if (__1 != null) return __1; } while ((_c_2 = getParent(_c_2)) != null); return null; }); } static public Boolean not(Boolean b) { return b == null ? null : !b; } static public void assertSetsEqual(Collection l1, Collection l2) { assertSetsEqual("", l1, l2); } static public void assertSetsEqual(String msg, Collection l1, Collection l2) { assertEquals("Set sizes", l(l1), l(l2)); Set set2 = asSet(l2); for (Object o : unnullForIteration(l1)) if (!contains(set2, o)) throw fail("Set 2 doesn't contain " + o); Set set1 = asSet(l1); for (Object o : unnullForIteration(l2)) if (!contains(set1, o)) throw fail("Set 1 doesn't contain " + o); } static public void setSliderMax(JSlider slider, int max) { if (slider != null) { swing(() -> { slider.setMaximum(max); }); } } static public void addKeyListener(final Component c, final KeyListener l) { if (c != null) { swing(() -> { c.addKeyListener(l); }); } } static public long totalIntRangesLength(Iterable l) { long total = 0; for (IntRange r : unnullForIteration(l)) total += r.length(); return total; } static public String shortToString(Object o) { return shorten(str(o), 100); } static public String deRoundBracket(String s) { if (startsWith(s, "(") && endsWith(s, ")")) return substring(s, 1, l(s) - 1); return s; } static public MultiMap similarEmptyMultiMap(MultiMap m) { if (m instanceof TreeMultiMap) return new TreeMultiMap((TreeMultiMap) m); return similarEmptyMultiMap(m == null ? null : m.data); } static public MultiMap similarEmptyMultiMap(Map m) { MultiMap mm = new MultiMap(); if (m != null) mm.data = similarEmptyMap(m); return mm; } static public double positiveInfinity() { return Double.POSITIVE_INFINITY; } static public char unquoteCharacter(String s) { assertTrue(s.startsWith("'") && s.length() > 1); return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length() - 1 : s.length()) + "\"").charAt(0); } static public int hexToInt(String s) { return Integer.parseInt(s, 16); } static public A setEditable(A a, boolean b) { if (a != null) { swing(() -> { a.setEditable(b); }); } return a; } static public JTextArea wordWrapTypeWriterTextArea() { return wrappedTextArea(newTypeWriterTextArea()); } static public JTextArea wordWrapTypeWriterTextArea(String text) { return wrappedTextArea(newTypeWriterTextArea(text)); } static public String programNameOrNull() { return replaceIfEqual(programName(), "?", null); } static public List filterNempty(Collection c) { List l = new ArrayList(); for (String x : unnull(c)) if (nempty(x)) l.add(x); return l; } static public List allWindows() { return asList(Window.getWindows()); } static public void closeAllAndClear(Collection l) { if (l == null) return; for (AutoCloseable c : cloneList(l)) { try { close(c); } catch (Throwable __e) { pcallFail(__e); } } l.clear(); } static public IterableIterator countTo(int b) { return countTo(0, b); } static public IterableIterator countTo(int a, int b) { return countIterator(a, b); } static public IterableIterator countTo(int b, IF1 f) { return countTo(0, b, f); } static public IterableIterator countTo(int a, int b, IF1 f) { return countIterator(a, b, f); } static public IterableIterator countTo(int a, int b, int step) { return countIterator(a, b, step); } static public IterableIterator countTo(double a, double b, double step, IF1 f) { return countIterator(a, b, step, f); } static public IterableIterator countTo(double a, double b, double step) { return countIterator(a, b, step); } static public IterableIterator countTo(IF1 f, double a, double b, double step) { return countIterator(f, a, b, step); } static public IterableIterator countTo(IF1 f, int b) { return countTo(f, 0, b); } static public IterableIterator countTo(IF1 f, int a, int b) { return countIterator(f, a, b); } static public IterableIterator countTo(List l) { return countIterator(l); } static public String concatMap_strings(Object f, Iterable l) { return join((List) map(f, l)); } static public String concatMap_strings(Object f, Object[] l) { return join((List) map(f, l)); } static public String concatMap_strings(Iterable l, Object f) { return concatMap_strings(f, l); } static public String concatMap_strings(Iterable l, IF1 f) { return concatMap_strings(f, l); } static public String concatMap_strings(IF1 f, Iterable l) { return concatMap_strings((Object) f, l); } static public String concatMap_strings(IF1 f, A[] l) { return concatMap_strings((Object) f, l); } static public String curlyBrace(String s) { return "{" + s + "}"; } static public String gazelleLogoImageID() { return "#1102967"; } static public JCheckBox jVarCheckBox(IVarWithNotify lv) { return jVarCheckBox("", lv); } static public JCheckBox jVarCheckBox(String text, IVarWithNotify lv) { JCheckBox cb = jCheckBox(text); bindCheckBoxToLiveValue(cb, lv); return cb; } static public void onSelectionChanged(JList list, VF1 f) { onSelectionChanged(list, toIVF1(f)); } static public void onSelectionChanged(JList list, IVF1 f) { if (list != null && f != null) { swing(() -> { list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { pcallF(f, getSelectedItem(list)); } }); }); } } static public Pt varyPoint(Pt p, int w, int h) { return tossACoin() ? randomPoint(w, h) : varyPoint(p, 10); } static public Pt varyPoint(Pt p, int range) { range = max(range, 1); return new Pt(random_incl(p.x - range, p.x + range), random_incl(p.y - range, p.y + range)); } static public Set fieldNames(Object o) { return allFields(o); } static public IntRange intRange_incl(int start, int end) { return new IntRange(start, end + 1); } static public boolean[] boolArrayFromBytes(byte[] a, int n) { boolean[] b = new boolean[n]; int m = min(n, l(a) * 8); for (int i = 0; i < m; i++) b[i] = (a[i / 8] & 1 << (i & 7)) != 0; return b; } static public JForm showFormTitled3(String title, Object... parts) { JForm form = new JForm(parts).disposeFrameOnSubmit(); showFrame(title, form); return form; } static public long hashCollisions; static public void reportHashCollision(Object... data) { printVars("Hash collision! " + shorten(joinWithComma(data))); ++hashCollisions; } static public byte[] loadBinaryFilePart(File file, long start, long end) { try { if (file == null) return null; RandomAccessFile raf = new RandomAccessFile(file, "r"); int n = toInt(min(raf.length(), end - start)); byte[] buffer = new byte[n]; try { raf.seek(start); raf.readFully(buffer, 0, n); return buffer; } finally { raf.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public String joinNemptiesWithSpacedPlus(Object... strings) { return joinNempties(" + ", strings); } static public String joinNemptiesWithSpacedPlus(Iterable strings) { return joinNempties(" + ", strings); } static public MultiSetMap reversedOrderedMultiSetMap(MultiMap map) { MultiSetMap mm = orderedMultiSetMap(); for (A key : keys(map)) for (B value : map.get(key)) mm.put(value, key); return mm; } static public boolean isInterface(Class c) { return c != null && c.isInterface(); } static public int[] sortIntArrayInPlaceDesc(int[] a) { if (a == null) return null; Arrays.sort(a); reverseIntArrayInPlace(a); return a; } static public String unquoteUsingCharArray(String s, char[] buf) { if (s == null) return null; if (startsWith(s, '[')) { int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; if (i < s.length() && s.charAt(i) == '[') { String m = s.substring(1, i); if (s.endsWith("]" + m + "]")) return s.substring(i + 1, s.length() - i - 1); } } if (s.length() > 1) { char c = s.charAt(0); if (c == '\"' || c == '\'') { int l = endsWith(s, c) ? s.length() - 1 : s.length(); if (l > buf.length) return unquote(s); int n = 0; for (int i = 1; i < l; i++) { char ch = s.charAt(i); if (ch == '\\') { char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1); if (nextChar >= '0' && nextChar <= '7') { String code = "" + nextChar; i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; } } buf[n++] = (char) Integer.parseInt(code, 8); continue; } switch(nextChar) { case '\"': ch = '\"'; break; case '\\': ch = '\\'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\'': ch = '\''; break; case 'u': if (i >= l - 5) { ch = 'u'; break; } int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16); char[] x = Character.toChars(code); int lx = x.length; for (int j = 0; j < lx; j++) buf[n++] = x[j]; i += 5; continue; default: ch = nextChar; } i++; } buf[n++] = ch; } return new String(buf, 0, n); } } return s; } static public String dropPrefixIC(String prefix, String s) { return s == null ? null : swic(s, prefix) ? s.substring(l(prefix)) : s; } static public BitSet emptyBitSet(int capacity) { return new BitSet(capacity); } static public BitSet emptyBitSet(Collection capacity) { return emptyBitSet(l(capacity)); } static public Double toDoubleOrNull(Object o) { if (o == null) return null; return toDouble(o); } static public Rect copyRect(Rect a, Rect b) { b.x = a.x; b.y = a.y; b.w = a.w; b.h = a.h; return b; } static public JButton findSubmitButton(Component c) { return findButton(c, showFormSubmitButtonName()); } static public Method findSingleInterfaceMethod(Class intrface) { return singletonOpt(findFunctionalInterfaceMethods(intrface)); } static public A setFontSize(final float size, final A a) { if (a == null) return a; { swing(() -> { a.setFont(a.getFont().deriveFont((float) size)); if (a instanceof JComboBox) { Component _a = ((JComboBox) a).getEditor().getEditorComponent(); if (_a instanceof JComponent) ((JComponent) _a).setFont(((JComponent) _a).getFont().deriveFont((float) size)); } }); } return a; } static public A setFontSize(A a, float size) { return setFontSize(size, a); } static public IntegralImage integralImage(BufferedImage img) { return img == null ? null : new IntegralImage(img); } static public void addIfNempty(Collection l, String s) { if (nempty(s)) l.add(s); } static public void addIfNempty(Collection l, Map m) { if (nempty(m)) l.add(m); } static public void addIfNempty(Collection l, Collection c) { if (nempty(c)) l.add(c); } static public List standardClassesSnippetIDs() { return ll("#1003674", "#1034167"); } static public JPanel scrollable_trackWidth(final Component component) { class P extends SingleComponentPanel implements Scrollable { public P() { super(component); } public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 20; } public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { return (direction == SwingConstants.HORIZONTAL ? visibleRect.width : visibleRect.height) * 5 / 6; } public boolean getScrollableTracksViewportWidth() { return true; } public boolean getScrollableTracksViewportHeight() { return false; } } return swing(new F0

() { public P get() { try { return new P(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return new P;"; } }); } static public float parseFloat(String s) { return Float.parseFloat(s); } static public double doubleSum(Iterable l) { double sum = 0; for (Double i : unnull(l)) if (i != null) sum += i; return sum; } static public double doubleSum(double... l) { double sum = 0; if (l != null) for (double i : l) sum += i; return sum; } static public double doubleSum(Iterable l, IF1_ObjectToDouble f) { double sum = 0; for (var a : l) sum += f.get(a); return sum; } static public double doubleSum(Iterable l, String field) { double sum = 0; for (var a : l) sum += toDouble(getOpt(a, field)); return sum; } static public double doubleSum(String field, Iterable l) { return doubleSum(l, field); } static public Color colorFromRGBA(int rgba) { return new Color(rgba, true); } static public List cyclicSubList_incl(List l, int startIndex, int endIndex) { return cyclicSubList(l, startIndex, endIndex + 1); } static public List toLinesFullTrim_java(String text) { return tlft(joinLines(map(__116 -> javaDropComments(__116), tlft(text)))); } static public void onSelect(JList list, IVF1 f) { onSelectionChanged(list, f); } static public boolean regexpFind(String pat, String s) { return regexpFinds(pat, s); } static public void consoleTitle(String title) { setConsoleTitle(title); } static public boolean isTrueOpt(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); return false; } static public boolean isTrueOpt(String field, Object o) { return isTrueOpt(getOpt(field, o)); } static public Object handleObjectMethodsInProxyInvocationHandler(Object invocationHandler, Method implementedMethod, Method method, Object proxy, Object[] actualArgs) { String name = method.getName(); if (name.equals("hashCode")) return invocationHandler.hashCode(); if (name.equals("equals")) return proxy == actualArgs[0]; if (name.equals("toString")) return invocationHandler.toString(); throw fail("No handler for method " + method + " (only have " + implementedMethod + ")"); } static public long longMul(long a, long b) { return a * b; } static public void pcallOpt_noArgs(Object o, String method) { try { callOpt_noArgs(o, method); } catch (Throwable __e) { pcallFail(__e); } } static public void clearPopupMenu(final JPopupMenu menu) { if (menu != null) { swing(() -> { menu.removeAll(); }); } } public static List toLinesTrim(String s) { List lines = new ArrayList(); int start = 0; while (true) { int i = toLinesTrim_nextLineBreak(s, start); if (i < 0) { if (s.length() > start) lines.add(rtrim(s.substring(start))); break; } lines.add(rtrim(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; } private static int toLinesTrim_nextLineBreak(String s, int start) { for (int i = start; i < s.length(); i++) { char c = s.charAt(i); if (c == '\r' || c == '\n') return i; } return -1; } static public int[] scaledPixelsFromIntegralImage(int w, IntegralImage img) { return scaledPixelsFromIntegralImage(img, w); } static public int[] scaledPixelsFromIntegralImage(IntegralImage img, int w) { return scaledPixelsFromIntegralImage(img, w, heightForWidth(img, w)); } static public int[] scaledPixelsFromIntegralImage(IntegralImage img, int w, int h) { int w1 = img.getWidth(), h1 = img.getHeight(); double stepX = doubleRatio(w1, w), stepY = doubleRatio(h1, h); int[] pixels = new int[w * h]; int i = 0; double srcY = 0; double area = stepX * stepY; for (int y = 0; y < h; y++) { double srcX = 0, nextSrcY = srcY + stepY; for (int x = 0; x < w; x++) { double nextSrcX = srcX + stepX; double r = doubleRatio(img.rectSum(srcX, srcY, nextSrcX, nextSrcY, 0), area); double g = doubleRatio(img.rectSum(srcX, srcY, nextSrcX, nextSrcY, 1), area); double b = doubleRatio(img.rectSum(srcX, srcY, nextSrcX, nextSrcY, 2), area); pixels[i++] = rgbIntFromDoubles_fullAlpha(r, g, b); srcX = nextSrcX; } srcY = nextSrcY; } return pixels; } static public int[] scaledPixelsFromIntegralImage(int w, IIntegralImage img) { return scaledPixelsFromIntegralImage(img, w); } static public int[] scaledPixelsFromIntegralImage(IIntegralImage img, int w) { return scaledPixelsFromIntegralImage(img, w, heightForWidth(img, w)); } static public int[] scaledPixelsFromIntegralImage(IIntegralImage img, int w, int h) { int w1 = img.getWidth(), h1 = img.getHeight(); double stepX = doubleRatio(w1, w), stepY = doubleRatio(h1, h); int[] pixels = new int[w * h]; int i = 0; double srcY = 0; double area = stepX * stepY; for (int y = 0; y < h; y++) { double srcX = 0, nextSrcY = srcY + stepY; for (int x = 0; x < w; x++) { double nextSrcX = srcX + stepX; double r = doubleRatio(img.rectSum(srcX, srcY, nextSrcX, nextSrcY, 0), area); double g = doubleRatio(img.rectSum(srcX, srcY, nextSrcX, nextSrcY, 1), area); double b = doubleRatio(img.rectSum(srcX, srcY, nextSrcX, nextSrcY, 2), area); pixels[i++] = rgbIntFromDoubles_fullAlpha(r, g, b); srcX = nextSrcX; } srcY = nextSrcY; } return pixels; } static public List hashRefTok(String s) { ArrayList tok = new ArrayList(); int l = s == null ? 0 : s.length(); int i = 0; while (i < l) { int j = i; char c; while (j < l) { if (j < l - 1 && s.charAt(j) == '#') { c = s.charAt(j + 1); if (Character.isJavaIdentifierStart(c) || Character.isDigit(c) || c == '(') break; } j++; } tok.add(quickSubstring(s, i, j)); i = j; if (i >= l) break; j = i + 1; c = s.charAt(j); if (Character.isJavaIdentifierStart(c)) { do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j))); } else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); } else if (c == '(') { do ++j; while (j < l && s.charAt(j) != ')'); j = Math.min(j + 1, l); } else ++j; tok.add(quickSubstring(s, i, j)); i = j; } if ((tok.size() & 1) == 0) tok.add(""); return tok; } static public MultiMap reversedOrderedMultiMap(MultiMap map) { MultiMap mm = orderedMultiMap(); for (A key : keys(map)) for (B value : map.get(key)) mm.put(value, key); return mm; } static public BWImage getAlphaChannel(BufferedImage src) { int w = src.getWidth(); int h = src.getHeight(); BWImage alpha = new BWImage(w, h); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { int a = (src.getRGB(x, y) >> 24) & 0xff; alpha.setByte(x, y, a); } return alpha; } static public MultiMap orderedMultiMap() { MultiMap mm = new MultiMap(); mm.data = new LinkedHashMap(); return mm; } static public List repF(int n, Object f, Object... args) { List l = emptyList(n); for (int i = 0; i < n; i++) l.add(callF(f, args)); return l; } static public List repF(Object f, int n) { return repF(n, f); } static public List repF(int n, IF0 f) { List l = emptyList(n); for (int i = 0; i < n; i++) l.add(f.get()); return l; } static public List repF(IF0 f, int n) { return repF(n, f); } static public List singlePredTok(ICharPred isPartOfToken, String s) { ArrayList tok = new ArrayList(); int l = s == null ? 0 : s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c; while (j < l) { c = s.charAt(j); if (isPartOfToken.get(c)) break; else ++j; } tok.add(substring(s, i, j)); i = j; if (i >= l) break; do ++j; while (j < l && isPartOfToken.get(s.charAt(j))); tok.add(substring(s, i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static public boolean isSameFile(File a, File b) { return sameFile(a, b); } static public double aspectRatio(Dimension img) { return aspectRatio(toWidthAndHeight(img)); } static public double aspectRatio(int img_w, int img_h) { return aspectRatio(widthAndHeight(img_w, img_h)); } static public double aspectRatio(WidthAndHeight img) { return img == null ? Double.NaN : doubleRatio(img.getWidth(), img.getHeight()); } static public List sortFilesAlphaNumIC(Collection l) { return sorted(l, new Comparator() { public int compare(File a, File b) { return cmpAlphaNumIC(a.getPath(), b.getPath()); } }); } static public IterableIterator iff_null(final Object f) { return iteratorFromFunction(f); } static public IterableIterator iff_null(F0 f) { return iteratorFromFunction(f); } static public IterableIterator iff_null(IF0 f) { return iteratorFromFunction(f); } static public List virtualNullList(int n) { return new RandomAccessAbstractList() { public int size() { return n; } public A get(int i) { return null; } }; } static public Rect rescaleRect(Rect r, int w1, int h1, int w2, int h2) { if (r == null) return null; double x = doubleRatio(w2, w1), y = doubleRatio(h2, h1); return rectFromPoints(iround(r.x * x), iround(r.y * y), iround(r.x2() * x), iround(r.y2() * y)); } static public Pt ptFromLong(long l) { return longToPt(l); } static public List tlft_j(String text) { return toLinesFullTrim_java(text); } static public boolean isIPv4(String s) { return s != null && l(javaTokC(s)) == 7 && jfind(javaTok(s), "...") == 1; } static public String joinWithEmptyLines(Iterable l) { return join("\n\n", map(__117 -> rtrim(__117), l)); } static public String joinWithEmptyLines(String... l) { return joinWithEmptyLines(asList(l)); } static public JSlider onSliderValueChanged(JSlider slider, IVF1 onChange) { return swing(() -> { slider.addChangeListener(new ChangeListener() { public int lastValue = slider.getValue(); public void stateChanged(ChangeEvent e) { int value = slider.getValue(); if (value != lastValue) { lastValue = value; setToolTip(slider, str(value)); pcallF(onChange, value); } } }); return slider; }); } static public JSlider onSliderValueChanged(JSlider slider, Runnable onChange) { if (onChange != null) onSliderValueChanged(slider, runnableToIVF1(onChange)); return slider; } static public WidthAndHeight scaleWidthAndHeight(double scale, WidthAndHeight size) { return size == null ? null : new WidthAndHeightImpl(iround(scale * size.w()), iround(scale * size.h())); } static public int totalIntRangesLength_int(Iterable l) { return toInt(totalIntRangesLength(l)); } static public TreeSet ciSet() { return caseInsensitiveSet(); } static public A awtStepContinuously(A component, Steppable steppable) { if (steppable == null) return component; SingleThread thread = new SingleThread(); BoolVar visible = new BoolVar(); var info = _threadInfo(); Runnable theLoop = new Runnable() { public void run() { try { _threadInheritInfo(info); while (visible.get() && steppable.step()) { ping(); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_threadInheritInfo(info);\r\n while (visible! && steppable.step()) { ping(); }"; } }; bindToComponent(component, () -> { visible.set(); thread.go(theLoop); }, () -> visible.clear()); return component; } static public String nPages(int n) { return n2(n, "page"); } static public String nPages(Collection l) { return nPages(l(l)); } static public boolean tossCoin() { return oneIn(2); } static public boolean tossCoin(Random random) { return oneIn(2, random); } static public boolean tossCoin(double probability) { return randomZeroToOneExclusive() < probability; } static public byte[] isGIF_magic = bytesFromHex("47494638"); static public boolean isGIF(byte[] data) { return byteArrayStartsWith(data, isGIF_magic); } static public boolean isGIF(File f) { return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic))); } static public int getIntColorWithoutAlphaOrMinus1(BufferedImage img, int x, int y) { return img == null || !inImage(x, y, img) ? -1 : getIntColorWithoutAlpha(img, x, y); } static public String joinNemptiesWithVBar(String... strings) { return joinNempties(" | ", strings); } static public String joinNemptiesWithVBar(Collection strings) { return joinNempties(" | ", strings); } static public long parseLongOpt(String s) { return isInteger(s) ? parseLong(s) : 0; } static public Font fontWithSpacing(double spacing, Font font) { return font.deriveFont(litmap(TextAttribute.TRACKING, spacing)); } static public void addInFront(List c, A a) { addFirst(c, a); } static public void addInFront(Container c, Component... l) { containerAddFirst(c, l); } static public List splitAtComma(String s) { return empty(s) ? emptyList() : asList(s.split(",")); } static public PrecisePolygon regularPolygon(double center_x, double center_y, double radius, int sides) { return regularPolygon(doublePt(center_x, center_y), radius, sides); } static public PrecisePolygon regularPolygon(IDoublePt center, double radius, int sides) { return regularPolygon(center, radius, sides, 0); } static public PrecisePolygon regularPolygon(double center_x, double center_y, double radius, int sides, double rotation) { return regularPolygon(doublePt(center_x, center_y), radius, sides, rotation); } static public PrecisePolygon regularPolygon(IDoublePt center, double radius, int sides, double rotation) { double angle = twoPi() / sides; var _rotation_1 = degToRadian(-rotation); return new PrecisePolygon(countIteratorToList(sides, i -> addDoublePts(center, scaleDoublePt(radius, doublePt(sin(_rotation_1 + angle * i), cos(_rotation_1 + angle * i)))))); } static public org.apache.bcel.generic.Type classToBCELType(Class c) { if (c == null) return null; if (isPrimitiveType(c)) { if (c == byte.class) return org.apache.bcel.generic.Type.BYTE; if (c == char.class) return org.apache.bcel.generic.Type.CHAR; if (c == short.class) return org.apache.bcel.generic.Type.SHORT; if (c == int.class) return org.apache.bcel.generic.Type.INT; if (c == long.class) return org.apache.bcel.generic.Type.LONG; if (c == double.class) return org.apache.bcel.generic.Type.DOUBLE; if (c == void.class) return org.apache.bcel.generic.Type.VOID; if (c == boolean.class) return org.apache.bcel.generic.Type.BOOLEAN; throw fail("TODO: classToBCELType " + c); } if (isArrayType(c)) { int dimensions = 0; while (c.isArray()) { ++dimensions; c = c.componentType(); } return new ArrayType(classToBCELType(c), dimensions); } return new ObjectType(className(c)); } static public int getIntColorWithoutAlpha(BufferedImage img, int x, int y) { return img.getRGB(x, y) & 0xFFFFFF; } static public int getIntColorWithoutAlpha(BufferedImage img, Pt p) { return getIntColorWithoutAlpha(img, p.x, p.y); } static public void imageSurfaceOnHover(ImageSurface is, VF1 onHover) { if (is == null || onHover == null) return; { swing(() -> { MouseAdapter ma = new MouseAdapter() { public void mouseMoved(MouseEvent e) { pick(e); } public void mouseEntered(MouseEvent e) { pick(e); } public void mouseExited(MouseEvent e) { pick(null); } public void pick(MouseEvent e) { try { callF(onHover, e == null ? (Pt) null : is.pointFromEvent(e)); } catch (Throwable __e) { pcallFail(__e); } } }; is.addMouseMotionListener(ma); is.addMouseListener(ma); }); } } static public void imageSurfaceOnHover(ImageSurface is, IVF1 onHover) { imageSurfaceOnHover(is, toVF1(onHover)); } static public List getLocalFonts(Iterable fontFamilies) { var families = asSet(localFontFamilies()); return mapNonNulls(fontFamilies, name -> families.contains(name) ? localFont(name) : null); } static public BufferedImage mergeBufferedImagesVertically(BufferedImage... images) { return mergeBufferedImagesVertically(asList(images)); } static public BufferedImage mergeBufferedImagesVertically(Collection images, Object... __) { if (l(images) == 1) return first(images); return mergeImagesVertically(map(__118 -> toRGBImage(__118), images), __).getBufferedImage(); } static public MultiSet asMultiSet(Iterable l) { return new MultiSet(l); } static public MultiSetMap orderedMultiSetMap() { MultiSetMap mm = new MultiSetMap(); mm.data = new LinkedHashMap(); return mm; } static public Window centerWindow(Component c) { Window w = getWindow(c); if (w != null) w.setLocationRelativeTo(null); return w; } static public Window centerWindow(Component c, int width, int height) { setWindowSize(c, width, height); return centerWindow(c); } static public JWindow centerWindow(JWindow w) { centerWindow(getRootPane(w)); return w; } static public List neighborhood8(int x, int y) { return ll(new Pt(x - 1, y - 1), new Pt(x, y - 1), new Pt(x + 1, y - 1), new Pt(x - 1, y), new Pt(x + 1, y), new Pt(x - 1, y + 1), new Pt(x, y + 1), new Pt(x + 1, y + 1)); } static public boolean isPrimitiveType(Class c) { return c != null && c.isPrimitive(); } static public MultiSet similarEmptyMultiSet(MultiSet m) { MultiSet ms = new MultiSet(); ms.map = similarEmptyMap(m.map); return ms; } static public MultiSet similarEmptyMultiSet(Map m) { MultiSet ms = new MultiSet(); ms.map = similarEmptyMap(m); return ms; } static public Object realMC() { return getThreadLocal(realMC_tl()); } static public String stringIf(boolean b, String s) { return stringIfTrue(b, s); } static public String stringIf(String s, boolean b) { return stringIf(b, s); } static public double averageBrightness(MakesBufferedImage img) { return averageBrightness(toBufferedImage(img)); } static public double averageBrightness(BufferedImage img) { return new BWImage(img).averageBrightness(); } static public String snippetImgLink(String snippetID) { return snippetImageURL(snippetID); } static public Map compileRegexpIC_cache = syncMRUCache(10); static public java.util.regex.Pattern compileRegexpIC(String pat) { java.util.regex.Pattern p = compileRegexpIC_cache.get(pat); if (p == null) { try { compileRegexpIC_cache.put(pat, p = java.util.regex.Pattern.compile(pat, Pattern.CASE_INSENSITIVE)); } catch (PatternSyntaxException e) { throw rethrow(wrapPatternSyntaxException(e)); } } return p; } static public IterableIterator linesIterator(String s) { return lines_iterator(s); } static public CloseableIterableIterator linesIterator(File f) { return linesFromFile(f); } static public String xltrim(String s) { int i = 0, n = l(s); while (i < n && contains(" \t\r\n", s.charAt(i))) ++i; return substr(s, i); } static public Font sansSerifFont() { return sansSerifFont(defaultFontSize()); } static public Font sansSerifFont(int fontSize) { return sansSerif(fontSize); } static public void disableSubmitButton(Component form) { enableSubmitButton(form, false); } static public A awtCalcEvery_returnComponent(A c, int delay, int firstDelay, final Object runnable) { awtCalcRegularly(c, delay, firstDelay, runnable); return c; } static public A awtCalcEvery_returnComponent(A c, int delay, final Object runnable) { awtCalcRegularly(c, delay, delay, runnable); return c; } static public A awtCalcEvery_returnComponent(A c, double delay, final Object runnable) { return awtCalcEvery_returnComponent(c, toMS_int(delay), runnable); } static public int dec(int i) { return i - 1; } static public long dec(long l) { return l - 1; } static public int dec(AtomicInteger i) { return i.decrementAndGet(); } static public long dec(AtomicLong l) { return l.decrementAndGet(); } static public Map stdFunctions_cached_map; static public Lock stdFunctions_cached_lock = lock(); static public Map stdFunctions_cached() { Lock __0 = stdFunctions_cached_lock; lock(__0); try { if (stdFunctions_cached_map == null) stdFunctions_cached_map = stdFunctions_uncached(); return stdFunctions_cached_map; } finally { unlock(__0); } } static synchronized public void stdFunctions_clearCache() { stdFunctions_cached_map = null; } static public int ubyteFromBits(boolean b7, boolean b6, boolean b5, boolean b4, boolean b3, boolean b2, boolean b1, boolean b0) { return (b7 ? 1 : 0) << 7 | (b6 ? 1 : 0) << 6 | (b5 ? 1 : 0) << 5 | (b4 ? 1 : 0) << 4 | (b3 ? 1 : 0) << 3 | (b2 ? 1 : 0) << 2 | (b1 ? 1 : 0) << 1 | (b0 ? 1 : 0); } static public int[] mapToIntArray(Object f, Collection l) { return toIntArray(map(f, l)); } static public int[] mapToIntArray(Object f, Object[] l) { return toIntArray(map(f, l)); } static public int[] mapToIntArray(Collection l, IF1 f) { return mapToIntArray((Object) f, l); } static public List reverseList(List l) { Collections.reverse(l); return l; } static public AutoCloseable tempHideWindow(Component c) { return swing(() -> { Window w = getWindow(c); if (w == null || !w.isVisible()) return null; w.setVisible(false); return () -> w.setVisible(true); }); } static public byte[] loadBinaryFileChunk(File f, long start, int l) { try { byte[] buf = new byte[l]; RandomAccessFile raf = new RandomAccessFile(f, "r"); try { raf.seek(start); raf.readFully(buf); return buf; } finally { raf.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public byte[] loadBinaryFileChunk(File f, LongRange r) { return loadBinaryFileChunk(f, r.start, toInt_checked(r.length())); } static public IterableIterator nonNullIterator(Iterator it) { return notNulls_iterator(it); } static public boolean isLocalFontFamily(String fontName) { return contains(localFontFamilies(), fontName); } static public String replaceRegexp(String s, String pat, IF1 f) { return regexpReplace(s, pat, f); } static public String replaceRegexp(String s, String pat, String replacement) { return regexpReplace(s, pat, replacement); } static public SingleComponentPanel scp() { return singleComponentPanel(); } static public SingleComponentPanel scp(Component c) { return singleComponentPanel(c); } static public long usedMemory() { return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); } static public String joinWithCommaOr(String def, Collection c) { return nempty(c) ? joinWithComma(c) : def; } static public String joinWithCommaOr(Collection c, String def) { return joinWithCommaOr(def, c); } static public Map nonDefaultInterfaceMethods_cache = newDangerousWeakHashMap(); static public Method[] nonDefaultInterfaceMethods(Class c) { Method[] methods; synchronized (nonDefaultInterfaceMethods_cache) { methods = nonDefaultInterfaceMethods_cache.get(c); if (methods == null) nonDefaultInterfaceMethods_cache.put(c, methods = toTypedArray(Method.class, findNonDefaultInterfaceMethods(c))); } return methods; } static public boolean notNull(Object o) { return o != null; } static public SortedMap subMap(SortedMap map, A fromKey, A toKey) { return map == null ? null : map.subMap(fromKey, toKey); } static public ImageSurface pixelatedZoomedImageSurface() { return pixelatedImageSurface().setAutoZoomToDisplay(true); } static public ImageSurface pixelatedZoomedImageSurface(MakesBufferedImage img) { return pixelatedZoomedImageSurface(toBufferedImage(img)); } static public ImageSurface pixelatedZoomedImageSurface(BufferedImage img) { var is = pixelatedZoomedImageSurface(); is.setImage(img); return is; } static public ImageSurface pixelatedZoomedImageSurface(double zoom, MakesBufferedImage img) { return pixelatedZoomedImageSurface(zoom, toBufferedImage(img)); } static public ImageSurface pixelatedZoomedImageSurface(double zoom, BufferedImage img) { return pixelatedImageSurface(img).setZoom(zoom); } static public ImageSurface pixelatedZoomedImageSurface(MakesBufferedImage img, double zoom) { return pixelatedZoomedImageSurface(toBufferedImage(img), zoom); } static public ImageSurface pixelatedZoomedImageSurface(BufferedImage img, double zoom) { return pixelatedZoomedImageSurface(zoom, img); } static public ImageSurface pixelatedZoomedImageSurface(double zoom) { return pixelatedImageSurface().setZoom(zoom); } static public AutoCloseable tempGlobalPopupMenu(IVF2 fillMenu) { return tempGlobalPopupMenu(fillMenu, 0.1); } static public AutoCloseable tempGlobalPopupMenu(IVF2 fillMenu, double delay) { return fillMenu == null ? null : tempAddPopupButtonListener(evt -> { var c = evt.getComponent(); if (c == null) return; var c2 = SwingUtilities.getDeepestComponentAt(c, evt.getX(), evt.getY()); var p = ptInComponentFromEvent(evt); var p2 = translateLocationBetweenComponents(p, c2); awtLater(delay, new Runnable() { public void run() { try { var menu = currentPopupMenu(); print("Pimping popup menu " + menu); PopupMenuMaker maker = new PopupMenuMaker(); maker.ptInComponent(p2); maker.event(evt).existingMenu(menu).fillMenu(_menu -> fillMenu.get(c2, _menu)).run(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var menu = currentPopupMenu();\r\n \r\n print(\"Pimping popup menu \" + m..."; } }); }); } static public IterableIterator roundRobinCombinedIterator(Iterator... iterators) { return roundRobinCombinedIterator(wrapAsList(iterators)); } static public IterableIterator roundRobinCombinedIterator(Collection> iterators) { if (empty(iterators)) return emptyItIt(); class Robin implements IF0 { public List> activeIterators = cloneList(iterators); public int i; public Object get() { while (licensed()) { Iterator it = activeIterators.get(i); if (!it.hasNext()) { activeIterators.remove(i); if (empty(activeIterators)) break; i %= l(activeIterators); } else { i = (i + 1) % l(activeIterators); return it.next(); } } return endMarker(); } } return iff(new Robin()); } static public int getPixel(BufferedImage img, int x, int y) { return img.getRGB(x, y); } static public int getPixel(BufferedImage img, Pt p) { return img.getRGB(p.x, p.y); } static public boolean containsPt(int x1, int y1, int w, int h, Pt p) { return p.x >= x1 && p.y >= y1 && p.x < x1 + w && p.y < y1 + h; } static public boolean containsPt(Rect a, int x, int y) { return a != null && a.contains(x, y); } static public boolean containsPt(Rect a, Pt p) { return a != null && p != null && a.contains(p.x, p.y); } static public boolean testBit(int i, int bit) { return (i & (1 << bit)) != 0; } static public Constructor findConstructor_precise_onTypes(Class c, Class... argTypes) { try { List ctors = constructorsWithNumberOfArguments(c, l(argTypes)); Lowest best = new Lowest(); if (ctors != null) for (Constructor ctor : ctors) { int score = methodApplicabilityScore_onTypes(ctor, argTypes); if (score < Integer.MAX_VALUE) best.put(ctor, score); } return best.get(); } catch (Exception __e) { throw rethrow(__e); } } static public HashSet mapToHashSet(Object f, Iterable l) { HashSet x = l instanceof Collection ? new HashSet(((Collection) l).size()) : new HashSet(); if (l != null) for (Object o : l) x.add(callF(f, o)); return x; } static public HashSet mapToHashSet(IF1 f, Iterable l) { HashSet x = l instanceof Collection ? new HashSet(((Collection) l).size()) : new HashSet(); if (l != null) for (A o : l) x.add(f.get(o)); return x; } static public MultiMap multiMapIndex(IF1 f, Iterable l) { MultiMap map = new MultiMap(); for (A a : unnullForIteration(l)) { B val = f.get(a); if (val != null) map.put(val, a); } return map; } static public MultiMap multiMapIndex(Iterable l, IF1 f) { return multiMapIndex(f, l); } static public boolean tossACoin() { return tossCoin(); } static public SortedMap synchroSortedMap(SortedMap map) { return new SynchronizedSortedMap(map); } static public void removeLast(List l) { if (!l.isEmpty()) l.remove(l(l) - 1); } static public void removeLast(List l, int n) { removeSubList(l, l(l) - n); } static public void removeLast(int n, List l) { removeLast(l, n); } static public void removeLast(StringBuilder buf) { if (buf == null) return; int n = buf.length(); if (n > 0) buf.setLength(n - 1); } static public boolean hasTransparency(BufferedImage img) { return img.getColorModel().hasAlpha(); } static public F0 toF0(final Object f) { return f0(f); } static public void setLast(List l, A a) { replaceLastElement(l, a); } static public Method mostApplicableMethod_onTypes(Iterable methods, Class... argTypes) { Lowest best = new Lowest(); if (methods != null) for (Method m : methods) { int score = methodApplicabilityScore_onTypes(m, argTypes); if (score < Integer.MAX_VALUE) best.put(m, score); } return best.get(); } static public A newObject(Class c, Object... args) { return (A) nuObject(c, args); } static public Object newObject(String className, Object... args) { return nuObject(className, args); } static public void assertInstanceOfOrNull(Class type, Object o) { if (o != null) assertIsInstance(type, o); } static public void assertInstanceOfOrNull(Object o, Class type) { assertInstanceOfOrNull(type, o); } static public void printAndSetConsoleTitleIfMain(String s) { print(s); if (isMain()) consoleTitle(s); } static public WidthAndHeight imageSize(BufferedImage img) { return img == null ? null : widthAndHeight(img.getWidth(), img.getHeight()); } static public WidthAndHeight imageSize(WidthAndHeight img) { return img == null ? null : widthAndHeight(img.getWidth(), img.getHeight()); } static public Pair reversedPair(Pair p) { return p == null ? null : pair(p.b, p.a); } static public A castTo(Class c, Object o) { assertInstanceOfOrNull(o, c); return (A) o; } static public A castTo(Object o, Class c) { return castTo(c, o); } static public A bindTextComponentToLiveValue_bothWays_noInitialUndo(A tc, SimpleLiveValue lv) { onFirstShow(tc, () -> clearTextComponentUndoList(tc)); return bindTextComponentToLiveValue_bothWays(tc, lv); } static public boolean charactersEqualIC(char c1, char c2) { if (c1 == c2) return true; char u1 = Character.toUpperCase(c1); char u2 = Character.toUpperCase(c2); if (u1 == u2) return true; return Character.toLowerCase(u1) == Character.toLowerCase(u2); } static public String javaDropComments(String s) { return javaDropAllComments(s); } static public List listMinus(Collection l, Object... stuff) { if (l == null) return null; List l2 = similarEmptyList(l); Set set = lithashset(stuff); for (Object o : l) if (!set.contains(o)) l2.add(o); return l2; } static public JLabel jrightAlignedLabel() { return jrightAlignedLabel(" "); } static public JLabel jrightAlignedLabel(String text) { return swing(() -> { return new JLabel(text, JLabel.RIGHT); }); } static public HashMap instanceFieldsMap(Object o) { return (HashMap) getOpt_getFieldMap(o); } static public String appendPrefixIfNempty(String prefix, String s) { return prependIfNempty(prefix, s); } static public String dropPrefixOrNull(String prefix, String s) { return s != null && s.startsWith(prefix) ? s.substring(l(prefix)) : null; } static public List stdFunctionListSnippetIDs() { return ll("#1006654", "#761"); } static public F0 f0(final Object f) { if (f instanceof F0) return ((F0) f); if (f instanceof String) { throw fail("callF_legacy"); } if (f instanceof IF0) return if0ToF0((IF0) f); return new F0() { public Object get() { return callF(f); } }; } static public List map_pcall(Iterable l, Object f) { return map_pcall(f, l); } static public List map_pcall(Object f, Iterable l) { List x = new ArrayList(); for (Object o : unnull(l)) { try { x.add(callF(f, o)); } catch (Throwable __e) { pcallFail(__e); } } return x; } static public List map_pcall(Object f, Object[] l) { List x = new ArrayList(); for (Object o : unnull(l)) { try { x.add(callF(f, o)); } catch (Throwable __e) { pcallFail(__e); } } return x; } static public List map_pcall(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : l) { try { x.add(f.get(o)); } catch (Throwable __e) { pcallFail(__e); } } return x; } static public List map_pcall(IF1 f, Iterable l) { return map_pcall(l, f); } static public int[] repIntAsArray(int n, int value) { int[] a = new int[n]; fillArray(a, value); return a; } static public RGB varyColor(RGB rgb) { return varyColor(rgb, 25); } static public RGB varyColor(RGB rgb, int maxSteps) { float max = maxSteps / 255f; int s = random(3); if (s == 0) return new RGB(vary0to1(rgb.r, max), rgb.g, rgb.b); else if (s == 1) return new RGB(rgb.r, vary0to1(rgb.g, max), rgb.b); else return new RGB(rgb.r, rgb.g, vary0to1(rgb.b, max)); } static public Color varyColor(Color color) { return varyColor(color, 25); } static public Color varyColor(Color color, int maxSteps) { return toColor(varyColor(new RGB(color), maxSteps)); } static public void addPair(Collection> c, A a, B b) { if (c != null) c.add(pair(a, b)); } static public int parseHexInt(String s) { return hexToInt(s); } static public String uploadToImageServer_new(BufferedImage img, String name) { return uploadToImageServer_new(null, img, name); } static public String uploadToImageServer_new(File f, BufferedImage img, String name) { byte[] imgData = f == null ? toPNG(img) : loadBinaryFile(f); return uploadToImageServer_rawBytes(imgData, name); } static public Object[] mapToArrayOrNull(A[] l, IF1 f) { if (l == null) return null; int n = l.length; if (n == 0) return null; Object[] array = new Object[n]; for (int i = 0; i < n; i++) array[i] = f.get(l[i]); return array; } static public Object[] mapToArrayOrNull(IF1 f, A[] l) { return mapToArrayOrNull(l, f); } static public Object[] mapToArrayOrNull(IF1 f, Collection l) { int n = l(l); if (n == 0) return null; Object[] array = new Object[n]; if (n != 0) { Iterator it = iterator(l); for (int i = 0; i < n; i++) array[i] = callF(f, it.next()); } return array; } static public Object[] mapToArrayOrNull(Collection l, IF1 f) { return mapToArrayOrNull(l, f); } static public List> overlappingPairs(List l) { return listToOverlappingPairs(l); } static public void closeAndClear(Collection l) { closeAllAndClear(l); } static public List findAllFiles(List dirs) { return findAllFiles(asObjectArray(dirs)); } static public List findAllFiles(Object... dirs) { List l = new ArrayList(); for (Object dir : dirs) { if (dir instanceof String && ((String) dir).endsWith("/.")) for (File f : listFiles(dropSuffix("/.", ((String) dir)))) l.add(f); else findAllFiles_impl(toFile(dir), l); } return l; } static public void findAllFiles_impl(File dir, List l) { for (File f : listFiles(dir)) { l.add(f); if (f.isDirectory()) findAllFiles_impl(f, l); } } static public String concatStrings(Object... l) { return join("", l); } static public String concatStrings(Iterable l) { return join("", l); } static public String joinNemptiesWithSpace(String... strings) { return joinNempties(" ", strings); } static public String joinNemptiesWithSpace(Collection strings) { return joinNempties(" ", strings); } static public void truncateContainer(Container c, int n) { swing(() -> { if (c != null) while (c.getComponentCount() > n) c.remove(c.getComponentCount() - 1); }); } static public DoublePt doublePt(double x) { return doublePt(x, x); } static public DoublePt doublePt(double x, double y) { return new DoublePt(x, y); } static public String concatMapStrings(Object f, Iterable l) { return concatMap_strings(f, l); } static public String concatMapStrings(Object f, Object[] l) { return concatMap_strings(f, l); } static public String concatMapStrings(Iterable l, Object f) { return concatMap_strings(l, f); } static public String concatMapStrings(Iterable l, IF1 f) { return concatMap_strings(l, f); } static public String concatMapStrings(IF1 f, Iterable l) { return concatMap_strings(f, l); } static public String concatMapStrings(IF1 f, A[] l) { return concatMap_strings(f, l); } static public String intToHexConstant(int i) { return "0x" + intToHex_flexLength(i); } static public A profileSingleThreadToConsole(IF0 f) { if (f == null) return null; AutoCloseable __1 = tempProfileSingleThreadToConsole(); try { return f.get(); } finally { _close(__1); } } static public void profileSingleThreadToConsole(Runnable r) { if (r == null) return; AutoCloseable __2 = tempProfileSingleThreadToConsole(); try { r.run(); } finally { _close(__2); } } static public Map javaxClassShortcuts_cache; static public Map javaxClassShortcuts() { if (javaxClassShortcuts_cache == null) javaxClassShortcuts_cache = javaxClassShortcuts_load(); return javaxClassShortcuts_cache; } static public Map javaxClassShortcuts_load() { return litmap("O", "Object", "S", "String", "L", "List", "Cl", "Collection", "Int", "Integer"); } static public String nBits(long n) { return n2(n, "bit"); } static public String nBits(Collection l) { return nBits(l(l)); } static public String nBits(Map map) { return nBits(l(map)); } static public JPanel jCenteredRaisedBoldLiveValueSection(IF0WithChangeListeners lv, Component c) { return swing(() -> { return new jCenteredLiveValueSection_class(lv, c).borderType(BevelBorder.RAISED).bold(true).init(); }); } static public List tok_integers(String s) { return tok_integersInOrder(s); } static public boolean isDirectory(File f) { return f != null && f.isDirectory(); } static public boolean isDirectory(String path) { return path != null && isDirectory(newFile(path)); } static public Pt translateLocationBetweenComponents(Pt p, Component c1, Component c2) { return p == null ? null : toPt(SwingUtilities.convertPoint(c1, toPoint(p), c2)); } static public PtInComponent translateLocationBetweenComponents(PtInComponent p, Component c2) { return new PtInComponent(translateLocationBetweenComponents(p.p, p.component, c2), c2); } static public String hostToIP(String host) { try { for (InetAddress a : InetAddress.getAllByName(host)) { String ip = a.getHostAddress(); if (isIPv4(ip)) return ip; } throw fail("No IP address found for " + host); } catch (Exception __e) { throw rethrow(__e); } } static public AutoCloseable tempAddConceptIndex(IConceptIndex index) { return tempAddConceptIndex(db_mainConcepts(), index); } static public AutoCloseable tempAddConceptIndex(Concepts cc, IConceptIndex index) { cc.addConceptIndex(index); return () -> cc.removeConceptIndex(index); } static public AutoCloseable tempSetBoolVar(BoolVar var) { return tempSetBoolVar(var, true); } static public AutoCloseable tempSetBoolVar(BoolVar var, boolean a) { if (var == null) return null; boolean prev = setBoolVar_returnPrevious(var, a); return () -> var.set(prev); } static public List allToInt(Collection l) { return map(__119 -> toInt(__119), l); } static public List allToInt(Object[] l) { return map(__120 -> toInt(__120), l); } static public Map getDeclaredConstructors_cached_cache = newDangerousWeakHashMap(); static public Constructor[] getDeclaredConstructors_cached(Class c) { Constructor[] ctors; synchronized (getDeclaredConstructors_cached_cache) { ctors = getDeclaredConstructors_cached_cache.get(c); if (ctors == null) { getDeclaredConstructors_cached_cache.put(c, ctors = c.getDeclaredConstructors()); for (var ctor : ctors) makeAccessible(ctor); } } return ctors; } static public String optionalCurlyBrace(String s) { return isCurlyBraced(s) ? s : curlyBrace(s); } static public IVF1 mainFunctionToIVF1(final String fname) { return (IVF1) a -> { callMC(fname, a); }; } static public Pair replacePairB(Pair p, B b) { return p == null ? null : pair(p.a, b); } static public Pt randomPt() { return randomPt(currentImage().getWidth(), currentImage().getHeight()); } static public Pt randomPt(BufferedImage img) { return img == null ? null : randomPt(img.getWidth(), img.getHeight()); } static public Pt randomPt(MakesBufferedImage img) { return img == null ? null : randomPt(img.getWidth(), img.getHeight()); } static public Pt randomPt(int w) { return randomPt(w, w); } static public Pt randomPt(int w, int h) { return new Pt(random(w), random(h)); } static public Pt randomPt(Rect r) { return r == null ? null : new Pt(r.x + random(r.w), r.y + random(r.h)); } static public String joinNemptiesWithEmptyLines(List l) { return joinWithEmptyLines(nempties(l)); } static public String joinNemptiesWithEmptyLines(String... l) { return joinNemptiesWithEmptyLines(asList(l)); } static public Pair replacePairA(Pair p, A a) { return p == null ? null : pair(a, p.b); } static public void bindCheckBoxMenuItemToVar(JCheckBoxMenuItem cb, IVarWithNotify lv) { bindChangeListenerToComponent(cb, lv, new Runnable() { public void run() { try { setChecked(cb, isTrue(lv.get())); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setChecked(cb, isTrue(lv!));"; } }); onChange(cb, new Runnable() { public void run() { try { lv.set(isChecked(cb)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lv.set(isChecked(cb));"; } }); } static public Object load(String varName) { readLocally(varName); return get(mc(), varName); } static public Object load(String progID, String varName) { readLocally(progID, varName); return get(mc(), varName); } static public List keysWithMultipleValues(IMultiMap mm) { List l = new ArrayList(); for (A key : mm.keySet()) if (l(mm.get(key)) > 1) l.add(key); return l; } static public void clearTextComponentUndoList(JTextComponent c) { swing(() -> { if (c instanceof RSyntaxTextArea) { ((RSyntaxTextArea) c).discardAllEdits(); return; } UndoManager undo = (UndoManager) (metaGet(c, "UndoManager")); if (undo != null) undo.discardAllEdits(); }); } static public double sin(double x) { return Math.sin(x); } static public AutoCompletion installCompletionProvider(DefaultCompletionProvider completionProvider, RSyntaxTextArea textArea) { return swing(() -> { if (completionProvider == null || textArea == null) return null; var autoComplete = new AutoCompletion(completionProvider); autoComplete.setAutoCompleteSingleChoices(false); autoComplete.install(textArea); return autoComplete; }); } static public Map standardClassesMap_uncached() { Map map = new HashMap(); for (String snippetID : standardClassesSnippetIDs()) for (String line : tlft_j(loadSnippet(snippetID))) { int idx = line.indexOf('/'); map.put(takeFirst(idx, line), substring(line, idx + 1)); } return map; } static public String md5OfRGBImage(RGBImage img) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(intToBytes(img.getWidth())); int[] pixels = img.getPixels(); for (int i = 0; i < l(pixels); i++) m.update(intToBytes(pixels[i])); return bytesToHex(m.digest()); } catch (Exception __e) { throw rethrow(__e); } } static public String dbProgramID() { return getDBProgramID(); } static public List concatMap_lists(Object f, Iterable l) { return concatMap(f, l); } static public List concatMap_lists(Iterable l, Object f) { return concatMap(l, f); } static public List concatMap_lists(Object f, Object[] l) { return concatMap(f, l); } static public List concatMap_lists(Object[] l, Object f) { return concatMap(l, f); } static public > List concatMap_lists(Iterable l, IF1 f) { return concatMap(l, f); } static public > List concatMap_lists(IF1 f, Iterable l) { return concatMap(f, l); } static public String str_toMB(long l) { return str_toM(l); } static public boolean canFontDisplay(Font font, String text) { for (String line : linesIterator(text)) if (font.canDisplayUpTo(line) >= 0) return false; return true; } static public AutoCloseable tempOnChangeAndNow(IHasChangeListeners src, Runnable listener) { if (src == null || listener == null) return null; src.onChangeAndNow(listener); return () -> src.removeChangeListener(listener); } static public int arrayLength(Object o) { return o != null ? Array.getLength(o) : 0; } public static byte[] loadBinaryFile(String fileName) { return loadBinaryFile(fileName, defaultBufferedOutputStreamSize()); } public static byte[] loadBinaryFile(String fileName, int bufSize) { try { if (!new File(fileName).exists()) return null; FileInputStream in = new FileInputStream(fileName); byte[] buf = new byte[bufSize]; ByteArrayOutputStream out = new ByteArrayOutputStream(); int l; while (true) { l = in.read(buf); if (l <= 0) break; out.write(buf, 0, l); } in.close(); return out.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } } public static byte[] loadBinaryFile(File file) { return loadBinaryFile(file, defaultBufferedOutputStreamSize()); } public static byte[] loadBinaryFile(File file, int bufSize) { return loadBinaryFile(file.getPath(), bufSize); } static public int[] pixelsOfBufferedImage(BufferedImage image) { try { int width = image.getWidth(); int height = image.getHeight(); int[] pixels = new int[width * height]; PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width); if (!pixelGrabber.grabPixels()) throw fail("Could not grab pixels"); return pixels; } catch (Exception __e) { throw rethrow(__e); } } static public JLabel jBoldLabel(String text) { return jboldLabel(text); } static public AlphanumComparator alphaNumComparatorIC_instance; static public Comparator alphaNumComparatorIC() { if (alphaNumComparatorIC_instance == null) { AlphanumComparator ac = new AlphanumComparator(); ac.ignoreCase = true; alphaNumComparatorIC_instance = ac; } return alphaNumComparatorIC_instance; } static public boolean isStaticField(Field f) { return (f.getModifiers() & Modifier.STATIC) != 0; } static public int idiv_round(int a, int b) { return (a + b / 2) / b; } static public int idiv_round(double a, double b) { return iround(a / b); } static public String spaceIfEmpty(String s) { return empty(s) ? " " : s; } static public Set weakHashSet() { return synchroWeakHashSet(); } static public JLabel liveValueLabel(LiveValue lv) { return jLiveValueLabel(lv); } static public JLabel liveValueLabel(IVarWithNotify var) { return jVarLabel(var); } static public IterableIterator arrayIterator(A[] l) { return l == null ? null : new IterableIterator() { public int i = 0; public boolean hasNext() { return i < l.length; } public A next() { return l[i++]; } }; } static public File conceptsFile(String progID) { return getProgramFile(progID, conceptsFileName()); } static public File conceptsFile() { return conceptsFile(dbProgramID()); } static public File conceptsFile(Concepts concepts) { return concepts.conceptsFile(); } static public long twoIntsToLong(int a, int b) { return (((long) a) << 32) | (((long) b) & 0xFFFFFFFFL); } static public String renderVarsInMultipleLines(Object... params) { List l = new ArrayList(); int i = 0; String header = null; if (odd(l(params))) { header = strOrNull(first(params)); addIfNempty(l, header); ++i; } for (; i + 1 < l(params); i += 2) l.add(stringIf(nempty(header), " ") + params[i] + "=" + params[i + 1]); return lines_rtrim(l); } static public DoublePt scaleDoublePt(DoublePt p, double f) { return new DoublePt(p.x * f, p.y * f); } static public DoublePt scaleDoublePt(double f, DoublePt p) { return scaleDoublePt(p, f); } static public List paragraphs(String text) { return paragraphsFromText(text); } static public String paragraphs(Iterable l) { return joinWithEmptyLines(l); } static public boolean setBoolVar_returnPrevious(BoolVar v, boolean value) { synchronized (v) { boolean prev = v.get(); v.set(value); return prev; } } static public void listPopupMenuItem(final JList list, final String name, final Object action) { listPopupMenu(list, new VF2() { public void get(JPopupMenu menu, final String item) { try { addMenuItem(menu, name, new Runnable() { public void run() { try { pcallF(action, item); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, item)"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, name, r { pcallF(action, item) });"; } }); } static public BufferedImage markPointsInImageWithAlpha(BufferedImage img, Iterable points, Color color, double alpha) { return markPointsInImageWithAlpha(img, points, color, alpha, 3); } static public BufferedImage markPointsInImageWithAlpha(BufferedImage img, Iterable points, Color color, double alpha, int size) { if (img != null) for (var p : unnullForIteration(points)) markPointInImageWithAlpha(img, p, color, alpha, size); return img; } static public Method findMethodNamed(Object obj, String method) { if (obj == null) return null; if (obj instanceof Class) return findMethodNamed((Class) obj, method); return findMethodNamed(obj.getClass(), method); } static public Method findMethodNamed(Class c, String method) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) { makeAccessible(m); return m; } c = c.getSuperclass(); } return null; } static public AtomicLong randomClassName_counter = new AtomicLong(); static public String randomClassName() { return "UserCode" + inc(randomClassName_counter); } static public long benchFor5(String desc, Runnable r) { return benchFor5Seconds(desc, r); } static public long benchFor5(Runnable r) { return benchFor5Seconds(r); } static public A benchFor5(IF0 f) { return benchFor5(str(f), f); } static public A benchFor5(String desc, IF0 f) { return benchFor5Seconds(desc, f); } 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 jimageButtonScaledToWidth(w, imageID, toolTip, action); } static public int parseHexConstant(String s) { return parseHexInt(dropPrefixIC("0x", s)); } static public int getIndent(String s) { int n = Integer.MAX_VALUE; for (String l : toLines(s)) n = min(n, getIndentOfLine(l)); return n; } static public String lower(String s) { return s == null ? null : s.toLowerCase(); } static public char lower(char c) { return Character.toLowerCase(c); } static public String substr(String s, int x) { return substring(s, x); } static public String substr(String s, int x, int y) { return substring(s, x, y); } static public A addComponentAtIndex(A c, int idx, Component component) { if (component != null) { swing(() -> { c.add(component, clamp(idx, 0, c.getComponentCount())); revalidate(c); }); } return c; } static public boolean isJPEG_GIF_PNG(byte[] data) { return isJPEG(data) || isGIF(data) || isPNG(data); } static public Map thisDollarOneFields_cache = newDangerousWeakHashMap(); static public Field[] thisDollarOneFields(Class c) { synchronized (thisDollarOneFields_cache) { Field[] l = thisDollarOneFields_cache.get(c); if (l == null) thisDollarOneFields_cache.put(c, l = thisDollarOneFields_uncached(c)); return l; } } static public Field[] thisDollarOneFields_uncached(Class c) { List fields = new ArrayList(); do { for (Field f : c.getDeclaredFields()) if (f.getName().startsWith("this$")) fields.add(makeAccessible(f)); c = c.getSuperclass(); } while (c != null); return toArray(new Field[l(fields)], fields); } static public List uniquifyBufferedImages(Iterable l) { return new UniquifyUsingHasher(__1 -> hashBufferedImage(__1), (__2, __3) -> imagesIdentical(__2, __3)).addAll(l).get(); } static public double[] toDoubleArray(Collection l) { double[] a = new double[l(l)]; int i = 0; if (a.length != 0) for (double x : l) a[i++] = x; return a; } static public double[] toDoubleArray(IntBuffer b) { int n = l(b); double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = b.get(i); return a; } static public double[] toDoubleArray(float... l) { double[] a = new double[l(l)]; for (int i = 0; i < a.length; i++) a[i] = l[i]; return a; } static public double[] toDoubleArray(int... l) { double[] a = new double[l(l)]; for (int i = 0; i < a.length; i++) a[i] = l[i]; return a; } static public double[] toDoubleArray(IDoubleBuffer b) { int n = l(b); double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = b.get(i); return a; } static public A bindTextComponentToVarWithNotify(A tc, IVarWithNotify lv) { bindHasChangeListenersToComponent(tc, lv, new Runnable() { public void run() { try { setTextKeepCaret(tc, lv.get()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setTextKeepCaret(tc, lv!)"; } }); onChange(tc, new Runnable() { public void run() { try { lv.set(getText(tc)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lv.set(getText(tc))"; } }); return tc; } static public A fontSize(float size, A a) { return setFontSize(size, a); } static public A fontSize(A a, float size) { return setFontSize(size, a); } static public Float fontSize(JComponent c) { Font f = getFont(c); return f == null ? null : f.getSize2D(); } static public boolean isArray(Object o) { return o != null && o.getClass().isArray(); } static public > MultiMap toMultiMap(Map map) { return mapToMultiMap(map); } static public MultiMap toMultiMap(Iterable> l) { return pairsToMultiMap(l); } static public List cloneTakeFirst(Collection l, int n) { n = min(n, l(l)); List out = emptyList(n); if (n != 0) for (A a : l) { out.add(a); if (l(out) >= n) break; } return out; } static public List cloneTakeFirst(int n, Collection l) { return cloneTakeFirst(l, n); } static public List cloneTakeFirst(List l, int n) { return l(l) <= n ? l : cloneSubList(l, 0, n); } static public List cloneTakeFirst(int n, List l) { return cloneTakeFirst(l, n); } static public Pt varyPt(Pt p, int w, int h) { return varyPoint(p, w, h); } static public Pt varyPt(Pt p, int range) { return varyPoint(p, range); } static public Pt ptMul(double d, Pt p) { return new Pt(iround(d * p.x), iround(d * p.y)); } static public Pt ptMul(Pt p, double d) { return ptMul(d, p); } static public List lmap(IF1 f, Iterable l) { return lambdaMap(f, l); } static public List lmap(IF1 f, A[] l) { return lambdaMap(f, l); } static public void fillArray(byte[] a, byte value) { Arrays.fill(a, value); } static public void fillArray(int[] a, int value) { Arrays.fill(a, value); } static public void fillArray(float[] a, float value) { Arrays.fill(a, value); } static public void fillArray(double[] a, double value) { Arrays.fill(a, value); } static public void spinnerSetNumberList(JSpinner spinner, List list) { swing(() -> { double value = toDouble(spinner.getValue()); spinner.setModel(new SpinnerListModel(list)); setSpinnerValue(spinner, lowestByScoreFunction(list, x -> absDiff(toDouble(x), value))); }); } static public List splitAtMinus(String s) { return trimAll(asList(s.split("\\-"))); } static public Matcher regexpIC(Pattern pat, String s) { return pat.matcher(unnull(s)); } static public Matcher regexpIC(String pat, String s) { return compileRegexpIC(pat).matcher(unnull(s)); } static public Pattern regexpIC(String pat) { return compileRegexpIC(pat); } static public List chunks(long end, long chunkSize) { return chunks(0, end, chunkSize); } static public List chunks(long start, long end, long chunkSize) { List l = new ArrayList(); long i = start; while (i < end) { l.add(new LongRange(i, min(end, i + chunkSize))); i += chunkSize; } return l; } static public List> chunks(int chunkSize, List l) { return listToChunks(chunkSize, l); } static public A[] toArrayOrNull(Class type, Collection c) { if (empty(c)) return null; return toArray(type, c); } static public String fileNameWithoutExtension(File f) { return dropExtension(fileName(f)); } static public A makeUneditable(final A tf) { if (tf != null) { swing(() -> { tf.setEditable(false); }); } return tf; } static public Font deriveBoldFont(Font font) { return font == null ? null : font.deriveFont(Font.BOLD); } static public byte[] PNG_MAGIC = bytesFromHex("89504E470D0A1A0A"); static public boolean isPNG(byte[] data) { if (data.length < PNG_MAGIC.length) return false; for (int i = 0; i < PNG_MAGIC.length; i++) if (data[i] != PNG_MAGIC[i]) return false; return true; } static public boolean isPNG(File f) { return isPNG(loadFirstBytes(f, l(PNG_MAGIC))); } static public Object callWithVarargs(Object o, String method, Object... args) { return call_withVarargs(o, method, args); } static public void saveLocalSnippet(String snippetID, String text) { saveLocalSnippet(psI(snippetID), text); } static public void saveLocalSnippet(long snippetID, String text) { saveTextFile(localSnippetFile(snippetID), text); } static public BWImage bwImage(RGBImage img) { return bwImage(img); } static public BWImage bwImage(BufferedImage img) { return toBWImage(img); } static public BWImage bwImage(MakesBufferedImage img) { return toBWImage(img); } static public JLabel jLabelShortCalcedEvery(IF0 calc, double interval) { JLabel label = jSimpleLabel(); if (calc != null) awtEveryAndNow(label, interval, () -> { try { Object o = calc.get(); String toolTip, text; if (o instanceof WithToolTip) { toolTip = ((WithToolTip) o).toolTip(); text = str(((WithToolTip) o).get()); } else { text = toolTip = str(o); } setToolTip(label, toolTip); label.setText(text); } catch (Throwable __e) { pcallFail(__e); } }); return label; } static public JLabel jLabelShortCalcedEvery(double interval, IF0 calc) { return jLabelShortCalcedEvery(calc, interval); } static public A singletonOpt(Collection l) { return l(l) == 1 ? first(l) : null; } static public A singletonOpt(A[] l) { return l(l) == 1 ? first(l) : null; } static public int modRange_incl(int i, int start, int end) { return start + mod(i - start, end - start + 1); } static public void copyMap(Map a, Map b) { if (a == null || b == null) return; b.clear(); b.putAll(a); } static public A onCtrlEnter(A c, Runnable action) { return onCtrlEnter(c, (Object) action); } static public A onCtrlEnter(A c, Object action) { addKeyListener(c, ctrlEnterKeyListener(action)); return c; } static public Constructor nuStubInnerObject_findConstructor(Class c) { return nuStubInnerObject_findConstructor(c, null); } static public Constructor nuStubInnerObject_findConstructor(Class c, Object classFinder) { try { Class outerType = getOuterClass(c, classFinder); Constructor m = c.getDeclaredConstructor(outerType); makeAccessible(m); return m; } catch (Exception __e) { throw rethrow(__e); } } static public Steppable combineSteppables_dontDropEnded(Iterable steppables) { List steppablesList = nonNulls(steppables); return () -> { boolean change = false; for (var s : steppablesList) change |= s.step(); return change; }; } static public Steppable combineSteppables_dontDropEnded(A... steppables) { return combineSteppables(asList(steppables)); } static public int charToTokenIndex_left(List tok, int charIndex) { int i = 0, idx = 0; while (i < l(tok) && idx + l(tok.get(i)) <= charIndex) { idx += l(tok.get(i)); i++; } return i; } static public A setWindowSize(A c, int w, int h) { Window window = getWindow(c); if (window != null) window.setSize(w, h); return c; } static public A setWindowSize(int w, int h, A c) { return setWindowSize(c, w, h); } static public RunResultWithTimestamps runResultWithTimestamps(IF0 f) { return new RunResultWithTimestamps().run(f); } static public JFilePathButton jFilePathButton(File f) { return swing(() -> new JFilePathButton(f)); } static public Object convertPrimitiveIfNecessary(Object o, Class b) { if (b.isPrimitive()) { if (o instanceof Character) { char x = (char) (((Character) o)); if (b == int.class) return Integer.valueOf(x); if (b == long.class) return Long.valueOf(x); if (b == float.class) return Float.valueOf(x); if (b == double.class) return Double.valueOf(x); } else if (o instanceof Number) { if (b == char.class) return Character.valueOf((char) ((Number) o).intValue()); if (b == short.class) return ((Number) o).shortValue(); if (b == int.class) return ((Number) o).intValue(); if (b == long.class) return ((Number) o).longValue(); if (b == float.class) return ((Number) o).floatValue(); } } return o; } static public int iceil_div(int a, int b) { return idiv_ceil(a, b); } static public int iceil_div(long a, long b) { return idiv_ceil(a, b); } static public String regexReplace(String s, String pat, Object f) { return regexReplace(regexpMatcher(pat, s), f); } static public String regexReplace(String s, String pat, String replacement) { return regexpReplace_direct(s, pat, replacement); } static public String regexReplace(Matcher m, Object f) { StringBuffer buf = new StringBuffer(); while (m.find()) m.appendReplacement(buf, m.quoteReplacement(str(callF(f, m)))); m.appendTail(buf); return str(buf); } static public String regexReplace(String s, String pat, IF1 f) { return regexReplace(s, pat, (Object) f); } static public String nameRelativeToPhysicalSubdirectory_nonCanonical(File inner, File outer) { try { if (inner == null || outer == null) return null; String path1 = inner.getAbsolutePath(); String path2a = outer.getAbsolutePath(); if (eq(path1, path2a)) return ""; String path2 = addFileSep(path2a); Matches m = new Matches(); if (startsWith(path1, path2, m)) return m.rest(); else return null; } catch (Exception __e) { throw rethrow(__e); } } static public Component getCenterComponent(Container container) { return ((BorderLayout) container.getLayout()).getLayoutComponent(BorderLayout.CENTER); } static public String appendNewLineIfNempty(String s) { return empty(s) ? "" : s + "\n"; } static public byte[] cloneByteArray(byte[] a) { if (a == null) return null; byte[] b = new byte[a.length]; System.arraycopy(a, 0, b, 0, a.length); return b; } static public String takeCharsWhile(String s, Object pred) { int i = 0; while (i < l(s) && isTrue(callF(pred, s.charAt(i)))) ++i; return substring(s, 0, i); } static public String takeCharsWhile(IF1 f, String s) { return takeCharsWhile(s, f); } static public int colorToInt(Color c) { return c.getRGB() & 0xFFFFFF; } static public void onConceptChangeByClass(Class type, Runnable r) { onConceptChangeByClass(db_mainConcepts(), type, r); } static public void onConceptChangeByClass(Concepts cc, Class type, Runnable r) { onConceptChangeByClass_notOnAllChanged(cc, type, r); cc.onAllChanged.add(r); } static public String uploadImage(BufferedImage img, String name) { return uploadImageToServer(img, name); } static public String uploadImage(String name, BufferedImage img) { return uploadImageToServer(img, name); } static public String uploadImage(File f, BufferedImage img, String name) { return uploadImageToServer(f, img, name); } static public String uploadImage(File f) { return uploadImageToServer(f); } static public String uploadImage(String urlOrPath) { if (isAbsoluteURL(urlOrPath)) { byte[] data = loadBinaryPage(urlOrPath); assertTrue(isJPEG_GIF_PNG(data)); return uploadToImageServer_rawBytes(data, urlOrPath); } else return uploadImage(newFile(urlOrPath)); } static public int onePathLookupDirection(Pt p) { return indexOf(onePathDirections(), p); } static public byte[] intToBytes(int i) { return new byte[] { (byte) (i >>> 24), (byte) (i >>> 16), (byte) (i >>> 8), (byte) i }; } static public void fillListWithStrings(JList list, Collection contents) { if (list == null) return; final DefaultListModel model = new DefaultListModel(); if (contents != null) for (String s : contents) model.addElement(empty(s) ? " " : s); { swing(() -> { list.setModel(model); }); } } static public void fillListWithStrings(final JList list, String[] contents) { fillListWithStrings(list, asList(contents)); } static public MultiMap keysWithMultipleValuesOnly(MultiMap mm) { MultiMap mm2 = new MultiMap(); for (A key : mm.keySet()) if (l(mm.get(key)) > 1) mm2.putAll(key, mm.get(key)); return mm2; } static public MultiSetMap keysWithMultipleValuesOnly(MultiSetMap mm) { MultiSetMap mm2 = new MultiSetMap(); for (A key : mm.keySet()) if (l(mm.get(key)) > 1) mm2.putAll(key, mm.get(key)); return mm2; } static public void moveCaretToLineAndCol(JTextArea ta, LineAndColumn lac) { swing(() -> { try { setCaretPosition(ta, ta.getLineStartOffset(lac.line - 1) + lac.col - 1); } catch (Throwable _e) { print("Have lines: " + countLines(ta.getText())); throw rethrow(_e); } }); } static public Object getThreadLocal(Object o, String name) { ThreadLocal t = (ThreadLocal) (getOpt(o, name)); return t != null ? t.get() : null; } static public A getThreadLocal(ThreadLocal tl) { return tl == null ? null : tl.get(); } static public A getThreadLocal(ThreadLocal tl, A defaultValue) { return or(getThreadLocal(tl), defaultValue); } static public Rect shrinkRectBottomAndRight(Rect r) { return shrinkRectBottomAndRight(r, 1); } static public Rect shrinkRectBottomAndRight(Rect r, int pixels) { return shrinkRectBottomAndRight(pixels, pixels, r); } static public Rect shrinkRectBottomAndRight(int x, int y, Rect r) { return new Rect(r.x, r.y, r.w - x, r.h - y); } static public Rect shrinkRectBottomAndRight(Rect r, int x, int y) { return shrinkRectBottomAndRight(x, y, r); } static public String roundBracketed(String s) { return roundBracket(s); } static public JFilePathLabel jFilePathLabel(File f) { return swing(() -> new JFilePathLabel(f)); } static public List regexpLastGroupsIC(String pat, String s) { if (s == null) return null; Matcher m = regexpIC(pat, s); List groups = null; while (m.find()) groups = regexpGetGroups(m); return groups; } static public Class primitiveToBoxedType(Class type) { if (type == boolean.class) return Boolean.class; if (type == int.class) return Integer.class; if (type == long.class) return Long.class; if (type == float.class) return Float.class; if (type == short.class) return Short.class; if (type == char.class) return Character.class; if (type == byte.class) return Byte.class; if (type == double.class) return Double.class; return null; } static public List iDoublePtsToDoublePts(List l) { return map(__121 -> toDoublePt(__121), l); } static public A optimizedUniq(Class c, Object... params) { return optimizedUniq(db_mainConcepts(), c, params); } static public A optimizedUniq(Concepts cc, Class c, Object... params) { { var __1 = conceptWhere(cc, c, params); if (__1 != null) return __1; } return uniq(cc, c, params); } static public A closeOnComponentHide(AutoCloseable closeable, A c) { if (closeable != null) { Var var = new Var<>(closeable); bindToComponent(c, null, () -> close(getAndClear(var))); } return c; } static public List firstOfPairs(Collection> l) { List out = new ArrayList(); for (Pair p : unnull(l)) out.add(firstOfPair(p)); return out; } static public boolean byteArrayStartsWith(byte[] a, byte[] b) { if (a == null || b == null) return false; if (a.length < b.length) return false; for (int i = 0; i < b.length; i++) if (a[i] != b[i]) return false; return true; } static public List allToBufferedImage(Iterable l) { return map(__122 -> toBufferedImage(__122), l); } static public Pt rotatePtRight(Pt p) { return pt(-p.y, p.x); } static public JCheckBox jcheckbox() { return jCheckBox(); } static public JCheckBox jcheckbox(boolean checked) { return jCheckBox(checked); } static public JCheckBox jcheckbox(String text, boolean checked) { return jCheckBox(text, checked); } static public JCheckBox jcheckbox(String text) { return jCheckBox(text); } static public JCheckBox jcheckbox(JCheckBox cb, String text) { return jcheckbox(text, isChecked(cb)); } static public double frac(double d) { return fraction(d); } static public JButton renameButton(JComponent c, String name) { JButton b = first(childrenOfType(c, JButton.class)); if (b != null) b.setText(name); return b; } static public JButton renameButton(JComponent c, String oldName, String newName) { JButton b = findButton(c, oldName); if (b != null) b.setText(newName); return b; } static public List>> multiMapToMapPairs(MultiMap mm) { List>> out = new ArrayList(); for (A key : keys(mm)) out.add(pair(key, mm.get(key))); return out; } static public List>> multiMapToMapPairs(IMultiMap mm) { List>> out = new ArrayList(); for (A key : keys(mm)) out.add(pair(key, mm.get(key))); return out; } static public BufferedImage renderShape(Shape shape, int w, int h) { return renderShape(Color.white, shape, w, h); } static public BufferedImage renderShape(Color bg, Shape shape, int w, int h) { BufferedImage img = newBufferedImage(w, h, bg); Graphics2D g = img.createGraphics(); g.setColor(Color.black); g.fill(shape); return img; } static public BufferedImage renderShape(Shape shape, Rect bounds) { return renderShape(Color.white, shape, bounds); } static public BufferedImage renderShape(Color bg, Shape shape, Rect bounds) { BufferedImage img = newBufferedImage(bounds.w, bounds.h, bg); Graphics2D g = img.createGraphics(); g.translate(-bounds.x, -bounds.y); g.setColor(Color.black); g.fill(shape); return img; } static public long bwRawImageDiff_sameSize(MakesBWImage a, MakesBWImage b) { return bwRawImageDiff_sameSize(a.getBWImage(), b.getBWImage()); } static public long bwRawImageDiff_sameSize(MakesBWImage a, BWImage b) { return bwRawImageDiff_sameSize(a.getBWImage(), b); } static public long bwRawImageDiff_sameSize(BWImage a, MakesBWImage b) { return bwRawImageDiff_sameSize(a, b.getBWImage()); } static public long bwRawImageDiff_sameSize(BWImage a, BWImage b) { assertSameSize(a, b); int w = a.w(), h = a.h(); byte[] pixels1 = a.pixels, pixels2 = b.pixels; int n = pixels1.length; long diff = 0; for (int i = 0; i < n; i++) diff += Math.abs(ubyteToInt(pixels1[i]) - ubyteToInt(pixels2[i])); return diff; } public static String rtrim(String s) { if (s == null) return null; int i = s.length(); while (i > 0 && " \t\r\n".indexOf(s.charAt(i - 1)) >= 0) --i; return i < s.length() ? s.substring(0, i) : s; } static public AutoCloseable onConceptChangeByClass_notOnAllChanged(Class type, Runnable r) { return onConceptChangeByClass_notOnAllChanged(db_mainConcepts(), type, r); } static public AutoCloseable onConceptChangeByClass_notOnAllChanged(Concepts cc, Class type, Runnable r) { return tempAddConceptIndex(cc, new IConceptIndex() { public void update(Concept c) { if (instanceOf(c, type)) pcallF(r); } public void remove(Concept c) { if (instanceOf(c, type)) pcallF(r); } }); } static public AutoCloseable onConceptChangeByClass_notOnAllChanged(Class type, IVF1 r) { return onConceptChangeByClass_notOnAllChanged(db_mainConcepts(), type, r); } static public AutoCloseable onConceptChangeByClass_notOnAllChanged(Concepts cc, Class type, IVF1 r) { return tempAddConceptIndex(cc, new IConceptIndex() { public void update(Concept c) { if (instanceOf(c, type)) pcallF(r, (A) c); } public void remove(Concept c) { if (instanceOf(c, type)) pcallF(r, (A) c); } }); } static public void enableSubmitButton(Component form) { enableSubmitButton(form, true); } static public void enableSubmitButton(final Component form, final boolean enable) { { swing(() -> { JButton btn = findSubmitButton(form); if (btn != null) btn.setEnabled(enable); }); } } static public String renderMultiSetAsLines_byPopularity(MultiSet ms, Object... __) { int padWidth = optPar("padWidth", __, 6); String connector = optPar("connector", __, ": "); if (ms == null) return "-"; List l = new ArrayList(); for (Object o : ms.highestFirst()) l.add(lpad(padWidth, n2(ms.get(o))) + connector + str(o)); return lines(l); } static public String renderMultiSetAsLines_byPopularity(Iterable l, Object... __) { return renderMultiSetAsLines_byPopularity(toMultiSet(l), __); } static public RGBImage toRGBImage(BWImage img) { return img == null ? null : img.toRGB(); } static public RGBImage toRGBImage(BufferedImage img) { return img == null ? null : new RGBImage(img); } static public IterableIterator intRangesIterator(Iterable l) { return nestedIterator(l, r -> countIterator(r.start, r.end)); } static public String addClassNameToInclude(String snippetID, String className) { List tok = javaTokSnippet(snippetID); if (jfind(tok, "please include class " + className) >= 0) return className + " already included"; tokPrepend(tok, l(tok) - 1, "\nplease include class " + className + "."); return editSnippet(snippetID, join(tok)); } static public Map.Entry lastEntry(NavigableMap map) { return map == null ? null : map.lastEntry(); } static public String nFonts(long n) { return n2(n, "font"); } static public String nFonts(Collection l) { return nFonts(l(l)); } static public String nFonts(Map map) { return nFonts(l(map)); } static public double pi() { return Math.PI; } static public TimedCache> standardClassesMap_cached_cache = new TimedCache>(() -> standardClassesMap(), 60.0); static public Map standardClassesMap_cached() { return standardClassesMap_cached_cache.get(); } static public void standardClassesMap_clearCache() { standardClassesMap_cached_cache.clear(); } static public List> listToChunks(List l, int chunkSize) { int rows = intRatio_ceil(l(l), chunkSize); List> out = emptyList(rows); for (int y = 0; y < rows; y++) out.add(subList(l, y * chunkSize, (y + 1) * chunkSize)); return out; } static public List> listToChunks(int chunkSize, List l) { return listToChunks(l, chunkSize); } static public int getSliderValue(JSlider slider) { return swing(() -> { return slider == null ? 0 : slider.getValue(); }); } static public String upper(String s) { return s == null ? null : s.toUpperCase(); } static public char upper(char c) { return Character.toUpperCase(c); } static public JPanel northCenterAndSouthWithMargins(Swingable n, Swingable c, Swingable s) { return northCenterAndSouthWithMargins(n, c, toComponent(s)); } static public JPanel northCenterAndSouthWithMargins(Swingable n, Swingable c, Component s) { return northCenterAndSouthWithMargins(n, toComponent(c), s); } static public JPanel northCenterAndSouthWithMargins(Swingable n, Component c, Swingable s) { return northCenterAndSouthWithMargins(n, c, toComponent(s)); } static public JPanel northCenterAndSouthWithMargins(Swingable n, Component c, Component s) { return northCenterAndSouthWithMargins(toComponent(n), c, s); } static public JPanel northCenterAndSouthWithMargins(Component n, Swingable c, Swingable s) { return northCenterAndSouthWithMargins(n, c, toComponent(s)); } static public JPanel northCenterAndSouthWithMargins(Component n, Swingable c, Component s) { return northCenterAndSouthWithMargins(n, toComponent(c), s); } static public JPanel northCenterAndSouthWithMargins(Component n, Component c, Swingable s) { return northCenterAndSouthWithMargins(n, c, toComponent(s)); } static public JPanel northCenterAndSouthWithMargins(Component n, Component c, Component s) { return applyDefaultMargin(northCenterAndSouth(withBottomMargin(n), c, withTopMargin(s))); } static public List listWithSingleElementChanged(List l, int i, A a) { var l2 = cloneList(l); l2.set(i, a); return l2; } static public int intFromBinary(String s) { return Integer.parseInt(s, 2); } static public Steppable iteratorToSteppable(Iterator it) { return it == null ? null : new Steppable() { public boolean step() { if (!it.hasNext()) return false; it.next(); return true; } }; } static public A floorKey(NavigableMap map, A key) { if (map == null) return null; return map.floorKey(key); } static public boolean hasParentOfType(Class type, Component c) { return parentOfType(c, type) != null; } static public String hijackPrint_tee(Runnable r) { final StringBuilder buf = new StringBuilder(); Object old = interceptPrintInThisThread(new F1() { public Boolean get(String s) { buf.append(s); return true; } }); try { callF(r); return str(buf); } finally { interceptPrintInThisThread(old); } } static public AutoCloseable tempAddGlobalCtrlKeyListener(IVF1 onStatusChanged) { AWTEventListener l = new AWTEventListener() { public Boolean status; public void eventDispatched(AWTEvent evt) { if (evt instanceof InputEvent) { Boolean b = ((InputEvent) evt).isControlDown(); if (!eq(b, status)) pcallF_typed(onStatusChanged, status = b); } } }; Toolkit.getDefaultToolkit().addAWTEventListener(l, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK); return () -> Toolkit.getDefaultToolkit().removeAWTEventListener(l); } static public String nCharacters(long n) { return n2(n, "character"); } static public String nCharacters(String s) { return nCharacters(l(s)); } static public List similarEmptyList(Collection m) { return new ArrayList(); } static public String uploadImageToServer(BufferedImage img, String name) { return uploadToImageServerIfNotThere(img, name); } static public String uploadImageToServer(File f, BufferedImage img, String name) { return uploadToImageServerIfNotThere(f, img, name); } static public String uploadImageToServer(File f) { return uploadToImageServerIfNotThere(f); } static public void saveTextFileVerbose(File f, String text) { boolean exists = f.exists(); saveTextFile(f, text); print((!exists ? "Created" : "Updated") + " file " + f2s(f) + " (" + f.length() + " bytes)"); } static public PleaseIncludeFunctionsStatement tok_nextPleaseIncludeFunctionsStatement(List tok) { return tok_nextPleaseIncludeFunctionsStatement(tok, 1); } static public PleaseIncludeFunctionsStatement tok_nextPleaseIncludeFunctionsStatement(List tok, int i) { i = jfind(tok, i, "please include functions"); if (i < 0) return null; PleaseIncludeFunctionsStatement p = new PleaseIncludeFunctionsStatement(); p.tok = tok; p.iStart = i; p.iFirstIdentifier = i + 6; p.iDot = smartIndexOf(tok, p.iFirstIdentifier, "."); p.iEnd = p.iDot + 2; return p; } static public List pairsA(Collection> l) { return firstOfPairs(l); } static public JLabel jClickableImage_instantToolTip(String imageID, String toolTip, Runnable action) { return onLeftClick(instaToolTip(toolTip, jImageLabel(imageID)), action); } static public void setOptAll_pcall(Object o, Map fields) { if (fields == null) return; for (String field : keys(fields)) try { setOpt(o, field, fields.get(field)); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } static public void setOptAll_pcall(Object o, Object... values) { warnIfOddCount(values); for (int i = 0; i + 1 < l(values); i += 2) { String field = (String) values[i]; Object value = values[i + 1]; try { setOpt(o, field, value); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } } static public double ptDistance(Pt a, Pt b) { return pointDistance(a, b); } static public double ptDistance(DoublePt a, DoublePt b) { return pointDistance(a, b); } static public double ptDistance(DoublePt a, Pt b) { return pointDistance(a.x, a.y, b.x, b.y); } static public JPanel westAndEastWithMargin(Component w, Component e) { JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.WEST, wrap(w)); panel.add(BorderLayout.CENTER, horizontalStrut(10)); panel.add(BorderLayout.EAST, wrap(e)); return panel; } static public BufferedImage mergeBufferedImagesInRows(Collection> l) { return mergeBufferedImagesVH(l); } static public File fileForLibrary(String snippetID) { return utils.DiskSnippetCache_getLibrary(snippetID); } static public A unlistedWithValues(Class c, Object... params) { A a = unlisted(c); cset(a, params); return a; } static public float vary0to1(float x) { return vary0to1(x, 0.1f); } static public float vary0to1(float x, float max) { return Math.max(0f, Math.min(1f, (float) (x + random(-max, max)))); } static public Font sansSerif() { return sansSerif(defaultFontSize()); } static public Font sansSerif(int fontSize) { return new Font(Font.SANS_SERIF, Font.PLAIN, fontSize); } static public JLabel transformedLiveValueLabel(IF1 f, IF0WithChangeListeners lv) { return bindJLabelToTransformedVar(f, jlabel(), lv); } static public Component getFrameContents(JFrame f) { Container cp = f.getContentPane(); if (cp.getLayout() instanceof BorderLayout && countComponents(cp) == 1) { Component c = getCenterComponent(cp); if (c != null) return c; } return cp; } static public JTextArea uneditableBlackTextArea_noUndo() { return uneditableBlackTextArea_noUndo(""); } static public JTextArea uneditableBlackTextArea_noUndo(String text) { return makeUneditableWithTextColor(Color.black, jTextArea_noUndo(text)); } static public String classNameForPrinting(Object o, Class c, String className) { return (o.getClass() != c ? "subclass of " : "") + className; } static public A bindJLabelToTransformedVar(IF1 f, A label, IF0WithChangeListeners var) { bindChangeListenerToComponent(label, var, () -> { setText(label, strOrNull(f.get(var.get()))); }); return label; } static public String intern(String s) { return fastIntern(s); } static public Path2D.Float alphaToShape(BufferedImage img) { BWImage bw = getAlphaChannel(img); Image2B alpha = new Image2B(bw); int w = alpha.w(), h = alpha.h(); Path2D.Float path = new Path2D.Float(); int x = w / 2; int y = -1; while (y < h && !alphaToShape_isInteresting(alphaToShape_getQuadrant(alpha, x, y))) ++y; int x1 = x, y1 = y; path.moveTo(x, y); HashSet seen = new HashSet(); while (seen.add(new Pt(x, y))) { int q = alphaToShape_getQuadrant(alpha, x, y); Pt next = null; for (Pt p : neighborhood8(x, y)) if (!seen.contains(p) && alphaToShape_isInteresting(alphaToShape_getQuadrant(alpha, p.x, p.y))) { next = p; break; } if (next == null) break; x = next.x; y = next.y; path.lineTo(x + 1, y + 1); } return path; } static public boolean alphaToShape_isInteresting(int q) { return q != 0 && q != 0x1111; } static public int alphaToShape_getQuadrant(Image2B img, int x, int y) { return (alphaToShape_getQuadrant_getPixel(img, x, y) ? 0x1000 : 0) + (alphaToShape_getQuadrant_getPixel(img, x + 1, y) ? 0x0100 : 0) + (alphaToShape_getQuadrant_getPixel(img, x, y + 1) ? 0x0010 : 0) + (alphaToShape_getQuadrant_getPixel(img, x + 1, y + 1) ? 0x0001 : 0); } static public boolean alphaToShape_getQuadrant_getPixel(Image2B img, int x, int y) { return x >= 0 && x < img.w && y >= 0 && y < img.h && img.getPixel(x, y); } static public A benchForNSeconds(double n, IF0 f) { return benchForNSeconds(n, str(f), f); } static public A benchForNSeconds(double n, String desc, IF0 f) { benchForNSeconds(new Runnable() { public void run() { try { f.get(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f!"; } }, n); return f.get(); } static public long benchForNSeconds(Runnable r, double n) { return benchForNSeconds(str(r), r, n); } static public long benchForNSeconds(String desc, Runnable r, double n) { long start = sysNow(), min = -1, print = sysNow(); int seconds = 1; long count = 0, sum = 0; while (seconds <= n) { long time = nanos(); r.run(); ++count; time = nanos() - time; min = min < 0 ? time : min(min, time); sum += time; double avg = doubleRatio(sum, count); if (sysNow() >= start + seconds * 1000) { printAndSetConsoleTitleIfMain("n=" + n2(count) + ", avg=" + formatDouble(nanosToMS(avg), 3) + " ms, " + "min=" + formatDouble(nanosToMS(min), 3) + " ms: " + desc + " (" + seconds + "/" + n + " s, last=" + formatDouble(nanosToMS(time), 3) + " ms, " + n2(count) + "/s)"); ++seconds; count = sum = 0; } } return min; } static public String mlsUnindent(String s) { return autoUnindent_mls(s); } static public long longPlus(long a, long b) { return a + b; } static public > A bindComboBoxToVar_withUserChangeListener(A cb, IVarWithNotify var, Runnable userChangeListener) { BoolVar inVarChange = new BoolVar(); if (var != null) { bindListenerToComponent(cb, var, () -> { AutoCloseable __1 = tempSetBoolVar(inVarChange, true); try { selectItem(cb, var.get()); } finally { _close(__1); } }); onChange(cb, (Runnable) () -> { var.set(getSelected(cb)); if (!inVarChange.get()) pcallF(userChangeListener); }); } return cb; } static public List virtualCountList_incl(int from, int to) { return virtualCountList(from, to + 1); } static public HashMap pairsToMap(Collection> l) { HashMap map = new HashMap(); if (l != null) for (Pair p : l) map.put(p.a, p.b); return map; } static public JLabel jVarLabel(IF0WithChangeListeners var) { return bindJLabelToVar(jlabel(), var); } static public byte[] loadFirstBytes(String file, int n) { return loadFirstBytes(new File(file), n); } static public byte[] loadFirstBytes(File f, int n) { n = asInt(min(n, f.length())); return loadBinaryFileChunk(f, 0, n); } static public BigInteger parseBigInt(String s) { return new BigInteger(s); } static public Map joinMaps(Map map1, Map map2) { if (empty(map2)) return map1; if (empty(map1)) return map2; Map map3 = cloneMap(map1); putAll(map3, map2); return map3; } static public String printStarFormat(String pattern, Object... args) { return print(starFormat(pattern, args)); } static public byte[] convertToPNG(BufferedImage img) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ImageIO.write(img, "png", stream); return stream.toByteArray(); } catch (Exception __e) { throw rethrow(__e); } } static public JPanel withTopAndLeftMargin(Component c) { return withTopAndLeftMargin(defaultMargin(), c); } static public JPanel withTopAndLeftMargin(int w, Component c) { return swing(() -> { JPanel p = marginPanel(); p.setBorder(BorderFactory.createEmptyBorder(w, w, 0, 0)); p.add(c); return p; }); } static public Producer javaTokC_noMLS_iterator(final String s) { return javaTokC_noMLS_iterator(s, 0); } static public Producer javaTokC_noMLS_iterator(final String s, final int startIndex) { return new Producer() { final public int l = s.length(); public int i = startIndex; public String next() { if (i >= l) return null; int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } i = j; if (i >= l) return null; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j))); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else ++j; String t = quickSubstring(s, i, j); i = j; return t; } }; } static public Rect growRect(int pixels, Rect r) { return growRect(r, pixels); } static public Rect growRect(double x, Rect r) { return growRect(x, x, r); } static public Rect growRect(double x, double y, Rect r) { return growRect(r, x, y); } static public Rect growRect(Rect r) { return growRect(r, 1); } static public Rect growRect(Rect r, int pixels) { return new Rect(r.x - pixels, r.y - pixels, r.w + pixels * 2, r.h + pixels * 2); } static public Rect growRect(Rect r, int x, int y) { return new Rect(r.x - x, r.y - y, r.w + x * 2, r.h + y * 2); } static public Rect growRect(Rect r, double x) { return growRect(r, x, x); } static public Rect growRect(Rect r, double x, double y) { return new Rect(iround(r.x - x), iround(r.y - y), r.w + iround(x * 2), r.h + iround(y * 2)); } static public boolean isTrueOrYes(Object o) { return isTrueOpt(o) || o instanceof String && (eqicOneOf(((String) o), "1", "t", "true") || isYes(((String) o))); } static public int rgbIntFromGrayscale(int brightness) { brightness = clampToUByte(brightness); return brightness | (brightness << 8) | (brightness << 16); } static public int rgbIntFromGrayscale(double brightness) { return rgbIntFromGrayscale(zeroToOneToZeroTo255(brightness)); } static public double threePointAngle(IDoublePt p1, IDoublePt center, IDoublePt p2) { double angle = atan2(p1.x_double() - center.x_double(), p1.y_double() - center.y_double()) - atan2(p2.x_double() - center.x_double(), p2.y_double() - center.y_double()); return mod(angle, pi() * 2); } static public byte[] longToBytes(long l) { return new byte[] { (byte) (l >>> 56), (byte) (l >>> 48), (byte) (l >>> 40), (byte) (l >>> 32), (byte) (l >>> 24), (byte) (l >>> 16), (byte) (l >>> 8), (byte) l }; } static public long imageServerCheckMD5(String md5) { assertTrue(isMD5(md5)); String s = loadPage(imageServerURL() + "checkmd5/" + md5); return parseLongOpt(s); } static public String bwImageHexPixelsSingleLine(BWImage img) { return img == null ? null : bytesToHex(img.pixels); } static public String bwImageHexPixelsSingleLine(IBWImage img) { return bwImageHexPixelsSingleLine(toBWImage(img)); } static public int defaultFontSize() { return 12; } static public Object[] concatMethodArgs(Object[] args1, Object[] args2) { int n1, n2; if (args1 == null || (n1 = args1.length) == 0) return args2; if (args2 == null || (n2 = args2.length) == 0) return args1; Object[] args = new Object[n1 + n2]; for (int i = 0; i < n1; i++) args[i] = args1[i]; for (int i = 0; i < n2; i++) args[n1 + i] = args2[i]; return args; } static public int cmpAlphaNumIC(String a, String b) { return alphaNumComparatorIC().compare(a, b); } static public List tok_parsedIntegers(String s) { return map(__123 -> parseInt(__123), tok_integers(s)); } static public Object consoleFrame_gen() { return getOpt(getOpt(getJavaX(), "console"), "frame"); } static public String dropLeadingNewLine(String s) { if (startsWith(s, "\r\n")) return substring(s, 2); if (startsWith(s, "\n")) return substring(s, 1); return s; } static public int limitToUByte(int i) { return max(0, min(255, i)); } static public boolean bwImagesIdentical(BWImage img1, BWImage img2) { if (img1 == img2) return true; if (img1 == null) return img2 == null; if (img2 == null) return false; int w = img1.getWidth(), h = img1.getHeight(); if (w != img2.getWidth() || h != img2.getHeight()) return false; byte[] pixels1 = img1.pixels, pixels2 = img2.pixels; return Arrays.equals(pixels1, pixels2); } static public double nanosToMS(double nanoseconds) { return nsToMS(nanoseconds); } static public boolean isGrandChildOf_limitedBy(Component a, Component b, Component outer) { return swing(() -> { if (a == null || b == null) return false; if (a == b) return true; var _a_1 = a; while (_a_1 != outer && (_a_1 = getParent(_a_1)) != null) if (_a_1 == b) return true; return false; }); } static public AutoCloseable tempGraphicsTransform(final Graphics2D g) { final AffineTransform t = g.getTransform(); return new AutoCloseable() { public void close() { g.setTransform(t); } }; } static public void selectTabComponent(JTabbedPane tabs, Component c) { swing(() -> { int idx = indexOfTabComponent(tabs, c); if (idx >= 0) tabs.setSelectedIndex(idx); }); } static public void selectTabComponent(JExtendedTabbedPane tabs, Component c) { swing(() -> { int idx = indexOfTabComponent(tabs, c); if (idx >= 0) tabs.setSelectedIndex(idx); }); } static public A lastKey(NavigableMap map) { return empty(map) ? null : map.lastKey(); } static public int matcherInt(Matcher m, int i) { return parseInt(m.group(i)); } static public void mapRemove(Map map, A key) { if (map != null && key != null) map.remove(key); } static public A firstOfPair(Pair p) { return p == null ? null : p.a; } static public String editSnippet(String id, String text) { if (isLocalSnippetID(id)) { saveLocalSnippet(id, text); return "Snippet saved"; } return editSnippet(id, text, standardCredentialsUser(), standardCredentialsPass()); } static public String editSnippet(String id, String text, String user, String pass) { if (!isSnippetID(id)) throw fail("Need snippet ID"); Map query = litmap("id", parseSnippetID(id), "text", text, "_user", user, "_pass", pass, "len", lUtf8(text)); String url = tb_mainServer() + "/tb-int/update_snippet_text.php"; String page = doPost(query, url); if (!page.contains("OK")) throw fail("Error editing snippet " + id + ": " + quote(page)); return page + " - edited " + fsI(id); } static public List listFilesOnly(String dir) { return listFilesOnly(new File(dir)); } static public List listFilesOnly(File... dirs) { return concatMap(dir -> listFilesWithSuffix("", dir), dirs); } static public boolean checkIntColorWithoutAlpha(BufferedImage img, int x, int y, int color) { return getIntColorWithoutAlphaOrMinus1(img, x, y) == color; } static public String multiLineQuoteWithSpaces(String s) { return multiLineQuote(" " + s + " "); } static public List uniquifyBWImages(Iterable l) { return new UniquifyUsingHasher(__1 -> hashBWImage(__1), (__2, __3) -> bwImagesIdentical(__2, __3)).addAll(l).get(); } static public List> zipTwoListsToPairs(List l1, List l2) { int n = min(l(l1), l(l2)); List> out = emptyList(n); for (int i = 0; i < n; i++) addPair(out, l1.get(i), l2.get(i)); return out; } static public double nsToMS(double nanoseconds) { return nanoseconds / 1e6; } static public boolean step(Steppable steppable) { return steppable == null ? null : steppable.step(); } static public String autoUnindent_mls(String s) { return autoUnindent(rtrim(dropLeadingNewLine(s))); } static public Field findField2(Object o, String field) { Class c = o.getClass(); HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } if (map == getOpt_special) { if (o instanceof Class) return findField2_findStaticField((Class) o, field); } return map.get(field); } static public Field findField2_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static public void copyRGBImage(RGBImage src, int srcX, int srcY, RGBImage dst, int dstX, int dstY) { copyRGBImage(src, srcX, srcY, dst, dstX, dstY, src.getWidth() - srcX, src.getHeight() - srcY); } static public void copyRGBImage(RGBImage src, int srcX, int srcY, RGBImage dst, int dstX, int dstY, int w, int h) { w = min(w, dst.getWidth() - dstX); h = min(h, dst.getHeight() - dstY); w = min(w, src.getWidth() - srcX); h = min(h, src.getHeight() - srcY); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) dst.setPixel(dstX + x, dstY + y, src.getInt(srcX + x, srcY + y)); } static public A innerExceptionOfType(Class c, Throwable e) { while (true) { ping(); if (e == null) return null; if (isInstanceOf(e, c)) return (A) e; e = e.getCause(); } } static public long hashBufferedImage(BufferedImage img) { return new HashBufferedImage(img).get(); } static public List cyclicSubList(List l, int startIndex, int endIndex) { if (l == null) return null; List subList = new ArrayList(); for (int i = startIndex; i < endIndex; i++) subList.add(cyclicGet(l, i)); return subList; } static public String programName() { return getProgramName(); } static public List> zip(List l1, List l2) { return zipTwoListsToPairs(l1, l2); } static public AutoCloseable tempRestoreMap(Map map) { if (map == null) return null; var cloned = cloneMap(map); return () -> copyMap(cloned, map); } static public String tabToSingleSpace(String s) { return replace(s, '\t', ' '); } static public JLabel rightAlignedLabel() { return jrightAlignedLabel(); } static public JLabel rightAlignedLabel(String text) { return jrightAlignedLabel(text); } static public String nSteps(long n) { return n2(n, "step"); } static public String nSteps(Collection l) { return nSteps(l(l)); } static public A waitUntilNotNull(Var v) { return waitForVarToBeNotNull(v); } static public A waitUntilNotNull(IVarWithNotify v) { Var myVar = new Var(); AutoCloseable __1 = tempOnChangeAndNow(v, () -> myVar.set(v.get())); try { return waitUntilNotNull(myVar); } finally { _close(__1); } } static public A waitUntilNotNull(VarWithNotify v) { return waitUntilNotNull((Var) v); } static public void upgradeJavaXAndRestart() { run("#1001639"); restart(); sleep(); } static public String formatElapsedTimeWithAppropriateUnit(double seconds) { if (seconds >= 1) return formatDouble(seconds, 3) + " s"; double ms = seconds * 1000; if (ms >= 1) return formatDouble(ms, 3) + " ms"; double us = ms * 1000; if (us >= 1) return formatDouble(us, 3) + " µs"; double ns = us * 1000; return formatDouble(ns, 3) + " ns"; } static public byte[] toPNG(BufferedImage img) { return convertToPNG(img); } static public byte[] loadBeginningOfBinaryFile(File file, int maxBytes) { return loadBinaryFilePart(file, 0, maxBytes); } static public long onePathDirection_long(int index) { return ptToLong(onePathDirections()[index]); } static public long onePathDirection_long(long p, int index) { Pt p2 = onePathDirection(index); return twoIntsToLong(firstIntFromLong(p) + p2.x, secondIntFromLong(p) + p2.y); } static public boolean imagesIdentical(BufferedImage img1, BufferedImage img2) { if (img1 == img2) return true; if (img1 == null) return img2 == null; if (img2 == null) return false; int w = img1.getWidth(), h = img1.getHeight(); if (w != img2.getWidth() || h != img2.getHeight()) return false; var gp1 = grabbableIntPixels_fastOrSlow(img1); var gp2 = grabbableIntPixels_fastOrSlow(img2); int[] pixels1 = gp1.data, pixels2 = gp2.data; int scanlineExtra1 = gp1.scanlineStride - w; int scanlineExtra2 = gp2.scanlineStride - w; int i1 = gp1.offset, i2 = gp2.offset; var ping = pingSource(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) if (pixels1[i1++] != pixels2[i2++]) return false; i1 += scanlineExtra1; i2 += scanlineExtra2; { if (ping != null) ping.get(); } } return true; } static public Method findNonStaticMethod_precise_onTypes(Object o, String method, Class... argTypes) { try { Class c = _getClass(o); if (c == null) return null; _MethodCache cache = callOpt_getCache(c); List methods = cache.cache.get(method); Lowest best = new Lowest(); if (methods != null) for (Method m : methods) { { if (isStaticMethod(m)) continue; } int score = methodApplicabilityScore_onTypes(m, argTypes); if (score < Integer.MAX_VALUE) best.put(m, score); } return best.get(); } catch (Exception __e) { throw rethrow(__e); } } static public void profileFor5(Runnable r) { profileSingleThreadToConsole(() -> benchFor5(r)); } static public BufferedImage intArrayToBufferedImageWithoutAlpha(int[] pixels, int w, int h) { int[] bitMasks = { 0xFF0000, 0xFF00, 0xFF }; SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, w, h, bitMasks); DataBufferInt db = new DataBufferInt(pixels, pixels.length); WritableRaster wr = Raster.createWritableRaster(sm, db, new Point()); DirectColorModel cm = new DirectColorModel(24, bitMasks[0], bitMasks[1], bitMasks[2], 0); return new BufferedImage(cm, wr, false, null); } static public int ii_getPixel(IntegralImage img, int x, int y) { if (img == null) return 0; int r = iround(img.rectSum(x, y, x + 1, y + 1, 0)); int g = iround(img.rectSum(x, y, x + 1, y + 1, 1)); int b = iround(img.rectSum(x, y, x + 1, y + 1, 2)); return rgbInt(r, g, b); } static public List parseList(String s) { return (List) safeUnstructure(s); } static public BufferedImage scaleImage(BufferedImage before, double scaleX) { return scaleImage(before, scaleX, scaleX); } static public BufferedImage scaleImage(BufferedImage before, double scaleX, double scaleY) { return scaleImageWithOp(before, scaleX, scaleY, AffineTransformOp.TYPE_BILINEAR); } static public BufferedImage scaleImage(double scale, BufferedImage before) { return scaleImage(before, scale); } static public void listPut(List l, int i, A a, A emptyElement) { listSet(l, i, a, emptyElement); } static public void listPut(List l, int i, A a) { listSet(l, i, a); } static public RGBImage mergeImagesVertically(RGBImage... images) { return mergeImagesVertically(toList(images)); } static public RGBImage mergeImagesVertically(List images, Object... __) { int spacing = optPar("spacing", __, imageMergeSpacing()); RGB spaceColor = optPar("spaceColor", __, new RGB(0.9f)); int h = intSum(images, "height") + (l(images) - 1) * spacing, w = intMax(images, "width"); RGBImage out = new RGBImage(w, h, spaceColor); int y = 0; for (int i = 0; i < l(images); i++) { RGBImage img = images.get(i); int x = (w - img.w()) / 2; copyRGBImage(img, 0, 0, out, x, y); y += img.h() + spacing; } return out; } static public void setBit(BitSet b, int bit) { { if (b != null) b.set(bit); } } static public void setBit(BitSet b, int bit, boolean value) { { if (b != null) b.set(bit, value); } } static public void setBit(byte[] b, int bit) { setBit(b, bit, true); } static public void setBit(byte[] b, int bit, boolean value) { int idx = bit >> 3; byte mask = (byte) (1 << (bit & 7)); if (value) b[idx] |= mask; else b[idx] &= ~mask; } static public String nPoints(long n) { return n2(n, "point"); } static public String nPoints(Collection l) { return nPoints(l(l)); } static public String nPoints(Map map) { return nPoints(l(map)); } static public String regexpExtract(String pat, String s) { if (s == null) return null; Matcher m = regexpMatcher(pat, s); return m.find() ? m.group() : null; } static public Class primitiveToBoxedTypeOpt(Class type) { return or(primitiveToBoxedType(type), type); } static public boolean isStandardClass(String name) { return isIdentifier(name) && standardClassesMap_cached().containsKey(name); } static public List tok_integersInOrder(String s) { return filter(__124 -> isInteger(__124), javaTokC(s)); } static public Map.Entry firstEntry(Map map) { return empty(map) ? null : first(map.entrySet()); } static public IterableIterator notNulls_iterator(Iterator it) { return filterIterator(it, new F1() { public Boolean get(A a) { try { return a != null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a != null"; } }); } static public A popFirst(List l) { if (empty(l)) return null; A a = first(l); l.remove(0); return a; } static public A popFirst(Collection l) { if (empty(l)) return null; A a = first(l); l.remove(a); return a; } static public Pair popFirst(Map map) { if (map == null) return null; var it = map.entrySet().iterator(); if (!it.hasNext()) return null; var p = mapEntryToPair(it.next()); it.remove(); return p; } static public List popFirst(int n, List l) { List part = cloneSubList(l, 0, n); removeSubList(l, 0, n); return part; } static public AppendableChain popFirst(AppendableChain a) { return a == null ? null : a.popFirst(); } static public A jHandleFileDrop(A c, final Object onDrop) { new DropTarget(c, new DropTargetAdapter() { public void drop(DropTargetDropEvent e) { try { Transferable tr = e.getTransferable(); DataFlavor[] flavors = tr.getTransferDataFlavors(); for (DataFlavor flavor : flavors) { if (flavor.isFlavorJavaFileListType()) { e.acceptDrop(e.getDropAction()); File file = first((List) tr.getTransferData(flavor)); if (file != null && !isFalse(callF(onDrop, file))) e.dropComplete(true); return; } } } catch (Throwable __e) { pcallFail(__e); } e.rejectDrop(); } }); return c; } static public A jHandleFileDrop(IVF1 onDrop, A c) { return jHandleFileDrop((Object) onDrop, c); } static public A jHandleFileDrop(Object onDrop, A c) { return jHandleFileDrop(c, onDrop); } static public String internIfLongerThan(String s, int l) { return s == null ? null : l(s) >= l ? intern(s) : s; } static public Component getComponentAtIndex(final Container c, final int i) { return c == null || i < 0 ? null : swing(new F0() { public Component get() { try { return i < c.getComponentCount() ? c.getComponent(i) : null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return i < c.getComponentCount() ? c.getComponent(i) : null;"; } }); } static public A waitForVarPredicate(Var v, IF0 pred) { try { synchronized (v) { while (!pred.get()) v.wait(); return v.get(); } } catch (Exception __e) { throw rethrow(__e); } } static public LineAndColumn parseLineAndColumn(String s) { String re = "\\bLine (" + regexpN2() + "), col (" + regexpN2() + ")"; List l = regexpLastGroupsIC(re, s); return l == null ? null : new LineAndColumn(parseIntN2(first(l)), parseIntN2(second(l))); } static public boolean isAbstract(Class c) { return (c.getModifiers() & Modifier.ABSTRACT) != 0; } static public boolean isAbstract(Method m) { return (m.getModifiers() & Modifier.ABSTRACT) != 0; } static public JTextArea jTypeWriterTextArea() { return newTypeWriterTextArea(); } static public JTextArea jTypeWriterTextArea(String text) { return newTypeWriterTextArea(text); } static public RuntimeException wrapPatternSyntaxException(PatternSyntaxException e) { if (e == null) return null; String pat = e.getPattern(); int i = e.getIndex(); return new RuntimeException("Regular expression error between " + multiLineQuoteWithSpaces(substring(pat, 0, i)) + " and " + multiLineQuoteWithSpaces(substring(pat, i)) + " - " + e.getMessage()); } static public void onTabSelectedAndNow(JExtendedTabbedPane tabs, Runnable r) { if (tabs != null) onTabSelectedAndNow(tabs.tabs, r); } static public void onTabSelectedAndNow(JTabbedPane tabs, Runnable r) { if (tabs != null && r != null) { swing(() -> { onTabSelected(tabs, r); r.run(); }); } } static public void onTabSelectedAndNow(JTabbedPane tabs, IVF1 r) { if (tabs != null && r != null) { swing(() -> { onTabSelected(tabs, r); r.get(tabs.getSelectedIndex()); }); } } static public void drawPixelChessboard(BufferedImage image) { int w = image.getWidth(), h = image.getHeight(); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) setPixel(image, x, y, even(x + y) ? Color.lightGray : Color.white); } static public JTextArea showLines(Iterable lines) { return showLines(autoFrameTitle(), lines); } static public JTextArea showLines(String title, Iterable lines) { return showText(title, lines(lines)); } static public Object newMultiDimensionalOuterArray(Class elementType, int dimensions, int length) { int[] dims = new int[dimensions]; dims[0] = length; return Array.newInstance(elementType, dims); } static public boolean addLibrary(String libID) { return addLibraryToCurrentProgram(libID); } static public boolean addLibrary(File f) { return addLibraryToCurrentProgram(f); } static public KeyListener ctrlEnterKeyListener(final Object action) { final Object info = _threadInfo(); return new KeyAdapter() { public void keyReleased(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_ENTER && ke.getModifiers() == KeyEvent.CTRL_MASK) { _threadInheritInfo(info); pcallF(action); } } }; } static public MultiMap pairsToMultiMap(Iterable> l) { MultiMap mm = new MultiMap(); for (Pair p : unnull(l)) mm.put(p.a, p.b); return mm; } static public int rgbInt(int r, int g, int b) { return (clamp(r, 0, 255) << 16) | (clamp(g, 0, 255) << 8) | clamp(b, 0, 255); } static public int rgbInt(byte r, byte g, byte b) { return (ubyteToInt(r) << 16) | (ubyteToInt(g) << 8) | ubyteToInt(b); } static public IterableIterator itIt(IterableIterator it) { if (it == null) return emptyItIt(); return it; } static public IterableIterator itIt(Iterator it) { if (it == null) return emptyItIt(); if (it instanceof IterableIterator) return ((IterableIterator) it); return new IterableIterator() { public boolean hasNext() { return it.hasNext(); } public A next() { return it.next(); } }; } static public IterableIterator itIt(Iterable l) { if (l == null) return emptyItIt(); if (l instanceof IterableIterator) return ((IterableIterator) l); Iterator it = l.iterator(); if (it instanceof IterableIterator) return ((IterableIterator) it); return new IterableIterator() { public boolean hasNext() { return it.hasNext(); } public A next() { return it.next(); } }; } static public List> multiSetToPairsByPopularity(MultiSet ms) { List> l = new ArrayList(); if (ms != null) for (A a : ms.highestFirst()) l.add(pair(a, ms.get(a))); return l; } static public Set similarEmptySet(Iterable m) { if (m instanceof TreeSet) return new TreeSet(((TreeSet) m).comparator()); if (m instanceof LinkedHashSet) return new LinkedHashSet(); return new HashSet(); } static public Set similarEmptySet(Map m) { if (m instanceof TreeMap) return new TreeSet(((TreeMap) m).comparator()); if (m instanceof LinkedHashMap) return new LinkedHashSet(); return new HashSet(); } static public List nempties(Collection c) { return filterNempty(c); } static public BufferedImage scaledBufferedImageFromIntegralImage_withMeta(int w, IIntegralImage img) { return scaledBufferedImageFromIntegralImage_withMeta(img, w); } static public BufferedImage scaledBufferedImageFromIntegralImage_withMeta_height(int h, BufferedImage img) { return scaledBufferedImageFromIntegralImage_withMeta_height(h, integralImage(img)); } static public BufferedImage scaledBufferedImageFromIntegralImage_withMeta_height(int h, IIntegralImage img) { return scaledBufferedImageFromIntegralImage_withMeta(img, widthForHeight(img, h), h); } static public BufferedImage scaledBufferedImageFromIntegralImage_withMeta(IIntegralImage img, int w) { return scaledBufferedImageFromIntegralImage_withMeta(img, w, heightForWidth(img, w)); } static public BufferedImage scaledBufferedImageFromIntegralImage_withMeta(IIntegralImage img, int w, int h) { ScaledBufferedImageFromIntegralImage x = new ScaledBufferedImageFromIntegralImage(img, w, h); x.run(); return setMetaSrc(x.result, x); } static public void setConsoleTitle(String title) { callOpt(consoleFrame_gen(), "setTitle", title); } static public Map> callOpt_noArgs_cache = newDangerousWeakHashMap(); static public Object callOpt_noArgs(Object o, String method) { try { if (o == null) return null; if (o instanceof Class) return callOpt(o, method); Class c = o.getClass(); HashMap map; synchronized (callOpt_noArgs_cache) { map = callOpt_noArgs_cache.get(c); if (map == null) map = callOpt_noArgs_makeCache(c); } Method m = map.get(method); return m != null ? m.invoke(o) : null; } catch (Exception __e) { throw rethrow(__e); } } static public HashMap callOpt_noArgs_makeCache(Class c) { HashMap map = new HashMap(); Class _c = c; do { for (Method m : c.getDeclaredMethods()) if (m.getParameterTypes().length == 0 && !reflection_isForbiddenMethod(m)) { makeAccessible(m); String name = m.getName(); if (!map.containsKey(name)) map.put(name, m); } _c = _c.getSuperclass(); } while (_c != null); callOpt_noArgs_cache.put(c, map); return map; } static public RuntimeException asRuntimeException(Throwable t) { if (t instanceof Error) _handleError((Error) t); return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } static public String n2_iround(double d) { return n2(iround(d)); } static public String tok_javaDropCommentsFromWhitespace(String s) { int l = l(s), j = 0; StringBuilder buf = new StringBuilder(); while (j < l) { char c = s.charAt(j); char d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else { buf.append(c); ++j; } } return str(buf); } static public A nextFromIterator(Iterator it) { return it == null || !it.hasNext() ? null : it.next(); } static public boolean isAbsoluteURL(String s) { return isURL(s); } static public void createOrRemoveFile(File f, boolean create) { if (create) { if (!fileExists(f)) touchFile(f); } else if (fileExists(f)) removeFile(f); } static public double degToRadian(double deg) { return degreeToRadian(deg); } static public IVF1 toIVF1(VF1 f) { return vf1ToIVF1(f); } static public IVF1 toIVF1(Object f) { if (f == null) return null; if (f instanceof IVF1) return (IVF1) f; if (isString(f)) return mainFunctionToIVF1((String) f); return (IVF1) a -> { callF(f, a); }; } static public JScrollPane jscroll_borderless(Component c) { return borderlessScrollPane(jscroll(c)); } static public List varyList(IF1 varyElement, List l) { if (empty(l)) return null; int i = randomIndex(l); A varied = varyElement.get(l.get(i)); if (varied == null) return null; return listWithSingleElementChanged(l, i, varied); } static public IntRange parseHexRange(String s) { List parts = splitAtMinus(s); int start = hexToInt(first(parts)); if (empty(parts)) return null; else if (l(parts) == 1) return intRange_incl(start, start); else if (l(parts) == 2) { int end = hexToInt(second(parts)); return intRange_incl(start, end); } else throw fail("Too many minuses"); } static public void deleteDB() { deleteAllConceptsOfProgram(dbProgramID()); } static public AutoCloseable tempAddPopupButtonListener(IVF1 onEvent) { if (onEvent == null) return null; return tempAddGlobalMouseListener(evt -> { if (evt.getID() == MouseEvent.MOUSE_PRESSED && isNotLeftMouseButton(evt)) onEvent.get(evt); }); } static public boolean newPreciseCall_debug = false; static public Object newPreciseCall(Object o, String method, Object... args) { try { if (o == null) return null; boolean staticCall = o instanceof Class; Class c = staticCall ? (Class) o : o.getClass(); Object target = staticCall ? null : o; _MethodCache cache = callOpt_getCache(c); List methods = cache.cache.get(method); Method best = null; int bestScore = Integer.MAX_VALUE; boolean widening = false; if (newPreciseCall_debug) printVars("newPreciseCall", "method", method, "staticCall", staticCall, "c", c, "methods", l(methods)); if (methods != null) for (Method m : methods) { if (staticCall && !isStaticMethod(m)) continue; int score = methodApplicabilityScore_withPrimitiveWidening(m, args); if (score == 0) return invokeMethod(m, target, args); if (newPreciseCall_debug) print("Method score: " + m + " " + score); if (abs(score) < bestScore) { best = m; bestScore = abs(score); widening = score < 0; } } if (best != null) if (widening) return invokeMethodWithWidening(best, target, args); else return invokeMethod(best, target, args); return callWithVarargs(o, method, args); } catch (Exception __e) { throw rethrow(__e); } } static public List findNonDefaultInterfaceMethods(Class intrface) { if (!isInterface(intrface)) return null; List l = new ArrayList(); _MethodCache cache = getMethodCache(intrface); Class c = intrface; do { for (Method m : c.getDeclaredMethods()) if (m.getDeclaringClass() != Object.class && !m.isDefault() && !isStaticMethod(m)) l.add(m); c = c.getSuperclass(); } while (c != null); return l; } static public Font getFont(JComponent c) { return c == null ? null : swing(new F0() { public Font get() { try { return c.getFont(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getFont();"; } }); } static public IntRange intersectIntRanges(IntRange a, IntRange b) { int start = max(a.start, b.start); int end = min(a.end, b.end); return start <= end ? new IntRange(start, end) : null; } static public List intersectIntRanges(Iterable l, IntRange b) { return map(l, r -> intersectIntRanges(r, b)); } static public Object[] repArray(Object a, int n) { return arrayrep(a, n); } static public A[] repArray(Class type, A a, int n) { return arrayrep(type, a, n); } static public Rect boundsOfPts(Iterable l) { BoundsFinder bf = new BoundsFinder(); for (var p : unnullForIteration(l)) bf.add(p); return bf.get(); } static public JPanel withBlackBorder(Component c) { return withBorder(BorderFactory.createLineBorder(Color.black), c); } static public BufferedImage withBlackBorder(BufferedImage img) { return withBlackBorder(1, img); } static public BufferedImage withBlackBorder(int width, BufferedImage img) { return addBorderToImage(Color.black, width, img); } static public > MultiMap mapToMultiMap(Map map) { if (map == null) return null; MultiMap mm = similarEmptyMultiMap(map); for (Map.Entry> __0 : _entrySet(map)) { A key = __0.getKey(); Collection values = __0.getValue(); mm.putAll(key, values); } return mm; } static public MultiMap mapToMultiMap(IF1> f, Iterable l) { MultiMap mm = new MultiMap(); for (A o : unnullForIteration(l)) { Pair p = f.get(o); mm.put(p.a, p.b); } return mm; } static public MultiMap mapToMultiMap(Iterable l, IF1> f) { return mapToMultiMap(f, l); } static public long hashBWImage(BWImage img) { return new HashBWImage(img).get(); } static public BufferedImage mergeBufferedImagesVH(Collection> l) { return mergeBufferedImagesVertically(map(__125 -> mergeBufferedImagesHorizontally(__125), l)); } static public A restructure(A a) { return (A) unstructure(structure(a)); } static public List sortByCalculatedFieldAlphaNumIC(Iterable c, IF1 f) { List l = cloneList(c); sort(l, (a, b) -> cmpAlphanumIC(f.get(a), f.get(b))); return l; } static public int indexOfTabComponent(JTabbedPane tabs, Component c) { return swing(() -> { if (tabs == null || c == null) return -1; int n = tabs.getTabCount(); for (int i = 0; i < n; i++) if (isGrandChildOf_limitedBy(c, tabs.getTabComponentAt(i), tabs) || isGrandChildOf_limitedBy(c, tabs.getComponentAt(i), tabs)) return i; return -1; }); } static public int indexOfTabComponent(JExtendedTabbedPane tabs, Component c) { return swing(() -> { if (tabs == null || c == null) return -1; int n = tabs.getTabCount(); for (int i = 0; i < n; i++) if (isGrandChildOf_limitedBy(c, tabs.getTabComponentAt(i), tabs.visualize()) || isGrandChildOf_limitedBy(c, tabs.getComponentAt(i), tabs.visualize())) return i; return -1; }); } static public Color blendColor(Color a, Color b, double bish) { return blendColors(a, b, bish); } static public Color blendColor(double bish, Color a, Color b) { return blendColors(a, b, bish); } static public void readLocally(String progID, String varNames) { readLocally2(mc(), progID, varNames); } static public void readLocally(String varNames) { readLocally2(mc(), programID(), varNames); } static public void readLocally2(Object obj, String varNames) { readLocally2(obj, programID(), varNames); } static public int readLocally_stringLength; static public ThreadLocal readLocally2_allDynamic = new ThreadLocal(); static public ThreadLocal readLocally2_classFinder = new ThreadLocal(); static public void readLocally2(Object obj, String progID, String varNames) { try { boolean allDynamic = isTrue(getAndClearThreadLocal(readLocally2_allDynamic)); for (String variableName : javaTokC(varNames)) { File textFile = new File(programDir(progID), variableName + ".text"); String value = loadTextFile(textFile); if (value != null) set(utils.class, variableName, value); else { File structureFile = new File(programDir(progID), variableName + ".structure"); value = loadTextFile(structureFile); if (value == null) { File structureGZFile = new File(programDir(progID), variableName + ".structure.gz"); if (!structureGZFile.isFile()) return; InputStream fis = new FileInputStream(structureGZFile); try { GZIPInputStream gis = newGZIPInputStream(fis); InputStreamReader reader = new InputStreamReader(gis, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(reader); Object o = unstructure_tok(javaTokC_noMLS_onReader(bufferedReader), allDynamic, readLocally2_classFinder.get()); readLocally_set(obj, variableName, o); return; } finally { _close(fis); } } readLocally_stringLength = l(value); if (nempty(value)) readLocally_set(obj, variableName, unstructure(value, allDynamic, readLocally2_classFinder.get())); } } } catch (Exception __e) { throw rethrow(__e); } } static public void readLocally_set(Object c, String varName, Object value) { Object oldValue = get(c, varName); if (oldValue instanceof List && !(oldValue instanceof ArrayList) && value != null) { value = synchroList((List) value); } set(c, varName, value); } static public Container dm_frame() { return dm_frame(dm_current_generic()); } static public Container dm_frame(Object module) { return (Container) getPossiblyInternalFrame(dm_vis(module)); } static public void uploadImageFileDialog(File imageFile) { if (!isFile(imageFile)) return; JTextField tf = jTextField(); showFormTitled("Upload Image", "Image file", new JFilePathLabel(imageFile), "Image title (optional)", focusOnShow(tf), new F0() { public Object get() { try { disableSubmitButton(getFrame(tf)); startThread("Upload Image", new Runnable() { public void run() { try { try { String url = uploadImage(imageFile, loadImage2(imageFile), getTextTrim(tf)); disposeFrame(tf); messageBox("Image uploaded as " + url); } catch (Throwable e) { enableSubmitButton(getFrame(tf)); messageBox(e); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n String url = uploadImage(imageFile, loadImage2(imageFile), g..."; } }); return false; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disableSubmitButton(getFrame(tf));\r\n thread \"Upload Image\" {\r\n tr..."; } }); } static public int rawRGBDiff(int a, int b) { int r1 = (a >> 16) & 0xFF; int g1 = (a >> 8) & 0xFF; int b1 = a & 0xFF; int r2 = (b >> 16) & 0xFF; int g2 = (b >> 8) & 0xFF; int b2 = b & 0xFF; return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2); } static public Object unstructure(String text) { return unstructure(text, false); } static public Object unstructure(String text, boolean allDynamic) { return unstructure(text, allDynamic, null); } static public Object unstructure(String text, IF1 classFinder) { return unstructure(text, false, classFinder); } static public int structure_internStringsLongerThan = 50; static public int unstructure_unquoteBufSize = 100; static public int unstructure_tokrefs; abstract static public class unstructure_Receiver { abstract public void set(Object o); } static public Object unstructure(String text, boolean allDynamic, Object classFinder) { if (text == null) return null; return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder); } static public Object unstructure_reader(BufferedReader reader) { return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null); } public interface unstructure_Handler { public void parse(int refID, int tokIndex, unstructure_Receiver out); } static public class Unstructurer { final public Unstructurer setTok(Producer tok) { return tok(tok); } public Unstructurer tok(Producer tok) { this.tok = tok; return this; } final public Producer getTok() { return tok(); } public Producer tok() { return tok; } public Producer tok; final public Unstructurer setAllDynamic(boolean allDynamic) { return allDynamic(allDynamic); } public Unstructurer allDynamic(boolean allDynamic) { this.allDynamic = allDynamic; return this; } final public boolean getAllDynamic() { return allDynamic(); } public boolean allDynamic() { return allDynamic; } public boolean allDynamic = false; public int i = -1; public Object classFinder; public String mcDollar = actualMCDollar(); public Unstructurer classFinder(Object _classFinder) { classFinder = _classFinder != null ? _classFinder : _defaultClassFinder(); return this; } public HashMap refs = new HashMap(); public HashMap tokrefs = new HashMap(); public HashSet concepts = new HashSet(); public List stack = new ArrayList(); public Map baseClassMap = new HashMap(); public HashMap innerClassConstructors = new HashMap(); public String curT; public char[] unquoteBuf = new char[unstructure_unquoteBufSize]; final public HashMap handlers = new HashMap(); public Unstructurer() { try { Class mc = (Class) (callF(classFinder, "
")); if (mc != null) mcDollar = mc.getName() + "$"; } catch (Throwable __e) { pcallFail(__e); } makeHandlers(); } public void makeHandlers() { unstructure_Handler h; handlers.put("bigint", (unstructure_Handler) (refID, tokIndex, out) -> out.set(parseBigInt())); handlers.put("d", (unstructure_Handler) (refID, tokIndex, out) -> out.set(parseDouble())); handlers.put("fl", (unstructure_Handler) (refID, tokIndex, out) -> out.set(parseFloat())); handlers.put("sh", (unstructure_Handler) (refID, tokIndex, out) -> { consume(); String t = tpp(); if (t.equals("-")) { t = tpp(); out.set((short) (-parseInt(t))); return; } out.set((short) parseInt(t)); }); handlers.put("enum", (unstructure_Handler) (refID, tokIndex, out) -> { consume(); String t = tpp(); assertTrue(isJavaIdentifier(t)); String fullClassName = mcDollar + t; Class _c = findAClass(fullClassName); if (_c == null) throw fail("Enum class not found: " + fullClassName); int ordinal = parseInt(tpp()); out.set(_c.getEnumConstants()[ordinal]); }); handlers.put("false", h = (unstructure_Handler) (refID, tokIndex, out) -> { consume(); out.set(false); }); handlers.put("f", h); handlers.put("true", h = (unstructure_Handler) (refID, tokIndex, out) -> { consume(); out.set(true); }); handlers.put("t", h); handlers.put("{", (unstructure_Handler) (refID, tokIndex, out) -> parseMap(out)); handlers.put("[", (unstructure_Handler) (refID, tokIndex, out) -> { ArrayList l = new ArrayList(); if (refID >= 0) refs.put(refID, l); this.parseList(l, out); }); handlers.put("bitset", (unstructure_Handler) (refID, tokIndex, out) -> parseBitSet(out)); handlers.put("array", h = (unstructure_Handler) (refID, tokIndex, out) -> parseArray(out)); handlers.put("intarray", h); handlers.put("dblarray", h); handlers.put("floatarray", h); handlers.put("shortarray", (unstructure_Handler) (refID, tokIndex, out) -> { consume(); String hex = trivialUnquote(tpp()); out.set(shortArrayFromBytes(hexToBytes(hex))); }); handlers.put("longarray", (unstructure_Handler) (refID, tokIndex, out) -> { consume(); String hex = trivialUnquote(tpp()); out.set(longArrayFromBytes(hexToBytes(hex))); }); } public Class findAClass(String fullClassName) { try { return classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName); } catch (Throwable __e) { return null; } } public String unquote(String s) { return unquoteUsingCharArray(s, unquoteBuf); } public String t() { return curT; } public String tpp() { String t = curT; consume(); return t; } public void parse(final unstructure_Receiver out) { String t = t(); int refID; if (structure_isMarker(t, 0, l(t))) { refID = parseInt(t.substring(1)); consume(); } else refID = -1; final int tokIndex = i; parse_inner(refID, tokIndex, new unstructure_Receiver() { public void set(Object o) { if (refID >= 0) refs.put(refID, o); if (o != null) tokrefs.put(tokIndex, o); out.set(o); } }); } public void parse_inner(int refID, int tokIndex, unstructure_Receiver out) { String t = t(); Object handler = handlers.get(t); if (handler instanceof unstructure_Handler) { ((unstructure_Handler) handler).parse(refID, tokIndex, out); return; } Class c = (Class) handler; if (c == null) { if (t.startsWith("\"")) { String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan); out.set(s); return; } if (t.startsWith("'")) { out.set(unquoteCharacter(tpp())); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("File")) { consume(); File f = new File(unquote(tpp())); out.set(f); return; } if (t.startsWith("r") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = refs.get(ref); if (o == null) warn("unsatisfied back reference " + ref); out.set(o); return; } if (t.startsWith("t") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = tokrefs.get(ref); if (o == null) warn("unsatisfied token reference " + ref + " at " + tokIndex); out.set(o); return; } if (t.equals("hashset")) { parseHashSet(out); return; } if (t.equals("lhs")) { parseLinkedHashSet(out); return; } if (t.equals("treeset")) { parseTreeSet(out); return; } if (t.equals("ciset")) { parseCISet(out); return; } if (eqOneOf(t, "hashmap", "hm")) { consume(); parseMap(new HashMap(), out); return; } if (t.equals("lhm")) { consume(); parseMap(new LinkedHashMap(), out); return; } if (t.equals("tm")) { consume(); parseMap(new TreeMap(), out); return; } if (t.equals("cimap")) { consume(); parseMap(ciMap(), out); return; } if (t.equals("ll")) { consume(); LinkedList l = new LinkedList(); if (refID >= 0) refs.put(refID, l); { parseList(l, out); return; } } if (t.equals("syncLL")) { consume(); { parseList(synchroLinkedList(), out); return; } } if (t.equals("sync")) { consume(); { parse(new unstructure_Receiver() { public void set(Object value) { if (value instanceof Map) { if (value instanceof NavigableMap) { out.set(synchroNavigableMap((NavigableMap) value)); return; } if (value instanceof SortedMap) { out.set(synchroSortedMap((SortedMap) value)); return; } { out.set(synchroMap((Map) value)); return; } } else { out.set(synchroList((List) value)); return; } } }); return; } } if (t.equals("ba")) { consume(); String hex = trivialUnquote(tpp()); out.set(hexToBytes(hex)); return; } if (t.equals("boolarray")) { consume(); int n = parseInt(tpp()); String hex = trivialUnquote(tpp()); out.set(boolArrayFromBytes(hexToBytes(hex), n)); return; } if (t.equals("class")) { out.set(parseClass()); return; } if (t.equals("l")) { parseLisp(out); return; } if (t.equals("null")) { consume(); out.set(null); return; } if (eq(t, "c")) { consume(); t = t(); assertTrue(isJavaIdentifier(t)); concepts.add(t); } if (eq(t, "cu")) { consume(); t = tpp(); assertTrue(isJavaIdentifier(t)); String fullClassName = mcDollar + t; Class _c = findAClass(fullClassName); if (_c == null) throw fail("Class not found: " + fullClassName); parse(new unstructure_Receiver() { public void set(Object value) { out.set(call(_c, "_deserialize", value)); } }); return; } } if (eq(t, "j")) { consume(); out.set(parseJava()); return; } if (eq(t, "bc")) { consume(); String c1 = tpp(); String c2 = tpp(); baseClassMap.put(c1, c2); { parse_inner(refID, i, out); return; } } if (c == null && !isJavaIdentifier(t)) throw new RuntimeException("Unknown token " + (i + 1) + ": " + quote(t)); consume(); String className, fullClassName; if (eq(t(), ".")) { className = t; do { consume(); className += "." + assertIdentifier(tpp()); } while (eq(t(), ".")); fullClassName = className; } else { className = t; fullClassName = mcDollar + t; } if (c == null && !allDynamic) { c = findAClass(fullClassName); handlers.put(className, c); } if (c == null && !allDynamic) { Set seen = new HashSet(); String parent = className; while (true) { String baseName = baseClassMap.get(parent); if (baseName == null) break; if (!seen.add(baseName)) throw fail("Cyclic superclass info: " + baseName); c = findAClass(mcDollar + baseName); if (c == null) print("Base class " + baseName + " of " + parent + " doesn't exist either"); else if (isAbstract(c)) print("Can't instantiate abstract base class: " + c); else { printVars_str("Reverting to base class", "className", className, "baseName", baseName, "c", c); handlers.put(className, c); break; } parent = baseName; } } boolean hasBracket = eq(t(), "("); if (hasBracket) consume(); boolean hasOuter = hasBracket && startsWith(t(), "this$"); DynamicObject dO = null; Object o = null; final String thingName = t; try { if (c != null) { if (hasOuter) try { Constructor ctor = innerClassConstructors.get(c); if (ctor == null) innerClassConstructors.put(c, ctor = nuStubInnerObject_findConstructor(c, classFinder)); o = ctor.newInstance(new Object[] { null }); } catch (Exception e) { print("Error deserializing " + c + ": " + e); o = nuEmptyObject(c); } else o = nuEmptyObject(c); if (o instanceof DynamicObject) dO = (DynamicObject) o; } else { if (concepts.contains(t) && (c = findAClass(mcDollar + "Concept")) != null) o = dO = (DynamicObject) nuEmptyObject(c); else dO = new DynamicObject(); dO.className = className; } } catch (Throwable __e) { pcallFail(__e); } if (o == null && dO == null) dO = new DynamicObject(); if (refID >= 0) refs.put(refID, o != null ? o : dO); tokrefs.put(tokIndex, o != null ? o : dO); HashMap fields = new HashMap(); Object _o = o; DynamicObject _dO = dO; if (hasBracket) { stack.add(new Runnable() { public void run() { try { if (eq(t(), ",")) consume(); if (eq(t(), ")")) { consume(")"); objRead(_o, _dO, fields, hasOuter); out.set(_o != null ? _o : _dO); } else { final String key = unquote(tpp()); String t = tpp(); if (!eq(t, "=")) throw fail("= expected, got " + t + " after " + quote(key) + " in object " + thingName); stack.add(this); parse(new unstructure_Receiver() { public void set(Object value) { fields.put(key, value); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef unstructure_debug\r\n print(\"in object values, token: \" + t());\r..."; } }); } else { objRead(o, dO, fields, hasOuter); out.set(o != null ? o : dO); } } public void objRead(Object o, DynamicObject dO, Map fields, boolean hasOuter) { Object outer = fields.get("this$0"); if (outer != null) fields.put("this$1", outer); else { outer = fields.get("this$1"); if (outer != null) fields.put("this$0", outer); } if (o != null) { if (dO != null) { setOptAllDyn_pcall(dO, fields); } else { setOptAll_pcall(o, fields); } if (hasOuter) fixOuterRefs(o); } else for (Map.Entry e : fields.entrySet()) setDynObjectValue(dO, intern(e.getKey()), e.getValue()); if (o != null) pcallOpt_noArgs(o, "_doneLoading"); } public void parseSet(final Set set, final unstructure_Receiver out) { this.parseList(new ArrayList(), new unstructure_Receiver() { public void set(Object o) { set.addAll((List) o); out.set(set); } }); } public void parseLisp(final unstructure_Receiver out) { throw fail("class Lisp not included"); } public void parseBitSet(final unstructure_Receiver out) { consume("bitset"); consume("{"); final BitSet bs = new BitSet(); stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); out.set(bs); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { bs.set((Integer) o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n } els..."; } }); } public void parseList(final List list, final unstructure_Receiver out) { tokrefs.put(i, list); consume("["); stack.add(new Runnable() { public void run() { try { if (eq(t(), "]")) { consume(); out.set(list); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"]\")) {\r\n consume();\r\n ifdef unstructure_debug\r\n ..."; } }); } public void parseArray(unstructure_Receiver out) { String _type = tpp(); int dims; if (eq(t(), "S")) { _type = "S"; consume(); } if (eq(t(), "/")) { consume(); dims = parseInt(tpp()); } else dims = 1; consume("{"); List list = new ArrayList(); String type = _type; stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); if (dims > 1) { Class atype; if (type.equals("intarray")) atype = int.class; else if (type.equals("S")) atype = String.class; else throw todo("multi-dimensional arrays of other types"); out.set(list.toArray((Object[]) newMultiDimensionalOuterArray(atype, dims, l(list)))); } else out.set(type.equals("intarray") ? toIntArray(list) : type.equals("dblarray") ? toDoubleArray(list) : type.equals("floatarray") ? toFloatArray(list) : type.equals("S") ? toStringArray(list) : list.toArray()); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n if (dims > 1) {\r\n ..."; } }); } public Object parseClass() { consume("class"); consume("("); String name = unquote(tpp()); consume(")"); Class c = allDynamic ? null : findAClass(name); if (c != null) return c; DynamicObject dO = new DynamicObject(); dO.className = "java.lang.Class"; name = dropPrefix(mcDollar, name); dynamicObject_setRawFieldValue(dO, "name", name); return dO; } public Object parseBigInt() { consume("bigint"); consume("("); String val = tpp(); if (eq(val, "-")) val = "-" + tpp(); consume(")"); return new BigInteger(val); } public Object parseDouble() { consume("d"); consume("("); String val = unquote(tpp()); consume(")"); return Double.parseDouble(val); } public Object parseFloat() { consume("fl"); String val; if (eq(t(), "(")) { consume("("); val = unquote(tpp()); consume(")"); } else { val = unquote(tpp()); } return Float.parseFloat(val); } public void parseHashSet(unstructure_Receiver out) { consume("hashset"); parseSet(new HashSet(), out); } public void parseLinkedHashSet(unstructure_Receiver out) { consume("lhs"); parseSet(new LinkedHashSet(), out); } public void parseTreeSet(unstructure_Receiver out) { consume("treeset"); parseSet(new TreeSet(), out); } public void parseCISet(unstructure_Receiver out) { consume("ciset"); parseSet(ciSet(), out); } public void parseMap(unstructure_Receiver out) { parseMap(new TreeMap(), out); } public Object parseJava() { String j = unquote(tpp()); Matches m = new Matches(); if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m)) return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2))); else { warn("Unknown Java object: " + j); return null; } } public void parseMap(final Map map, final unstructure_Receiver out) { consume("{"); stack.add(new Runnable() { public boolean v = false; public Object key; public void run() { if (v) { v = false; stack.add(this); if (!eq(tpp(), "=")) throw fail("= expected, got " + t() + " in map of size " + l(map)); parse(new unstructure_Receiver() { public void set(Object value) { map.put(key, value); if (eq(t(), ",")) consume(); } }); } else { if (eq(t(), "}")) { consume("}"); out.set(map); } else { v = true; stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { key = o; } }); } } } }); } public void consume() { curT = tok.next(); ++i; } public void consume(String s) { if (!eq(t(), s)) { throw fail(quote(s) + " expected, got " + quote(t())); } consume(); } public void parse_initial(unstructure_Receiver out) { consume(); parse(out); while (nempty(stack)) popLast(stack).run(); } } static public Object unstructure_tok(Producer tok, boolean allDynamic, Object classFinder) { boolean debug = unstructure_debug; AutoCloseable __1 = tempSetTL(dynamicObjectIsLoading_threadLocal(), true); try { Var v = new Var(); var unstructurer = new Unstructurer().tok(tok).allDynamic(allDynamic).classFinder(classFinder); unstructurer.parse_initial(new unstructure_Receiver() { public void set(Object o) { v.set(o); } }); unstructure_tokrefs = unstructurer.tokrefs.size(); return v.get(); } finally { _close(__1); } } static public boolean unstructure_debug = false; static public void fixOuterRefs(Object o) { try { if (o == null) return; Field[] l = thisDollarOneFields(o.getClass()); if (l.length <= 1) return; Object father = null; for (Field f : l) { father = f.get(o); if (father != null) break; } if (father == null) return; for (Field f : l) f.set(o, father); } catch (Exception __e) { throw rethrow(__e); } } static public Class boxedToPrimitiveType(Class type) { if (type == Boolean.class) return boolean.class; if (type == Integer.class) return int.class; if (type == Long.class) return long.class; if (type == Float.class) return float.class; if (type == Short.class) return short.class; if (type == Character.class) return char.class; if (type == Byte.class) return byte.class; if (type == Double.class) return double.class; return null; } static public A printIndentedStructIf(boolean b, A a) { if (b) printIndentedStruct(a); return a; } static public A printIndentedStructIf(boolean b, String s, A a) { if (b) printIndentedStruct(s, a); return a; } static public A printIndentedStructIf(boolean b, String s, IF0 makeStructureData, A a) { if (b) if (makeStructureData != null) printIndentedStruct(s, a, makeStructureData.get()); else printIndentedStruct(s, a); return a; } static public A print_tabToSingleSpace(A o) { print(tabToSingleSpace(str(o))); return o; } static public BufferedImage cloneClipBufferedImage(BufferedImage src, Rectangle clip) { return cloneBufferedImage(clipBufferedImage(src, clip)); } static public BufferedImage cloneClipBufferedImage(BufferedImage src, Rect r) { return cloneBufferedImage(clipBufferedImage(src, r)); } static public BufferedImage cloneClipBufferedImage(BufferedImage src, int x, int y, int w, int h) { return cloneBufferedImage(clipBufferedImage(src, x, y, w, h)); } static public List cloneClipBufferedImage(BufferedImage src, Iterable rects) { return map(rects, r -> cloneClipBufferedImage(src, r)); } static public FontMetrics fontMetrics(String fontSnippetID, float fontSize) { return fontMetrics(loadFont_cached(fontSnippetID, fontSize)); } static public FontMetrics fontMetrics(Font font) { BufferedImage dummyImg = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics g = antiAliasGraphics(dummyImg); g.setFont(font); return g.getFontMetrics(); } static public FontMetrics fontMetrics(Graphics g) { return g == null ? null : g.getFontMetrics(); } static public void addOrRemoveComponent(boolean add, Container a, Component b) { if (a == null || b == null) return; if (add) { swing(() -> { if (b.getParent() != a) addAndValidate(a, b); }); } else removeAndValidate(a, b); } static public String collapseWord(String s) { if (s == null) return ""; StringBuilder buf = new StringBuilder(); for (int i = 0; i < l(s); i++) if (i == 0 || !charactersEqualIC(s.charAt(i), s.charAt(i - 1))) buf.append(s.charAt(i)); return buf.toString(); } static public AutoCloseable tempAddGlobalMouseListener(IVF1 onEvent) { AWTEventListener l = new AWTEventListener() { public void eventDispatched(AWTEvent evt) { if (evt instanceof MouseEvent) pcallF_typed(onEvent, ((MouseEvent) evt)); } }; Toolkit.getDefaultToolkit().addAWTEventListener(l, AWTEvent.MOUSE_EVENT_MASK); return () -> Toolkit.getDefaultToolkit().removeAWTEventListener(l); } static public Pt randomPoint(int w, int h) { return new Pt(random(w), random(h)); } static public Pt randomPoint(RGBImage img) { return randomPoint(img.w(), img.h()); } static public void printVarsInMultipleLines(Object... params) { print(renderVarsInMultipleLines(params)); } static public List toDoublePts(List l) { return map(__126 -> toDoublePt(__126), l); } static public List toDoublePts(double... coords) { int n = l(coords) / 2; List l = emptyList(n); for (int i = 0; i < n; i++) l.add(doublePt(coords[i * 2], coords[i * 2 + 1])); return l; } static public void drawRect(BufferedImage image, int x, int y, int w, int h, Color color) { Graphics2D g = imageGraphics(image); drawRect(g, x, y, w, h, color); g.dispose(); } static public void drawRect(Graphics2D g, int x, int y, int w, int h, Color color) { g.setColor(color); g.drawRect(x, y, w, h); } static public void drawRect(Graphics2D g, Color color, Rect r) { drawRect(g, r, color); } static public void drawRect(Graphics2D g, Rect r, Color color) { g.setColor(color); g.drawRect(r.x, r.y, r.w, r.h); } static public void drawRect(Graphics2D g, Rect r) { g.drawRect(r.x, r.y, r.w, r.h); } static public void drawRect(int x, int y, int w, int h, Color color) { drawRect(currentImage(), x, y, w, h, color); } static public void drawRect(Rect r, Color color) { drawRect(r.x, r.y, r.w, r.h, color); } static public void drawRect(BufferedImage image, Rect r, Color c) { if (r != null) drawRect(image, r.x, r.y, r.w, r.h, c); } static public String replacePrefixes(String s, String... replacements) { for (Pair p : listToPairs(replacements)) s = replacePrefix(p.a, p.b, s); return s; } static public String lookupStandardFunctionOrClassNameIC(String name) { if (isStandardFunction(name) || isStandardClass(name)) return name; { var __1 = resolveKeyIC(stdFunctions_cached(), name); if (__1 != null) return __1; } return resolveKeyIC(stdClasses_cached(), name); } static public String unquote_relaxedMLS(String s) { if (s == null) return null; if (startsWith(s, '[')) { int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; if (i < s.length() && s.charAt(i) == '[') { String m = s.substring(1, i); int n = s.length(); if (s.endsWith("]" + m + "]")) n -= i + 1; return s.substring(i + 1, n); } } return unquoteSingleOrDoubleQuotes(s); } static public double intAverage(Collection l) { return doubleRatio(intSumAsLong(l), l(l)); } static public BufferedImage blurFilterBufferedImage(BufferedImage img) { return blurFilterBufferedImage(1, img); } static public BufferedImage blurFilterBufferedImage(int hradius, BufferedImage img) { return blurFilterBufferedImage(hradius, hradius, img); } static public BufferedImage blurFilterBufferedImage(int hradius, int vradius, BufferedImage img) { if (hradius <= 0 || vradius <= 0) return img; return new BoxBlurFilter(hradius, vradius).get(img); } static public JWindow makeUnimportantWindow(final Component c) { return swing(new F0() { public JWindow get() { try { Map map = (Map) (vm_generalMap_get("unimportant windows")); if (map == null) vm_generalMap_put("unimportant windows", map = (Map) callJavaX("newWeakHashMap")); JWindow w = makeWindow(c); map.put(w, true); return w; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Map map = cast vm_generalMap_get(\"unimportant windows\");\r\n if (map == null..."; } }); } static public A[] singlePlusArray(A a, A[] l) { A[] out = newObjectArrayOfSameType(l, l(l) + 1); out[0] = a; arraycopy(l, 0, out, 1, l(l)); return out; } static public BufferedImage transparentImage(Dimension size) { return transparentImage(toWidthAndHeight(size)); } static public BufferedImage transparentImage(int size_w, int size_h) { return transparentImage(widthAndHeight(size_w, size_h)); } static public BufferedImage transparentImage(WidthAndHeight size) { return transparentBufferedImage(size); } static public void drawPixels(BufferedImage img, Iterable points, Color color) { if (img == null) return; var g = createGraphics(img); drawPixels(g, points, color); } static public void drawPixels(Graphics2D g, Iterable points, Color color) { for (var p : unnullForIteration(points)) drawPixel(g, p, color); } static public List parseDoublesOpt(Iterable l) { return map(__127 -> parseDoubleOpt(__127), l); } static public AutoCloseable tempOnFrameClose(JFrame f, Runnable r) { if (f == null || r == null) return null; return swing(() -> { var listener = new WindowAdapter() { public void windowClosing(WindowEvent e) { try { r.run(); } catch (Throwable __e) { messageBox(__e); } } }; f.addWindowListener(listener); return () -> { swing(() -> { f.removeWindowListener(listener); }); }; }); } static public String lastIdentifier(List l) { for (int i = l(l) - 1; i >= 0; i--) { String t = l.get(i); if (isIdentifier(t)) return t; } return null; } static public String regexpQuote_optimized(String s) { return regexpLiteralNeedsQuoting(s) ? Pattern.quote(s) : s; } static public byte[] byteListToArray(List l) { if (l == null) return null; int n = l(l), i = 0; byte[] a = new byte[n]; for (var x : l) a[i++] = x; return a; } static public TimeZone timeZone(String name) { return TimeZone.getTimeZone(name); } static public List diff(Collection a, Collection b) { Set set = asSet(b); List l = new ArrayList(); for (String s : a) if (!set.contains(s)) l.add(s); return l; } static public String concat(Object... l) { return concatStrings(l); } static public String concat(Iterable l) { return concatStrings(l); } static public long printN2(String s, long n) { print(s, n2(n)); return n; } static public long printN2(long n) { print(n2(n)); return n; } static public BufferedImage posterizeBufferedImage(int brightnessLevels, MakesBufferedImage img) { return posterizeBufferedImage(brightnessLevels, toBufferedImage(img)); } static public BufferedImage posterizeBufferedImage(int brightnessLevels, BufferedImage img) { PosterizeBufferedImage x = new PosterizeBufferedImage(brightnessLevels, img); return x.get(); } static public BufferedImage posterizeBufferedImage(IPosterizer posterizer, MakesBufferedImage img) { return posterizeBufferedImage(posterizer, toBufferedImage(img)); } static public BufferedImage posterizeBufferedImage(IPosterizer posterizer, BufferedImage img) { PosterizeBufferedImage x = new PosterizeBufferedImage(posterizer, img); return x.get(); } static public BufferedImage posterizeBufferedImage(MakesBufferedImage img, IPosterizer posterizer) { return posterizeBufferedImage(toBufferedImage(img), posterizer); } static public BufferedImage posterizeBufferedImage(BufferedImage img, IPosterizer posterizer) { return posterizeBufferedImage(posterizer, img); } static public A randomKey(Map map) { return empty(map) ? null : random(keys(map)); } static public BufferedImageWithMeta imageFromPixels(int[] pixels, int w) { return imageFromPixels(pixels, w, pixels.length / w); } static public BufferedImageWithMeta imageFromPixels(int[] pixels, int w, int h) { return intArrayToBufferedImage(pixels, w, h); } static public BufferedImageWithMeta imageFromPixels(int w, int... pixels) { return intArrayToBufferedImage(w, pixels); } static public List shallowCloneElements(List l) { return lmap(__128 -> shallowClone(__128), l); } static public JTextField setTextAndSelectAll(final JTextField tf, final String text) { if (tf != null) { swing(() -> { tf.setText(text); tf.selectAll(); }); } return tf; } static public AutoCloseable flagAsAutoCloseable(Flag flag) { return flag == null ? null : new AutoCloseable() { public String toString() { return "flag.raise();"; } public void close() throws Exception { flag.raise(); } }; } static public Pair textAndCaretPosition(final JTextComponent tc) { return swing(new F0>() { public Pair get() { try { return pair(getText(tc), getCaretPosition(tc)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return pair(getText(tc), getCaretPosition(tc));"; } }); } static public BufferedOutputStream bufferedFileOutputStream(File f) { try { return bufferedOutputStream(newFileOutputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } static public BWImage regionToBWImage(IImageRegion region) { return region == null ? null : new RegionToBWImage(region).get(); } static public String domain() { return domainName(); } static public String domain(String url) { return hostNameFromURL(url); } static public ListIterator listIterator(List l) { return l == null ? emptyListIterator() : l.listIterator(); } static public BigInteger factorial_bigint(int i) { BigInteger n = bigint(1); while (i > 1) n = mul(n, i--); return n; } static public JSplitPane jvsplitSections(String titleN, Component n, String titleS, Component s) { return jvsplitSections(titleN, n, titleS, s, 0.5); } static public JSplitPane jvsplitSections(String titleN, Component n, String titleS, Component s, double splitPoint) { return jvsplit_minZero(jCenteredSection(titleN, n), jCenteredSection(titleS, s), splitPoint); } static public int blendRGBInts(double bish, int a, int b) { return blendRGBInts(a, b, bish); } static public int blendRGBInts(int a, int b, double bish) { bish = normalizeTo0to1(bish); return rgbInt(blend(rgbRed(a), rgbRed(b), bish), blend(rgbGreen(a), rgbGreen(b), bish), blend(rgbBlue(a), rgbBlue(b), bish)); } static public float average(float a, float b) { return (a + b) / 2; } static public double average(double a, double b) { return (a + b) / 2; } static public List biggestSSIsFirst(Collection l) { return sortByCalculatedFieldDesc(l, __1 -> __1.numberOfPixels()); } static public LineThroughPoint perpendicularBisector(IDoublePt a, IDoublePt b) { DoublePt midpoint = doublePt((a.x_double() + b.x_double()) / 2, (a.y_double() + b.y_double()) / 2); double angle = atan2(b.y_double() - a.y_double(), a.x_double() - b.x_double()); return new LineThroughPoint(midpoint, angle); } static public void drawPixel(BufferedImage image, int x, int y, Color color) { drawPixel(imageGraphics(image), x, y, color); } static public void drawPixel(Graphics2D g, int x, int y, Color color) { g.setColor(color); g.drawLine(x, y, x, y); } static public void drawPixel(BufferedImage image, Pt p, Color color) { drawPixel(image, p.x, p.y, color); } static public void drawPixel(Graphics2D g, Pt p, Color color) { drawPixel(g, p.x, p.y, color); } static public List> allPermutations(List l) { List> out = new ArrayList(); allPermutations_impl(cloneList(l), l(l), out); return out; } static public void allPermutations_impl(List l, int n, List> out) { if (n <= 1) { ping(); out.add(cloneList(l)); } else for (int i = 0; i < n; i++) { allPermutations_impl(l, n - 1, out); swapElements(l, n % 2 == 0 ? i : 0, n - 1); } } static public File ffmpegExecutableIfSet() { return newFile(nullIfEmpty(loadTextFileTrim(ffmpegLocationFile()))); } static public MultiSetMap multiSetMap_outerDescTreeMap_innerCompactLinkedHashSet() { return new MultiSetMap(descTreeMap()) { public Set _makeEmptySet() { return new CompactLinkedHashSet(); } }; } static public List filteredChromeBookmarks() { return filteredChromeBookmarks(getChromeBookmarks()); } static public List filteredChromeBookmarks(List bm) { FreeOfLocalBlockedKeyword check = new FreeOfLocalBlockedKeyword(); var urlCheck = domainPredicateToURLPredicate(check); bm = filter(x -> urlCheck.get(x.url), bm); return sortedByDesc(x -> x.dateAdded, bm); } static public long ymdToTimestamp(int year, int month, int day) { return ymdToTimestamp(year, month, day, defaultTimeZone()); } static public long ymdToTimestamp(int year, int month, int day, TimeZone tz) { try { return simpleDateFormat("y/M/d", tz).parse(year + "/" + month + "/" + day).getTime(); } catch (Exception __e) { throw rethrow(__e); } } static public List> listToPairs(List l) { return listToPairs((Iterable) l); } static public List> listToPairs(A[] l) { return listToPairs(asList(l)); } static public List> listToPairs(Iterable l) { List> out = new ArrayList(); Iterator it = iterator(l); while (it.hasNext()) { ping(); A a = it.next(); if (!it.hasNext()) break; A b = it.next(); addPair(out, a, b); } return out; } static public Pt pointOnCircle(Pt center, double radius, double angle) { return pt(iround(center.x + sin(angle) * radius), iround(center.y - cos(angle) * radius)); } static public String snippetURL(String id) { return snippetLink(id); } static public Timestamp lastConceptChange(Concepts cc) { if (cc == null) return null; Concept c = highestConceptByField(cc, Concept.class, conceptField_modified()); return c == null ? null : toTimestamp(c._modified); } static public Color hi15ToColor_clean(short hi15) { return intToColorOpaque(hi15ToRGBInt_clean(hi15)); } static public Map mapItemsToListIndex(List l) { HashMap map = new HashMap(); for (int i = 0; i < l(l); i++) map.put(l.get(i), i); return map; } static public boolean trueBecause(Object something) { return true; } static public A[] itemPlusArray(A a, A[] l) { return singlePlusArray(a, l); } static public Set createOrAddToSet(Set set, A a) { if (set == null) set = new HashSet(); set.add(a); return set; } static public Set createOrAddToSet(Set set, A... l) { for (A a : unnullForIteration(l)) set = createOrAddToSet(set, a); return set; } static public CachedPosterizer cachePosterizer(IPosterizer posterizer) { if (posterizer == null) return null; if (posterizer instanceof CachedPosterizer) return ((CachedPosterizer) posterizer); return new CachedPosterizer(posterizer); } static public boolean same(Object a, Object b) { return a == b; } static public List parseDoubles(Iterable l) { return map(__129 -> parseDouble(__129), l); } static public boolean clipboardContainsImage() { try { Transferable t = rawClipboardContents(); if (t == null) return false; if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) return true; List l = (List) (getTransferData(t, DataFlavor.javaFileListFlavor)); if (isImageFile(first(l))) return true; String text = getTextFromClipboard(); return isImageMimeType(dataURLMimeType(text)); } catch (Throwable __e) { return false; } } static public double distancePointToLineSegment(Pt a, Pt b, Pt p) { int x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y, x3 = p.x, y3 = p.y; float px = x2 - x1; float py = y2 - y1; float temp = (px * px) + (py * py); float u = ((x3 - x1) * px + (y3 - y1) * py) / (temp); if (u > 1) u = 1; else if (u < 0) u = 0; float x = x1 + u * px; float y = y1 + u * py; float dx = x - x3; float dy = y - y3; return sqrt(dx * dx + dy * dy); } static public List lazyMap_noSave(IF1 f, List l) { return new RandomAccessAbstractList() { final public int size = l(l); public int size() { return size; } public B get(int i) { return f.get(l.get(i)); } }; } static public List lazyMap_noSave(List l, IF1 f) { return lazyMap_noSave(f, l); } static public Timestamp unixSecondsToTimestamp(long unixSeconds) { return new Timestamp(unixSeconds * 1000); } static public ButtonGroup jRadioButtons(Collection strings) { return jradiobuttons(strings); } static public ButtonGroup jRadioButtons(String... strings) { return jradiobuttons(strings); } static public String codePoint(int codePoint) { return codePointToString(codePoint); } static public JSlider jLiveValueSlider_double_bothWays(double min, double max, IVarWithNotify lv) { AtomicInteger changing = new AtomicInteger(); JSlider slider = liveSliderZeroToOne((float) ((unnull(lv.get()) - min) / (max - min)), new VF1() { public void get(Float f) { try { if (changing.get() == 0) lv.set(min + f * (max - min)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (changing! == 0)\r\n lv.set(min+f*(max-min));"; } }); bindLiveValueListenerToComponent(slider, lv, new Runnable() { public void run() { try { AutoCloseable __1 = tempIncAtomicInt(changing); try { setRelativeSliderValue(slider, (unnull(lv.get()) - min) / (max - min)); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp tempIncAtomicInt(changing);\r\n setRelativeSliderValue(slider, (unnull(..."; } }); return slider; } static public String orCombineRegexps(List regexps) { return join("|", regexps); } static public StringWriter stringWriter() { return new StringWriter(); } static public List spaceTok(String s) { return splitAtSpaceTokenizer(s); } static public String toHexString(byte[] a) { return bytesToHex(a); } static public String toHexString(List a) { return bytesToHex(byteListToArray(a)); } static public BufferedImage renderImageOnBackground(Color bg, BufferedImage img) { if (img == null) return null; BufferedImage canvas = newBufferedImage(img.getWidth(), img.getHeight(), bg); drawImageOnImage(img, canvas); return canvas; } static public BufferedImage renderImageOnBackground(BufferedImage img, Color bg) { return renderImageOnBackground(bg, img); } static public String dropStarPrefix(String s) { return dropPrefix("*", s); } static public String formatDouble2X(double d) { return formatDoubleX(d, 2); } static public int firstInt_regexp(String s) { return parseIntOr0(regexpExtract("\\d+", s)); } static public IterableIterator byteArrayChunksIterator(byte[] l, int chunkSize) { return iteratorFromFunction(new IF0() { public int n = l(l), i; public byte[] get() { if (i >= n) return null; i += chunkSize; return subByteArray(l, i - chunkSize, i); } }); } static public String chromeCmd() { return chromeCmd(false); } static public String chromeCmd(boolean needSpeech) { return platformQuote(isWindows() ? f2s(assertNotNull("chrome.exe not found", windowsFindChromeExe())) : isMac() ? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" : needSpeech ? firstCmdOnPATH_mandatory("google-chrome") : firstCmdOnPATH_mandatory("google-chrome", "chromium-browser")); } static public int generalizedBinarySearch2(List l, IF1 cmp) { return generalizedBinarySearch2(l, 0, l(l), cmp); } static public int generalizedBinarySearch2(List l, int fromIndex, int toIndex, IF1 cmp) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; A midVal = l.get(mid); int c = cmp.get(midVal); if (c < 0) low = mid + 1; else if (c > 0) high = mid - 1; else return mid; } return -(low + 1); } static public long fileModificationTime(File f) { return f == null ? 0 : f.lastModified(); } static public Object newPreciseCall_sentinel(Object o, String method, Object methodNotFoundSentinel, Object... args) { try { if (o == null) return null; boolean staticCall = o instanceof Class; Class c = staticCall ? (Class) o : o.getClass(); Object target = staticCall ? null : o; _MethodCache cache = callOpt_getCache(c); List methods = cache.cache.get(method); Method best = null; int bestScore = Integer.MAX_VALUE; boolean widening = false; if (methods != null) for (Method m : methods) { if (staticCall && !isStaticMethod(m)) continue; int score = methodApplicabilityScore_withPrimitiveWidening(m, args); if (score == 0) return invokeMethod(m, target, args); if (abs(score) < bestScore) { best = m; bestScore = abs(score); widening = score < 0; } } if (best != null) if (widening) return invokeMethodWithWidening(best, target, args); else return invokeMethod(best, target, args); return callWithVarargs_sentinel(o, method, methodNotFoundSentinel, args); } catch (Exception __e) { throw rethrow(__e); } } static public List listZipFile(File inZip) { try { ZipFile zipFile = new ZipFile(inZip); try { return listZipFile(zipFile); } finally { zipFile.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public List listZipFile(ZipFile zipFile) { try { List list = new ArrayList(); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) list.add(entry.getName()); } return list; } catch (Exception __e) { throw rethrow(__e); } } static public List listZipFile(String name) { if (isSnippetID(name)) return listZipFile(loadLibrary(name)); return listZipFile(getProgramFile(name)); } static public int rgbGreen(int rgb) { return (rgb >> 8) & 0xFF; } static public BufferedImage mergeBufferedImagesAsSquare(Iterable l) { return mergeBufferedImagesVH(listToSquareishChunks(asList(l))); } static public List sortedByDesc(Collection c, final Object f) { return sortByCalculatedFieldDesc(c, f); } static public List sortedByDesc(Object f, Collection c) { return sortByCalculatedFieldDesc(f, c); } static public List sortedByDesc(Iterable c, IF1 f) { return sortByCalculatedFieldDesc(c, f); } static public List sortedByDesc(IF1 f, Iterable c) { return sortByCalculatedFieldDesc(f, c); } static public int bitCount(BitSet bs) { return bs == null ? 0 : bs.cardinality(); } static public int bitCount(int i) { return Integer.bitCount(i); } static public int bitCount(byte[] array) { if (array == null) return 0; int sum = 0; for (var b : array) sum += bitCount(ubyteToInt(b)); return sum; } static public Image2B resizeImage2B(int w, Image2B img) { return resizeImage2B(w, widthToHeight(w, img), img); } static public Image2B resizeImage2B(int w, int h, Image2B img) { if (img == null) return null; int w1 = img.getWidth(), h1 = img.getHeight(); if (w == w1 && h == h1) return img; byte[] pixels1 = img.pixels, pixels2 = new byte[(w * h + 7) / 8]; int i = 0; double y1 = 0, ystep = doubleRatio(h1, h), xstep = doubleRatio(w1, w); for (int y = 0; y < h; y++) { int i1 = ifloor(y1) * w1; y1 += ystep; double x1 = 0; for (int x = 0; x < w; x++) { int i2 = i1 + ifloor(x1); if ((pixels1[i2 / 8] & (1 << (i2 & 7))) != 0) pixels2[i / 8] |= 1 << (i & 7); x1 += xstep; i++; } } return new Image2B(w, h, pixels2); } static public AutoCloseable tempPut(Map map, A key, B value) { if (map != null) { boolean wasContained = map.containsKey(key); B old = map.put(key, value); return () -> { if (wasContained) map.put(key, old); else map.remove(key); }; } return null; } static public boolean isJPEGFile(File f) { return isJPEG(f); } static public int unsignedShortToInt(short i) { return i & 0x0FFFF; } static public boolean isRoot() { return isRootUser(); } static public String baseDirInZip(File zip) { String prefix = commonPrefix(listZip(zip)); return takeFirst(prefix, indexOf(prefix, '/')); } static public File makeFileNameUnique(File f) { File orig = f; int n = 0; while (f.exists()) f = new File(dirOfFile(orig), orig.getName() + "." + ++n); return f; } static public String insertAt(String s, int i, String a) { return spliceString(s, i, i, a); } static public Object jsonDecode(String text) { return new jsonDecode_Y(text).parse(); } static public class jsonDecode_Y { public String text; public List tok; public boolean useOrderedMaps = false; public int i = 1; public jsonDecode_Y(String text) { this.text = text; tok = jsonTok(text); } transient public IF1 fail; public RuntimeException fail(String msg) { return fail != null ? fail.get(msg) : fail_base(msg); } final public RuntimeException fail_fallback(IF1 _f, String msg) { return _f != null ? _f.get(msg) : fail_base(msg); } public RuntimeException fail_base(String msg) { return utils.fail(msg); } public Object parse() { if (l(tok) == 1) return null; return parseExpr(); } public Object parseExpr() { String t = tok.get(i); if (t.startsWith("\"") || t.startsWith("'")) { String s = unquote(tok.get(i)); i += 2; return s; } if (t.equals("{")) return parseMap(); if (t.equals("[")) return this.parseList(); if (t.equals("null")) { i += 2; return null; } if (t.equals("false")) { i += 2; return false; } if (t.equals("true")) { i += 2; return true; } boolean minus = false; if (t.equals("-")) { minus = true; i += 2; t = get(tok, i); } if (isInteger(t)) { int j = i; i += 2; if (eqOneOf(get(tok, i), ".", "e", "E")) { while (isInteger(get(tok, i)) || eqOneOf(get(tok, i), ".", "e", "E", "-")) i += 2; double d = parseDouble(joinSubList(tok, j, i - 1)); if (minus) d = -d; return d; } else { long l = parseLong(t); return boxedIntOrLong(minus ? -l : l); } } throw fail("Unknown token " + (i + 1) + ": " + t + ": " + text); } public Object parseList() { consume("["); List list = new ArrayList(); while (!tok.get(i).equals("]")) { list.add(parseExpr()); if (tok.get(i).equals(",")) i += 2; } consume("]"); return list; } public Object parseMap() { consume("{"); Map map = useOrderedMaps ? new LinkedHashMap() : new TreeMap(); while (!tok.get(i).equals("}")) { String key = unquote(tok.get(i)); i += 2; consume(":"); Object value = parseExpr(); map.put(key, value); if (tok.get(i).equals(",")) i += 2; } consume("}"); return map; } public void consume(String s) { if (!tok.get(i).equals(s)) { String prevToken = i - 2 >= 0 ? tok.get(i - 2) : ""; String nextTokens = join(tok.subList(i, Math.min(i + 4, tok.size()))); throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")"); } i += 2; } } static public String renderElapsedSecondsPleasantly(double seconds) { if (seconds >= 1) return formatDouble(seconds, 3) + " s"; double ms = seconds * 1000; if (ms >= 1) return formatDouble(ms, 3) + " ms"; double us = ms * 1000; if (us >= 1) return formatDouble(us, 3) + " µs"; double ns = us * 1000; return formatDouble(ns, 3) + " ns"; } static public String renderElapsedSecondsPleasantly(Duration d) { return d == null ? null : renderElapsedSecondsPleasantly(nanosToSeconds(d.toNanos())); } static public AutoCloseable tempIncAtomicInt(AtomicInteger v) { if (v == null) return null; incAtomicInt(v); return new AutoCloseable() { public String toString() { return "decAtomicInt(v);"; } public void close() throws Exception { decAtomicInt(v); } }; } static public void setConsoleInput(String text) { consoleSetInput(text); } static public byte[] stringToHuffmanBytes(String s) { return new HuffmanByteArray(toUtf8(s)).toByteArray(); } static public String pad(Object s, int l) { return pad(s, l, ' '); } static public String pad(Object s, int l, char c) { String _s = str(s); if (lengthOfString(_s) >= l) return _s; return rep(c, l - lengthOfString(_s)) + _s; } static public String pad(int l, Object s) { return pad(s, l); } static public int[] iroundAll(double[] a, int start, int end) { return iroundDoubleArray(a, start, end); } static public int[] iroundAll(double[] a) { return iroundDoubleArray(a); } static public Image2B iBinaryImageToImage2B(IBinaryImage img) { if (img == null) return null; if (img instanceof Image2B) return ((Image2B) img); int w = img.getWidth(), h = img.getHeight(); byte[] pixels = new byte[(w * h + 7) / 8]; int i = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { if (img.getBoolPixel(x, y)) pixels[i / 8] |= 1 << (i & 7); i++; } return new Image2B(w, h, pixels); } static public byte[] intArrayToBytes_littleEndian(int[] a) { byte[] b = new byte[a.length * 4]; for (int i = 0; i < a.length; i++) intToBytes_inArray_littleEndian(a[i], b, i * 4); return b; } static public String platformQuoteArgs(Iterable args) { return joinWithSpace(map(__130 -> platformQuoteOpt(__130), args)); } static public List mergeNeighboringRects(List boxes, int maxDistance) { while (true) { ping(); boolean change = false; for (var box1 : boxes) { for (var box2 : boxes) { if (box1 == box2) continue; if (rectDistance(box1, box2) <= maxDistance) { copyRect(rectUnion(box1, box2), box1); box2.w = 0; box2.h = 0; change = true; } ; } } if (!change) break; boxes = filter(boxes, b -> nempty(b)); } return boxes; } static public String shortenToMaxLinesAndChars(String s, int maxLines, int maxChars) { s = shorten(s, maxChars); List lines = lines(s); if (l(lines) <= maxLines) return s; return lines(takeFirst(maxLines, lines)) + "..."; } static public List wrapArrayAsImmutableList(Object array) { if (array == null) return null; if (array instanceof Object[]) return wrapObjectArrayAsImmutableList((Object[]) array); else return wrapPrimitiveArrayAsImmutableList(array); } static public String nlCombine_rtrim(Object... l) { return rtrim(nlCombine(l)); } static public RGB randomColor() { return new RGB(random(), random(), random()); } static public List litsynclist(A... a) { List l = syncList(); if (a != null) for (A x : a) l.add(x); return l; } static public Range intersectRanges(Range a, Range b) { float min = max(a.min, b.min); float max = min(a.max, b.max); return min <= max ? new Range(min, max) : null; } static public DoubleRange intersectRanges(DoubleRange a, DoubleRange b) { return intersectDoubleRanges(a, b); } static public double preciseCenter(IntRange r) { return (r.start + r.end) / 2.0; } static public List> parseCSV_unquote(String csv) { List lines = toLines(csv); List> l = new ArrayList(); if (nempty(lines)) { List fields = tok_splitAtComma_unquote(first(lines)); for (String s : dropFirst(lines)) { Map line = litorderedmap(); List data = tok_splitAtComma_unquote(s); for (int i = 0; i < l(data); i++) line.put(get(fields, i), data.get(i)); l.add(line); } } return l; } static public int count(Collection l, Object o) { int count = 0; for (Object x : l) if (eq(x, o)) ++count; return count; } static public BufferedImage lenna() { return loadImage2("#1103020"); } static public int threadCount() { return threadMXBean().getThreadCount(); } static public File createTempFile() { return createTempFile("tmp", null); } static public File createTempFile(String prefix, String suffix) { try { prefix = nohup_sanitize(prefix); suffix = nohup_sanitize(suffix); if (shouldKeepTempFiles()) return mkdirsForFile(javaxCachesDir("Temp/" + prefix + "-" + randomID() + "-" + suffix)); File f = File.createTempFile(takeFirst(10, pad(prefix, 3, '-')), suffix); f.deleteOnExit(); return f; } catch (Exception __e) { throw rethrow(__e); } } static public List findAllMaps(Object json) { List l = new ArrayList(); findAllMaps_impl(json, l); return l; } static public void findAllMaps_impl(Object json, List l) { if (json instanceof List) for (Object x : (List) json) findAllMaps_impl(x, l); else if (json instanceof Map) { l.add((Map) json); for (Object x : values((Map) json)) findAllMaps_impl(x, l); } } static public IF0 shouldKeepTempFiles; static public boolean shouldKeepTempFiles() { return shouldKeepTempFiles != null ? shouldKeepTempFiles.get() : shouldKeepTempFiles_base(); } final static public boolean shouldKeepTempFiles_fallback(IF0 _f) { return _f != null ? _f.get() : shouldKeepTempFiles_base(); } static public boolean shouldKeepTempFiles_base() { return false; } static public Map putOrCreateLinkedHashMap(Map map, A key, B value) { if (map == null) map = new LinkedHashMap(); map.put(key, value); return map; } static public int bitAnd(int a, int b) { return a & b; } static public String domainName() { Object session = call(getMainBot(), "getSession"); Map headers = (Map) (call(session, "getHeaders")); String host = (String) (headers.get("host")); if (host == null) return null; return dropFrom(host, ":"); } static public void componentToFront(Component c) { if (c != null) { swing(() -> { var parent = c.getParent(); { if (parent != null) parent.setComponentZOrder(c, 0); } }); } } static public byte[] toUTF8(String s) { return toUtf8(s); } static public List genericStreaks(IIntPred pred, int n) { List out = new ArrayList(); int i = 0; while (i < n) { int j = i; while (j < n && pred.get(j)) ++j; if (j > i) out.add(intRange(i, j)); i = j + 1; } return out; } static public List genericStreaks(int n, IIntPred pred) { return genericStreaks(pred, n); } static public int lDoubleArray(double[] a) { return a == null ? 0 : a.length; } static public String colorToHex(Color c) { return c == null ? null : new RGB(c).getHexString(); } static public IVF1 openPlatformBrowser; static public void openPlatformBrowser(String url) { if (openPlatformBrowser != null) openPlatformBrowser.get(url); else openPlatformBrowser_base(url); } final static public void openPlatformBrowser_fallback(IVF1 _f, String url) { if (_f != null) _f.get(url); else openPlatformBrowser_base(url); } static public void openPlatformBrowser_base(String url) { try { if (isHeadless()) return; print("Opening platform-specific browser on: " + url); Desktop.getDesktop().browse(uri(url)); } catch (Exception __e) { throw rethrow(__e); } } static public void openPlatformBrowser(URL url) { if (url == null) return; openPlatformBrowser(str(url)); } static public String myBestIP() { return first(getMyIPs()); } static public void setRelativeSliderValue(JSlider slider, double value) { if (slider != null) { swing(() -> { slider.setValue(iround(value * slider.getMaximum())); }); } } static public AutoCloseable tempShowLoadingAnimation() { return tempShowLoadingAnimation("Hold on user..."); } static public AutoCloseable tempShowLoadingAnimation(String text) { try { return tempDisposeWindow(showAnimationInTopRightCorner("#1003543", text)); } catch (Throwable __e) { return null; } } static public List tlft_beforeVerticalBar(String text) { return nempties(map(__131 -> beforeVerticalBar(__131), lines(text))); } static public int dir2zip(File inDir, ZipOutputStream outZip, String outPrefix) { try { List files = new ArrayList(); for (File f : inDir.listFiles()) if (f.isFile()) files.add(f); sortFilesByName(files); for (File f : files) { System.out.println("Copying " + f.getName()); outZip.putNextEntry(new ZipEntry(outPrefix + f.getName())); InputStream fin = new FileInputStream(f); copyStream(fin, outZip); fin.close(); } return files.size(); } catch (Exception __e) { throw rethrow(__e); } } static public int dir2zip(File inDir, ZipOutputStream outZip) { return dir2zip(inDir, outZip, ""); } static public int dir2zip(String inDir, ZipOutputStream outZip) { return dir2zip(new File(inDir), outZip, ""); } static public int dir2zip(File inDir, File zip) { return dir2zip(inDir, zip, ""); } static public int dir2zip(File inDir, File zip, String outPrefix) { try { mkdirsForFile(zip); FileOutputStream fout = new FileOutputStream(zip); ZipOutputStream outZip = new ZipOutputStream(fout); try { return dir2zip(inDir, outZip, outPrefix); } finally { outZip.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public String withIdentityHash(Object o, String s) { return o == null ? s : addSuffix(s, "@" + intToHex_flexLength(identityHashCode(o))); } static public String copyTextToClipboard_infoBox(Object _text) { String text = copyTextToClipboard(_text); infoBox("Copied to clipboard (" + n2(l(text), "char") + "): " + shorten(text, 50)); return text; } static public boolean mouseEventIsInBorder(MouseEvent e) { return swing(() -> { var c = optCast(JComponent.class, e.getComponent()); if (c == null) return false; var border = c.getBorder(); if (border == null) return false; Insets insets = border.getBorderInsets(c); int x = e.getX(), y = e.getY(); int w = c.getWidth(), h = c.getHeight(); boolean result = x < insets.left || x >= w - insets.right || y < insets.top || y >= h - insets.bottom; return result; }); } static public void revalidateIncludingFullCenterContainer(Component c) { if (c == null) return; { swing(() -> { c.revalidate(); var parent = c.getParent(); if (parent != null && parent.getLayout() instanceof GridBagLayout) { parent.revalidate(); } }); } } static public Color hi15color(short hi15) { return hi15ToColor_clean(hi15); } static public String trimSubstring(String s, int x) { return trim(substring(s, x)); } static public String trimSubstring(String s, int x, int y) { return trim(substring(s, x, y)); } static public String trimSubstring(String s, IntRange r) { return trim(substring(s, r)); } static public String trimSubstring(int x, String s) { return trimSubstring(s, x); } static public List mapsGet(A key, Iterable> maps) { return map(maps, map -> map == null ? null : map.get(key)); } static public List mapsGet(Iterable> maps, A key) { return mapsGet(key, maps); } static public BufferedImage imageFromClipboard() { return getImageFromClipboard(); } static public Graphics2D getGraphics2D(BufferedImage img) { return imageGraphics(img); } static public int getMinimumWidth(final Component c) { return c == null ? 0 : swing(() -> c.getMinimumSize().width); } static public boolean isTransparent(int rgba) { return (rgba & 0xFF000000) != 0xFF000000; } static public int decAtomicInt(AtomicInteger i) { return i.decrementAndGet(); } static public KeyListener functionKeyListener(int functionKeyNr, Runnable action) { return new KeyAdapter() { public void keyReleased(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_F1 + functionKeyNr - 1 && ke.getModifiers() == 0) { pcallF(action); } } }; } static public void moveCaretToStart(JTextComponent ta) { setCaretPosition(ta, 0); } static public String formatDoubleX2(double d) { return formatDouble2X(d); } static public List allToStrOrNull(Iterable c) { return lmap(__132 -> strOrNull(__132), c); } static public List allToStrOrNull(Object... c) { return lmap(__133 -> strOrNull(__133), c); } static public String readChunkThroughUTF8Processor(UTF8Processor p, InputStream in, byte[] buf) { try { StringBuilder input = new StringBuilder(); int n = in.read(buf); for (int i = 0; i < n; i++) input.append(p.processByte(buf[i])); return input.toString(); } catch (Exception __e) { throw rethrow(__e); } } static public int charToKeyCode(char c) { c = lower(c); assertTrue(c >= 'a' && c <= 'z'); return charDiff(c, 'a') + KeyEvent.VK_A; } static public int rgbRed(int rgb) { return (rgb >> 16) & 0xFF; } static public RangeSlider rangeSliderZeroToOne(DoubleRange defRange, Object f) { return swing(new F0() { public RangeSlider get() { try { int max = 9999; RangeSlider slider = new RangeSlider(0, max); rangeSliderSetZeroToOneDoubleRange(slider, max, defRange); slider.addChangeListener(new ChangeListener() { public DoubleRange lastValue = zeroToOneDoubleRangeFromRangeSlider(max, slider); public void stateChanged(ChangeEvent e) { DoubleRange value = zeroToOneDoubleRangeFromRangeSlider(max, slider); if (neq(value, lastValue)) { lastValue = value; setToolTip(slider, str(value)); pcallF(f, value); } } }); return slider; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "int max = 9999;\r\n RangeSlider slider = new RangeSlider(0, max);\r\n range..."; } }); } static public short rgbToHi15(RGB rgb) { return rgbIntToHi15(rgb.asInt()); } static public short rgbToHi15(Color color) { return rgbIntToHi15(colorToInt(color)); } static public short rgbToHi15(int rgb) { return rgbIntToHi15(rgb); } static public short rgbToHi15(int r, int g, int b) { r >>= 3; g >>= 3; b >>= 3; return (short) ((r << 10) | (g << 5) | b); } static public String bytesToHex_upper(byte[] bytes) { return upper(bytesToHex(bytes)); } static public String bytesToHex_upper(byte[] bytes, int ofs, int len) { return upper(bytesToHex(bytes, ofs, len)); } static public String printNoNewLine_fix(String s) { return printNoNewLine(fixNewLines(s)); } static public int widthToHeight(int w, int h, int newWidth) { return heightForWidth(w, h, newWidth); } static public int widthToHeight(BufferedImage img, int newWidth) { return heightForWidth(img.getWidth(), img.getHeight(), newWidth); } static public int widthToHeight(int newWidth, BufferedImage img) { return widthToHeight(img, newWidth); } static public int widthToHeight(WidthAndHeight img, int newWidth) { return heightForWidth(img.getWidth(), img.getHeight(), newWidth); } static public int widthToHeight(int newWidth, WidthAndHeight img) { return widthToHeight(img, newWidth); } static public A jMinHeight_pure(int h, A c) { if (c != null) { swing(() -> { Dimension size = c.getMinimumSize(); c.setMinimumSize(new Dimension(size.width, h)); }); } return c; } static public A jMinHeight_pure(A c, int h) { return jMinHeight_pure(h, c); } static public void focusConsole(String s) { setConsoleInput(s); focusConsole(); } static public void focusConsole() { JComponent tf = consoleInputFieldOrComboBox(); if (tf != null) { tf.requestFocus(); } } static public int lengthOfString(String s) { return s == null ? 0 : s.length(); } static public int indexOfInSortedArray(A[] array, A a) { return array == null ? -1 : Arrays.binarySearch(array, a); } static public A setTextCaret0(final String text, final A c) { { swing(() -> { setText(c, text); moveCaretToStart(c); }); } return c; } static public A setTextCaret0(A c, String text) { return setTextCaret0(text, c); } static public BufferedImage pixelsToBufferedImage(int[] pixels, int w) { return pixelsToBufferedImage(pixels, w, pixels.length / w); } static public BufferedImage pixelsToBufferedImage(int[] pixels, int w, int h) { return intArrayToBufferedImage(pixels, w, h); } static public int orZero(Integer i) { return i == null ? 0 : i; } static public long orZero(Long l) { return l == null ? 0L : l; } static public double orZero(Double d) { return d == null ? 0.0 : d; } static public int intAreaRoot(Rect r) { return iround(areaRoot(r)); } static public int intAreaRoot(DoubleRect r) { return iround(areaRoot(r)); } static public int intAreaRoot(WidthAndHeight r) { return iround(areaRoot(r)); } static public B firstNonNull(Iterable l, IF1 f) { if (l != null) for (var a : l) { ping(); { var __1 = f.get(a); if (__1 != null) return __1; } } return null; } static public void file2stream(File src, OutputStream out) throws IOException { FileInputStream inputStream = new FileInputStream(src); try { copyStream(inputStream, out); } finally { inputStream.close(); } } static public Number boxedIntOrLong(long l) { return l != (int) l ? boxed(l) : boxed((int) l); } static public HashMap hashMap() { return new HashMap(); } static public String colonCombine(Object... l) { return joinNemptiesWithColon(flattenCollectionsAndArrays(ll(l))); } static public String stdToString(Object o) { return standard_toString(o); } static public KeyListener ctrlLetterKeyListener(char letter, Runnable action) { return new KeyAdapter() { public void keyReleased(KeyEvent ke) { if (ke.getKeyCode() == charToKeyCode(letter) && ke.getModifiers() == KeyEvent.CTRL_MASK) { pcallF(action); } } }; } static public boolean eqOrGreaterThan(Object a, Object b) { return greaterOrEq(a, b); } static public boolean eqOrGreaterThan(int a, int b) { return greaterOrEq(a, b); } static public boolean eqOrGreaterThan(double a, double b) { return greaterOrEq(a, b); } static public String dropFrom(String s, String x) { if (s == null) return null; int i = s.indexOf(x); if (i < 0) return s; return substring(s, 0, i); } static public int rgbBlue(int rgb) { return rgb & 0xFF; } static public Writer outputStreamToWriter(OutputStream out) { try { return new OutputStreamWriter(out, "UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } static public Object callHtmlMethod2(Object o, String uri) { return callHtmlMethod2(o, uri, null); } static public Object callHtmlMethod2(Object o, String uri, Map params) { Object s = callOpt(o, "html", uri, params); if (s == null) s = callOpt(o, "html", uri); if (s == null) s = callOpt(o, "html"); return s; } static public long maxMemory() { return Runtime.getRuntime().maxMemory(); } static public String compilationDateFromClassPath(Object referenceObject) { return loadTextFileResource(classLoader(referenceObject), "compilation-date.txt"); } static public double relativeSliderValue(JSlider slider) { return swing(() -> { if (slider == null) return 0.0; int min = slider.getMinimum(); int max = slider.getMaximum(); int val = slider.getValue(); return doubleRatio(val - min, max - min); }); } static public List sortedKeys(Map map) { return sorted(keys(map)); } static public List sortedKeys(Object map) { return sorted(keys(map)); } static public List sortedKeys(MultiSet ms) { return sorted(keys(ms)); } static public List sortedKeys(MultiMap mm) { return sorted(keys(mm)); } static public String intToBinary_flexLength(int i) { return Integer.toString(i, 2); } static public File forceInstallYouTubeDL() { File file = youTubeDLExecutable(); print("Installing youtube-dl"); loadBinaryPageToFile(youTubeDL_URL(), file); makeExecutable(file); return file; } static public BufferedImage shootScreen() { return shootScreen2(); } static public BufferedImage shootScreen(Rectangle area) { return shootScreen2(area); } static public BufferedImage shootScreen(Rect area) { return shootScreen2(area); } static public BufferedImage shootScreen(int x, int y, int w, int h) { return shootScreen2(x, y, w, h); } static public Pt toPt_round(IDoublePt pt) { return pt(iround(pt.x_double()), iround(pt.y_double())); } static public List wrapObjectArrayAsImmutableList(A[] array) { if (array == null) return null; int n = Array.getLength(array); return new RandomAccessAbstractList() { public int size() { return n; } public A get(int i) { return array[i]; } }; } static public boolean onPATH(String cmd) { return isOnPATH(cmd); } static public List uniquify(Collection l) { return uniquifyList(l); } static public BWImage averageOfBinaryImages(List l) { int n = l(l); if (n == 0) return null; var it = iterator(l); var img = it.next(); int w = img.getWidth(), h = img.getHeight(); int[] pixels = new int[w * h]; while (true) { int i = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { if (img.getBoolPixel(x, y)) pixels[i]++; i++; } if (!it.hasNext()) break; img = it.next(); } byte[] bytes = new byte[w * h]; for (int i = 0; i < l(pixels); i++) bytes[i] = (byte) iround(pixels[i] * (255 / n)); return new BWImage(w, h, bytes); } static public void saveJPGVerbose(BufferedImage img, File file) { try { saveJPG(img, file); print("Saved JPEG: " + f2s(file)); } catch (Exception __e) { throw rethrow(__e); } } static public void saveJPGVerbose(File file, BufferedImage img) { saveJPGVerbose(img, file); } static public int[] iroundDoubleArray(double[] a, int start, int end) { int[] b = new int[end - start]; for (int i = start; i < end; i++) b[i - start] = iround(a[i]); return b; } static public int[] iroundDoubleArray(double[] a) { return a == null ? null : iroundDoubleArray(a, 0, a.length); } static public List asVirtualReversedList(A[] array) { return wrapAsReversedList(array); } static public String loadTextFile_trim(String fileName) { return trim(loadTextFile(fileName)); } static public String loadTextFile_trim(File f, String defaultContents) { return trim(loadTextFile(f, defaultContents)); } static public String loadTextFile_trim(File fileName) { return trim(loadTextFile(fileName)); } static public String loadTextFile_trim(String fileName, String defaultContents) { return trim(loadTextFile(fileName, defaultContents)); } static public boolean rectsOverlap(Rect a, Rect b) { return !intersectRects(a, b).empty(); } static public void moveFile(File a, File b) { if (!renameFile(a, b)) throw fail("File move failed: " + a + " to " + b); } static public Timed returnTimed(String desc, IF0 f) { return returnTimed(f).description(desc); } static public Timed returnTimed(IF0 f) { long time = nanos(); A a = f.get(); time = nanos() - time; return new Timed(a, nsToMS(time)); } static public Timed returnTimed(Runnable r) { return returnTimed(runnableToIF0(r)); } static public List chromeBookmarks() { return getChromeBookmarks(); } static public int toPercent(double ratio) { return toIntPercent(ratio); } static public double doubleAverage(int... a) { double sum = 0; for (int i = 0; i < l(a); i++) sum += a[i]; return doubleRatio(sum, l(a)); } static public double doubleAverage(double... l) { return doubleRatio(doubleSum(l), l(l)); } static public double doubleAverage(Iterable l) { double sum = 0; long n = 0; for (Double i : unnullForIteration(l)) if (i != null) { sum += i; ++n; } return doubleRatio(sum, n); } static public void waitForFrameClose(JComponent c) { JFrame f = getFrame(c); if (f == null) return; Flag flag = new Flag(); CloseablesHolder closer = new CloseablesHolder(); { swing(() -> { if (!isShowing(f)) flag.raise(); else closer.add(tempOnFrameClose(f, flag)); }); } AutoCloseable __1 = closer; try { flag.waitUntilUp(); } finally { _close(__1); } } static public Image2B imageToBinary(BufferedImage img, double threshold) { return bwImageToBinary(new BWImage(img), zeroToOneToZeroTo255(threshold)); } static public Image2B imageToBinary(BufferedImage img, int threshold) { return bwImageToBinary(new BWImage(img), threshold); } static public Image2B imageToBinary(BWImage img, double threshold) { return bwImageToBinary(img, zeroToOneToZeroTo255(threshold)); } static public Image2B imageToBinary(BWImage img, int threshold) { return bwImageToBinary(img, threshold); } static public BufferedImage scaleBufferedImageToMaxPixels(int max, BufferedImage img) { int w = img.getWidth(), h = img.getHeight(); if (w * h <= max) return img; double scale = max / (double) (w * h); return scaleImage(img, scale); } static public int bitXor(int a, int b) { return a ^ b; } static public List> llPairs(A... l) { List> out = new ArrayList(); for (int i = 0; i + 1 < l(l); i += 2) addPair(out, l[i], l[i + 1]); return out; } static public ThreadMXBean threadMXBean_cache; static public ThreadMXBean threadMXBean() { if (threadMXBean_cache == null) threadMXBean_cache = threadMXBean_load(); return threadMXBean_cache; } static public ThreadMXBean threadMXBean_load() { return ManagementFactory.getThreadMXBean(); } static public DoubleRange doubleRange(double start, double end) { return new DoubleRange(start, end); } static public IntRange addToIntRange(IntRange r, int val) { if (r == null || r.empty()) return new IntRange(val, val + 1); if (val < r.start) return intRange(val, r.end); if (val >= r.end) return intRange(r.start, val + 1); return r; } static public JPanel singleColorPanel(final Color color) { return swing(new F0() { public JPanel get() { try { JPanel p = new JPanel(); p.setOpaque(true); p.setBackground(color); return p; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new JPanel p;\r\n p.setOpaque(true);\r\n p.setBackground(color);\r\n ret p;"; } }); } static public RunResultWithTimestamps runResultWithTimestamps_dontPrintStackTrace(IF0 f) { return new RunResultWithTimestamps().run(f, false); } static public Pair pairWithLowestB(Iterable> l) { Lowest> lowest = new Lowest(); for (var p : unnullForIteration(l)) lowest.put(p, p.b); return lowest.get(); } static public JRadioButton jradiobutton(String text, ButtonGroup group) { return swing(new F0() { public JRadioButton get() { try { JRadioButton rb = new JRadioButton(text); if (group != null) group.add(rb); return rb; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JRadioButton rb = new JRadioButton(text);\r\n if (group != null) group.add(r..."; } }); } static public JRadioButton jradiobutton(ButtonGroup group, String text) { return jradiobutton(text, group); } static public JRadioButton jradiobutton(ButtonGroup group, String text, boolean selected) { var rb = jradiobutton(group, text); if (selected) selectRadioButton(rb); return rb; } static public double msToNanos(double ms) { return ms * 1e6; } static public int autoVMExit_visibleObjects() { int objectCount = 0; Map unimportantWindows = (Map) (vm_generalMap_get("unimportant windows")); Window[] windowList = Window.getWindows(); for (Window window : windowList) { if (window.isVisible() && !containsKey(unimportantWindows, window)) ++objectCount; } try { objectCount += SystemTray.getSystemTray().getTrayIcons().length; } catch (Throwable e) { } try { objectCount += l((List) call(_getClass("com.sun.javafx.robot.impl.FXRobotHelper"), "getStages")); } catch (Throwable _e) { } return objectCount; } static public String appendPercent(Object o) { String s = str(o); return endsWith(s, "%") ? s : s + " %"; } static public JSlider liveSliderZeroToOne(final float def, final Object f) { return swing(new F0() { public JSlider get() { try { final int max = 9999; final JSlider slider = new JSlider(0, max, iround(def * max)); slider.addChangeListener(new ChangeListener() { public int lastValue = slider.getValue(); public void stateChanged(ChangeEvent e) { int value = slider.getValue(); if (value != lastValue) { lastValue = value; float x = value / (float) max; setToolTip(slider, str(x)); pcallF(f, x); } } }); return slider; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final int max = 9999;\r\n final JSlider slider = new JSlider(0, max, iround(..."; } }); } static public String formatDateAndTime(long timestamp) { return formatDate(timestamp); } static public String formatDateAndTime() { return formatDate(); } static public boolean isImageMimeType(String mimeType) { return startsWith(mimeType, "image/"); } static public String assertValidFileName(String s) { if (!isValidFileName(s)) throw fail("Not a valid file name: " + quote(s)); return s; } static public List regexpQuoteAll(Iterable l) { return map(__134 -> regexpQuote_optimized(__134), l); } static public List> zipTwoLists(List l1, List l2) { return zipTwoListsToPairs(l1, l2); } static public Rect growRectRight(Rect r, int pixels) { return new Rect(r.x, r.y, r.w + pixels, r.h); } static public String getTextFromClipboard() { return (String) getTransferData(rawClipboardContents(), DataFlavor.stringFlavor); } static public Rect rectRelative(double x1, double y1, double x2, double y2, Rect r) { return rectFromPoints(iround_blend(r.x, r.x2(), x1), iround_blend(r.y, r.y2(), y1), iround_blend(r.x, r.x2(), x2), iround_blend(r.y, r.y2(), y2)); } static public List findMethodsNamed_cached(Object obj, String method) { return findMethodsNamed_cached(_getClass(obj), method); } static public List findMethodsNamed_cached(Class c, String method) { if (c == null) return null; return getMethodCache(c).cache.get(method); } static public List sortByCalculatedFieldDesc_inPlace(List l, final Object f) { sort(l, new Comparator() { public int compare(A b, A a) { return stdcompare((Object) callF(f, a), (Object) callF(f, b)); } }); return l; } static public List sortByCalculatedFieldDesc_inPlace(Object f, List c) { return sortByCalculatedFieldDesc_inPlace(c, f); } static public String nThreads(long n) { return n2(n, "thread"); } static public String nThreads(Collection l) { return nThreads(l(l)); } static public String nThreads(Map map) { return nThreads(l(map)); } static public String addParamsToURL(String url, Map params) { return appendQueryToURL(url, params); } static public String addParamsToURL(String url, Object... data) { return appendQueryToURL(url, data); } static public int[] pixelsWithInvertedAlpha(int[] pixels) { int n = pixels.length; int[] pixels2 = new int[n]; for (int i = 0; i < n; i++) pixels2[i] = pixels[i] ^ 0xFF000000; return pixels2; } static public long totalSizeInInts(Iterable l) { long sum = 0; for (var a : unnullForIteration(l)) if (a != null) sum += a.sizeInInts(); return sum; } static public List cloneAndClearList(Collection l) { List l2 = cloneList(l); l.clear(); return l2; } static public void makeEmptyFile(File f) { try { new FileOutputStream(f).close(); } catch (Exception __e) { throw rethrow(__e); } } static public JSlider jLiveValueSlider_double_noScaling(int min, int max, IVarWithNotify lv) { AtomicInteger changing = new AtomicInteger(); JSlider slider = liveSlider(min, max, clamp(iround(unnull(lv.get())), min, max), v -> { if (changing.get() == 0) lv.set((double) v); }); bindLiveValueListenerToComponent(slider, lv, new Runnable() { public void run() { try { AutoCloseable __1 = tempIncAtomicInt(changing); try { setSliderValue(slider, iround(unnull(lv.get()))); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp tempIncAtomicInt(changing);\r\n setSliderValue(slider, iround(unnull(lv..."; } }); return slider; } static public List shiftIntRanges(int shift, Iterable l) { return map(l, r -> shiftIntRange(shift, r)); } static public double degreesToRadians(double deg) { return degreeToRadian(deg); } static public URI uri(String uri) { try { return new URI(uri); } catch (Exception __e) { throw rethrow(__e); } } static public Object dm_getOS(String field) { return get(dm_os(), field); } static public String beforeVerticalBar(String s) { return trimSubstring(s, 0, smartIndexOf(s, '|')); } static public boolean isPowerOfTwo(int x) { return (x != 0) && ((x & (x - 1)) == 0); } static public boolean syncMapRemoveKeyAndValuePair(Map map, A key, B value) { if (map == null || key == null || value == null) return false; synchronized (collectionMutex(map)) { B actualValue = map.get(key); if (eq(actualValue, value)) { map.remove(key); return true; } return false; } } static public IterableIterator iff_endOnNull(final Object f) { return iteratorFromFunction(f); } static public IterableIterator iff_endOnNull(F0 f) { return iteratorFromFunction(f); } static public A printWithStackTrace(A o) { printStackTrace(str(o)); return o; } static public void bindVarToVar(IVarWithNotify var1, IVarWithNotify var2) { linkVars(var1, var2); } static public WeakIdentityHashMap weakIdentityHashMap() { return new WeakIdentityHashMap(); } static public File googleClientSecretFileForDomain(String domain) { if (!isSimpleDomainName(domain)) return null; return firstThat(listFiles(javaxSecretDir(domain)), f -> startsWith(fileName(f), "client_secret") && endsWith(fileName(f), ".json")); } static public void assertNotSame(String msg, Object a, Object b) { if (a == b) throw fail(msg); } static public void assertNotSame(Object a, Object b) { if (a == b) throw fail(); } static public int[] byteHistogramArray(byte[] data) { var histogram = new int[256]; if (data != null) for (var b : data) histogram[b & 0xFF]++; return histogram; } static public double ratioToProbability(double ratio) { if (ratio < 0) throw fail("No negative values allowed"); if (ratio > 1) ratio = 1 / ratio; return ratio; } static public double ratioToProbability(double a, double b) { if (a < 0 || b < 0) throw fail("No negative values allowed"); return b == 0 ? (a == 0 ? 1 : 0) : ratioToProbability(a / b); } static public double ld(double d) { return Math.log(d) / Math.log(2); } static public File fileIfExists(File f) { return fileExists(f) ? f : null; } static public int rgbAlpha(int rgb) { return (rgb >> 24) & 0xFF; } static public String conceptField_modified() { return "_modified"; } static public String afterLastSlash(String s) { if (s == null) return null; int i = s.lastIndexOf('/'); return i < 0 ? s : substring(s, i + 1); } static public DoublePt lineIntersectionPt(LineThroughPoint l1, LineThroughPoint l2) { DoublePt p1 = doublePt(l1.x, l1.y), p2 = l1.pointOnLine(1); DoublePt p3 = doublePt(l2.x, l2.y), p4 = l2.pointOnLine(1); double d = (p1.x - p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x - p4.x); double x = ((p1.x * p2.y - p1.y * p2.x) * (p3.x - p4.x) - (p1.x - p2.x) * (p3.x * p4.y - p3.y * p4.x)) / d; double y = ((p1.x * p2.y - p1.y * p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x * p4.y - p3.y * p4.x)) / d; return doublePt(x, y); } static public String sfSnippet(String function) { return stdFunctions_cached().get(function); } static public String firstCmdOnPATH_mandatory(String... cmds) { for (String cmd : cmds) if (onPATH(cmd)) return cmd; throw fail("None of the commands found on PATH: " + asList(cmds)); } static public String shortenToMaxLines(String s, int maxLines) { return shortenToMaxLinesAndChars(s, maxLines, Integer.MAX_VALUE); } static public String shortenToMaxLines(int maxLines, String s) { return shortenToMaxLines(s, maxLines); } static public int sign(double x) { return x == 0.0 ? 0 : x < 0 ? -1 : 1; } static public int sign(long x) { return x == 0 ? 0 : x < 0 ? -1 : 1; } static public int sign(int x) { return x == 0 ? 0 : x < 0 ? -1 : 1; } static public Object getTransferData(Transferable t, DataFlavor flavor) { try { return t != null && t.isDataFlavorSupported(flavor) ? t.getTransferData(flavor) : null; } catch (Exception __e) { throw rethrow(__e); } } static public String formatDouble1X(double d) { return formatDoubleX(d, 1); } static public BufferedImage renderAll(int w, int h, Iterable drawables) { return renderAll(drawables, whiteImage(w, h)); } static public BufferedImage renderAll(Iterable drawables, BufferedImage canvas) { for (var d : unnullForIteration(drawables)) { if (d != null) d.drawOn(canvas); } return canvas; } static public BufferedImage renderAll(Iterable drawables, WidthAndHeight size) { return renderAll(size.w(), size.h(), drawables); } static public DoubleRange growRange(DoubleRange r, double amount) { return r == null ? null : doubleRange(r.start - amount, r.end + amount); } static public DoubleRange growRange(double amount, DoubleRange r) { return growRange(r, amount); } static public IntRange growRange(IntRange r, int amount) { return r == null ? null : intRange(r.start - amount, r.end + amount); } static public IntRange growRange(int amount, IntRange r) { return growRange(r, amount); } static public JComponent jMaxSpeedAnimationWithText(IF0_Pair renderFrameWithText) { ImageSurface is = new ImageSurface(); is.pixelate(true); is.autoZoomToDisplay(true); DoubleFPSCounter fps = new DoubleFPSCounter(); var textArea = typeWriterFont(uneditableTextArea()); awtCalcContinuously(is, () -> { try { var imageAndText = renderFrameWithText.get(); fps.inc(); is.setImage(pairA(imageAndText)); setText(textArea, nlCombine_rtrim(fps, pairB(imageAndText))); } catch (Throwable e) { printStackTrace(e); setText(textArea, exceptionToStringShort(e)); sleepSeconds(1); } }); return jvsplit(jscroll_center_borderless(is), textArea); } static public File defaultExtension(String ext, File file) { if (empty(ext)) return file; if (file == null || fileHasAnyExtensionAtAll(file)) return file; return appendToFileName(addDotPrefix(ext), file); } static public String defaultExtension(String ext, String fileName) { if (empty(ext)) return fileName; if (fileName == null || contains(fileName, '.')) return fileName; return rjoin(addDotPrefix(ext), fileName); } static public File windowsFindChromeExe() { return windowsFindExe("Google\\Chrome\\Application\\chrome.exe"); } static public TimeZone utcTimeZone() { return timeZone("UTC"); } static public IterableIterator shuffledIterator(List l) { return new IterableIterator() { public int n = l(l); public int i = 0; public HashMap shuffled = new HashMap(); public boolean hasNext() { return i < n; } public A next() { int j = random(i, n); A a = get(i), b = get(j); shuffled.put(j, a); shuffled.remove(i); ++i; return b; } public A get(int i) { return shuffled.containsKey(i) ? shuffled.get(i) : l.get(i); } }; } static public String commonPrefix(String a, String b) { int i = 0, nb = b.length(), na = a.length(), n = min(na, nb); while (i < n && a.charAt(i) == b.charAt(i)) ++i; return i == nb ? b : substring(a, 0, i); } static public String commonPrefix(List l) { if (empty(l)) return ""; String s = first(l); for (int i = 1; i < l(l); i++) { if (empty(s)) return s; s = commonPrefix(s, l.get(i)); } return s; } static public IBinaryImage regionToIBinaryImage(IImageRegion region) { Rect r = region.bounds(); return iBinaryImageFromFunction(r.w, r.h, (x, y) -> !region.contains(r.x + x, r.y + y)); } static public int methodApplicabilityScore_withPrimitiveWidening_onTypes(Executable m, Class[] argTypes) { Class[] types = m.getParameterTypes(); if (types.length != l(argTypes)) return Integer.MAX_VALUE; int score = 0; boolean widenings = false; for (int i = 0; i < types.length; i++) { Class t = argTypes[i]; Class c = types[i]; int s = typeConversionScoreWithUnboxing(t, c); if (s == Integer.MAX_VALUE) return Integer.MAX_VALUE; if (s < 0) widenings = true; score += abs(s); } return widenings ? -score : score; } static public List startingWithIC(Collection l, final String prefix) { return filter(unnull(l), new F1() { public Boolean get(String s) { try { return swic(s, prefix); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "swic(s, prefix)"; } }); } static public List startingWithIC(String prefix, Collection l) { return startingWithIC(l, prefix); } static public BWImage regionToBWImage_inverted(IImageRegion region) { return region == null ? null : new RegionToBWImage(region).bgColor(255).color(0).get(); } static public IterableIterator takeFirstI(int n, Iterator i) { return i == null ? null : iff(new F0() { public int remaining = n; public Object get() { return remaining-- <= 0 || !i.hasNext() ? endMarker() : i.next(); } }); } static public double scoreForIndexInProbabilisticList(int index) { return index < 0 ? 0 : distanceToProbability(index); } static public double rgbAlphaZeroToOne(int rgb) { return rgbAlpha(rgb) / 255.0; } static public double minusPercent(double a, double percent) { return a * (1 - percent / 100); } static public String lineRange(String s, int from, int to) { return lines(subList(lines(s), from, to)); } static public String withIdentity(Object o, String s) { return withIdentityHash(o, s); } static public NanoHTTPD.IHTTPSession nanoHTTPDCurrentSession() { return NanoHTTPD.currentSession.get(); } static public int intFromBytes_littleEndian(byte[] a, int i) { return (ubyteToInt(a[i + 3]) << 24 | (ubyteToInt(a[i + 2]) << 16 | (ubyteToInt(a[i + 1]) << 8 | ubyteToInt(a[i])))); } static public int assertDivisibleBy(int divisor, int a) { if ((a % divisor) != 0) throw fail("Not divisible by " + divisor + ":" + a); return a; } static public List getMyIPs() { try { TreeSet ips = new TreeSet(); Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface iface = interfaces.nextElement(); if (iface.isLoopback() || !iface.isUp()) continue; Enumeration addresses = iface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); String ip = addr.getHostAddress(); if (ip.startsWith("127.")) continue; ips.add(ip); } } return new ArrayList(ips); } catch (Exception __e) { throw rethrow(__e); } } static public void cleanKillVM() { try { ping(); assertNotOnAWTThread(); cleanKillVM_noSleep(); Object o = new Object(); synchronized (o) { o.wait(); } } catch (Exception __e) { throw rethrow(__e); } } static public void cleanKillVM_noSleep() { call(getJavaX(), "cleanKill"); } static public IBinaryImage iBinaryImageFromFunction(IIntIntPred f, int w, int h) { return new IBinaryImage() { public int getWidth() { return w; } public int getHeight() { return h; } public boolean getBoolPixel(int x, int y) { return f.get(x, y); } }; } static public IBinaryImage iBinaryImageFromFunction(int w, int h, IIntIntPred f) { return iBinaryImageFromFunction(f, w, h); } static public URLConnection urlConnection(String url) { return openConnection(url); } static public URLConnection urlConnection(URL url) { return openConnection(url); } static public JTextArea uneditableTypeWriterTextArea() { return uneditableTypeWriterTextArea(""); } static public JTextArea uneditableTypeWriterTextArea(String text) { return typeWriterFont(uneditableTextArea(text)); } static public File jpegify(File imageFile) { return jpegify(imageFile, true); } static public File jpegify(File imageFile, boolean makeBackup) { if (isJPEGFile(imageFile)) return imageFile; { AutoCloseable __1 = tempShowLoadingAnimation("JPEGify"); try { BufferedImage img = loadImage2(imageFile); File destFile = replaceExtension(imageFile, ".jpg"); File atticFile = makeBackup ? newFile(javaxDataDir("JPEGified original pictures"), imageFile.getName()) : null; if (makeBackup) atticFile = makeFileNameUnique(atticFile); saveJPGVerbose(destFile, img); if (makeBackup) moveFileVerbose(imageFile, atticFile); else deleteFile(imageFile); print("Conversion done."); return destFile; } finally { _close(__1); } } } static public List structTok(String s) { return javaTok_noMLS(s); } static public void scrollToCenter(JScrollPane sp) { if (sp == null) return; { swing(() -> { var viewPort = sp.getViewport(); Dimension viewSize = viewPort.getExtentSize(); Dimension contentSize = viewPort.getViewSize(); int x = max(0, contentSize.width - viewSize.width) / 2; int y = max(0, contentSize.height - viewSize.height) / 2; viewPort.setViewPosition(new Point(x, y)); }); } } static public String ipAddress() { return getMyIP(); } static public List shuffled(Collection l) { var l2 = cloneList(l); Collections.shuffle(l2); return l2; } static public void pnlStruct(Object o) { if (o instanceof Collection) pnlStruct((Collection) o); else if (o instanceof Map) pnlStruct((Map) o); else if (o != null) pnlStruct(ll(o)); } static public > B pnlStruct(B l) { pnlStruct((Iterable) l); return l; } static public Iterable pnlStruct(Iterable l) { return pnlStruct("", l); } static public Iterable pnlStruct(String prefix, Iterable l) { int i = 0; if (l != null) for (A a : l) print(prefix + (++i) + ". " + struct_noStringSharing(a)); return l; } static public A[] pnlStruct(A[] l) { pnlStruct(asList(l)); return l; } static public Map pnlStruct(Map map) { pnl(map(map, new F2() { public Object get(A a, B b) { try { return sfu(a) + " = " + sfu(b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "sfu(a) + \" = \" + sfu(b)"; } })); return map; } static public short[] newShortArrayOrNull(int n) { return n <= 0 ? null : new short[n]; } static public boolean cset_trueIfChanged(Concept c, Object... values) { try { return cset(c, values) != 0; } catch (Exception __e) { throw rethrow(__e); } } static public OutputStream teeOutputStream(final OutputStream a, final OutputStream b) { if (a == null) return b; if (b == null) return a; return new OutputStream() { public void write(int byt) throws IOException { a.write(byt); b.write(byt); } public void write(byte[] byt, int off, int len) throws IOException { a.write(byt, off, len); b.write(byt, off, len); } }; } static public List getChildren(final Container c) { return c == null ? emptyList() : swing(new F0>() { public List get() { try { return asList(c.getComponents()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return asList(c.getComponents());"; } }); } static public void makeExecutable_java7(File file) { try { if (isWindows()) return; Set p = new HashSet(Files.getPosixFilePermissions(file.toPath())); p.add(PosixFilePermission.OWNER_READ); p.add(PosixFilePermission.OWNER_EXECUTE); p.add(PosixFilePermission.GROUP_READ); p.add(PosixFilePermission.GROUP_EXECUTE); p.add(PosixFilePermission.OTHERS_READ); p.add(PosixFilePermission.OTHERS_EXECUTE); Files.setPosixFilePermissions(file.toPath(), p); } catch (Exception __e) { throw rethrow(__e); } } static public String n2_iceil(double d) { return n2(iceil(d)); } static public BufferedImage blackImage(int w, int h) { return newBufferedImage(w, h, Color.black); } static public BufferedImage blackImage(int size) { return blackImage(size, size); } static public int getSelectedIndex(final JComboBox cb) { return cb == null ? -1 : swing(new F0() { public Integer get() { try { return cb.getSelectedIndex(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return cb.getSelectedIndex();"; } }); } static public int getSelectedIndex(final JList l) { return l == null ? -1 : swing(new F0() { public Integer get() { try { return l.getSelectedIndex(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return l.getSelectedIndex();"; } }); } static public Complex[] eigenvaluesOfSymmetricMatrix(double[][] matrixData) { var matrix = new DMatrixRMaj(matrixData); var evd = new SymmetricQRAlgorithmDecomposition_DDRM(false); if (!evd.decompose(matrix)) return null; int n = evd.getNumberOfEigenvalues(); Complex[] eigenvalues = new Complex[n]; for (int i = 0; i < n; i++) { var v = evd.getEigenvalue(i); eigenvalues[i] = new Complex(v.real, v.imaginary); } return eigenvalues; } static public boolean flatInfoBox_alwaysOnTop = true; static public double flatInfoBox_defaultTime = 2.0; static public int flatInfoBox_x = 28, flatInfoBox_y = 5; static public JWindow flatInfoBox(String text) { return flatInfoBox(text, flatInfoBox_defaultTime); } static public JWindow flatInfoBox(final String text, final double seconds) { if (empty(text)) return null; print(text); return flatInfoBox_noprint(text, seconds); } static public JWindow flatInfoBox_noprint(String text) { return flatInfoBox_noprint(text, flatInfoBox_defaultTime); } static public JWindow flatInfoBox_noprint(final String text, final double seconds) { if (empty(text)) return null; logQuotedWithDate(infoBoxesLogFile(), text); if (isHeadless()) return null; return (JWindow) swingAndWait(new F0() { public Object get() { try { final JWindow window = makeUnimportantWindow(flatInfoBox_makePanel(text)); window.pack(); window.setBounds(flatInfoBox_x, flatInfoBox_y, 300, window.getHeight()); if (flatInfoBox_alwaysOnTop) window.setAlwaysOnTop(true); window.setVisible(true); disposeWindowAfter(iround(seconds * 1000), window); return window; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JWindow window = makeUnimportantWindow(flatInfoBox_makePanel(text));\r\n ..."; } }); } static public JWindow flatInfoBox(Throwable e) { showConsole(); printStackTrace(e); return flatInfoBox(exceptionToStringShort(e)); } static public Color intToColorOpaque(int rgb) { return new Color(rgb); } static public HashMap lithashmap(Object... x) { return litmap(x); } static public void assertPowerOfTwo(int i) { if (!isPowerOfTwo(i)) throw fail(i); } static public ArrayList doubleArrayToList(double[] a) { if (a == null) return null; return doubleArrayToList(a, 0, a.length); } static public ArrayList doubleArrayToList(double[] a, int from, int to) { if (a == null) return null; ArrayList l = new ArrayList<>(to - from); for (int i = from; i < to; i++) l.add(a[i]); return l; } static public MultiSet toMultiSet(Iterable l) { return asMultiSet(l); } static public List cloneAndClear(Collection l) { return cloneAndClearList(l); } static public boolean regexpContains(String pat, String s) { return regexpFinds(pat, s); } static public boolean regexpContains(Pattern pat, String s) { return regexpFinds(pat, s); } static public List tok_splitAtComma_unquote(String s) { return tok_splitAtComma_unquote(javaTok(s)); } static public List tok_splitAtComma_unquote(List tok) { List out = new ArrayList(); for (int i = 0; i < l(tok); i++) { int j = smartIndexOf(tok, ",", i); out.add(unquote(trimJoinSubList(tok, i, j))); i = j; } return out; } static public String loadTextFileTrim(String fileName) { return loadTextFile_trim(fileName); } static public String loadTextFileTrim(File f, String defaultContents) { return loadTextFile_trim(f, defaultContents); } static public String loadTextFileTrim(File fileName) { return loadTextFile_trim(fileName); } static public String loadTextFileTrim(String fileName, String defaultContents) { return loadTextFile_trim(fileName, defaultContents); } static public JLabel flatInfoBox_makePanel(String text) { return jlabel(text); } static public int[] intArrayFromBytes_littleEndian(byte[] a) { int[] b = new int[(a.length + 3) / 4]; for (int i = 0; i < b.length; i++) b[i] = intFromBytes_littleEndian(a, i * 4); return b; } static public File installYouTubeDL() { File file = youTubeDLExecutable(); if (file.exists()) return file; return forceInstallYouTubeDL(); } static public boolean isRootUser() { return eq(System.getProperty("user.name"), "root"); } static public BigInteger times(BigInteger a, BigInteger b) { return mul(a, b); } static public BigInteger times(BigInteger a, long b) { return mul(a, b); } static public int times(int a, int b) { return mul(a, b); } static public double times(double a, double b) { return mul(a, b); } static public A _print(String s, A a) { return print(s, a); } static public A _print(A a) { return print(a); } static public void _print() { print(); } static public List sortedDesc(Collection c, Object comparator) { List l = cloneList(c); sort(l, makeReversedComparator(comparator)); return l; } static public List sortedDesc(Collection c, Comparator comparator) { List l = cloneList(c); sort(l, makeReversedComparator(comparator)); return l; } static public List sortedDesc(Collection c) { List l = cloneList(c); sort(l); Collections.reverse(l); return l; } static public A setSize(final A c, final int w, final int h) { if (c != null) { swing(() -> { c.setSize(w, h); }); } return c; } static public void setSize(Component c, Dimension d) { setSize(c, d.width, d.height); } static public Color hi15ToColor_dirty(short hi15) { return intToColorOpaque(hi15ToRGBInt_dirty(hi15)); } static public String backtickToConsole_returnOutput(String cmd) { return loadTextFile(backtickToConsole(cmd)); } static public OutputStream printOutputStream() { final UTF8Processor utf8 = new UTF8Processor(); return new OutputStream() { public void write(int b) { print_noNewLine(utf8.processByte((byte) b)); } }; } static public void stepMaxWithPrintIndentedStruct(long maxSteps, Steppable s) { if (s == null) return; String struct = null; long steps = 0; do { if (steps++ > maxSteps) break; print(struct = indentedStruct(s)); } while (s.step()); String struct2 = indentedStruct(s); if (!eq(struct, struct2)) print(struct2); } static public void stepMaxWithPrintIndentedStruct(Steppable s, long maxSteps) { stepMaxWithPrintIndentedStruct(maxSteps, s); } static public File dirOtherwiseNull(File dir) { return isDirectory(dir) ? dir : null; } static public BufferedImage render(WidthAndHeight size, G2Drawable drawable) { return drawableToImage(size, drawable); } static public TailFile tailFile2(File file, int interval, IVF1 onData) { TailFile tf = new TailFile(file, interval, onData); tf.start(); return tf; } static public String nlCombine(Object... l) { return nemptyLines_extractLists(l); } static public List rectsToRectangles(Collection l) { List x = new ArrayList(); for (Rect r : l) x.add(r.getRectangle()); return x; } static public DoubleRange zeroToOneDoubleRangeFromRangeSlider(int max, RangeSlider slider) { return swing(new F0() { public DoubleRange get() { try { return new DoubleRange(doubleRatio(slider.getValue(), max), doubleRatio(slider.getUpperValue(), max)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return DoubleRange(doubleRatio(slider.getValue(), max), doubleRatio(slider.ge..."; } }); } static public BufferedImage decodeImage(byte[] data) { try { if (empty(data)) return null; return ImageIO.read(new ByteArrayInputStream(data)); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedImage bwImageAsAlpha(BWImage bwImage, Color color) { int w = bwImage.w(), h = bwImage.h(), n = w * h; int rgb = colorToInt(color); byte[] in = bwImage.pixels; int[] out = new int[n]; for (int i = 0; i < n; i++) out[i] = ubyteToInt(in[i]) << 24 | rgb; return bufferedImage(w, h, out); } static public Object preciseGetOrCallMethod_sentinel(Object object, String name, Object sentinel) { if (object == null) return null; if (canCallWithVarargs(object, name)) return call(object, name); Field f = getField(object, name); if (f != null) return fieldGet(f, object); return sentinel; } static public boolean intRangesOverlap(IntRange a, IntRange b) { return intersectIntRanges(a, b) != null; } static public boolean intRangesOverlap(int a1, int a2, int b1, int b2) { return intRangesOverlap(intRange(a1, a2), intRange(b1, b2)); } static public void drawCircle(Graphics2D g, int x, int y, int r, Color color) { g.setColor(color); g.drawOval(x - r, y - r, r * 2, r * 2); } static public void assertIntArraysEqual(int[] a, int... b) { assertIntArraysEqual("", a, b); } static public void assertIntArraysEqual(String msg, int[] a, int... b) { List l1 = wrapIntArrayAsList(a), l2 = wrapIntArrayAsList(b); assertListsEqual(msg, l1, l2); } static public A setForeground(Color color, A a) { if (a != null) a.setForeground(color); return a; } static public boolean regexpMatchesIC(String pat, String s) { return regexpICMatches(pat, s); } static public boolean regexpMatchesIC(Pattern pat, String s) { return regexpICMatches(pat, s); } static public String addDotPrefix(String s) { return addPrefix(".", s); } static public Set immutableSet(Set set) { return Collections.unmodifiableSet(set); } static public String classNameWithIdentity(Object o) { return o == null ? null : withIdentity(o, className(o)); } static public AutoCloseable tempPrintAlsoToSystemOut() { return tempSetGeneric(() -> printAlsoToSystemOut, x -> printAlsoToSystemOut = x, true); } static public int parseFirstInt_regexp(String s) { return firstInt_regexp(s); } static public JSlider jLiveValueSlider_int_bothWays(int min, int max, IVarWithNotify lv) { AtomicInteger changing = new AtomicInteger(); JSlider slider = liveSlider(min, max, clamp(lv.get(), min, max), v -> { if (changing.get() == 0) lv.set(v); }); bindLiveValueListenerToComponent(slider, lv, new Runnable() { public void run() { try { AutoCloseable __1 = tempIncAtomicInt(changing); try { setSliderValue(slider, lv.get()); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp tempIncAtomicInt(changing);\r\n setSliderValue(slider, lv!);"; } }); return slider; } static public WidthAndHeight toWidthAndHeight(Dimension d) { return d == null ? null : widthAndHeight(d.width, d.height); } static public long hotSpotCompilationTime() { try { CompilationMXBean bean = ManagementFactory.getCompilationMXBean(); if (bean != null && bean.isCompilationTimeMonitoringSupported()) return bean.getTotalCompilationTime(); } catch (Throwable e) { silentException(e); } return 0; } static public Object dm_osGet(String field) { return dm_getOS(field); } static public boolean containsRegExpSpecialChars(String regexp) { return regexpContains("[\\[\\]\\(\\)\\+\\|\\^\\$\\\\\\*\\?\\{\\}]", regexp); } static public List listCombine(Object... l) { return flattenToList(l); } static public String nemptyLines_extractLists(Object... l) { return nemptyLines(flattenCollectionsAndArrays(ll(l))); } static public NanoHTTPD.Response serve404() { return serve404("Not found"); } static public NanoHTTPD.Response serve404(String msg) { return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Code 404 - " + msg); } static public String structWordWrap(Object o) { return structTokWordWrap(struct(o)); } static public Rect combinedChildBounds(Container c) { return mergeRects(map(listChildren(c), child -> toRect(getBounds(child)))); } static public BufferedImage bufferedImageContrastAndBrightness(BufferedImage img, float scaleFactor, float offset) { new RescaleOp(scaleFactor, offset, null).filter(img, img); return img; } static public String copyTextToClipboardVerbose(Object _text) { String text = copyTextToClipboard(_text); print("Copied to clipboard (" + n2(l(text), "char") + "): " + quote(shorten(text, 1000))); return text; } static public List allToStr(Iterable c) { return allToString(c); } static public List allToStr(Object[] c) { return allToString(c); } static public int cyclicAdd(int a, int b, int n) { return mod(a + b, n); } static public BWImage invertImageInPlace(BWImage bw) { if (bw != null) { byte[] pixels = bw.pixels; int n = pixels.length; for (int i = 0; i < n; i++) pixels[i] = (byte) ~pixels[i]; } return bw; } static public boolean isSimpleDomainName(String s) { return regexpMatchesIC("[a-z0-9\\-]+\\.[a-z]+", s); } static public String unidiff(String a, String b) { int contextSize = 1; return fromLines(BlockDiffer.generateUniDiff(toLines(a), toLines(b), contextSize)); } static public VectorSSI toVectorSSI(AbstractSSI ssi) { if (ssi == null) return null; if (ssi instanceof VectorSSI) return ((VectorSSI) ssi); return new VectorSSI(ssi.toSSI()); } static public RGB hi15ToRGB(short hi15) { return new RGB(hi15ToRGBInt_clean(hi15)); } static public Map immutableMap(Map map) { return Collections.unmodifiableMap(map); } public static String rtrimSpaces(String s) { if (s == null) return null; int i = s.length(); while (i > 0 && " \t".indexOf(s.charAt(i - 1)) >= 0) --i; return i < s.length() ? s.substring(0, i) : s; } static public List collectInstances(Iterable i, Class c) { List l = new ArrayList(); if (i == null) return l; c = primitiveToBoxedTypeOpt(c); for (Object o : i) if (isInstance(c, o)) l.add(o); return l; } static public List collectInstances(Class c, Iterable i) { return collectInstances(i, c); } static public List localMaxima(List l) { return localMaxima(toDoubleArray(l)); } static public List localMaxima(double[] l) { List out = new ArrayList(); int n = l(l); for (int i = 0; i < n; i++) if ((i == 0 || l[i] > l[i - 1]) && (i == n - 1 || l[i] > l[i + 1])) out.add(i); return out; } static public Comparator makeReversedComparator(Object f) { return new Comparator() { public int compare(Object a, Object b) { return (int) callF(f, b, a); } }; } static public Comparator makeReversedComparator(Comparator c) { return (a, b) -> c.compare(b, a); } static public long modificationTime(File f) { return fileModificationTime(f); } static public int hi15ToRGBInt_dirty(short hi15) { int r = hi15 >> 10; int g = (hi15 >> 5) & 0x1F; int b = hi15 & 0x1F; return (r << 19) | (g << 11) | (b << 3); } static public Timestamp chromeTimestampToTimestamp(long chromeDate) { return new Timestamp(ymdToTimestamp(1601, 1, 1, utcTimeZone()) + chromeDate / 1000); } static public long currentThreadTotalCPUNanos() { return threadMXBean().getCurrentThreadCpuTime(); } static public AutoCloseable tempSetGeneric(IF0 getter, IVF1 setter, A newValue) { A value = getter.get(); if (eq(value, newValue)) return null; setter.get(newValue); return () -> setter.get(value); } static public boolean classIs(Class c, Object o) { return _getClass(o) == c; } static public int majorJavaVersion() { return parseFirstInt_regexp(System.getProperty("java.version")); } static public long intSumAsLong(Iterable l) { long sum = 0; for (Integer i : unnull(l)) if (i != null) sum += i; return sum; } static public AbstractSSI vectorizeSSIIfBeneficial(SSI ssi) { var vectorSSI = new VectorSSI(ssi); return vectorSSI.sizeInInts() < ssi.sizeInInts() ? vectorSSI : ssi; } static public BWImage certaintyImage(IBWImage img) { return bwImageFromFunction(img.getWidth(), img.getHeight(), (x, y) -> { double pix = img.getFloatPixel(x, y); return absdiff(pix, 0.5) * 2; }); } static public boolean greaterOrEq(Object a, Object b) { return cmp(a, b) >= 0; } static public boolean greaterOrEq(int a, int b) { return a >= b; } static public boolean greaterOrEq(double a, double b) { return a >= b; } static public List wrapAsReversedList(A[] array) { int n = l(array); return new RandomAccessAbstractList() { public int size() { return n; } public A get(int i) { return array[n - 1 - i]; } public A set(int i, A a) { A old = array[n - 1 - i]; array[n - 1 - i] = a; return old; } }; } static public double twoPointAngle(IDoublePt p1, IDoublePt p2) { return atan2(p2.x_double() - p1.x_double(), p2.y_double() - p1.y_double()); } static public Runnable runnableWithCustomToString(String s, Runnable r) { if (r == null) return null; return new Runnable() { public void run() { try { r.run(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return unnull(s); } }; } static public double rectDistance(Rect r1, Rect r2) { double x1, x2, y1, y2; double w, h; if (r1.x > r2.x) { x1 = r2.x; w = r2.w; x2 = r1.x; } else { x1 = r1.x; w = r1.w; x2 = r2.x; } if (r1.y > r2.y) { y1 = r2.y; h = r2.h; y2 = r1.y; } else { y1 = r1.y; h = r1.h; y2 = r2.y; } double a = Math.max(0, x2 - x1 - w); double b = Math.max(0, y2 - y1 - h); return Math.sqrt(a * a + b * b); } static public List takeLast(List l, int n) { return newSubList(l, l(l) - n); } static public List takeLast(int n, List l) { return takeLast(l, n); } static public String takeLast(int n, String s) { return substring(s, l(s) - n); } static public String takeLast(String s, int n) { return substring(s, l(s) - n); } static public TimeZone defaultTimeZone() { return TimeZone.getDefault(); } static public Integer boxed(int i) { return i; } static public Long boxed(long l) { return l; } static public IterableIterator iteratorFF(Object f) { return iteratorFromFunction_withEndMarker(f); } static public IterableIterator iteratorFF(F0 f) { return iteratorFromFunction_withEndMarker(f); } static public IterableIterator iteratorFF(IF0 f) { return iteratorFromFunction_withEndMarker(f); } static public String loadTextFilePart(File file, long start, long end) { return fromUtf8(loadBinaryFilePart(file, start, end)); } static public File windowsFindExe(String relativeName) { return firstFileThatExists(map(windowsProgramFilesDirs(), dir -> defaultExtension("exe", newFile(dir, relativeName)))); } static public Class getRawTypeClass(Type t) { return typeToClass(t); } static public T3 t3(A a, B b, C c) { return new T3(a, b, c); } static public String formatPercent(double ratio) { return formatDouble(ratio * 100, 1) + "%"; } static public JSpinner jLiveValueSpinner(IVarWithNotify lv, int min, int max) { return liveValueSpinner(lv, min, max); } static public JSpinner jLiveValueSpinner(int min, int max, IVarWithNotify lv) { return liveValueSpinner(lv, min, max); } static public String n2_noPlural(long l, String text) { return empty(text) ? n2(l) : n2(l) + " " + text; } static public String n2_noPlural(Collection l, String text) { return n2_noPlural(l(l), text); } static public String n2_noPlural(Map m, String text) { return n2(l(m), text); } static public double percentRatio(double x, double y) { return ratioToPercent(x, y); } static public List instancesOf(Iterable i, Class c) { return collectInstances(i, c); } static public List instancesOf(Class c, Iterable i) { return collectInstances(c, i); } static public String regexpSpecialCharacters() { return "\\[.^$?*+{|()"; } static public IBinaryImage scaledIBinaryImage(WidthAndHeight size, IBinaryImage img) { return scaledIBinaryImage(size.w(), size.h(), img); } static public IBinaryImage scaledIBinaryImage(int w, IBinaryImage img) { return scaledIBinaryImage(w, widthToHeight(w, img), img); } static public IBinaryImage scaledIBinaryImage(int w, int h, IBinaryImage img) { if (img == null) return null; int w1 = img.getWidth(), h1 = img.getHeight(); if (w == w1 && h == h1) return img; double factorX = doubleRatio(w1, w); double factorY = doubleRatio(h1, h); return iBinaryImageFromFunction(w, h, (x, y) -> img.getBoolPixel(ifloor(x * factorX), ifloor(y * factorY))); } static public int factorial(int i) { int n = 1; while (i > 1) n *= i--; return n; } static public Frequency freq(double freq) { return toFrequency(freq); } static public String unquoteSingleOrDoubleQuotes(String s) { if (s == null) return null; if (s.length() > 1) { char c = s.charAt(0); if (c == '\"' || c == '\'') { int l = endsWith(s, c) ? s.length() - 1 : s.length(); StringBuilder sb = new StringBuilder(l - 1); for (int i = 1; i < l; i++) { char ch = s.charAt(i); if (ch == '\\') { char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1); if (nextChar >= '0' && nextChar <= '7') { String code = "" + nextChar; i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; } } sb.append((char) Integer.parseInt(code, 8)); continue; } switch(nextChar) { case '\"': ch = '\"'; break; case '\\': ch = '\\'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\'': ch = '\''; break; case 'u': if (i >= l - 5) { ch = 'u'; break; } int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16); sb.append(Character.toChars(code)); i += 5; continue; default: ch = nextChar; } i++; } sb.append(ch); } return sb.toString(); } } return s; } static volatile public int silentException_count; static volatile public Throwable silentException_lastException; static public Throwable silentException(Throwable e) { ++silentException_count; lastException(e); return silentException_lastException = e; } static public Throwable lastSilentException() { return silentException_lastException; } static public List assertProperStreaks(List l) { int n = l(l); for (int i = 0; i + 1 < n; i++) if (l.get(i + 1).start <= l.get(i).end) throw fail("assertProperStreaks", str(l)); return l; } static public int[] imageToPixels(BufferedImage image) { return pixelsOfBufferedImage(image); } static public Transferable rawClipboardContents() { try { return Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); } catch (Exception __e) { throw rethrow(__e); } } static public String appendRoundBracketed(String b) { return empty(b) ? "" : "" + " (" + b + ")"; } static public String appendRoundBracketed(String a, String b) { return empty(b) ? a : a + appendRoundBracketed(b); } static public double alphaChannelAverage(int[] pixels) { int n = pixels.length; long sum = 0; for (int i = 0; i < n; i++) sum += rgbAlpha(pixels[i]); return doubleRatio(sum, n); } static public double radiansToDegrees(double rad) { return radianToDegree(rad); } static public ButtonGroup jUnselectedRadioButtons(Collection strings) { final ButtonGroup g = new ButtonGroup(); for (String s : unnull(strings)) jradiobutton(s, g); return g; } static public Color randomAWTColor() { return toColor(randomColor()); } static public boolean fileHasAnyExtensionAtAll(File f) { return contains(fileName(f), '.'); } static public List llSync(A... a) { return litsynclist(a); } static public void setWindowShape(Window w, Shape shape) { if (w != null) { swing(() -> { w.setShape(shape); }); } } static public String structTokWordWrap(String s) { return structTokWordWrap(120, s); } static public String structTokWordWrap(int cols, String s) { int col = 0; List tok = structTok(s); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && col >= cols && !containsNewLine(t)) tok.set(i, t = rtrimSpaces(t) + "\n"); int idx = t.lastIndexOf('\n'); if (idx >= 0) col = l(t) - (idx + 1); else col += l(t); } return join(tok); } static public byte[] bytesFromDataURL(String url) { String pref = "base64,"; int i = indexOf(url, pref); if (i < 0) return null; return base64decode(substring(url, i + l(pref))); } static public JComponent consoleInputFieldOrComboBox() { Object console = get(getJavaX(), "console"); JComboBox cb = (JComboBox) (getOpt(console, "cbInput")); if (cb != null) return cb; return (JTextField) getOpt(console, "tfInput"); } static public double minutesToDays(double minutes) { return minutes / (60 * 24); } static public PrintWriter filePrintWriter(File f) { return printWriter(bufferedFileOutputStream(f)); } static public List antiFilter(Iterable c, Object pred) { if (pred instanceof F1) return antiFilter(c, (F1) pred); List x = new ArrayList(); if (c != null) for (Object o : c) if (!isTrue(callF(pred, o))) x.add(o); return x; } static public List antiFilter(Object pred, Iterable c) { return antiFilter(c, pred); } static public List antiFilter(Object pred, Object[] c) { return antiFilter(pred, wrapArrayAsList(c)); } static public List antiFilter(Iterable c, F1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (!pred.get(o).booleanValue()) x.add(o); return x; } static public List antiFilter(F1 pred, Iterable c) { return antiFilter(c, pred); } static public List antiFilter(Iterable c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (!pred.get(o).booleanValue()) x.add(o); return x; } static public List antiFilter(IF1 pred, Iterable c) { return antiFilter(c, pred); } static public A keyForValue(B value, Map map) { return reverseLookup(value, map); } static public A keyForValue(Map map, B value) { return reverseLookup(map, value); } static public void arrayCopy(Object[] a, Object[] b) { arraycopy(a, b); } static public void arrayCopy(Object src, Object dest, int destPos, int n) { arrayCopy(src, 0, dest, destPos, n); } static public void arrayCopy(Object src, int srcPos, Object dest, int destPos, int n) { arraycopy(src, srcPos, dest, destPos, n); } static public Map decodeJSONMap(String s) { return jsonDecodeMap(s); } static public Pt pt_iround(double x, double y) { return new Pt(iround(x), iround(y)); } static public Pt pt_iround(IDoublePt p) { return p == null ? null : pt_iround(p.x_double(), p.y_double()); } static public String indentedStruct(Object o) { return indentedStructure(o); } static public String indentedStruct(Object o, structure_Data data) { return indentedStructure(o, data); } static public StringReader stringReader(String s) { return new StringReader(s); } static public ListIterator emptyListIterator() { return Collections.emptyListIterator(); } static public int totalVectorSSIPoints(Iterable l) { int sum = 0; for (var ssi : unnullForIteration(l)) if (ssi != null) sum += ssi.nPoints(); return sum; } static public PrintWriter bufferedFileWriter(File f) { return filePrintWriter(f); } static public BufferedImage minFilterBufferedImage(BufferedImage img) { return new MinimumFilter(1).get(img); } static public BufferedImage minFilterBufferedImage(int radius, BufferedImage img) { return new MinimumFilter(radius).get(img); } static public BufferedImage minFilterBufferedImage(int hradius, int vradius, BufferedImage img) { return new MinimumFilter(hradius, vradius).get(img); } static public short castIntToShort(int i) { return (short) i; } static public A nextToLast(List l) { return get(l, l(l) - 2); } static public List allToStruct(Iterable l) { return lmap(__135 -> struct(__135), l); } static public File transpilationPasswordFile() { return javaxSecretDir("transpilation-pw"); } static public boolean haveTranspilationPassword() { return nempty(transpilationPassword()); } static public int totalSSILines(Iterable l) { int sum = 0; for (var ssi : unnullForIteration(l)) if (ssi != null) sum += ssi.height(); return sum; } static public File installOrUpdateYouTubeDL() { File file = youTubeDLExecutable(); if (!file.exists()) return forceInstallYouTubeDL(); try { String newVersion = loadPage("https://rg3.github.io/youtube-dl/update/LATEST_VERSION"); File versionFile = javaxCodeDir("youtube-dl/youtube-dl.version"); if (!eq(newVersion, loadTextFile(versionFile))) { print("Found new youtube-dl version: " + newVersion); saveTextFile(versionFile, newVersion); return forceInstallYouTubeDL(); } } catch (Throwable __e) { pcallFail(__e); } return file; } static public List takeRandom(int n, List l) { return takeFirst(n, shuffledIterator(l)); } static public void assertIntArrayEquals(int[] a, int... b) { assertIntArrayEquals("", a, b); } static public void assertIntArrayEquals(String msg, int[] a, int... b) { assertIntArraysEqual(msg, a, b); } static public boolean isSpace(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } static public List regexpEscapeAll(Iterable l) { return regexpQuoteAll(l); } static public String readLineHidden() { try { if (get(javax(), "readLine_reader") == null) set(javax(), "readLine_reader", new BufferedReader(new InputStreamReader(System.in, "UTF-8"))); try { return ((BufferedReader) get(javax(), "readLine_reader")).readLine(); } finally { consoleClearInput(); } } catch (Exception __e) { throw rethrow(__e); } } static public MultiSet multiSet(Iterable l) { return toMultiSet(l); } static public JPanel panelWithoutLayoutManager() { return new JPanel(null); } static public DoubleRange intersectDoubleRanges(DoubleRange a, DoubleRange b) { double start = max(a.start, b.start); double end = min(a.end, b.end); return start <= end ? new DoubleRange(start, end) : null; } static public String textFromClipboard() { return getTextFromClipboard(); } static public java.util.regex.Pattern compileRegexpPossiblyIC(String pat, boolean ic) { return ic ? compileRegexpIC(pat) : compileRegexp(pat); } static public String trimLoadTextFile(String fileName) { return loadTextFile_trim(fileName); } static public String trimLoadTextFile(File f, String defaultContents) { return loadTextFile_trim(f, defaultContents); } static public String trimLoadTextFile(File fileName) { return loadTextFile_trim(fileName); } static public String trimLoadTextFile(String fileName, String defaultContents) { return loadTextFile_trim(fileName, defaultContents); } static public void zip2dir(File inZip, String outDir) { zip2dir(inZip, newFile(outDir)); } static public void zip2dir(File inZip, File outDir) { zip2dir(inZip, outDir, ""); } static public void zip2dir(File inZip, String outDir, String prefix) { zip2dir(inZip, newFile(outDir), prefix); } static public void zip2dir(File inZip, File outDir, String prefix) { try { if (prefix.length() != 0 && !prefix.endsWith("/")) prefix += "/"; ZipFile zipFile = new ZipFile(inZip); try { Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) continue; if (!entry.getName().startsWith(prefix)) continue; File outFile = new File(outDir, entry.getName()); print("Unzipping " + entry.getName() + " to " + outFile.getAbsolutePath()); stream2file(zipFile.getInputStream(entry), outFile); } } finally { _close(zipFile); } } catch (Exception __e) { throw rethrow(__e); } } static public JComponent jSliderPlusValue(JSlider slider) { return jSliderPlusValue(slider, ""); } static public JComponent jSliderPlusValue(JSlider slider, String unit) { return jSliderPlusValue(slider, value -> spaceCombine(n2(value), unit)); } static public JComponent jSliderPlusValue(JSlider slider, IF1 renderValue) { var lbl = jlabel(); onChangeAndNow(slider, () -> lbl.setText(renderValue.get(slider.getValue()))); return centerAndEastWithMargin(slider, lbl); } static public String spliceString(String a, int from, int to, String b) { return substring(a, 0, from) + b + substring(a, Math.max(from, to)); } static public String spliceString(String a, int from, int to, char b) { return spliceString(a, from, to, str(b)); } static final public short[] sqrUbyte_table = sqrUbyte_makeTable(); static public int sqrUbyte(int ubyte) { if ((ubyte & ~0xFF) != 0) throw fail("bad ubyte: " + ubyte); return unsignedShortToInt(sqrUbyte_table[ubyte]); } static public short[] sqrUbyte_makeTable() { short[] tbl = new short[256]; for (int i = 0; i < 256; i++) tbl[i] = (short) (i * i); return tbl; } static public int indexOfDifference(Iterable i1, Iterable i2) { var it1 = iterator(i1); var it2 = iterator(i2); int i = 0; while (true) { ping(); boolean a = it1.hasNext(), b = it2.hasNext(); if (a != b) return i; if (!a) return -1; A el1 = it1.next(); A el2 = it2.next(); if (!eq(el1, el2)) return i; ++i; } } static public short colorToHi15(RGB rgb) { return rgbToHi15(rgb); } static public short colorToHi15(Color color) { return rgbToHi15(color); } static public short colorToHi15(int rgb) { return rgbToHi15(rgb); } static public List virtualList(int n, IF1 f) { return listFromFunction(n, f); } static public List virtualList(IF1 f, int n) { return listFromFunction(f, n); } static public List jsonTok(String s) { List tok = new ArrayList(); int l = l(s); int i = 0; while (i < l) { int j = i; char c; String cc; while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j + 2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isLetter(c)) do ++j; while (j < l && Character.isLetter(s.charAt(j))); else if (Character.isDigit(c)) do ++j; while (j < l && Character.isDigit(s.charAt(j))); else ++j; tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static public String domainOrNull(String url) { try { return hostNameFromURL(url); } catch (Throwable e) { return null; } } static public String urlFileName(String url) { try { return empty(url) ? null : afterLastSlash(new URL(url).getPath()); } catch (Exception __e) { throw rethrow(__e); } } static public byte[] base64decode(String s) { byte[] alphaToInt = base64decode_base64toint; int sLen = s.length(); int numGroups = sLen / 4; if (4 * numGroups != sLen) throw new IllegalArgumentException("String length must be a multiple of four."); int missingBytesInLastGroup = 0; int numFullGroups = numGroups; if (sLen != 0) { if (s.charAt(sLen - 1) == '=') { missingBytesInLastGroup++; numFullGroups--; } if (s.charAt(sLen - 2) == '=') missingBytesInLastGroup++; } byte[] result = new byte[3 * numGroups - missingBytesInLastGroup]; int inCursor = 0, outCursor = 0; for (int i = 0; i < numFullGroups; i++) { int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); int ch3 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4)); result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2)); result[outCursor++] = (byte) ((ch2 << 6) | ch3); } if (missingBytesInLastGroup != 0) { int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4)); if (missingBytesInLastGroup == 1) { int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2)); } } return result; } static public int base64decode_base64toint(char c, byte[] alphaToInt) { int result = alphaToInt[c]; if (result < 0) throw new IllegalArgumentException("Illegal character " + c); return result; } static final public byte[] base64decode_base64toint = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 }; static public String nemptyLines(Iterable l) { return lines(nempties(allToStrOrNull(l))); } static public String nemptyLines(Object... l) { return nemptyLinesLL(l); } static public A centerTextField(A tf) { if (tf != null) { swing(() -> { tf.setHorizontalAlignment(JTextField.CENTER); }); } return tf; } static public long unixTime() { return unixTime(now()); } static public long unixTime(long timestamp) { return timestamp / 1000; } static public long unixTime(Date date) { return unixTime(toLong(date)); } static public String sfOrSCSnippet(String name) { { var __1 = sfSnippet(name); if (__1 != null) return __1; } return scSnippet(name); } static public void rangeSliderSetZeroToOneDoubleRange(RangeSlider slider, int max, DoubleRange r) { if (slider != null && r != null) { swing(() -> { slider.setValues(iround(r.start * max), iround(r.end * max)); }); } } static public void consoleSetInput(final String text) { if (headless()) return; setTextAndSelectAll(consoleInputField(), text); focusConsole(); } static public long stupidFib(int n) { return n < 3 ? 1 : stupidFib(n - 1) + stupidFib(n - 2); } static public JComponent jMaxSpeedAnimation(IF0 renderFrame) { ImageSurface is = new ImageSurface(); is.pixelate(true); is.autoZoomToDisplay(true); awtCalcContinuously(is, () -> { var img = renderFrame.get(); if (img != null) is.setImage(img); }); return jscroll_center_borderless(is); } static public Set valueSet(Map map) { return asHashSet(values(map)); } static public java.awt.Color color(String hex) { return awtColor(hex); } static public Timestamp ymdHMSToTimestamp(int year, int month, int day, int hour, int minute, int second) { return ymdHMSToTimestamp(year, month, day, hour, minute, second, defaultTimeZone()); } static public Timestamp ymdHMSToTimestamp(int year, int month, int day, int hour, int minute, int second, TimeZone tz) { try { return new Timestamp(simpleDateFormat("y/M/d H:m:s", tz).parse(year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second)); } catch (Exception __e) { throw rethrow(__e); } } static public ButtonGroup selectFirstRadioButton(ButtonGroup g) { selectRadioButton(first(buttonsInGroup(g))); return g; } static public String snippetLink(String id) { return empty(id) ? id : snippetLink(parseSnippetID(id)); } static public String snippetLink(long id) { return "https://code.botcompany.de/" + id; } static public void fileSavedInfoBox(File f) { infoBox("Saved " + fileInfo(f)); } static public boolean flipCoin() { return tossCoin(); } static public boolean flipCoin(Random random) { return tossCoin(random); } static public boolean flipCoin(double probability) { return tossCoin(probability); } static public int conceptCount(Concepts concepts, Class c, Object... params) { return countConcepts(concepts, c, params); } static public int conceptCount(Class c, Object... params) { return countConcepts(c, params); } static public int conceptCount() { return countConcepts(); } static public int conceptCount(String className) { return countConcepts(className); } static public int conceptCount(Concepts concepts, String className) { return countConcepts(concepts, className); } static public int conceptCount(Concepts concepts) { return countConcepts(concepts); } static public double cbrt(double x) { return Math.cbrt(x); } static public IntRange shiftIntRange(int shift, IntRange r) { return r == null ? null : shift == 0 ? r : intRange(r.start + shift, r.end + shift); } static public IntRange shiftIntRange(IntRange r, int shift) { return shiftIntRange(shift, r); } static public double sysSeconds() { return nanosToSeconds(nanoTime()); } static public List firstNCubes(int n) { return virtualList(n, i -> cubed(i + 1)); } static public float avg(float a, float b) { return (a + b) / 2; } static public double avg(double a, double b) { return (a + b) / 2; } static public double avg(double[] l) { return doubleAverage(l); } static public List directChildrenOfType(Container c, Class theClass) { return instancesOf(theClass, getChildren(c)); } static public List directChildrenOfType(Class theClass, Container c) { return directChildrenOfType(c, theClass); } static public String loadJavaXSecretTextFile(String name) { return loadSecretJavaXFile(name); } static public int idiv_floor(int a, int b) { return a / b; } static public int idiv_floor(double a, double b) { return ifloor(a / b); } static public int y2(Rectangle r) { return r.y + r.height; } static public BufferedImage imageWithMarkedBoxes(BufferedImage image, Collection boxes, Color color) { image = cloneBufferedImage(image); Graphics2D g = image.createGraphics(); for (var r : boxes) drawRect(g, r.x - 1, r.y - 1, r.w + 2, r.h + 2, color); return image; } static public Rect growRectTopAndLeft(Rect r) { return growRectTopAndLeft(r, 1); } static public Rect growRectTopAndLeft(Rect r, int pixels) { return new Rect(r.x - pixels, r.y - pixels, r.w + pixels, r.h + pixels); } static public long sysNanos() { return nanoTime(); } static public org.apache.bcel.generic.Type typeToBCELType(Type t) { return classToBCELType(getRawTypeClass(t)); } static public String takeFirst_unnull(int n, String s) { return unnull(takeFirst(n, s)); } static public void swapIntArray(int[] l, int i, int j) { if (i == j) return; int o = l[i]; l[i] = l[j]; l[j] = o; } static public Pair findMethod_withPrimitiveWidening_onTypes(Object o, String method, Class... argTypes) { try { Lowest best = new Lowest(); boolean widening = false; if (o instanceof Class) { _MethodCache cache = callOpt_getCache((Class) o); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) { { if (!(isStaticMethod(m))) continue; } int score = methodApplicabilityScore_withPrimitiveWidening_onTypes(m, argTypes); if (abs(score) < Integer.MAX_VALUE) { best.put(m, abs(score)); widening = score < 0; } } return pair(best.get(), widening); } if (o == null) return null; _MethodCache cache = callOpt_getCache(o.getClass()); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) { int score = methodApplicabilityScore_withPrimitiveWidening_onTypes(m, argTypes); if (abs(score) < Integer.MAX_VALUE) { best.put(m, abs(score)); widening = score < 0; } } return pair(best.get(), widening); } catch (Exception __e) { throw rethrow(__e); } } static public String rjoin(Iterable strings) { return rjoin("", strings); } static public String rjoin(String glue, Iterable strings) { if (strings == null) return ""; if (strings instanceof Collection) { if (((Collection) strings).size() == 1) return str(first((Collection) strings)); } StringBuilder buf = new StringBuilder(); Iterator i = reversed(strings).iterator(); if (i.hasNext()) { buf.append(i.next()); while (i.hasNext()) buf.append(glue).append(i.next()); } return buf.toString(); } static public String rjoin(String glue, String... strings) { return join(glue, asVirtualReversedList(strings)); } static public String rjoin(Iterable strings, String glue) { return rjoin(glue, strings); } static public String rjoin(String[] strings) { return rjoin("", strings); } static public String resolveKeyIC(Map map, String key) { return resolveKeyCI(map, key); } static public long longSum(Iterable l) { long sum = 0; for (Long i : unnull(l)) if (i != null) sum += i; return sum; } static public long longSum(IF1 f, Iterable l) { return longSum(mapI(f, l)); } static volatile public boolean readLine_noReadLine = false; static public String readLine_lastInput; static public String readLine_prefix = "[] "; static public String readLine() { if (readLine_noReadLine) return null; String s = readLineHidden(); if (s != null) { readLine_lastInput = s; print(readLine_prefix + s); } return s; } static public File canonicalFile(String path) { return getCanonicalFile(path); } static public File canonicalFile(File f) { return getCanonicalFile(f); } static public Timestamp toTimestamp(long unixTime) { return unixTime == 0 ? null : new Timestamp(unixTime); } static public Timestamp toTimestamp(java.nio.file.attribute.FileTime fileTime) { return fileTime == null ? null : toTimestamp(fileTime.toMillis()); } static public JTextField consoleInputField() { Object console = get(getJavaX(), "console"); return (JTextField) getOpt(console, "tfInput"); } static public JSlider jSlider(int min, int max, int value) { return swing(() -> { return new JSlider(min, max, value); }); } static public JSlider jSlider(int max) { return jSlider(0, max, 0); } static public A wrapStuff(String name, A object, Object... args) { return or((A) callOpt(mc(), "_wrap", object, asList(args)), object); } static public JLabel jcenterlabel(String text) { return jcenteredlabel(text); } static public JLabel jcenterlabel() { return jcenteredlabel(); } static public int[] imageToIntPixels(BufferedImage image) { return pixelsOfBufferedImage(image); } static public void consoleClearInput() { consoleSetInput(""); } static public String formatDouble2(double d) { return formatDouble(d, 2); } static public String standard_toString(Object o) { if (o == null) return "null"; String name = shortClassName(o); Set fields = fieldNames(o); if (empty(fields)) return name; return name + "(" + joinWithComma(mapNonNulls(fields, field -> { Object value = get(o, field); if (value == null) return null; return field + "=" + str(value); })) + ")"; } static public byte[] toByteArray(ByteArrayOutputStream baos) { return baos == null ? null : baos.toByteArray(); } static public byte[] toByteArray(Iterator it) { ByteBuffer buf = new ByteBuffer(); while (it.hasNext()) buf.add((byte) it.next().intValue()); return buf.toByteArray(); } static public byte[] toByteArray(Collection it) { int n = l(it), i = 0; byte[] a = new byte[n]; for (var x : it) a[i++] = (byte) x.intValue(); return a; } static public byte[] toByteArray(Object o) { if (o == null) return null; if (o instanceof byte[]) return ((byte[]) o); if (o instanceof Iterator) return toByteArray((Iterator) o); if (o instanceof Collection) return toByteArray((Collection) ((Collection) o)); throw fail("toByteArray", o); } static public byte[] toByteArray(java.nio.ByteBuffer buf) { if (buf == null) return null; byte[] a = new byte[buf.remaining()]; buf.get(a); return a; } static public BufferedOutputStream bufferedOutputStream(OutputStream out) { if (out == null) return null; if (out instanceof BufferedOutputStream) return ((BufferedOutputStream) out); return new BufferedOutputStream(out, defaultBufferedOutputStreamSize()); } static public BufferedOutputStream bufferedOutputStream(File f) { return bufferedOutputStream(fileOutputStream(f)); } static public int parseIntOr0(String s) { return parseInt(s); } static public int parseIntOr0(char c) { return parseInt(c); } static public IterableIterator splitAtSpaceIterator(String s) { return iff_null(new IF0() { public int i = 0, l = l(s); public String get() { while (i < l) { if (isSpaceEtc(s.charAt(i))) ++i; else break; } if (i >= l) return null; int j = i; while (j < l && !isSpaceEtc(s.charAt(j))) ++j; String part = substring(s, i, j); i = j; return part; } }); } static public double standardDeviation(int... a) { if (empty(a)) return 0; double avg = doubleAverage(a), sum = 0; for (int i = 0; i < l(a); i++) sum += sqr(a[i] - avg); return sqrt(sum / l(a)); } static public double standardDeviation(double... a) { if (empty(a)) return 0; double avg = doubleAverage(a), sum = 0; for (int i = 0; i < l(a); i++) sum += sqr(a[i] - avg); return sqrt(sum / l(a)); } static public double standardDeviation(Collection a) { if (empty(a)) return 0; double avg = doubleAverage(a), sum = 0; for (double d : a) sum += sqr(d - avg); return sqrt(sum / l(a)); } static public BWImage bwImageFromFunction(int w, IF2_IntInt_Double f) { return bwImageFromFunction(w, w, f); } static public BWImage bwImageFromFunction(int w, int h, IF2_IntInt_Double f) { BWImage img = new BWImage(w, h); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) img.setPixel(x, y, (float) f.get(x, y)); return img; } static public BWImage bwImageFromFunction(int w, IF0 f) { return bwImageFromFunction(w, w, f); } static public BWImage bwImageFromFunction(int w, int h, IF0 f) { return bwImageFromFunction(w, (x, y) -> f.get()); } static public Color withOpacity(Color c, double alpha) { return colorWithAlpha(c, alpha); } static public Color withOpacity(double alpha, Color c) { return colorWithAlpha(alpha, c); } static public int withOpacity(int opacity, int rgb) { return (opacity << 24) | (rgb & 0xFFFFFF); } static public String formatDate() { return formatDate(now()); } static public String formatDate(long timestamp) { return timestamp == 0 ? "-" : str(new Date(timestamp)); } static public String formatDate(long timestamp, String format, TimeZone tz) { return simpleDateFormat(format, tz).format(timestamp); } static public String str_toKB_oneDecimal(long l) { return formatDouble1(l / 1024.0 + 0.09999) + " KB"; } static public WeakIdentityHashMap weakIdentityMap() { return weakIdentityHashMap(); } static public JPanel jSingleColor(Color color) { return singleColorPanel(color); } static public HashSet asHashSet(Collection c) { synchronized (collectionMutex(c)) { return new HashSet(c); } } static public HashSet asHashSet(A[] a) { return a == null ? null : new HashSet(Arrays.asList(a)); } static public List lasTok(String s) { return javaTok(s); } static public List lasTok(List tok) { return javaTok(tok); } static public String dataURLMimeType(String dataURL) { if (!isDataURL(dataURL)) return null; String s = dropPrefixOrNull("data:", dataURL); if (s == null) return null; int i = indexOfAny(s, ";,"); if (i < 0) return null; return takeFirst(s, i); } static public IterableIterator allPermutations_iterator(final List theList) { return new IterableIterator() { public int[] next; public int n = l(theList); public int[] perm, dirs; { if (n > 0) { perm = new int[n]; dirs = new int[n]; for (int i = 0; i < n; i++) { perm[i] = i; dirs[i] = -1; } dirs[0] = 0; } next = perm; } @Override public Object[] next() { int[] r = makeNext(); next = null; Object[] out = new Object[n]; for (int i = 0; i < n; i++) out[i] = theList.get(r[i]); return out; } @Override public boolean hasNext() { return (makeNext() != null); } @Override public void remove() { throw new UnsupportedOperationException(); } public int[] makeNext() { ping(); if (next != null) return next; if (perm == null) return null; int i = -1, e = -1; for (int j = 0; j < n; j++) if ((dirs[j] != 0) && (perm[j] > e)) { e = perm[j]; i = j; } if (i == -1) return (next = (perm = (dirs = null))); int k = i + dirs[i]; swapIntArray(dirs, i, k); swapIntArray(perm, i, k); if ((k == 0) || (k == n - 1) || (perm[k + dirs[k]] > e)) dirs[k] = 0; for (int j = 0; j < n; j++) if (perm[j] > e) dirs[j] = (j < k) ? +1 : -1; return (next = perm); } }; } static public void setRGB(BufferedImage img, Pt p, RGB rgb) { { if (img != null) img.setRGB(p.x, p.y, rgb.asIntWithAlpha()); } } static public void setRGB(BufferedImage img, int x, int y, RGB rgb) { { if (img != null) img.setRGB(x, y, rgb.asIntWithAlpha()); } } static public void setRGB(BufferedImage img, int x, int y, Color color) { { if (img != null) img.setRGB(x, y, colorToIntOpaque(color)); } } static public void setSliderValue(JSlider slider, int value) { if (slider != null) { swing(() -> { slider.setValue(clamp(value, slider.getMinimum(), slider.getMaximum())); }); } } static public List sortByCalculatedFieldDesc(Collection c, final Object f) { return sortByCalculatedFieldDesc_inPlace(cloneList(c), f); } static public List sortByCalculatedFieldDesc(Object f, Collection c) { return sortByCalculatedFieldDesc(c, f); } static public List sortByCalculatedFieldDesc(Iterable c, IF1 f) { List l = cloneList(c); sort(l, new Comparator() { public int compare(A a, A b) { return stdcompare(f.get(b), f.get(a)); } }); return l; } static public List sortByCalculatedFieldDesc(IF1 f, Iterable c) { return sortByCalculatedFieldDesc(c, f); } static public List> biggestRegionsFirst(Collection> l) { return sortByCalculatedFieldDesc(l, r -> r.numberOfPixels()); } static public Image2B image2B_growBlack(Image2B img, int dx, int dy) { return image2BFromFunction(img.getWidth(), img.getHeight(), (x, y) -> img.getPixel(x + dx, y + dy, true) && img.getPixel(x, y)); } static public PrintWriter newPrintWriter(OutputStream out) { return new PrintWriter(outputStreamToWriter(out)); } static public PrintWriter newPrintWriter(Writer out) { return new PrintWriter(out); } static public NanoHTTPD.Response serveHTML(Object text) { return NanoHTTPD.newFixedLengthResponse(str(text)); } static public List windowsProgramFilesDirs() { return dirsThatExist("C:\\Program Files", "C:\\Program Files (x86)"); } static public String ubyteToHex(int b) { return bytesToHex(new byte[] { (byte) b }); } static public File chromeBookmarksFile() { File bookmarksDir = isWindows() ? userDir_oneOf("Local Settings/Application Data/Google/Chrome/User Data/Default", "AppData/Local/Google/Chrome/User Data/Default") : userDir(".config/google-chrome/Default"); return fileIfExists(newFile(bookmarksDir, "Bookmarks")); } static public void printMyIPs() { String ip; try { Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface iface = interfaces.nextElement(); if (iface.isLoopback() || !iface.isUp()) continue; Enumeration addresses = iface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); ip = addr.getHostAddress(); if (ip.startsWith("127.")) continue; boolean local = addr.isSiteLocalAddress() || ip.startsWith("fe"); System.out.println(iface.getDisplayName() + " " + ip + " " + (local ? "(private address)" : "(public address)")); } } } catch (Throwable e) { e.printStackTrace(); } } static public Concept options(List l) { return l(l) == 1 ? first(l) : new Options(l); } static public double ratioToPercent(double x, double y) { return x * 100 / y; } static public List flattenCollections(Iterable a) { List l = new ArrayList(); for (Object x : a) if (x instanceof Collection) l.addAll(flattenCollections((Collection) x)); else l.add(x); return l; } static public void assertBetween(long a, long b, long x) { assertBetween("", a, b, x); } static public void assertBetween(String msg, long a, long b, long x) { { if (x >= a && x <= b) return; } throw fail(colonCombine(msg, x + " is not between " + a + " and " + b)); } static public void assertBetween(int a, int b, int x) { assertBetween("", a, b, x); } static public void assertBetween(String msg, int a, int b, int x) { { if (x >= a && x <= b) return; } throw fail(colonCombine(msg, x + " is not between " + a + " and " + b)); } static public void assertBetween(double a, double b, double x) { assertBetween("", a, b, x); } static public void assertBetween(String msg, double a, double b, double x) { { if (x >= a && x <= b) return; } throw fail(colonCombine(msg, x + " is not between " + a + " and " + b)); } static public A highestBy(Iterable l, Object f) { return highestByFunction(l, f); } static public A highestBy(Object f, Iterable l) { return highestByFunction(f, l); } static public A highestBy(Iterable l, IF1 f) { return highestByFunction(f, l); } static public A highestBy(IF1 f, Iterable l) { return highestByFunction(f, l); } static public A highestBy(IF1 f, A[] l) { return highestByFunction(f, wrapAsList(l)); } static public int numberOfBits(int i) { return 32 - Integer.numberOfLeadingZeros(i); } static public boolean between(long x, long min, long max) { return isBetween(x, min, max); } static public boolean between(double x, double min, double max) { return isBetween(x, min, max); } static public BufferedImage imageFromDataURL(String url) { return decodeImage(bytesFromDataURL(url)); } static public Image2B bwImageToBinary(BWImage img, int threshold) { return new Image2B(img, threshold); } static public double intsToKB(double ints) { return ints / 512; } static public double[] resizeDoubleArray(double[] a, int n) { if (n == l(a)) return a; double[] b = new double[n]; arraycopy(a, 0, b, 0, min(l(a), n)); return b; } static public Image2B toImage2B(BufferedImage img) { return img == null ? null : new Image2B(img); } static public Image2B toImage2B(MakesBufferedImage img) { if (img == null) return null; if (img instanceof Image2B) return ((Image2B) img); if (img instanceof BWImage) return new Image2B((BWImage) img); if (img instanceof IBinaryImage) return iBinaryImageToImage2B((IBinaryImage) img); return new Image2B(toBufferedImage(img)); } static public boolean isSingleton(Collection l) { return l(l) == 1; } static public void selectRadioButton(final AbstractButton rb) { if (rb == null) return; { swing(() -> { rb.setSelected(true); }); } } static public void selectRadioButton(ButtonGroup group, int index) { selectRadioButton(get(buttonsInGroup(group), index)); } static public String hexDump(byte[] bytes) { return mapToLines(chunk -> insertSpaceAt(32, bytesToHex_upper(chunk)), byteArrayChunksIterator(bytes, 32)); } static public String hexDump(File f) { return hexDump(loadBinaryFile(f)); } static public String parentName(File f) { return fileName(parentFile(f)); } static public List reallyLazyMap(IF1 f, List l) { return lazyMap_noSave(f, l); } static public List reallyLazyMap(List l, IF1 f) { return lazyMap_noSave(f, l); } static public double doubleMin(Iterable l) { double min = infinity(); for (double d : unnullForIteration(l)) min = Math.min(min, d); return min; } static public double doubleMin(double... l) { double min = infinity(); for (double d : unnullForIteration(l)) min = Math.min(min, d); return min; } static public A bindTextComponentToVarWithNotify_noInitialUndo(A tc, IVarWithNotify lv) { onFirstShow(tc, () -> clearTextComponentUndoList(tc)); return bindTextComponentToVarWithNotify(tc, lv); } static public boolean regexpLiteralNeedsQuoting(String s) { int n = l(s); for (int i = 0; i < n; i++) if (regexpSpecialCharacters().indexOf(s.charAt(i)) >= 0) return true; return false; } static public boolean lessThanOrEqual(int a, int b) { return a <= b; } static public boolean lessThanOrEqual(double a, double b) { return a <= b; } static public > boolean lessThanOrEqual(A a, A b) { return cmp(a, b) <= 0; } static public String nemptyLinesLL(Object... l) { return nemptyLines(ll(l)); } static public String indentedStructure(Object o) { return indentStructureString(struct(o)); } static public String indentedStructure(Object o, structure_Data data) { return indentStructureString(struct(o, data)); } static public List listChildren(Container c) { return getChildren(c); } static public String classNameToByteCodeFormat(String className) { return "L" + className.replace('.', '/'); } static public String classNameToByteCodeFormat(Class c) { return classNameToByteCodeFormat(className(c)); } static public Map parsePrimitiveType_map = litmap("int", int.class, "char", char.class, "byte", byte.class, "short", short.class, "long", long.class, "float", float.class, "double", double.class, "bool", boolean.class); static public Class parsePrimitiveType(String s) { return parsePrimitiveType_map.get(s); } static public double asPercentIncrease(double ratio) { return (ratio - 1) * 100; } static public double asPercentIncrease(double a, double b) { return asPercentIncrease(doubleRatio(a, b)); } static public BufferedImage averageBrightnessImage(BufferedImage img) { return newBufferedImage(1, 1, blendColor(Color.black, Color.white, new BWImage(img).averageBrightness())); } static public void moveFileVerbose(File f, File dest) { moveFile(f, dest); print("Moved file " + f2s(f) + " to " + dest); } static public long gzippedSize(byte[] data) { try { JustCountingOutputStream jcos = new JustCountingOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(jcos); gos.write(data, 0, l(data)); gos.close(); return jcos.get(); } catch (Exception __e) { throw rethrow(__e); } } static public int gzippedSize(String s) { return l(gzipString(s)); } static public long gzippedSize(File f) { try { JustCountingOutputStream jcos = new JustCountingOutputStream(); var gos = new GZIPOutputStream(jcos); file2stream(f, gos); gos.close(); return jcos.get(); } catch (Exception __e) { throw rethrow(__e); } } static public Map putOrCreateSyncMap(Map map, A key, B value) { if (map == null) map = syncHashMap(); map.put(key, value); return map; } static public double log(double d) { return Math.log(d); } static public double log(double d, double base) { return Math.log(d) / Math.log(base); } static public A highestByField(String field, Collection l) { A best = null; Object bestValue = null; if (l != null) for (A a : l) { Object val = getOpt(a, field); if (val != null && (bestValue == null || cmp(val, bestValue) > 0)) { best = a; bestValue = val; } } return best; } static public A highestByField(Collection l, String field) { return highestByField(field, l); } static public IF0 transpilationPassword; static public String transpilationPassword() { return transpilationPassword != null ? transpilationPassword.get() : transpilationPassword_base(); } final static public String transpilationPassword_fallback(IF0 _f) { return _f != null ? _f.get() : transpilationPassword_base(); } static public String transpilationPassword_base() { return trimLoadTextFile(transpilationPasswordFile()); } static public Comparator reverseOrder() { return new Comparator() { public int compare(Object a, Object b) { return cmp(b, a); } }; } static public Object callWithVarargs_sentinel(Object o, String methodName, Object methodNotFoundSentinel, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findStaticMethod(methodName, args); if (me != null) return invokeMethod(me, null, args); List methods = cache.cache.get(methodName); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } { if (!(isStaticMethod(m))) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, null, newArgs); } return methodNotFoundSentinel; } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me != null) return invokeMethod(me, o, args); List methods = cache.cache.get(methodName); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, o, newArgs); } return methodNotFoundSentinel; } } catch (Exception __e) { throw rethrow(__e); } } static public Double parseDoubleOpt(String s) { try { return empty(s) ? null : Double.parseDouble(s); } catch (Throwable __e) { return null; } } static public BufferedImage randomImage(int w) { return randomImage(w, w); } static public BufferedImage randomImage(int w, int h) { return imageFromFunction(w, h, (x, y) -> random(0x1000000) | fullAlphaMask()); } static public double cyclicDistance(double a, double b, double cycleLength) { a = mod(a, cycleLength); b = mod(b, cycleLength); double diff = absDiff(a, b); if (a < b) diff = min(diff, a + cycleLength - b); else diff = min(diff, b + cycleLength - a); return diff; } static public List mergeOverlappingRects(List boxes) { while (true) { ping(); boolean change = false; for (var box1 : boxes) { for (var box2 : boxes) { if (box1 == box2) continue; if (rectsOverlap(box1, box2)) { copyRect(rectUnion(box1, box2), box1); box2.w = 0; box2.h = 0; change = true; } ; } } if (!change) break; boxes = filter(boxes, b -> nempty(b)); } return boxes; } static public PrintWriter printWriter(OutputStream out) { return newPrintWriter(out); } static public PrintWriter printWriter(Writer out) { return newPrintWriter(out); } static public boolean hasStaticMethodNamed(Class c, String method) { if (c == null) return false; var methods = getMethodCache(c).cache.get(method); if (methods != null) for (var m : methods) if (isStaticMethod(m)) return true; return false; } static public String byteToHex(int b) { return ubyteToHex(b); } static public ButtonGroup jradiobuttons(Collection strings) { return selectFirstRadioButton(jUnselectedRadioButtons(strings)); } static public ButtonGroup jradiobuttons(String... strings) { return jradiobuttons(asList(strings)); } static public String youTubeDL_URL() { return isWindows() ? "https://yt-dl.org/latest/youtube-dl.exe" : "https://yt-dl.org/downloads/latest/youtube-dl"; } static public String getClientIPFromHeaders(Map headers) { if (headers == null) return null; String remoteAddr = (String) (headers.get("remote-addr")); String client = (String) (headers.get("x-forwarded-for")); if (nempty(client)) remoteAddr += "," + client; return remoteAddr; } static public Object fieldGet(Field f, Object o) { try { return f == null ? null : f.get(o); } catch (Exception __e) { throw rethrow(__e); } } static public void makeExecutable(File file) { try { if (!isWindows()) try { makeExecutable_java7(file); } catch (Throwable _e) { warn("Java 6 fallback for makeExecutable"); backtick("chmod a+rx " + bashQuote(file)); } } catch (Exception __e) { throw rethrow(__e); } } static public String prependWithColonSpace(String s) { return appendColonIfNempty(s); } static public int iround_blend(double x, double y, double yish) { return iround(blend(x, y, yish)); } static public Collection addOrCreate(Collection l, A a) { return addDyn(l, a); } static public List addOrCreate(List l, A a) { return addDyn(l, a); } static public Set addOrCreate(Set l, A a) { return createOrAddToSet(l, a); } static public void truncateList(List l, int n) { if (l(l) <= n) return; removeSubList(l, n, l(l)); } static public String loadSecretJavaXFile(String name) { return loadTextFile(new File(javaxSecretDir(), name)); } static public int cubed(int i) { return i * i * i; } static public double cubed(double d) { return pow(d, 3); } static public double timesPercent(double a, double b) { return a * b / 100; } static public double distanceToProbability(double distance) { return genericDistanceToProbability(distance); } static public double distanceToProbability(double a, double b) { return genericDistanceToProbability(a, b); } static public boolean isUByte(int i) { return (i & 0xFF) == i; } static public Image2B image2BFromFunction(int w, IIntIntPred f) { return image2BFromFunction(w, w, f); } static public Image2B image2BFromFunction(int w, int h, IIntIntPred f) { Image2B img = new Image2B(w, h); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) img.setPixel(x, y, f.get(x, y)); return img; } static public Image2B image2BFromFunction(int w, IF0_Bool f) { return image2BFromFunction(w, w, f); } static public Image2B image2BFromFunction(int w, int h, IF0_Bool f) { return image2BFromFunction(w, h, (x, y) -> f.get()); } static public JSplitPane jvsplit_minZero(Component n, Component s) { return jvsplit_minZero(n, s, 0.5); } static public JSplitPane jvsplit_minZero(Component n, Component s, double splitPoint) { return jvsplit(jMinHeight0(n), jMinHeight0(s), splitPoint); } static public JSplitPane jvsplit_minZero(double splitPoint, Component n, Component s) { return jvsplit_minZero(n, s, splitPoint); } static public Map jsonDecodeMap(String s) { Object o = jsonDecode(s); if (o instanceof List && empty((List) o)) return new HashMap(); if (o instanceof Map) return (Map) o; else throw fail("Not a JSON map: " + s); } static public short toShort_enforce(long l) { if (l != (short) l) throw fail("Too large for short: " + l); return (short) l; } static public int rgbIntFullAlpha(int r, int g, int b) { return (clamp(r, 0, 255) << 16) | (clamp(g, 0, 255) << 8) | clamp(b, 0, 255) | fullAlphaMask(); } static public List takeFirstNSSILines(int maxLines, Iterable l) { if (maxLines == Integer.MAX_VALUE) return asList(l); int sum = 0; List out = new ArrayList(); for (var ssi : unnullForIteration(l)) { if (sum >= maxLines) break; int linesToCopy = min(ssi.height(), maxLines - sum); if (linesToCopy < ssi.height()) break; out.add(ssi); sum += ssi.height(); } return out; } static public int selectedIndex(JComboBox cb) { return getSelectedIndex(cb); } static public int selectedIndex(JList l) { return getSelectedIndex(l); } static public int selectedIndex(ButtonGroup group) { return swing(() -> { return indexOfPred(buttonsInGroup(group), btn -> btn.isSelected()); }); } static public A getWeakRef(Reference ref) { return ref == null ? null : ref.get(); } static public String insertSpaceAt(String s, int i) { return insertAt(s, i, " "); } static public String insertSpaceAt(int i, String s) { return insertSpaceAt(s, i); } static public JScrollPane jscroll_borderless_center(Component c) { return jscroll_centered_borderless(c); } static public BufferedImage transparentBufferedImage(Dimension size) { return transparentBufferedImage(toWidthAndHeight(size)); } static public BufferedImage transparentBufferedImage(int size_w, int size_h) { return transparentBufferedImage(widthAndHeight(size_w, size_h)); } static public BufferedImage transparentBufferedImage(WidthAndHeight size) { BufferedImage img = new BufferedImage(size.w(), size.h(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = getGraphics2D(img); g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR)); g.fillRect(0, 0, size.w(), size.h()); return img; } static public String apacheCommonsExec(List args) { try { var cmdLine = new org.apache.commons.exec.CommandLine(first(args)); for (var arg : dropFirst(args)) cmdLine.addArgument(arg); return apacheCommonsExec(cmdLine); } catch (Exception __e) { throw rethrow(__e); } } static public String apacheCommonsExec(String cmd) { return apacheCommonsExec(org.apache.commons.exec.CommandLine.parse(cmd)); } static public String apacheCommonsExec(org.apache.commons.exec.CommandLine cmdLine) { try { org.apache.commons.exec.DefaultExecutor executor = new org.apache.commons.exec.DefaultExecutor(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream stream = teeOutputStream(printOutputStream(), baos); org.apache.commons.exec.PumpStreamHandler pump = new org.apache.commons.exec.PumpStreamHandler(stream, stream); executor.setStreamHandler(pump); print("Exit value: " + executor.execute(cmdLine)); return fromUTF8(toByteArray(baos)); } catch (Exception __e) { throw rethrow(__e); } } static public List splitAtSpaceTokenizer(String s) { ArrayList tok = new ArrayList(); int l = l(s); int i = 0, n = 0; while (i < l) { int j = i; char c; while (j < l) { c = s.charAt(j); if (isSpace(c)) ++j; else break; } tok.add(javaTok_substringN(s, i, j)); ++n; i = j; if (i >= l) break; while (j < l && !isSpace(s.charAt(j))) ++j; tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static public int hi15ToRGBInt_clean(short hi15) { int r = (hi15 >> 10) & 0x1F; int g = (hi15 >> 5) & 0x1F; int b = hi15 & 0x1F; double factor = 255.0 / 31; r = iround(r * factor); g = iround(g * factor); b = iround(b * factor); return (r << 16) | (g << 8) | b; } static public BufferedImage blurBufferedImage(BufferedImage img) { return blurFilterBufferedImage(img); } static public BufferedImage blurBufferedImage(int hradius, BufferedImage img) { return blurBufferedImage(hradius, hradius, img); } static public BufferedImage blurBufferedImage(int hradius, int vradius, BufferedImage img) { return blurFilterBufferedImage(hradius, vradius, img); } static public BufferedImage blurBufferedImage(BufferedImage img, int hradius) { return blurBufferedImage(img, hradius, hradius); } static public BufferedImage blurBufferedImage(BufferedImage img, int hradius, int vradius) { return blurFilterBufferedImage(hradius, vradius, img); } static public double percentIncrease(double a, double b) { return (doubleRatio(a, b) - 1) * 100; } static public BufferedImage drawableToImage(WidthAndHeight size, G2Drawable drawable) { var img = whiteImage(size); { if (drawable != null) drawable.drawOn(img); } return img; } static public List listZip(File inZip) { return listZipFile(inZip); } static public List listZip(String inZip) { return listZipFile(inZip); } static public MyHTTPD serveHttpFromWebServable(int port, WebServable webServable) { try { assertNotNull("webServable", webServable); MyHTTPD server = new MyHTTPD(port); server.serveFunction = new F2, Object>() { public Object get(String uri, Map params) { try { var session = nanoHTTPDCurrentSession(); var req = new WebRequest(session, uri, params); return webServable.html(req); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var session = nanoHTTPDCurrentSession();\r\n var req = new WebRequest(sessio..."; } }; server.start(); print("HTTP port " + port + " open exposing " + webServable); return server; } catch (Exception __e) { throw rethrow(__e); } } static public File youTubeDLExecutable() { return javaxCodeDir("youtube-dl/" + (isWindows() ? "youtube-dl.exe" : "youtube-dl")); } static public double relativeToRange(double x, DoubleRange r) { return doubleRatio(x - r.start, r.length()); } static public class ChromeBookmark implements IFieldsToList { static final public String _fieldOrder = "url name dateAdded"; public String url; public String name; public long dateAdded; public ChromeBookmark() { } public ChromeBookmark(String url, String name, long dateAdded) { this.dateAdded = dateAdded; this.name = name; this.url = url; } public boolean equals(Object o) { if (!(o instanceof ChromeBookmark)) return false; ChromeBookmark __1 = (ChromeBookmark) o; return eq(url, __1.url) && eq(name, __1.name) && dateAdded == __1.dateAdded; } public int hashCode() { int h = -63795728; h = boostHashCombine(h, _hashCode(url)); h = boostHashCombine(h, _hashCode(name)); h = boostHashCombine(h, _hashCode(dateAdded)); return h; } public Object[] _fieldsToList() { return new Object[] { url, name, dateAdded }; } public String toString() { return name + appendRoundBracketed(url) + " " + timestamp(); } public Timestamp timestamp() { return chromeTimestampToTimestamp(dateAdded); } } static public List getChromeBookmarks() { return getChromeBookmarks(chromeBookmarksFile()); } static public List getChromeBookmarks(File bookmarksFile) { assertTrue("No bookmarks dir", isFile(bookmarksFile)); String text = loadTextFile(bookmarksFile); assertNotNull("No Bookmarks file: " + bookmarksFile.getAbsolutePath(), text); Object json = jsonDecode(text); List list = new ArrayList(); for (Map map : findAllMaps(json)) { try { Object url = map.get("url"); if (url instanceof String) { ChromeBookmark b = new ChromeBookmark(); b.url = (String) url; b.name = (String) map.get("name"); b.dateAdded = parseLong(map.get("date_added")); list.add(b); } } catch (Throwable __e) { pcallFail(__e); } } return list; } static public List pointsAroundCircle(Pt center, int n, double radius) { double step = doubleRatio(pi() * 2, n); return listFromFunction(n, i -> pointOnCircle(center, radius, i * step)); } static public int iround_clamp(double d) { return iround(clamp(d, Integer.MIN_VALUE, Integer.MAX_VALUE)); } static public List mapPairsToList(Iterable> l, F2 f) { List x = emptyList(l); if (l != null) for (Pair p : l) x.add(callF(f, p.a, p.b)); return x; } static public List mapPairsToList(Iterable> l, IF2 f) { List x = emptyList(l); if (l != null) for (Pair p : l) x.add(f.get(p.a, p.b)); return x; } static public List mapPairsToList(Object f, Iterable> l) { List x = emptyList(l); if (l != null) for (Pair p : l) x.add(callF(f, p.a, p.b)); return x; } static public String typeToVMSignature(Type t) { Class c = getRawTypeClass(t); if (t instanceof ParameterizedType) { List args = map(__136 -> getRawTypeClass(__136), ((ParameterizedType) t).getActualTypeArguments()); if (nempty(args)) return classNameToByteCodeFormat(c) + "<" + joinMap(args, arg -> classNameToByteCodeFormat(arg) + ";") + ">;"; } return classNameToByteCodeFormat(c) + ";"; } static public String scSnippet(String name) { return stdClasses_cached().get(name); } static public File backtickToConsole(String cmd) { ping(); File outputFile = createTempFile(cmd, ".out"); makeEmptyFile(outputFile); TailFile tail = tailFile2(outputFile, 1000, __1 -> printNoNewLine_fix(__1)); print("Running: " + cmd); try { backtickToFile(cmd, outputFile); } catch (Throwable __e) { pcallFail(__e); } tail.stop(); return outputFile; } static public int zeroToOneToZeroTo255(double brightness) { return iround(brightness * 255.0); } static public boolean intRangesOverlapNempty(IntRange a, IntRange b) { return nempty(intersectIntRanges(a, b)); } static public boolean intRangesOverlapNempty(int a1, int a2, int b1, int b2) { return intRangesOverlapNempty(intRange(a1, a2), intRange(b1, b2)); } static public List clipboardContentsDataFlavors() { try { return asList(Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors()); } catch (Exception __e) { throw rethrow(__e); } } static public int absdiff(int a, int b) { return abs(a - b); } static public long absdiff(long a, long b) { return abs(a - b); } static public float absdiff(float a, float b) { return abs(a - b); } static public double absdiff(double a, double b) { return abs(a - b); } static public int rgbDistanceSquaredInt(int a, int b) { return sqrUbyte(absDiff(rgbRed(a), rgbRed(b))) + sqrUbyte(absDiff(rgbGreen(a), rgbGreen(b))) + sqrUbyte(absDiff(rgbBlue(a), rgbBlue(b))); } static public String spaceCombine(Object... l) { return joinNemptiesWithSpace(flattenCollections(ll(l))); } static public IF1 domainPredicateToURLPredicate(IF1 p) { return p == null ? null : url -> p.get(domainOrNull(url)); } static public void swapElements(List l, int i, int j) { if (i == j) return; Object o = l.get(i); l.set(i, l.get(j)); l.set(j, o); } static public double zeroToOneSine(double x) { return 0.5 * (1 + sin(x * (pi() * 2))); } static public BufferedImage getImageFromClipboard() { try { Transferable t = rawClipboardContents(); if (t == null) return null; List l = (List) (getTransferData(t, DataFlavor.javaFileListFlavor)); if (nempty(l)) return loadImage2(first(l)); if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) return (BufferedImage) t.getTransferData(DataFlavor.imageFlavor); return imageFromDataURL(getTextFromClipboard()); } catch (Exception __e) { throw rethrow(__e); } } static public int loadTextFilePart_iterator_chunkSize = 65536; static public Iterable loadTextFilePart_iterator(File file, long start, long end) { try { if (end - start <= loadTextFilePart_iterator_chunkSize) return ll(loadTextFilePart(file, start, end)); final FileInputStream in = newFileInputStream(file); in.skip(start); final byte[] buf = new byte[loadTextFilePart_iterator_chunkSize]; final UTF8Processor p = new UTF8Processor(); return iteratorFF(new F0() { public Object get() { try { String s = readChunkThroughUTF8Processor(p, in, buf); if (nempty(s)) return s; in.close(); return endMarker(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "S s = readChunkThroughUTF8Processor(p, in, buf);\r\n //print(\"Chunk read: \" ..."; } }); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedImage mapPixels(IF1_IntToInt f, BufferedImage image) { if (image == null) return null; int[] pixels = imageToIntPixels(image); for (int i = 0; i < pixels.length; i++) pixels[i] = f.get(pixels[i]); return bufferedImage(pixels, imageSize(image)); } static public BufferedImage mapPixels(BufferedImage image, IF1_IntToInt f) { return mapPixels(f, image); } static public int percentIncreaseInt(double a, double b) { return iround_clamp(percentIncrease(a, b)); } static public List> pairsSortedByA(Collection> l) { return sortedByComparator(l, (a, b) -> cmp(a.a, b.a)); } static public String takeFirstNLines(int n, String s) { return takeFirstLines(n, s); } static public int hi15ToRGBInt(short hi15) { return hi15ToRGBInt_clean(hi15); } static public Frequency toFrequency(double freq) { return new Frequency(freq); } static public JSlider liveSlider(int min, int max, int value, IVF1 onChange) { return swing(() -> { JSlider slider = new JSlider(min, max, value); slider.addChangeListener(new ChangeListener() { public int lastValue = slider.getValue(); public void stateChanged(ChangeEvent e) { int value = slider.getValue(); if (value != lastValue) { lastValue = value; setToolTip(slider, str(value)); pcallF(onChange, value); } } }); return slider; }); } static public double areaRoot(Rect r) { return r == null ? 0 : sqrt(area(r)); } static public double areaRoot(DoubleRect r) { return r == null ? 0 : sqrt(area(r)); } static public double areaRoot(WidthAndHeight img) { return img == null ? 0 : sqrt(area(img)); } static public double areaRoot(BufferedImage img) { return img == null ? 0 : sqrt(area(img)); } static public boolean allEq(Object... l) { if (empty(l)) return true; int n = l(l); Object o = l[0]; for (int i = 1; i < n; i++) if (neq(l[i], o)) return false; return true; } static public boolean allEq(Iterable l) { var it = iterator(l); if (!it.hasNext()) return true; A o = it.next(); while (it.hasNext()) if (neq(it.next(), o)) return false; return true; } static public double megapixels(BufferedImage img) { return img == null ? 0 : area(imageSize(img)) / 1_000_000.0; } static public double megapixels(WidthAndHeight img) { return img == null ? 0 : area(imageSize(img)) / 1_000_000.0; } static public B randomValue(Map map) { if (map == null) return null; A key = random(keys(map)); return key == null ? null : map.get(key); } static public List dirsThatExist(String... dirs) { return mapNonNulls(dirs, d -> dirOtherwiseNull(newFile(d))); } static public IterableIterator> parseExtendedCSV_iterator(String csv) { return parseExtendedCSV_iterator(new ExtendedCSVParser(), csv); } static public IterableIterator> parseExtendedCSV_iterator(ExtendedCSVParser parser, String csv) { parser.csv = csv; return iff_endOnNull(new IF0>() { public List currentRecord = new ArrayList(); public boolean recordComplete = false; { parser.onValueFound = v -> currentRecord.add(v); parser.onEndOfRecord = () -> recordComplete = true; } public List get() { while (!recordComplete) if (!parser.step()) return null; recordComplete = false; List record = currentRecord; currentRecord = new ArrayList(); return record; } }); } static public String readLineFromReader(BufferedReader r) { try { return r.readLine(); } catch (Exception __e) { throw rethrow(__e); } } static public boolean isDataURL(String url) { return startsWith(url, "data:"); } static public List wrapIntArrayAsList(int[] l) { return new RandomAccessAbstractList() { public int size() { return l.length; } public Integer get(int i) { return l[i]; } public Integer set(int i, Integer val) { Integer a = l[i]; l[i] = val; return a; } }; } static public void stream2file(InputStream in, File out) { try { mkdirsForFile(out); FileOutputStream fos = new FileOutputStream(out); copyStream(in, fos); in.close(); fos.close(); } catch (Exception __e) { throw rethrow(__e); } } static public String sanitizeFileName(String s) { return nohup_sanitize(s); } static public Rect leftScreenHalf(GraphicsDevice screen) { return rectRelative(0, 0, 0.5, 1, screenBounds(screen)); } static public Rect leftScreenHalf() { return leftScreenHalf(0); } static public Rect leftScreenHalf(int iScreen) { return rectRelative(0, 0, 0.5, 1, screenBounds(iScreen)); } static public String resolveKeyCI(Map map, String key) { if (map == null) return null; if (map.containsKey(key)) return key; return first(keys(map), k -> eqic(key, k)); } static public A reverseLookup(B value, Map map) { return reverseLookup(map, value); } static public A reverseLookup(Map map, B value) { if (map != null && value != null) for (A key : map.keySet()) if (eq(map.get(key), value)) return key; return null; } static public Shape onePathToShape(OnePath onePath) { if (onePath == null) return null; Path2D.Float path = new Path2D.Float(); Iterator it = onePath.pointIterator(); Pt p = it.next(); path.moveTo(p.x, p.y); while (it.hasNext()) { p = it.next(); path.lineTo(p.x, p.y); } return path; } static public BufferedImage assertPixels(BufferedImage img, int... pixels) { assertIntArrayEquals(pixels, imageToPixels(img)); return img; } static public A replaceIfEquals(A a, A b, A c) { return replaceIfEqual(a, b, c); } static public List longerThan(Iterable l, int x) { return filter(l, s -> l(s) > x); } static public List longerThan(int x, Iterable l) { return longerThan(l, x); } static public boolean longerThan(Collection a, Collection b) { return l(a) > l(b); } static public File firstFileThatExists(String... paths) { return oneOfTheFiles(paths); } static public File firstFileThatExists(File... files) { return oneOfTheFiles(files); } static public File firstFileThatExists(Iterable files) { return oneOfTheFiles(files); } static public MultiSetMap treeMultiSetMap() { return new MultiSetMap(true); } static public MultiSetMap treeMultiSetMap(Comparator comparator) { return new MultiSetMap(new TreeMap>(comparator)); } static public List sortedByCalculatedFieldDesc(Collection c, final Object f) { return sortByCalculatedFieldDesc(c, f); } static public List sortedByCalculatedFieldDesc(Object f, Collection c) { return sortByCalculatedFieldDesc(f, c); } static public List sortedByCalculatedFieldDesc(Iterable c, IF1 f) { return sortByCalculatedFieldDesc(c, f); } static public List sortedByCalculatedFieldDesc(IF1 f, Iterable c) { return sortByCalculatedFieldDesc(f, c); } static public void printFunctionCall(Object fname, Object... args) { print(formatFunctionCall(fname, args)); } static public String intToHex_fullLength(int i) { return intToHex(i); } static public JComponent jMaxSpeedAnimationWithStats(IF0> renderFrameWithStats) { ImageSurface is = new ImageSurface(); is.pixelate(true); DoubleFPSCounter fps = new DoubleFPSCounter(); var lblStats = jlabel(); awtCalcContinuously(is, () -> { try { var imageAndStats = renderFrameWithStats.get(); var image = pairA(imageAndStats); if (image != null) { fps.inc(); is.setImage(image); setText(lblStats, joinNemptiesWithComma(fps, pairB(imageAndStats))); } else sleep(10); } catch (Throwable e) { printStackTrace(e); setText(lblStats, exceptionToStringShort(e)); sleepSeconds(1); } }); return centerAndSouth(jscroll_center_borderless(is), withMargin(lblStats)); } static public Type getRawType(Type t) { if (t instanceof ParameterizedType) return ((ParameterizedType) t).getRawType(); return t; } static public String intToBinary(int i) { return intToBinary_flexLength(i); } static public void onEnclosingScrollPaneResize(JComponent c, Runnable r) { new OnEnclosingScrollPaneResize(c, r).install(); } static public class OnEnclosingScrollPaneResize implements IFieldsToList { public JComponent c; public Runnable r; public OnEnclosingScrollPaneResize() { } public OnEnclosingScrollPaneResize(JComponent c, Runnable r) { this.r = r; this.c = c; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + c + ", " + r + ")"; } public Object[] _fieldsToList() { return new Object[] { c, r }; } final public OnEnclosingScrollPaneResize setDebug(boolean debug) { return debug(debug); } public OnEnclosingScrollPaneResize debug(boolean debug) { this.debug = debug; return this; } final public boolean getDebug() { return debug(); } public boolean debug() { return debug; } public boolean debug = false; public ComponentAdapter listener; public JViewport viewport; public void install() { if (r == null) return; bindToComponent(c, () -> { viewport = optCast(JViewport.class, getParent(getParent(c))); if (viewport != null) { listener = new ComponentAdapter() { public void componentResized(ComponentEvent e) { if (debug) print("Viewport resized"); pcallF(r); } }; viewport.addComponentListener(listener); if (debug) print("OnEnclosingScrollPaneResize installed"); } }, () -> { if (listener != null && viewport != null) { viewport.removeComponentListener(listener); if (debug) print("OnEnclosingScrollPaneResize removed"); } }); } } static public int rgbIntFromBrightness(int brightness) { return rgbIntFromGrayscale(brightness); } static public int rgbIntFromBrightness(double brightness) { return rgbIntFromGrayscale(brightness); } static public int[] repIntArray(int value, int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = value; return a; } static public Object unstructureGZFile(File f) { return unstructureGZFile(f, null); } static public Object unstructureGZFile(File f, IF1 classFinder) { try { if (!fileExists(f)) return null; BufferedReader reader = utf8BufferedReader(gzInputStream(f)); try { return unstructure_tok(javaTokC_noMLS_onReader(reader), false, classFinder); } finally { _close(reader); } } catch (Exception __e) { throw rethrow(__e); } } static public String getMyIP() { return myBestIP(); } static public int[] pixelsFromBufferedImage(BufferedImage image) { return pixelsOfBufferedImage(image); } static public A waitForCalculatedValueUsingChangeListener(IF0 f, IHasChangeListeners sender) { return waitForCalculatedValueUsingChangeListener(infinity(), f, sender); } static public A waitForCalculatedValueUsingChangeListener(double timeout, IF0 f, IHasChangeListeners sender) { BoolVar trigger = new BoolVar(); AutoCloseable __2 = tempOnChange(sender, () -> trigger.set(true)); try { while (true) { ping(); { var __1 = f.get(); if (__1 != null) return __1; } trigger.waitUntilTrueAndClear(timeout); } } finally { _close(__2); } } static public BufferedReader utf8BufferedReader(InputStream in) { return utf8bufferedReader(in); } static public BufferedReader utf8BufferedReader(File f) { return utf8bufferedReader(f); } static public int defaultBufferedOutputStreamSize() { return 65536; } static public boolean isFullyTransparent(int rgba) { return (rgba & 0xFF000000) == 0; } static public boolean isFullyTransparent(Color color) { return color.getAlpha() == 0; } static public void openInBrowser(String url) { openPlatformBrowser(url); } static public void openInBrowser(URL url) { openPlatformBrowser(url); } static public Class typeToClass(Type type) { if (type == null) return null; if (type instanceof Class) return ((Class) type); if (type instanceof ParameterizedType) return optCast(Class.class, ((ParameterizedType) type).getRawType()); if (type instanceof GenericArrayType) return typeToClass(((GenericArrayType) type).getGenericComponentType()).arrayType(); if (type instanceof IResolvableClass) return ((IResolvableClass) type).resolveToClass(); return null; } static public File javaxBackupDir_dir; static public File javaxBackupDir() { return javaxBackupDir_dir != null ? javaxBackupDir_dir : new File(userHome(), "JavaX-Backup"); } static public File javaxBackupDir(String sub) { return newFile(javaxBackupDir(), sub); } static public File ffmpegLocationFile() { return javaxDataDir("ffmpeg-location.txt"); } static public A highestByFunction(Iterable l, Object f) { A best = null; Object bestValue = null; if (l != null) for (A a : l) { Object val = callF(f, a); if (best == null || cmp(val, bestValue) > 0) { best = a; bestValue = val; } } return best; } static public A highestByFunction(Object f, Iterable l) { return highestByFunction(l, f); } static public A highestByFunction(IF1 f, Iterable l) { return highestByFunction(l, (Object) f); } static public A highestByFunction(Iterable l, IF1 f) { return highestByFunction(f, l); } static public Object loadJSONPage(String url) { return jsonDecode(loadPage(url)); } static public Object loadJSONPage(URLConnection urlConnection) { return jsonDecode(loadPage(urlConnection)); } static public BufferedImage shootLeftScreenHalf() { return shootScreen2(leftScreenHalf()); } static public List uniquifyList(Collection l) { if (l == null) return null; if (l(l) < 2) return asList(l); HashSet set = new HashSet(); List out = new ArrayList(); for (A a : l) if (set.add(a)) out.add(a); return out; } static public Map stdClasses_cached() { return standardClassesMap_cached(); } static public byte[] alphaChannelFromPixels(int[] pixels) { int n = pixels.length; byte[] pixels2 = new byte[n]; for (int i = 0; i < n; i++) pixels2[i] = (byte) (pixels[i] >> 24); return pixels2; } static public String takeFirstLines(int n, String s) { return lineRange(s, 0, n); } static public boolean syncSetAdd(Collection c, A a) { if (c == null) return false; synchronized (collectionMutex(c)) { if (c.contains(a)) return false; c.add(a); return true; } } static public A highestConceptByField(Class c, String field) { return highestConceptByField(db_mainConcepts(), c, field); } static public A highestConceptByField(Concepts concepts, Class c, String field) { IFieldIndex index = concepts.getFieldIndex(c, field); if (index instanceof ConceptFieldIndexDesc) { Map.Entry e = ((NavigableMap) ((ConceptFieldIndexDesc) index).valueToObject.data).firstEntry(); return e == null ? null : (A) first((Collection) e.getValue()); } return highestByField(field, concepts.list(c)); } static public List> pairsSortedByADesc(Collection> l) { return sortedByComparator(l, new Comparator>() { public int compare(Pair a, Pair b) { return cmp(b.a, a.a); } }); } static public String trimJoinSubList(List l, int i, int j) { return trim(join(subList(l, i, j))); } static public String trimJoinSubList(List l, int i) { return trim(join(subList(l, i))); } static public boolean isHiddenVM() { return isTrue(getOpt(getJavaX(), "hiddenVM")); } static public boolean cicOneOf(String s, String... l) { for (String x : l) if (cic(s, x)) return true; return false; } static public boolean cicOneOf(Collection l, String... bla) { for (String x : unnull(l)) if (eqicOneOf(x, bla)) return true; return false; } static public RegExp cicAnyToRegexp(String... strings) { return cicAnyToRegexp(asList(strings)); } static public RegExp cicAnyToRegexp(Iterable strings) { return new RegExp(orCombineRegexps(regexpEscapeAll(strings)), true); } static public short rgbIntToHi15(int rgb) { int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = rgb & 0xFF; return rgbToHi15(r, g, b); } static public byte toUByte(int i) { if (!isUByte(i)) throw fail("Not a u-byte: " + i); return (byte) i; } static public String renderKB(long l) { return str_toKB(l); } static public A jMinHeight0(A c) { return jMinHeight_pure(0, c); } static public A printNoNewLine(A a) { print_noNewLine(str(a)); return a; } static public void drawBoxes(BufferedImage image, List boxes, Color color, float opaqueness) { Graphics2D g = image.createGraphics(); g.setColor(colorWithAlpha(color, opaqueness)); for (Rectangle r : boxes) g.drawRect(r.x - 1, r.y - 1, r.width + 2, r.height + 2); g.dispose(); } static public boolean regexpICMatches(String pat, String s) { return regexpIC(pat, s).matches(); } static public boolean regexpICMatches(Pattern pat, String s) { return pat.matcher(s).matches(); } static public List containingIC(Collection l, final String x) { List out = new ArrayList(); for (String s : unnull(l)) if (cic(s, x)) out.add(s); return out; } static public List containingIC(String x, Collection l) { return containingIC(l, x); } static public AutoCloseable tempOnChange(IHasChangeListeners src, Runnable listener) { if (src == null || listener == null) return null; src.onChange(listener); return () -> src.removeChangeListener(listener); } static public void assertListsEqual(List l1, List l2) { assertListsEqual("", l1, l2); } static public void assertListsEqual(String msg, List l1, List l2) { if (l(l1) != l(l2)) throw fail("Different size: " + l(l1) + "/" + l(l2)); int iDiff = indexOfDifference(l1, l2); if (iDiff < 0) print(msg, "OK (" + l(l1) + ")"); else throw fail(prependWithColonSpace(msg) + "Error in element " + iDiff + "/" + l(l1) + " (" + get(l1, iDiff) + "/" + get(l2, iDiff) + ")"); } static public boolean isBetween(long x, long min, long max) { return x >= min && x <= max; } static public boolean isBetween(double x, double min, double max) { return x >= min && x <= max; } static public double genericDistanceToProbability(double distance) { return 1 / (1 + abs(distance)); } static public double genericDistanceToProbability(double a, double b) { return genericDistanceToProbability(a - b); } static public JPanel jpanelWithoutLayoutManager() { return panelWithoutLayoutManager(); } static public void addGlobalLastErrorsBufferToDefaultPCallPolicy() { var oldPolicy = defaultPCallPolicy(); defaultPCallPolicy_set(error -> { { if (oldPolicy != null) oldPolicy.handlePcallFail(error); } globalLastErrorsBuffer().add(error); }); } static public String loadPageWithHeaders(String url, String... headers) { loadPage_extraHeaders.set(litmap(headers)); return loadPage(url); } static public String loadPageWithHeaders(String url, Map headers) { loadPage_extraHeaders.set(headers); return loadPage(url); } static public boolean directNohupJava_loggingOn = true; static public File directNohupJavax(String javaxargs) { return directNohupJavax(javaxargs, javaxDefaultVMArgs()); } static public File directNohupJavax(final String _javaxargs, final String _vmArgs) { if (directNohupJava_loggingOn) appendToLocalMechLog("nohupJavax Log", sfu(dropSecondIfEmpty(str(parseFirstInt(_javaxargs)), _vmArgs))); String javaxargs = _javaxargs.trim(); if (javaxargs.startsWith("#")) javaxargs = javaxargs.substring(1); String snippetID = javaTok(javaxargs).get(1); int idx = javaxargs.indexOf(' '); String args = idx < 0 ? "" : javaxargs.substring(idx + 1).trim(); String vmArgs = trim(_vmArgs); if (empty(vmArgs) && usePreSpunVMs()) { String line; if (args.length() != 0) line = format3("please start program * with arguments *", snippetID, args); else line = format3("please start program *", snippetID); String answer = sendToLocalBotOpt("A pre-spun VM.", line); if (match3("ok", answer)) { print("OK, used pre-spun VM."); return null; } if (answer != null) print("> " + answer); print("Using standard nohup."); } return classicNohupJavax(javaxargs, vmArgs); } static public A _revalidate(A c) { return revalidate(c); } static public void _revalidate(JFrame f) { revalidate(f); } static public void _revalidate(JInternalFrame f) { revalidate(f); } static public Container _getParent(Component c) { return getParent(c); } static public void fillArrayUnlessZero(byte[] a, byte value) { if (value != 0) Arrays.fill(a, value); } static public void fillArrayUnlessZero(int[] a, int value) { if (value != 0) Arrays.fill(a, value); } static public void fillArrayUnlessZero(float[] a, float value) { if (value != 0) Arrays.fill(a, value); } static public int getInt(List c, int i) { return toInt(get(c, i)); } static public int getInt(Map map, Object key) { return toInt(mapGet(map, key)); } static public int getInt(Object o, String field) { return toInt(getOpt(o, (String) field)); } static public int getInt(String field, Object o) { return getInt(o, field); } static public Flag dm_initErrorHandling_flag = new Flag(); static public void dm_initErrorHandling() { raiseFlagAndDo(dm_initErrorHandling_flag, new Runnable() { public void run() { try { _handleException_addHandler(__1 -> dm_initErrorHandling_handler(__1)); assertNull(_onRegisterThread); _onRegisterThread = new VF1() { public void get(Thread t) { try { Object m = dm_current_generic(); if (m == null) printStackTrace("New thread made outside of a module"); else if (m instanceof DynModule) ((DynModule) m).ownTimer(t); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O m = dm_current_generic();\r\n if (m == null) printStackTrace(\"New thread..."; } }; _threadInfo_makers.add(new VF1() { public void get(Map map) { try { mapPut(map, "currentModule", dm_currentModule()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "mapPut(map, \"currentModule\", dm_currentModule())"; } }); _threadInheritInfo_retrievers.add(new VF1() { public void get(Map map) { try { Object mod = map.get("currentModule"); if (mod instanceof DynModule) dm_current_generic_tl().set(new WeakReference((DynModule) mod)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O mod = map.get(\"currentModule\");\r\n if (mod cast DynModule)\r\n dm_..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_handleException_addHandler(lambda1 dm_initErrorHandling_handler);\r\n \r\n ..."; } }); } static public void dm_initErrorHandling_handler(Throwable e) { DynModule m = dm_currentModule(); if (m == null) print("Weird: Error outside of module"); else m.setField("_error", persistableThrowable(e)); } static public void setMainDesktopPane(JDesktopPane desktop) { mainDesktopPane_value = desktop; } static public A getCreatorOpt(String field) { return (A) getOpt(creator(), field); } static public boolean isTrue(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); if (o == null) return false; if (o instanceof ThreadLocal) return isTrue(((ThreadLocal) o).get()); throw fail(getClassName(o)); } static public boolean isTrue(Boolean b) { return b != null && b.booleanValue(); } static public A possiblyInternalFrameTitle(A c, String title) { JInternalFrame f = getInternalFrame(c); if (f != null) internalFrameTitle(f, title); else frameTitle(getFrame(c), title); return c; } static public String possiblyInternalFrameTitle(Component c) { JInternalFrame f = getInternalFrame(c); return f != null ? internalFrameTitle(f) : frameTitle(getFrame(c)); } static public void cancelTimerOrInterruptThread(Object timer) { if (timer instanceof Thread && !(timer instanceof AutoCloseable)) interruptThread((Thread) timer); else cancelTimer(timer); } static public void pcallFail(Throwable e) { pcallPolicyForThread().handlePcallFail(e); } static public void pcallFail(String msg) { pcallFail(new Throwable(msg)); } static public Map getAndClearMap(Map map) { if (map == null) return emptyMap(); synchronized (collectionMutex(map)) { Map out = cloneMap(map); map.clear(); return out; } } static public boolean dm_isPersistentField(String field) { return dm_isPersistentField(dm_current_mandatory(), field); } static public boolean dm_isPersistentField(DynModule m, String field) { return m.persistOnChangedField && !isTransientField(m, field) && !isFalse(mapGet(m._persistenceInfo, field)); } static public Rect dm_getBounds(Object module) { return shallowCloneToClass(Rect.class, call(dm_getStem(module), "getFrameRect")); } static public Rect dm_getBounds() { return dm_getBounds(dm_current_generic()); } static public boolean hasMethod_onTypes(Object o, String method, Class... argTypes) { return findMethod_precise_onTypes(o, method, argTypes) != null; } static public void dm_onTopInput_q(final VF1 r) { final DynModule m = dm_current_mandatory(); dm_onTopInput(new VF1() { public void get(final String s) { try { m.q().add(new Runnable() { public void run() { try { callF(r, s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(r, s);"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "switch to m.q();\r\n callF(r, s);"; } }); } static public AutoCloseable tempSetBetterThreadLocalIfNecessary_weakRef(x30_pkg.x30_util.BetterThreadLocal tl, A a) { if (tl == null) return null; WeakReference prev = tl.get(); if (eq(getWeakRef(prev), a)) return null; tl.set(weakRef(a)); return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); } }; } static public x30_pkg.x30_util.BetterThreadLocal dm_current_generic_tl; static public x30_pkg.x30_util.BetterThreadLocal dm_current_generic_tl() { if (dm_current_generic_tl == null) dm_current_generic_tl = vm_generalMap_getOrCreate("currentModule", () -> new x30_pkg.x30_util.BetterThreadLocal()); return dm_current_generic_tl; } static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) { return print_byThread().get() == null ? tempInterceptPrint(f) : null; } static public ThreadLocal realMC_tl_tl = new ThreadLocal(); static public ThreadLocal realMC_tl() { return realMC_tl_tl; } static public boolean addIfNotThere(Collection c, A a) { return setAdd(c, a); } static public void zeroAllFieldsOfTypeExcept(Object o, Class type, String... exceptions) { zeroAllFieldsOfTypeExcept(o, type, asSet(exceptions)); } static public void zeroAllFieldsOfTypeExcept(Object o, Class type, Collection exceptions) { Set set = asSet(exceptions); for (String field : allFields(o)) if (!set.contains(field) && instanceOf(getOpt(o, field), type)) set(o, field, null); } static public List paramsToAbstractActions(Object... params) { List l = new ArrayList(); for (int i = 0; i + 1 < l(params); i += 2) { String text = (String) (params[i]); Runnable action = (Runnable) (params[i + 1]); if (nempty(text)) l.add(abstractAction(text, action)); } return l; } static public void internalFramePopupMenuFromActions_threaded(Container f, List actions) { if (!(f instanceof JInternalFrame)) return; for (final AbstractAction a : unnull(actions)) if (a != null) internalFramePopupMenuItem(((JInternalFrame) f), str(a.getValue(Action.NAME)), runnableThread(new Runnable() { public void run() { try { callAction(a); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callAction(a)"; } })); } static public LinkedHashSet asLinkedHashSet(A[] array) { LinkedHashSet set = new LinkedHashSet(); for (A o : array) if (o != null) set.add(o); return set; } static public LinkedHashSet asLinkedHashSet(Collection l) { if (l instanceof LinkedHashSet) return (LinkedHashSet) l; LinkedHashSet set = new LinkedHashSet(); for (A o : l) if (o != null) set.add(o); return set; } static public void dm_boolFieldMenuItem(Container frame, final String field, final Object... __) { final DynModule m = dm_current_mandatory(); final String humanized = humanizeFormLabel(field); internalFrameTitlePopupMenu(((JInternalFrame) frame), new VF1() { public void get(JPopupMenu menu) { try { menu.add(jCheckBoxMenuItem(humanized, (boolean) _get(m, field), new VF1() { public void get(Boolean b) { try { m.setField(field, b); callF(optPar(__, "onSet")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, b);\r\n callF(optPar(_, 'onSet));"; } })); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "menu.add(jCheckBoxMenuItem(humanized, (bool) _get(m, field), voidfunc(bool b)..."; } }); } static public void dm_intFieldMenuItem(Container frame, final String field, final Object... __) { final DynModule m = dm_current_mandatory(); final String humanized = humanizeFormLabel(field); internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() { public void run() { try { final JTextField tf = jtextfield(get(m, field)); showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() { public void run() { try { m.setField(field, parseInt(gtt(tf))); callF(optPar(__, "onSet")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, parseInt(gtt(tf)));\r\n callF(optPar(__, \"onSet\"));"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tf = jtextfield(get(m, field));\r\n showFormTitled(or2(stri..."; } }); } static public void dm_longFieldMenuItem(Container frame, final String field, final Object... __) { final DynModule m = dm_current_mandatory(); final String humanized = humanizeFormLabel(field); internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() { public void run() { try { final JTextField tf = jtextfield(get(m, field)); showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() { public void run() { try { m.setField(field, parseLong(gtt(tf))); callF(optPar(__, "onSet")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, parseLong(gtt(tf)));\r\n callF(optPar(__, \"onSet\"));"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tf = jtextfield(get(m, field));\r\n showFormTitled(or2(stri..."; } }); } static public void dm_doubleFieldMenuItem(Container frame, final String field, final Object... __) { final DynModule m = dm_current_mandatory(); internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() { public void run() { try { AutoCloseable __1 = m.enter(); try { dm_doubleFieldSetterDialog(field, __); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n dm_doubleFieldSetterDialog(field, __);"; } }); } static public void dm_floatFieldMenuItem(Container frame, String field, Object... __) { DynModule m = dm_current_mandatory(); internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() { public void run() { try { AutoCloseable __1 = m.enter(); try { dm_floatFieldSetterDialog(field, __); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n dm_floatFieldSetterDialog(field, __);"; } }); } static public void dm_stringFieldMenuItem(Container frame, final String field, final Object... __) { final DynModule m = dm_current_mandatory(); internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() { public void run() { try { AutoCloseable __1 = m.enter(); try { dm_stringFieldDialog(field, __); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n dm_stringFieldDialog(field, __);"; } }); } static public void dm_fileFieldMenuItem(Container frame, String field, Object... __) { DynModule m = dm_current_mandatory(); internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() { public void run() { try { AutoCloseable __1 = m.enter(); try { dm_fileFieldDialog(field, __); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n dm_fileFieldDialog(field, __);"; } }); } static public Q dm_startQ() { return dm_ownQ(startQ()); } static public Q dm_startQ(String name) { return dm_ownQ(startQ(name)); } static public JComponent dm_noVisualisation() { return setToolTip("Module has no visualization", jimage("#1101480")); } static public String snippetTitle(String id) { return getSnippetTitle(id); } static public String snippetTitle(long id) { return getSnippetTitle(id); } static public Class mainClass() { return getMainClass(); } static public Class mainClass(Object o) { return getMainClass(o); } static public Set _registerTimer_list = newWeakHashSet(); static public void _registerTimer_original(java.util.Timer timer) { _registerTimer_list.add(timer); } static public void cleanMeUp__registerTimer() { cancelTimers(getAndClearList(_registerTimer_list)); } static public DynModule dm_currentModule() { return optCast(DynModule.class, dm_current_generic()); } static public String getPrintLog() { return str(print_log); } static public void dm_clearModulePrintLog() { clearStringBuffer_gen(dm_current_mandatory()._actualPrintLog()); } static public StringBuffer liveLocalPrintLog_realMC(Object o) { Object realMC = getMainClass(o); if (realMC != mc()) return (StringBuffer) getOpt(realMC, "local_log"); return liveLocalPrintLog(); } static public List addDyn_sync(List l, A a) { if (l == null) l = synchroList(); l.add(a); return l; } static public void dm_vmBus_send(String msg, Object... args) { vmBus_send(msg, args); } static public void dm_vmBus_send(String msg) { vmBus_send(msg); } static public int indexOf(List l, A a, int startIndex) { if (l == null) return -1; int n = l(l); for (int i = startIndex; i < n; i++) if (eq(l.get(i), a)) return i; return -1; } static public int indexOf(List l, int startIndex, A a) { return indexOf(l, a, startIndex); } static public int indexOf(List l, A a) { if (l == null) return -1; return l.indexOf(a); } static public int indexOf(String a, String b) { return a == null || b == null ? -1 : a.indexOf(b); } static public int indexOf(String a, String b, int i) { return a == null || b == null ? -1 : a.indexOf(b, i); } static public int indexOf(String a, char b) { return a == null ? -1 : a.indexOf(b); } static public int indexOf(String a, int i, char b) { return indexOf(a, b, i); } static public int indexOf(String a, char b, int i) { return a == null ? -1 : a.indexOf(b, i); } static public int indexOf(String a, int i, String b) { return a == null || b == null ? -1 : a.indexOf(b, i); } static public int indexOf(A[] x, A a) { int n = l(x); for (int i = 0; i < n; i++) if (eq(x[i], a)) return i; return -1; } static public int indexOf(Iterable l, A a) { if (l == null) return -1; int i = 0; for (A x : l) { if (eq(x, a)) return i; i++; } return -1; } static public ArrayList clonedList(Iterable l) { return cloneList(l); } static public ArrayList clonedList(Collection l) { return cloneList(l); } static public String ymd_minus_hms_minus_millis() { return ymd() + "-" + spliceString(replace(hmsWithColonsAndMS(), ":", ""), 6, 6, "-"); } static public void saveGZStructToFile(String file, Object o) { saveGZStructureToFile(file, o); } static public void saveGZStructToFile(File file, Object o) { saveGZStructureToFile(file, o); } static public void internalFramePopupMenuItem(Container f, final String name, final Object action) { internalFrameTitlePopupMenuItem(((JInternalFrame) f), name, action); } static public String dm_moduleID(Object module) { return strOrNull(getOpt(dm_getStem(module), "id")); } static public String dm_moduleID() { return dm_moduleID(dm_current_mandatory_generic()); } static public A setHorizontalMargin(final int margin, final A a) { { swing(() -> { Insets i = a.getMargin(); a.setMargin(new Insets(i.top, margin, i.bottom, margin)); }); } return a; } static public A setHorizontalMargin(A a, int margin) { return setHorizontalMargin(margin, a); } static public Object _onAWTEnter_f; static public AutoCloseable _onAWTEnter() { return (AutoCloseable) callF(_onAWTEnter_f); } static public List _registerWeakMap_preList; static public A _registerWeakMap(A map) { if (javax() == null) { if (_registerWeakMap_preList == null) _registerWeakMap_preList = synchroList(); _registerWeakMap_preList.add(map); return map; } try { call(javax(), "_registerWeakMap", map); } catch (Throwable e) { printException(e); print("Upgrade JavaX!!"); } return map; } static public void _onLoad_registerWeakMap() { assertNotNull(javax()); if (_registerWeakMap_preList == null) return; for (Object o : _registerWeakMap_preList) _registerWeakMap(o); _registerWeakMap_preList = null; } static public void rotateStringBuffer(StringBuffer buf, int max) { try { if (buf == null) return; synchronized (buf) { if (buf.length() <= max) return; try { int newLength = max / 2; int ofs = buf.length() - newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } buf.trimToSize(); } } catch (Exception __e) { throw rethrow(__e); } } static public void rotateStringBuilder(StringBuilder buf, int max) { try { if (buf == null) return; synchronized (buf) { if (buf.length() <= max) return; try { int newLength = max / 2; int ofs = buf.length() - newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } buf.trimToSize(); } } catch (Exception __e) { throw rethrow(__e); } } static public Field getOpt_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static public Object getOptDynOnly(DynamicObject o, String field) { if (o == null || o.fieldValues == null) return null; return o.fieldValues.get(field); } static public Map newDangerousWeakHashMap() { return _registerDangerousWeakMap(synchroMap(new WeakHashMap())); } static public Map newDangerousWeakHashMap(Object initFunction) { return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction); } static public Map findBot_cache = synchroHashMap(); static public int findBot_timeout = 5000; static public DialogIO findBot(String searchPattern) { String subBot = null; int i = searchPattern.indexOf('/'); if (i >= 0 && (isJavaIdentifier(searchPattern.substring(0, i)) || isInteger(searchPattern.substring(0, i)))) { subBot = searchPattern.substring(i + 1); searchPattern = searchPattern.substring(0, i); if (!isInteger(searchPattern)) searchPattern = "Multi-Port at " + searchPattern + "."; } if (isInteger(searchPattern)) return talkToSubBot(subBot, talkTo(parseInt(searchPattern))); if (eq(searchPattern, "remote")) return talkToSubBot(subBot, talkTo("second.tinybrain.de", 4999)); Integer port = findBot_cache.get(searchPattern); if (port != null) try { DialogIO io = talkTo("localhost", port); io.waitForLine(); String line = io.readLineNoBlock(); if (indexOfIgnoreCase(line, searchPattern) == 0) { call(io, "pushback", line); return talkToSubBot(subBot, io); } } catch (Exception e) { e.printStackTrace(); } List bots = quickBotScan(); for (ProgramScan.Program p : bots) { if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) { findBot_cache.put(searchPattern, p.port); return talkToSubBot(subBot, talkTo("localhost", p.port)); } } for (ProgramScan.Program p : bots) { String botName = firstPartOfHelloString(p.helloString); boolean isVM = startsWithIgnoreCase(p.helloString, "This is a JavaX VM."); boolean shouldRecurse = startsWithIgnoreCase(botName, "Multi-Port") || isVM; if (shouldRecurse) try { Map subBots = (Map) unstructure(sendToLocalBotQuietly(p.port, "list bots")); for (Number vport : subBots.keySet()) { String name = subBots.get(vport); if (startsWithIgnoreCase(name, searchPattern)) return talkToSubBot(vport.longValue(), talkTo("localhost", p.port)); } } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } return null; } static public boolean structure_showTiming, structure_checkTokenCount; static public String structure(Object o) { return structure(o, new structure_Data()); } static public String structure(Object o, structure_Data d) { StringWriter sw = new StringWriter(); d.out = new PrintWriter(sw); structure_go(o, d); String s = str(sw); if (structure_checkTokenCount) { print("token count=" + d.n); assertEquals("token count", l(javaTokC(s)), d.n); } return s; } static public void structure_go(Object o, structure_Data d) { structure_1(o, d); while (nempty(d.stack)) popLast(d.stack).run(); } static public void structureToPrintWriter(Object o, PrintWriter out) { structureToPrintWriter(o, out, new structure_Data()); } static public void structureToPrintWriter(Object o, PrintWriter out, structure_Data d) { d.out = out; structure_go(o, d); } static public boolean structure_allowShortening = false; static public class structure_ClassInfo { public Class c; public String shortName; public List fields; public Method customSerializer; public IVF1 serializeObject; public boolean special = false; public boolean nullInstances = false; public boolean javafy = false; public Object emptyInstance; public String toString() { return commaCombine("Class " + className(c), stringIf("special", special), stringIf("customSerializer", customSerializer != null), stringIf("javafy", javafy), stringIf("nullInstances", nullInstances)); } public void nullInstances(boolean b) { this.nullInstances = b; if (b) special = true; } public void javafy(boolean b) { this.javafy = b; if (b) special = true; } public boolean handle(A o) { return false; } } static public class structure_Data { public PrintWriter out; public int stringSizeLimit; public int shareStringsLongerThan = 20; public boolean noStringSharing = false; public boolean storeBaseClasses = false; public boolean honorFieldOrder = true; public String mcDollar = actualMCDollar(); final public structure_Data setWarnIfUnpersistable(boolean warnIfUnpersistable) { return warnIfUnpersistable(warnIfUnpersistable); } public structure_Data warnIfUnpersistable(boolean warnIfUnpersistable) { this.warnIfUnpersistable = warnIfUnpersistable; return this; } final public boolean getWarnIfUnpersistable() { return warnIfUnpersistable(); } public boolean warnIfUnpersistable() { return warnIfUnpersistable; } public boolean warnIfUnpersistable = true; final public structure_Data setStackTraceIfUnpersistable(boolean stackTraceIfUnpersistable) { return stackTraceIfUnpersistable(stackTraceIfUnpersistable); } public structure_Data stackTraceIfUnpersistable(boolean stackTraceIfUnpersistable) { this.stackTraceIfUnpersistable = stackTraceIfUnpersistable; return this; } final public boolean getStackTraceIfUnpersistable() { return stackTraceIfUnpersistable(); } public boolean stackTraceIfUnpersistable() { return stackTraceIfUnpersistable; } public boolean stackTraceIfUnpersistable = true; final public structure_Data setSkipDefaultValues(boolean skipDefaultValues) { return skipDefaultValues(skipDefaultValues); } public structure_Data skipDefaultValues(boolean skipDefaultValues) { this.skipDefaultValues = skipDefaultValues; return this; } final public boolean getSkipDefaultValues() { return skipDefaultValues(); } public boolean skipDefaultValues() { return skipDefaultValues; } public boolean skipDefaultValues = false; public structure_Data d() { return this; } transient public IF1 shouldIncludeField; public boolean shouldIncludeField(Field f) { return shouldIncludeField != null ? shouldIncludeField.get(f) : shouldIncludeField_base(f); } final public boolean shouldIncludeField_fallback(IF1 _f, Field f) { return _f != null ? _f.get(f) : shouldIncludeField_base(f); } public boolean shouldIncludeField_base(Field f) { return true; } public IdentityHashMap seen = new IdentityHashMap(); public HashMap strings = new HashMap(); public HashSet concepts = new HashSet(); public HashMap infoByClass = new HashMap(); public HashMap> persistenceInfo = new HashMap(); public int n; public List stack = new ArrayList(); public structure_Data append(String token) { out.print(token); ++n; return this; } public structure_Data append(int i) { out.print(i); ++n; return this; } public structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; } public structure_Data app(String token) { out.print(token); return this; } public structure_Data app(int i) { out.print(i); return this; } public structure_Data app(char c) { out.print(c); return this; } public structure_ClassInfo infoForClass(Class c) { structure_ClassInfo info = infoByClass.get(c); if (info == null) info = newClass(c); return info; } transient public IF1 realShortName; public String realShortName(String name) { return realShortName != null ? realShortName.get(name) : realShortName_base(name); } final public String realShortName_fallback(IF1 _f, String name) { return _f != null ? _f.get(name) : realShortName_base(name); } public String realShortName_base(String name) { return dropPrefix("main$", dropPrefix("loadableUtils.utils$", dropPrefix(mcDollar, name))); } public structure_ClassInfo newClass(Class c) { var d = d(); boolean isJavaXClass = isJavaXClassName(c.getName(), mcDollar); if (c == String.class) return new structure_ClassInfo() { @Override public boolean handle(String o) { String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o; if (!d.noStringSharing) { if (d.shareStringsLongerThan == Integer.MAX_VALUE) d.seen.put(o, d.n); if (l(s) >= d.shareStringsLongerThan) d.strings.put(s, d.n); } quoteToPrintWriter(s, d.out); d.n++; return true; } }; if (c == File.class) return new structure_ClassInfo() { @Override public boolean handle(File o) { append("File ").append(quote(o.getPath())); return true; } }; if (!isJavaXClass) { if (isSubClassOf(c, Set.class)) return new structure_ClassInfo() { @Override public boolean handle(Set o) { writeSet(o); return true; } }; if (isSubClassOf(c, Collection.class)) return new structure_ClassInfo() { @Override public boolean handle(Collection o) { writeCollection(o); return true; } }; if (isSubClassOf(c, Map.class)) return new structure_ClassInfo() { @Override public boolean handle(Map o) { writeMap(o); return true; } }; } structure_ClassInfo info = new structure_ClassInfo(); info.c = c; infoByClass.put(c, info); String name = c.getName(); String shortName = realShortName(name); if (startsWithDigit(shortName)) shortName = name; info.shortName = shortName; try { if (isSyntheticOrAnonymous(c)) { info.nullInstances(true); return info; } if (c.isEnum()) { info.special = true; return info; } if (isSubClassOf(c, SynchronizedMap.class)) return new structure_ClassInfo() { @Override public boolean handle(SynchronizedMap o) { append("sync "); structure_1(o.m, d); return true; } }; if (isSubClassOf(c, SynchronizedList.class)) return new structure_ClassInfo() { @Override public boolean handle(SynchronizedList o) { append("sync "); structure_1(unwrapSynchronizedList(o), d); return true; } }; if (c.isArray()) { return info; } if ((info.customSerializer = findMethodNamed(c, "_serialize")) != null) info.special = true; if (storeBaseClasses) { Class sup = c.getSuperclass(); if (sup != Object.class) { append("bc "); append(shortDynClassNameForStructure(c)); out.print(" "); append(shortDynClassNameForStructure(sup)); out.print(" "); infoForClass(sup); } } if (eqOneOf(name, "java.awt.Color", "java.lang.ThreadLocal")) info.javafy(true); else if (name.startsWith("sun") || !isPersistableClass(c)) { info.javafy(true); if (warnIfUnpersistable) { String msg = "Class not persistable: " + c + " (anonymous or no default constructor), referenced from " + last(stack); if (stackTraceIfUnpersistable) printStackTrace(new Throwable(msg)); else print(msg); } } else if (skipDefaultValues) { var ctor = getDefaultConstructor(c); if (ctor != null) info.emptyInstance = invokeConstructor(ctor); } } catch (Throwable e) { printStackTrace(e); info.nullInstances(true); } return info; } public void setFields(structure_ClassInfo info, List fields) { info.fields = fields; } public void writeObject(Object o, String shortName, Map fv) { String singleField = fv.size() == 1 ? first(fv.keySet()) : null; append(shortName); n += countDots(shortName) * 2; int l = n; Iterator it = fv.entrySet().iterator(); class WritingObject implements Runnable { public String lastFieldWritten; public void run() { try { if (!it.hasNext()) { if (n != l) append(")"); } else { Map.Entry e = (Map.Entry) (it.next()); append(n == l ? "(" : ", "); append(lastFieldWritten = (String) e.getKey()).append("="); stack.add(this); structure_1(e.getValue(), structure_Data.this); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return shortName + "." + lastFieldWritten; } } stack.add(new WritingObject()); } public void writeMap(Map o) { var d = this; String name = o.getClass().getName(); if (o instanceof LinkedHashMap) d.append("lhm"); else if (o instanceof HashMap) d.append("hm"); else if (o instanceof TreeMap) d.append(isCIMap_gen((TreeMap) o) ? "cimap" : "tm"); else if (name.equals("java.util.Collections$SynchronizedMap") || name.equals("java.util.Collections$SynchronizedSortedMap") || name.equals("java.util.Collections$SynchronizedNavigableMap")) { d.append("sync "); { structure_1(unwrapSynchronizedMap(((Map) o)), d); return; } } d.append("{"); final int l = d.n; final Iterator it = cloneMap((Map) o).entrySet().iterator(); class WritingMap implements Runnable { public boolean v = false; public Map.Entry e; public String toString() { return renderVars("WritingMap", "e", mapEntryToPair(e), "v", !v); } public void run() { try { if (v) { d.append("="); v = false; d.stack.add(this); structure_1(e.getValue(), d); } else { if (!it.hasNext()) d.append("}"); else { e = (Map.Entry) it.next(); v = true; d.stack.add(this); if (d.n != l) d.append(", "); structure_1(e.getKey(), d); } } } catch (Exception __e) { throw rethrow(__e); } } } d.stack.add(new WritingMap()); } public void writeSet(Set o) { var d = this; String name = o.getClass().getName(); if (o instanceof TreeSet) { d.append(isCISet_gen(o) ? "ciset" : "treeset"); structure_1(new ArrayList(o), d); return; } d.append(o instanceof LinkedHashSet ? "lhs" : "hashset"); structure_1(new ArrayList(o), d); } public void writeCollection(Collection o) { var d = this; String name = o.getClass().getName(); if (name.equals("java.util.Collections$SynchronizedList") || name.equals("java.util.Collections$SynchronizedRandomAccessList")) { d.append("sync "); { structure_1(unwrapSynchronizedList(((List) o)), d); return; } } else if (name.equals("java.util.LinkedList")) d.append("ll"); d.append("["); int l = d.n; Iterator it = cloneList(o).iterator(); d.stack.add(new Runnable() { public void run() { try { if (!it.hasNext()) d.append("]"); else { d.stack.add(this); if (d.n != l) d.append(", "); structure_1(it.next(), d); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.stack.add..."; } }); } } static public void structure_1(Object o, structure_Data d) { try { if (o == null) { d.append("null"); return; } Class c = o.getClass(); boolean concept = false; concept = o instanceof Concept; structure_ClassInfo info = d.infoForClass(c); boolean isJavaXName = isJavaXClassName(c.getName(), d.mcDollar); boolean referencable = isJavaXName && !(o instanceof Number || o instanceof Character || o instanceof Boolean) || o instanceof Collection || o instanceof Map || o instanceof Rectangle; if (referencable) { Integer ref = d.seen.get(o); if (ref != null) { d.append("t").app(ref); return; } d.seen.put(o, d.n); } if (info.handle(o)) { return; } if (info.special) { if (info.javafy) { d.append("j ").append(quote(str(o))); return; } if (c.isEnum()) { d.append("enum "); d.append(info.shortName); d.out.append(' '); d.append(((Enum) o).ordinal()); return; } if (info.customSerializer != null) { Object o2 = invokeMethod(info.customSerializer, o); if (o2 == o) { } else { d.append("cu "); String name = c.getName(); String shortName = d.realShortName(name); d.append(shortName); d.out.append(' '); structure_1(o2, d); return; } } else if (info.nullInstances) { d.append("null"); return; } else if (info.serializeObject != null) { info.serializeObject.get(o); return; } else throw fail("unknown special type"); } List lFields = info.fields; if (lFields == null) { if (o instanceof Number) { PrintWriter out = d.out; if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; } if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; } if (o instanceof Short) { short s = ((Short) o).shortValue(); d.append("sh "); out.print(s); d.n += s < 0 ? 2 : 1; return; } if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; } if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; } if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; } } if (o instanceof Boolean) { d.append(((Boolean) o).booleanValue() ? "t" : "f"); return; } if (o instanceof Character) { d.append(quoteCharacter((Character) o)); return; } String name = c.getName(); if (!isJavaXName) { if (o instanceof Set) { d.writeSet((Set) o); return; } if (o instanceof Collection) { { d.writeCollection((Collection) o); return; } } if (o instanceof Map) { d.writeMap((Map) o); return; } } if (c.isArray()) { if (o instanceof byte[]) { d.append("ba ").append(quote(bytesToHex((byte[]) o))); return; } final int n = Array.getLength(o); if (o instanceof boolean[]) { String hex = boolArrayToHex((boolean[]) o); int i = l(hex); while (i > 0 && hex.charAt(i - 1) == '0' && hex.charAt(i - 2) == '0') i -= 2; d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return; } if (o instanceof short[]) { String hex = shortArrayToHex_bigEndian((short[]) o); d.append("shortarray \"").append(hex).app('\"'); return; } if (o instanceof long[]) { String hex = longArrayToHex_bigEndian((long[]) o); d.append("longarray \"").append(hex).app('\"'); return; } String atype = "array"; if (o instanceof int[]) { atype = "intarray"; } else if (o instanceof double[]) { atype = "dblarray"; } else if (o instanceof float[]) { atype = "floatarray"; } else { Pair p = arrayTypeAndDimensions(c); if (p.a == int.class) atype = "intarray"; else if (p.a == byte.class) atype = "bytearray"; else if (p.a == boolean.class) atype = "boolarray"; else if (p.a == double.class) atype = "dblarray"; else if (p.a == float.class) atype = "floatarray"; else if (p.a == String.class) { atype = "array S"; d.n++; } else atype = "array"; if (p.b > 1) { atype += "/" + p.b; d.n += 2; } } d.append(atype).append("{"); d.stack.add(new Runnable() { public int i; public void run() { if (i >= n) d.append("}"); else { d.stack.add(this); if (i > 0) d.append(", "); structure_1(Array.get(o, i++), d); } } }); return; } if (o instanceof Class) { d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return; } if (o instanceof Throwable) { d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return; } if (o instanceof BitSet) { BitSet bs = (BitSet) o; d.append("bitset{", 2); int l = d.n; for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { if (d.n != l) d.append(", "); d.append(i); } d.append("}"); return; } String dynName = shortDynClassNameForStructure(o); if (concept && !d.concepts.contains(dynName)) { d.concepts.add(dynName); d.append("c "); } TreeSet fields = new TreeSet(new Comparator() { public int compare(Field a, Field b) { return stdcompare(a.getName(), b.getName()); } }); Class cc = c; while (cc != Object.class) { for (Field field : getDeclaredFields_cached(cc)) { if (!d.shouldIncludeField(field)) continue; String fieldName = field.getName(); if (fieldName.equals("_persistenceInfo")) d.persistenceInfo.put(c, obj -> (Map) fieldGet(field, obj)); if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0) continue; fields.add(field); } cc = cc.getSuperclass(); } Method persistenceInfoMethod = findInstanceMethod(c, "_persistenceInfo"); if (persistenceInfoMethod != null) d.persistenceInfo.put(c, obj -> (Map) invokeMethod(persistenceInfoMethod, obj)); lFields = asList(d.honorFieldOrder ? fieldObjectsInFieldOrder(c, fields) : fields); int n = l(lFields); for (int i = 0; i < n; i++) { Field f = lFields.get(i); if (f.getName().startsWith("this$")) { lFields.remove(i); lFields.add(0, f); break; } } d.setFields(info, lFields); } IF1 piGetter = d.persistenceInfo.get(c); Map persistenceInfo = piGetter == null ? null : piGetter.get(o); if (piGetter == null && o instanceof DynamicObject) persistenceInfo = (Map) getOptDynOnly(((DynamicObject) o), "_persistenceInfo"); LinkedHashMap fv = new LinkedHashMap(); Object defaultInstance = info.emptyInstance; if (!referencable) throw fail("Not referencable: " + className(o)); for (Field f : lFields) { Object value, defaultValue = null; try { value = f.get(o); defaultValue = defaultInstance == null ? null : f.get(defaultInstance); } catch (Exception e) { value = "?"; } if (!eq(defaultValue, value) && (persistenceInfo == null || !Boolean.FALSE.equals(persistenceInfo.get(f.getName())))) fv.put(f.getName(), value); } String shortName = info.shortName; Object classNameFromFV = fv.get("className"); if (concept && eq(classNameFromFV, shortName)) fv.remove("className"); if (o instanceof DynamicObject) { putAll(fv, (Map) fv.get("fieldValues")); fv.remove("fieldValues"); if (((DynamicObject) o).className != null) { shortName = shortDynClassNameForStructure((DynamicObject) o); fv.remove("className"); if (eq(shortName, "java.lang.Class")) { d.append("class("); d.append(quoted(fv.get("name"))); d.append(")"); return; } } } d.writeObject(o, shortName, fv); } catch (Exception __e) { throw rethrow(__e); } } volatile static public boolean conceptsAndBot_running = false; static public boolean conceptsAndBot_thinOnStart = true; static public void conceptsAndBot() { conceptsAndBot(null); } static public void conceptsAndBot(Integer autoSaveInterval) { if (conceptsAndBot_running) return; conceptsAndBot_running = true; Concepts cc = db_mainConcepts(); cc.programID = getDBProgramID(); try { if (cc.useFileLock) { if (!cc.fileLock().tryToLock()) { ensureDBNotRunning(dbBotStandardName()); cc.fileLock().forceLock(); } } else ensureDBNotRunning(dbBotStandardName()); } catch (Throwable e) { printStackTrace(e); cc.dontSave = true; throw rethrow(e); } cc.persist(autoSaveInterval); dbBot(false); if (conceptsAndBot_thinOnStart) { try { thinAProgramsBackups(getDBProgramID(), true); } catch (Throwable __e) { pcallFail(__e); } } } static public Object derefRef(Object o) { if (o instanceof Concept.Ref) o = ((Concept.Ref) o).get(); return o; } static public A derefRef(Concept.Ref r) { return r == null ? null : r.get(); } static public boolean _csetField(Concept c, String field, Object value) { try { Field f = setOpt_findField(c.getClass(), field); if (value instanceof RC) value = c._concepts.getConcept((RC) value); value = deref(value); if (value instanceof String && l((String) value) >= concepts_internStringsLongerThan) value = intern((String) value); if (f == null) { assertIdentifier(field); Object oldVal = mapGet(c.fieldValues, field); if (value instanceof Concept) { if (oldVal instanceof Concept.Ref) return ((Concept.Ref) oldVal).set((Concept) value); else { dynamicObject_setRawFieldValue(c, field, c.new Ref((Concept) value)); c.change(); return true; } } else { if (oldVal instanceof Concept.Ref) ((Concept.Ref) oldVal).unindexAndDrop(); if (eq(oldVal, value)) return false; if (isConceptList(value) && nempty(((List) value))) { dynamicObject_setRawFieldValue(c, field, c.new RefL(((List) value))); c.change(); return true; } if (value == null) { dynamicObject_dropRawField(c, field); } else { if (!isPersistable(value)) throw fail("Can't persist: " + c + "." + field + " = " + value); dynamicObject_setRawFieldValue(c, field, value); } c.change(); return true; } } else if (isSubtypeOf(f.getType(), Concept.Ref.class)) { ((Concept.Ref) f.get(c)).set((Concept) derefRef(value)); c.change(); return true; } else if (isSubtypeOf(f.getType(), Concept.RefL.class)) { ((Concept.RefL) f.get(c)).replaceWithList(lmap(__137 -> derefRef(__137), (List) value)); c.change(); return true; } else { Object old = f.get(c); if (neq(value, old)) { boolean isTransient = isTransient(f); if (!isTransient && !isPersistable(value)) throw fail("Can't persist: " + c + "." + field + " = " + value); f.set(c, value); if (!isTransient) c.change(); return true; } } return false; } catch (Exception __e) { throw rethrow(__e); } } static public String combinePrintParameters(String s, Object o) { return (endsWithLetterOrDigit(s) ? s + ": " : s) + o; } static public boolean match3(String pat, String s) { return match3(pat, s, null); } static public boolean match3(String pat, String s, Matches matches) { if (pat == null || s == null) return false; return match3(pat, parse3_cachedInput(s), matches); } static public boolean match3(String pat, List toks, Matches matches) { List tokpat = parse3_cachedPattern(pat); return match3(tokpat, toks, matches); } static public boolean match3(List tokpat, List toks, Matches matches) { String[] m = match2(tokpat, toks); if (m == null) return false; if (matches != null) matches.m = m; return true; } static public boolean isNonNegativeInteger(String s) { int n = l(s); if (n == 0) return false; int i = 0; while (i < n) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } static public Map newWeakMap() { return newWeakHashMap(); } static public String loadLocalSnippet(String snippetID) { return loadLocalSnippet(psI(snippetID)); } static public String loadLocalSnippet(long snippetID) { return loadTextFile(localSnippetFile(snippetID)); } static public DialogIO talkTo(int port) { return talkTo("localhost", port); } static public int talkTo_defaultTimeout = 10000; static public int talkTo_timeoutForReads = 0; static public ThreadLocal> talkTo_byThread = new ThreadLocal(); static public DialogIO talkTo(String ip, int port) { try { String full = ip + ":" + port; Map map = talkTo_byThread.get(); if (map != null && map.containsKey(full)) return map.get(full); if (isLocalhost(ip) && port == vmPort()) return talkToThisVM(); return new talkTo_IO(ip, port); } catch (Exception __e) { throw rethrow(__e); } } static public class talkTo_IO extends DialogIO { public String ip; public int port; public Socket s; public Writer w; public BufferedReader in; public talkTo_IO(String ip, int port) { this.port = port; this.ip = ip; try { s = new Socket(); try { if (talkTo_timeoutForReads != 0) s.setSoTimeout(talkTo_timeoutForReads); s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout); } catch (Throwable e) { throw fail("Tried talking to " + ip + ":" + port, e); } w = new OutputStreamWriter(s.getOutputStream(), "UTF-8"); in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8")); } catch (Exception __e) { throw rethrow(__e); } } public boolean isLocalConnection() { return s.getInetAddress().isLoopbackAddress(); } public boolean isStillConnected() { return !(eos || s.isClosed()); } public void sendLine(String line) { try { Lock __0 = lock; lock(__0); try { w.write(line + "\n"); w.flush(); } finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } } public String readLineImpl() { try { return in.readLine(); } catch (Exception __e) { throw rethrow(__e); } } public void close() { try { if (!noClose) s.close(); } catch (IOException e) { } } public Socket getSocket() { return s; } } static public Map newFindBot2_cache = synchroHashMap(); static public boolean newFindBot2_verbose = false; static public DialogIO newFindBot2(String name) { Integer port = newFindBot2_cache.get(name); if (port != null) { if (newFindBot2_verbose) print("newFindBot2: testing " + name + " => " + port); DialogIO io = talkTo(port); String q = format("has bot *", name); String s = io.ask(q); if (match("yes", s)) { io = talkToSubBot(name, io); call(io, "pushback", "?"); return io; } newFindBot2_cache.remove(name); if (newFindBot2_verbose) print("newFindBot2: dropping " + name + " => " + port); } DialogIO io = findBot(name); if (io != null) { newFindBot2_cache.put(name, io.getPort()); if (newFindBot2_verbose) print("newFindBot2: remembering " + name + " => " + port); } return io; } static public TableWithTooltips tableWithToolTips() { return tableWithTooltips(); } static public List getTableLine(JTable tbl, int row) { if (row >= 0 && row < tbl.getModel().getRowCount()) { List l = new ArrayList(); for (int i = 0; i < tbl.getModel().getColumnCount(); i++) l.add(String.valueOf(tbl.getModel().getValueAt(row, i))); return l; } return null; } static public JComponent showTitledForm(String title, Object... _parts) { return showFormTitled(title, _parts); } static public int convertTableRowToModel(final JTable t, final int viewRow) { return t == null || viewRow < 0 ? -1 : swing(new F0() { public Integer get() { try { return t.convertRowIndexToModel(viewRow); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return t.convertRowIndexToModel(viewRow);"; } }); } static public MouseListener findComponentPopupMenuListener_gen(final JComponent c) { return c == null ? null : swing(() -> firstWithClassShortNamed("componentPopupMenu_Adapter", c.getMouseListeners())); } static public boolean internalFrameActive(Component c) { final JInternalFrame f = getInternalFrame(c); return f != null && swing(new F0() { public Boolean get() { try { return f.isSelected(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return f.isSelected();"; } }); } static public boolean isUnstructuring() { return isTrue(getTL(dynamicObjectIsLoading_threadLocal())); } static public String jarBotURL() { return "https://botcompany.de/jar/"; } static public String jarBotURL(String snippetID) { return jarBotURL() + psI(snippetID); } static public String fulltag(String tag) { return hfulltag(tag); } static public String fulltag(String tag, Object contents, Object... params) { return hfulltag(tag, contents, params); } static public Method findMethod_cached(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { _MethodCache cache = callOpt_getCache((Class) o); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false)) return m; return null; } else { _MethodCache cache = callOpt_getCache(o.getClass()); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) if (findMethod_checkArgs(m, args, false)) return m; return null; } } catch (Exception __e) { throw rethrow(__e); } } static public void assertTrue(Object o) { if (!(eq(o, true))) throw fail(str(o)); } static public boolean assertTrue(String msg, boolean b) { if (!b) throw fail(msg); return b; } static public boolean assertTrue(boolean b) { if (!b) throw fail("oops"); return b; } static public boolean assertTrue(Scorer scorer, boolean b) { scorer.add(b); return b; } static public A toComponent(A c) { return c; } static public Component toComponent(Swingable c) { return c == null ? null : c.visualize(); } static public IF0 ping_v3_pingSourceMaker_cache; static public IF0 ping_v3_pingSourceMaker() { if (ping_v3_pingSourceMaker_cache == null) ping_v3_pingSourceMaker_cache = ping_v3_pingSourceMaker_load(); return ping_v3_pingSourceMaker_cache; } static public IF0 ping_v3_pingSourceMaker_load() { return or((IF0) vm_generalMap_get("ping_v3_pingSourceMaker"), () -> null); } static transient public Set> onExecutingSwingCode; public static void onExecutingSwingCode(IVF1 f) { onExecutingSwingCode = createOrAddToSyncLinkedHashSet(onExecutingSwingCode, f); } public static void removeExecutingSwingCodeListener(IVF1 f) { utils.remove(onExecutingSwingCode, f); } public static void executingSwingCode(Runnable code) { if (onExecutingSwingCode != null) for (var listener : onExecutingSwingCode) pcallF_typed(listener, code); } static public ITokCondition tokCondition(IIntPred condition) { return condition == null ? null : (tok, nIdx) -> condition.get(nIdx); } static public DynModule dm_current_mandatory() { return assertNotNull("No module set!", dm_currentModule()); } static public A getNext(Iterator it) { return nextFromIterator(it); } static public boolean arraysEqual(Object[] a, Object[] b) { if (a.length != b.length) return false; for (int i = 0; i < a.length; i++) if (neq(a[i], b[i])) return false; return true; } static public IMeta initIMeta(Object o) { if (o == null) return null; if (o instanceof IMeta) return ((IMeta) o); if (o instanceof JComponent) return initMetaOfJComponent((JComponent) o); if (o instanceof BufferedImage) return optCast(IMeta.class, ((BufferedImage) o).getProperty("meta")); return null; } static public Rectangle restrictWindowToScreenSize_maxBounds = maxWindowBounds(); static public void restrictWindowToScreenSize(Window window) { if (window == null) return; onBoundsChange(window, new Runnable() { public int recursionCounter; public void run() { try { Rectangle max = restrictWindowToScreenSize_maxBounds; Rectangle r = window.getBounds(); if (r.width > max.width || r.height > max.height) { if (recursionCounter != 0) { warn("restrictWindowToScreenSize recursion"); return; } ++recursionCounter; try { window.setSize(min(r.width, max.width), min(r.height, max.height)); } finally { --recursionCounter; } } } catch (Exception __e) { throw rethrow(__e); } } }); } static public Integer centerX(Rect r) { return rectCenterX(r); } static public Integer centerY(Rect r) { return rectCenterY(r); } static public Map mapWithout(Map map, Object... keys) { return mapMinus(map, keys); } static public DocumentListener runnableToDocumentListener(Runnable r) { return new DocumentListener() { public void insertUpdate(DocumentEvent e) { pcallF(r); } public void removeUpdate(DocumentEvent e) { pcallF(r); } public void changedUpdate(DocumentEvent e) { pcallF(r); } }; } static public Dimension toDimension(WidthAndHeight wh) { return wh == null ? null : new Dimension(wh.getWidth(), wh.getHeight()); } static public String localCourierFontName() { return isLinux() ? "Courier" : "Courier New"; } static public Color gazelle_color1() { return awtColor("ADD8E6"); } static public List graphAsPolygon(IF1 formula, int w, int h) { List points = new ArrayList(); points.add(new DoublePt(0, 0)); for (int x = 0; x < w; x++) { double y = formula.get(doubleRatio(x, w)) * h; points.add(new DoublePt(x, y)); } points.add(new DoublePt(w - 1, 0)); return points; } static public double sineSigmoid(double x) { return 0.5 * (1 + sin(pi() * (x - .5))); } static public void fillPrecisePolygon(BufferedImage g, List points, Color color) { fillPrecisePolygon(graphics(g), points, color); } static public void fillPrecisePolygon(Graphics2D g, List points, Color color) { g.setColor(color); g.fill(new PrecisePolygon(points)); } static public void fillPrecisePolygon(BufferedImage g, List points) { fillPrecisePolygon(graphics(g), points); } static public void fillPrecisePolygon(Graphics2D g, List points) { g.fill(new PrecisePolygon(points)); } static public int tok_findEndOfBlock_IContentsIndexedList2_v2(IContentsIndexedList2 tok, int i) { int n = l(tok); HasIndex start = new HasIndex(i); TreeSet openers = tok.indicesOf_treeSetOfHasIndex("{"); Iterator iOpener = openers == null ? null : openers.tailSet(start, false).iterator(); TreeSet closers = tok.indicesOf_treeSetOfHasIndex("}"); Iterator iCloser = closers == null ? null : closers.tailSet(start, false).iterator(); int level = 1; HasIndex nextOpener = iOpener != null && iOpener.hasNext() ? iOpener.next() : null; HasIndex nextCloser = iCloser != null && iCloser.hasNext() ? iCloser.next() : null; while (true) { if (nextCloser == null) return n; if (nextOpener != null && nextOpener.idx < nextCloser.idx) { ++level; nextOpener = iOpener.hasNext() ? iOpener.next() : null; } else { if (--level == 0) return nextCloser.idx + 1; nextCloser = iCloser.hasNext() ? iCloser.next() : null; } } } static public byte[] md5AsByteArray(byte[] data) { try { return MessageDigest.getInstance("MD5").digest(data); } catch (Exception __e) { throw rethrow(__e); } } static public Map takeFirstFromMap(int n, Map map) { if (map == null) return null; Map map2 = similarEmptyMap(map); if (n > 0) for (Map.Entry e : map.entrySet()) if (n-- <= 0) break; else map2.put(e.getKey(), e.getValue()); return map2; } static public Map makeObjectMetaMap() { return new CompactHashMap(); } static public String regularLineBreaks(int charsPerLine, String s) { if (l(s) < charsPerLine) return s; StringBuilder buf = new StringBuilder(); int n = l(s), j = 0; for (int i = 0; i < n; i++) { buf.append(s.charAt(i)); if (++j >= charsPerLine) { buf.append('\n'); j = 0; } } return str(buf); } static public A firstWithClassShortNamed(String shortName, Iterable l) { if (l != null) for (A o : l) if (eq(shortClassName(o), shortName)) return o; return null; } static public A firstWithClassShortNamed(String shortName, A[] l) { if (l != null) for (A o : l) if (eq(shortClassName(o), shortName)) return o; return null; } static public String[][] htmldecode_escapes() { return htmldecode_ESCAPES; } static final public String[][] htmldecode_ESCAPES = { { "\"", "quot" }, { "&", "amp" }, { "<", "lt" }, { ">", "gt" }, { "\u00A0", "nbsp" }, { "\u00A1", "iexcl" }, { "\u00A2", "cent" }, { "\u00A3", "pound" }, { "\u00A4", "curren" }, { "\u00A5", "yen" }, { "\u00A6", "brvbar" }, { "\u00A7", "sect" }, { "\u00A8", "uml" }, { "\u00A9", "copy" }, { "\u00AA", "ordf" }, { "\u00AB", "laquo" }, { "\u00AC", "not" }, { "\u00AD", "shy" }, { "\u00AE", "reg" }, { "\u00AF", "macr" }, { "\u00B0", "deg" }, { "\u00B1", "plusmn" }, { "\u00B2", "sup2" }, { "\u00B3", "sup3" }, { "\u00B4", "acute" }, { "\u00B5", "micro" }, { "\u00B6", "para" }, { "\u00B7", "middot" }, { "\u00B8", "cedil" }, { "\u00B9", "sup1" }, { "\u00BA", "ordm" }, { "\u00BB", "raquo" }, { "\u00BC", "frac14" }, { "\u00BD", "frac12" }, { "\u00BE", "frac34" }, { "\u00BF", "iquest" }, { "\u00C0", "Agrave" }, { "\u00C1", "Aacute" }, { "\u00C2", "Acirc" }, { "\u00C3", "Atilde" }, { "\u00C4", "Auml" }, { "\u00C5", "Aring" }, { "\u00C6", "AElig" }, { "\u00C7", "Ccedil" }, { "\u00C8", "Egrave" }, { "\u00C9", "Eacute" }, { "\u00CA", "Ecirc" }, { "\u00CB", "Euml" }, { "\u00CC", "Igrave" }, { "\u00CD", "Iacute" }, { "\u00CE", "Icirc" }, { "\u00CF", "Iuml" }, { "\u00D0", "ETH" }, { "\u00D1", "Ntilde" }, { "\u00D2", "Ograve" }, { "\u00D3", "Oacute" }, { "\u00D4", "Ocirc" }, { "\u00D5", "Otilde" }, { "\u00D6", "Ouml" }, { "\u00D7", "times" }, { "\u00D8", "Oslash" }, { "\u00D9", "Ugrave" }, { "\u00DA", "Uacute" }, { "\u00DB", "Ucirc" }, { "\u00DC", "Uuml" }, { "\u00DD", "Yacute" }, { "\u00DE", "THORN" }, { "\u00DF", "szlig" }, { "\u00E0", "agrave" }, { "\u00E1", "aacute" }, { "\u00E2", "acirc" }, { "\u00E3", "atilde" }, { "\u00E4", "auml" }, { "\u00E5", "aring" }, { "\u00E6", "aelig" }, { "\u00E7", "ccedil" }, { "\u00E8", "egrave" }, { "\u00E9", "eacute" }, { "\u00EA", "ecirc" }, { "\u00EB", "euml" }, { "\u00EC", "igrave" }, { "\u00ED", "iacute" }, { "\u00EE", "icirc" }, { "\u00EF", "iuml" }, { "\u00F0", "eth" }, { "\u00F1", "ntilde" }, { "\u00F2", "ograve" }, { "\u00F3", "oacute" }, { "\u00F4", "ocirc" }, { "\u00F5", "otilde" }, { "\u00F6", "ouml" }, { "\u00F7", "divide" }, { "\u00F8", "oslash" }, { "\u00F9", "ugrave" }, { "\u00FA", "uacute" }, { "\u00FB", "ucirc" }, { "\u00FC", "uuml" }, { "\u00FD", "yacute" }, { "\u00FE", "thorn" }, { "\u00FF", "yuml" }, { "\u2013", "ndash" }, { "\u2018", "lsquo" }, { "\u2019", "rsquo" }, { "\u201D", "rdquo" }, { "\u201C", "ldquo" }, { "\u2014", "mdash" }, { "'", "apos" } }; static public void setVar(IVar v, A value) { if (v != null) v.set(value); } static public IVF1 setVar(IVar v) { return a -> { if (v != null) v.set(a); }; } static public TextImageAction textImageActionToolTip(String text, String image, Object action, String toolTip) { TextImageAction t = new TextImageAction(text, image, action); t.toolTip = toolTip; return t; } static public void genericUI_openFile(File f) { appendToMechQ_withDate("User actions", "User clicked on file " + f2s(f)); infoBox("TODO"); } static public Object cloneWithoutField(Object o, String fieldToSkip) { try { if (o == null) return null; final Object clone = nuObject(o.getClass()); Class c = o.getClass(); while (c != Object.class) { Field[] fields = c.getDeclaredFields(); for (final Field field : fields) { if (eq(field.getName(), fieldToSkip)) continue; if ((field.getModifiers() & Modifier.STATIC) != 0) continue; field.setAccessible(true); field.set(clone, field.get(o)); } c = c.getSuperclass(); } return clone; } catch (Exception __e) { throw rethrow(__e); } } static public List simpleSpaces(List tok) { tok = cloneList(tok); for (int i = 0; i < l(tok); i += 2) tok.set(i, tok.get(i).equals("") ? "" : " "); return tok; } static public String simpleSpaces(String s) { return join(simpleSpaces(nlTok(s))); } static public String newLinesToSpaces(String s) { return s == null ? null : fixNewLines(s).replace("\n", " "); } static public void appendToLocalMechLog(String listName, String text) { logMechListAppendLocally(listName, text); } static public JButton jImageAndTextButton(String imageID, String text, Object action) { JButton btn = jImageAndTextButton_defaultPlacement(imageID, text, action); btn.setVerticalTextPosition(SwingConstants.BOTTOM); btn.setHorizontalTextPosition(SwingConstants.CENTER); return btn; } static public JButton jImageAndTextButton(String imageID, String text) { return jImageAndTextButton(imageID, text, null); } static public void resizeImageButtonToMax(final JButton b, final int max) { { swing(() -> { BufferedImage img = imageToBufferedImage(((ImageIcon) b.getIcon()).getImage()); if (img == null) return; BufferedImage img2 = scaleBufferedImageToMaxWidthOrHeight(img, max); if (img2 != img) setButtonImage(img2, b); }); } } static public int niceButtons_maxImageSize = 128; static public int niceButtons_maxImageSize() { return niceButtons_maxImageSize; } static public A setVerticalTextPosition(final int pos, final A a) { if (a != null) { swing(() -> { a.setVerticalTextPosition(pos); }); } return a; } static public A setVerticalAlignment(final int pos, final A a) { if (a != null) { swing(() -> { a.setVerticalAlignment(pos); }); } return a; } static public A setVerticalAlignment(final int pos, final A a) { if (a != null) { swing(() -> { a.setVerticalAlignment(pos); }); } return a; } static public void onMouseEnter(final Component c, final Object r) { if (c != null) { swing(() -> { c.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent e) { pcallF(r); } }); }); } } static public void onMouseExit(final Component c, final Object r) { if (c != null) { swing(() -> { c.addMouseListener(new MouseAdapter() { public void mouseExited(MouseEvent e) { pcallF(r); } }); }); } } static public IF0 preferredScreen; static public int preferredScreen() { return preferredScreen != null ? preferredScreen.get() : preferredScreen_base(); } final static public int preferredScreen_fallback(IF0 _f) { return _f != null ? _f.get() : preferredScreen_base(); } static public int preferredScreen_base() { return 0; } static public boolean hasExtension(File f, String ext) { return f != null && ewic(f.getName(), addPrefixOptIfNempty(".", ext)); } static public BufferedImage loadQOI(File f) { try { if (f == null) return null; var imageReader = new QOIImageReaderSPI().createReaderInstance(); try { var stream = ImageIO.createImageInputStream(f); imageReader.setInput(stream); return imageReader.read(0); } finally { imageReader.dispose(); } } catch (Exception __e) { throw rethrow(__e); } } static public boolean shouldTranspileOnDedi() { return nempty(trimLoadTextFile(javaxDataDir("transpile-on-dedi"))); } static public Pair transpileOnDediServer(String snippetID) { return transpileOnDediServer(snippetID, "quick"); } static public Pair transpileOnDediServer(long snippetID) { return transpileOnDediServer(fsI(snippetID)); } static public Pair transpileOnDediServer(long snippetID, String mode) { return transpileOnDediServer(fsI(snippetID), mode); } static public Pair transpileOnDediServer(String snippetID, String mode) { try { String url = "https://transpile-coffee.botcompany.de/"; print("Transpiling " + formatSnippetID(snippetID) + " on " + url); String result = postPage(url, paramsPlus(transpilationCredentials(), "snippetID", snippetID, "medium", eq(mode, "medium") ? "1" : null, "fresh", eq(mode, "fresh") ? "1" : null)); print(result); boolean ok = cic(htmlDecode(result), "Transpiled & uploaded"); return pair(ok, result); } catch (Exception __e) { throw rethrow(__e); } } static public float[] emptyFloatArray = new float[0]; static public float[] emptyFloatArray() { return emptyFloatArray; } static public Symbol emptySymbol_value; static public Symbol emptySymbol() { if (emptySymbol_value == null) emptySymbol_value = symbol(""); return emptySymbol_value; } static public A addComponents(A c, Collection components) { if (nempty(components)) { swing(() -> { for (Component comp : components) if (comp != null) c.add(comp); revalidate(c); }); } return c; } static public A addComponents(A c, Component... components) { return addComponents(c, asList(components)); } static public MultiMap mapMultiMapValues(Object func, MultiMap mm) { MultiMap m = similarEmptyMultiMap(mm); for (Object key : keys(mm)) for (Object value : mm.get(key)) m.put(key, callF(func, value)); return m; } static public MultiMap mapMultiMapValues(MultiMap mm, Object func) { return mapMultiMapValues(func, mm); } static public MultiMap mapMultiMapValues(IF1 func, MultiMap mm) { return mapMultiMapValues((Object) func, mm); } static public String formatArgumentClasses(Object[] args) { return joinWithComma(map(__138 -> getClassName(__138), args)); } static public String str_nullIfEmpty(Object o) { return nullIfEmpty(strOrNull(o)); } static public void gazelle22_highlightRegionOutline(int[] pixels, Gazelle22_ImageToRegions itr, RegionBorder_innerPoints x) { class X { public boolean hole = false; public int n; public Gazelle22_GradientImage gradientImage = new Gazelle22_GradientImage(itr.posterized); public X() { gradientImage.init(); int color = 0xFF008000, holeColor = 0xFFFFB266; x.onNewTrace(isHole -> hole = isHole); x.onFoundPoint(p -> { ++n; boolean gradient = gradientImage.isGradientPoint(p.x, p.y); int col = hole ? holeColor : color; if (gradient) if (odd(n)) return; pixels[p.y * itr.regions.w + p.x] = col; }); x.run(); } } new X(); } static public BufferedReader inputStreamReader(InputStream in) { return utf8Reader(in); } static public BufferedReader inputStreamReader(File f) { return utf8Reader(f); } static public void setMetaAndVerify(Object o, Object key, Object value) { setMeta(o, key, value); assertSame(() -> "setMeta failed (class: " + className(o) + ", key: " + key + ")", value, metaGet(o, key)); } static public void setMetaAndVerify(IMeta o, Object key, Object value) { setMeta(o, key, value); assertSame(() -> "setMeta failed (class: " + className(o) + ", key: " + key + ")", value, metaGet(o, key)); } static public Runnable rPcall(Runnable r) { return r == null ? null : () -> { try { r.run(); } catch (Throwable __e) { pcallFail(__e); } }; } static public IVF2 showForm_makeFrame; static public void showForm_makeFrame(String title, JPanel panel) { if (showForm_makeFrame != null) showForm_makeFrame.get(title, panel); else showForm_makeFrame_base(title, panel); } final static public void showForm_makeFrame_fallback(IVF2 _f, String title, JPanel panel) { if (_f != null) _f.get(title, panel); else showForm_makeFrame_base(title, panel); } static public void showForm_makeFrame_base(String title, JPanel panel) { handleEscapeKey(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400)); } static public void onTableSelectionChangedAndNow(final JTable table, final Runnable r) { { swing(() -> { table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { swingLater(r); } }); callF(r); }); } } static public Object[] transpilationCredentials() { String _pass = transpilationPassword(); return nempty(_pass) ? new Object[] { "_pass", _pass } : new Object[0]; } static public MultiMap mapMultiMapKeys(IF1 f, MultiMap mm) { MultiMap m = similarEmptyMultiMap(mm); for (var key : keys(mm)) m.put(f.get(key), mm.get(key)); return m; } static public MultiMap mapMultiMapKeys(MultiMap mm, IF1 f) { return mapMultiMapKeys(f, mm); } static public MultiSetMap mapMultiSetMapKeys(IF1 f, MultiSetMap mm) { MultiSetMap m = similarEmptyMultiSetMap(mm); for (var key : keys(mm)) m.put(f.get(key), mm.get(key)); return m; } static public MultiSetMap mapMultiSetMapKeys(MultiSetMap mm, IF1 f) { return mapMultiSetMapKeys(f, mm); } static public List linesFromFile_list(File f) { try { return asList_closeIterator(linesFromFile(f)); } catch (Exception __e) { throw rethrow(__e); } } static public List linesFromFile_list(String path) { return linesFromFile_list(newFile(path)); } static public IBWIntegralImage toIBWIntegralImage(IBWImage img) { if (img instanceof IBWIntegralImage) return ((IBWIntegralImage) img); return bwIntegralImage(img); } static public A[] newArray(Class c, int n) { return typedArray(c, n); } static public Boolean trueOrNull(Boolean b) { return eq(b, false) ? null : b; } static public boolean initSyntaxTextArea_numPadFix = true; static public void initSyntaxTextArea(RSyntaxTextArea textArea) { swing(() -> { if (initSyntaxTextArea_numPadFix) new NumPadFixingInputMap().replaceOn(textArea); textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); textArea.setHighlightCurrentLine(false); textArea.setTabSize(2); textArea.setTabsEmulated(true); textArea.setCodeFoldingEnabled(false); textArea.setMarkOccurrences(true); }); } static public String plural(String s) { return getPlural(s); } static public A toJComponent(A c) { return c; } static public JComponent toJComponent(Swingable c) { return c == null ? null : c.visualize(); } static public byte[] emptyByteArray_a = new byte[0]; static public byte[] emptyByteArray() { return emptyByteArray_a; } static public float clampToZeroOne(float x) { return x < 0 ? 0 : x > 1 ? 1 : x; } static public double clampToZeroOne(double x) { return x < 0 ? 0 : x > 1 ? 1 : x; } static public int subclassDistance(Class a, Class b) { int n = 0; while (a != b) { a = a.getSuperclass(); if (a == null) return Integer.MAX_VALUE; ++n; } return n; } static public List findFunctionalInterfaceMethods(Class intrface) { if (!isInterface(intrface)) return null; List l = new ArrayList(); _MethodCache cache = getMethodCache(intrface); Class c = intrface; do { for (Method m : c.getDeclaredMethods()) { String name = m.getName(); var args = m.getParameterTypes(); if (m.getDeclaringClass() != Object.class && !m.isDefault() && !isStaticMethod(m) && !m.isSynthetic() && !(eq(name, "equals") && l(args) == 1 && args[0] == Object.class)) l.add(m); } c = c.getSuperclass(); } while (c != null); return l; } static public class listPopupMenu_Maker { public List menuMakers = new ArrayList(); } static public Map listPopupMenu_map = new WeakHashMap(); static public ThreadLocal listPopupMenu_mouseEvent = new ThreadLocal(); static public ThreadLocal listPopupMenu_first = new ThreadLocal(); static public void listPopupMenu(final JList list, final Object menuMaker) { final boolean first = isTrue(getAndClearThreadLocal(listPopupMenu_first)); swingNowOrLater(new Runnable() { public void run() { try { listPopupMenu_Maker maker = listPopupMenu_map.get(list); if (maker == null) { listPopupMenu_map.put(list, maker = new listPopupMenu_Maker()); final listPopupMenu_Maker _maker = maker; list.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { displayMenu(e); } public void mouseReleased(MouseEvent e) { displayMenu(e); } public void displayMenu(MouseEvent e) { if (e.isPopupTrigger()) { JPopupMenu menu = new JPopupMenu(); int idx = list.locationToIndex(e.getPoint()); Object item = list.getModel().getElementAt(idx); list.setSelectedIndex(idx); int emptyCount = menu.getComponentCount(); listPopupMenu_mouseEvent.set(e); for (Object menuMaker : _maker.menuMakers) pcallF(menuMaker, menu, item); if (menu.getComponentCount() == emptyCount) return; vmBus_send("showingPopupMenu", list, menu); menu.show(e.getComponent(), e.getX(), e.getY()); } } }); } if (first) maker.menuMakers.add(0, menuMaker); else maker.menuMakers.add(menuMaker); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "listPopupMenu_Maker maker = listPopupMenu_map.get(list);\r\n if (maker == nu..."; } }); } static public Class main() { return getMainClass(); } static public Object safeUnstructure(String s) { return unstructure(s, true); } static public Object safeUnstructure(File f) { return safeUnstructureGZFile(f); } static public boolean isNotLeftMouseButton(MouseEvent e) { return e.getButton() != e.BUTTON1; } static public String trivialUnquote(String s) { return dropPrefixSuffix("\"", s); } static public short[] shortArrayFromBytes(byte[] a) { return shortArrayFromBytes(a, 0, l(a)); } static public short[] shortArrayFromBytes(byte[] a, int from, int to) { short[] b = new short[(to - from) / 2]; for (int i = 0; i < b.length; i++) b[i] = shortFromBytes(a, from + i * 2); return b; } static public long[] longArrayFromBytes(byte[] a) { return longArrayFromBytes(a, 0, l(a)); } static public long[] longArrayFromBytes(byte[] a, int from, int to) { long[] b = new long[(to - from) / 8]; for (int i = 0; i < b.length; i++) b[i] = longFromBytes_bigEndian(a, from + i * 8); return b; } static public float[] toFloatArray(List l) { float[] a = new float[l(l)]; for (int i = 0; i < a.length; i++) a[i] = l.get(i); return a; } static public float[] toFloatArray(double[] l) { float[] a = new float[l(l)]; for (int i = 0; i < a.length; i++) a[i] = (float) l[i]; return a; } static public ThreadLocal DynamicObject_loading = or((ThreadLocal) get(getClass("x30_pkg.x30_util"), "DynamicObject_loading"), new ThreadLocal()); static public ThreadLocal dynamicObjectIsLoading_threadLocal() { return DynamicObject_loading; } static public FileOutputStream fileOutputStream(File path) { try { return newFileOutputStream(path); } catch (Exception __e) { throw rethrow(__e); } } static public FileOutputStream fileOutputStream(String path) { try { return newFileOutputStream(path); } catch (Exception __e) { throw rethrow(__e); } } static public FileOutputStream fileOutputStream(File path, boolean append) { try { return newFileOutputStream(path, append); } catch (Exception __e) { throw rethrow(__e); } } static public FileOutputStream fileOutputStream(String path, boolean append) { try { return newFileOutputStream(path, append); } catch (Exception __e) { throw rethrow(__e); } } static public PCallPolicy defaultPCallPolicy = __1 -> printStackTrace(__1); static public PCallPolicy defaultPCallPolicy() { return defaultPCallPolicy; } static public void defaultPCallPolicy_set(PCallPolicy policy) { defaultPCallPolicy = policy; } static public SynchronizedCircularFifoBuffer globalLastErrorsBuffer = new SynchronizedCircularFifoBuffer(10); static public SynchronizedCircularFifoBuffer globalLastErrorsBuffer() { return globalLastErrorsBuffer; } static public String javaxDefaultVMArgs() { File fileNew, fileOld; String text = loadTextFile(fileNew = javaxDataDir("default-vm-args")); if (text == null) { text = loadTextFile(fileOld = programFile("#1005850", "default-vm-args")); if (text != null) moveFile(fileOld, fileNew); } return trim(unnull(text)); } static public List dropSecondIfEmpty(String a, String b) { return empty(b) ? ll(a) : ll(a, b); } static public int parseFirstInt(String s) { return parseInt(jextract("", s)); } static public int parseFirstInt(Iterable l) { return parseInt(firstIntegerString(l)); } static public boolean usePreSpunVMs() { return eq("1", trim(loadProgramTextFile("#1005457", "enable-prespun-vms"))); } static public void usePreSpunVMs(boolean flag) { saveProgramTextFile("#1005457", "enable-prespun-vms", flag ? "1" : null); } static public File classicNohupJavax(String javaxargs) { return classicNohupJavax(javaxargs, ""); } static public File classicNohupJavax(String javaxargs, String vmArgs) { try { File jar = pathToJavaxJar(); if (javaxargs.startsWith("#")) javaxargs = javaxargs.substring(1); String tempPrefix = takeFirst(30, nohup_sanitize(ymd_minus_hms() + "_" + javaxargs + "_")); File outFile; try { outFile = File.createTempFile(tempPrefix, ""); } catch (Throwable e) { printStackTrace(e); print("Temp file creation failed for " + tempPrefix + ", trying again."); outFile = File.createTempFile("", ""); } String cmd = joinWithSpace((platformParseArgs(_javaCommand() + " " + vmArgs))) + " -jar " + (isWindows() ? winQuote(jar) : bashQuote(jar)) + " " + javaxargs; nohup(cmd, outFile, false); return outFile; } catch (Exception __e) { throw rethrow(__e); } } static public void raiseFlagAndDo(Flag flag, Runnable r) { if (flag.raise()) callF(r); } static public void _handleException_addHandler(Object handler) { addIfNotThere(_handleException_onException, handler); } static public void _handleException_addHandler(IVF1 handler) { _handleException_addHandler((Object) handler); } static public A assertNull(A a) { assertTrue(a == null); return a; } static public A assertNull(String msg, A a) { assertTrue(msg, a == null); return a; } static public A internalFrameTitle(A c, final String title) { final JInternalFrame f = getInternalFrame(c); if (f != null) { swing(() -> { f.setTitle(unnull(title)); toolTip(getInternalFrameTitlePaneComponent(f), title); }); } return c; } static public A internalFrameTitle(String title, A c) { return internalFrameTitle(c, title); } static public String internalFrameTitle(Component c) { final JInternalFrame f = getInternalFrame(c); return f == null ? null : swing(new F0() { public String get() { try { return f.getTitle(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return f.getTitle();"; } }); } static public A frameTitle(A c, String title) { return setFrameTitle(c, title); } static public A frameTitle(String title, A c) { return setFrameTitle(c, title); } static public String frameTitle(Component c) { return getFrameTitle(c); } static public PCallPolicy pcallPolicyForThread() { var policy = pcallPolicyForThread_tl().get(); if (policy != null) return policy; return defaultPCallPolicy(); } static public boolean isTransientField(Object object, String name) { Field f = getField(object, name); return f != null && (f.getModifiers() & Modifier.TRANSIENT) != 0; } static public A shallowCloneToClass(Class c, Object o) { if (o == null) return null; A a = nuInstance(c); copyFields(o, a); return a; } static public void dm_onTopInput(final VF1 r) { final DynModule m = dm_current_mandatory(); dm_ownResource(vmBus_onMessage("topInput", new VF1() { public void get(final String s) { try { m.enter(); callF(r, s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.enter();\r\n callF(r, s)"; } })); } static public void dm_onTopInput(final Runnable r) { final DynModule m = dm_current_mandatory(); dm_ownResource(vmBus_onMessage("topInput", new VF1() { public void get(final String s) { try { m.enter(); callF(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.enter();\r\n callF(r)"; } })); } static public A vm_generalMap_getOrCreate(Object key, F0 create) { return vm_generalMap_getOrCreate(key, f0ToIF0(create)); } static public A vm_generalMap_getOrCreate(Object key, IF0 create) { Map generalMap = vm_generalMap(); if (generalMap == null) return null; synchronized (generalMap) { A a = (A) (vm_generalMap_get(key)); if (a == null) vm_generalMap_put(key, a = create == null ? null : create.get()); return a; } } static public AutoCloseable tempInterceptPrint(F1 f) { return tempSetThreadLocal(print_byThread(), f); } static public void callAction(Action a) { if (a != null) a.actionPerformed(null); } static public void internalFrameTitlePopupMenu(final JInternalFrame f, final Object... params) { { swing(() -> { Object menuMaker; if (l(params) == 1 && !(params[0] instanceof JMenu)) menuMaker = params[0]; else menuMaker = new VF1() { public void get(JPopupMenu menu) { try { addMenuItems(menu, params); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItems(menu, params)"; } }; Component titleComponent = getInternalFrameTitlePaneComponent(f); if (!(titleComponent instanceof JComponent)) print("Can't add internal frame title popup menu!"); else { componentPopupMenu((JComponent) titleComponent, menuMaker); setOpt(componentPopupMenu_initForComponent((JComponent) titleComponent), "internalFrameLeftButtonMagic", isTrue(vm_generalMap_get("internalFramePopupOnLeftButton"))); } componentPopupMenu(f, menuMaker); }); } } static public String stringOptPar(Object[] params, String name) { return (String) optPar(params, name); } static public void dm_doubleFieldSetterDialog(String field, Object... __) { final DynModule m = dm_current_mandatory(); final String humanized = humanizeFormLabel(field); final JTextField tf = jtextfield(get(m, field)); showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() { public void run() { try { m.setField(field, parseDouble(gtt(tf))); callF(optPar(__, "onSet")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, parseDouble(gtt(tf)));\r\n callF(optPar(__, \"onSet\"));"; } }); } static public void dm_floatFieldSetterDialog(String field, Object... __) { DynModule m = dm_current_mandatory(); String humanized = humanizeFormLabel(field); JTextField tf = jtextfield(get(m, field)); showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() { public void run() { try { m.setField(field, parseFloat(gtt(tf))); callF(optPar(__, "onSet")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, parseFloat(gtt(tf)));\r\n callF(optPar(__, \"onSet\"));"; } }); } static public void dm_stringFieldDialog(final String field, final Object... __) { final DynModule m = dm_current_mandatory(); final String humanized = humanizeFormLabel(field); final JTextField tf = jtextfield(get(m, field)); showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() { public void run() { try { m.setField(field, gtt(tf)); callF(optPar(__, "onSet")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, gtt(tf));\r\n callF(optPar(__, \"onSet\"));"; } }); } static public void dm_fileFieldDialog(final String field, final Object... __) { DynModule m = dm_current_mandatory(); String humanized = humanizeFormLabel(field); JTextField tf = jtextfield(strOrNull(get(m, field))); showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() { public void run() { try { m.setField(field, toFile_nullOnEmpty(gtt(tf))); callF(optPar(__, "onSet")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "m.setField(field, toFile_nullOnEmpty(gtt(tf)));\r\n callF(optPar(__, \"onSe..."; } }); } static public Q dm_ownQ(Q q) { q.rst.enter = dm_rEnter(dm_current_mandatory()); dm_ownResource(q); return q; } static public void clearStringBuffer_gen(Object buf) { if (buf != null) { call(buf, "setLength", 0); call(buf, "trimToSize"); } } static public StringBuffer liveLocalPrintLog() { return local_log; } static public void internalFrameTitlePopupMenuItem(JInternalFrame f, final String name, final Object action) { internalFrameTitlePopupMenu(f, new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, name, action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, name, action)"; } }); } static public DialogIO talkToSubBot(final long vport, final DialogIO io) { return talkToSubBot(String.valueOf(vport), io); } static public DialogIO talkToSubBot(final String subBot, final DialogIO io) { if (subBot == null) return io; return new talkToSubBot_IO(subBot, io); } static public class talkToSubBot_IO extends DialogIO { public String subBot; public DialogIO io; public talkToSubBot_IO(String subBot, DialogIO io) { this.io = io; this.subBot = subBot; } public boolean isStillConnected() { return io.isStillConnected(); } public String readLineImpl() { return io.readLineImpl(); } public boolean isLocalConnection() { return io.isLocalConnection(); } public Socket getSocket() { return io.getSocket(); } public void close() { try { io.close(); } catch (Exception __e) { throw rethrow(__e); } } public void sendLine(String line) { io.sendLine(format3("please forward to bot *: *", subBot, line)); } } static public List quickBotScan() { return ProgramScan.quickBotScan(); } static public List quickBotScan(int[] preferredPorts) { return ProgramScan.quickBotScan(preferredPorts); } static public List quickBotScan(String searchPattern) { List l = new ArrayList(); for (ProgramScan.Program p : ProgramScan.quickBotScan()) if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) l.add(p); return l; } static public String firstPartOfHelloString(String s) { int i = s.lastIndexOf('/'); return i < 0 ? s : rtrim(s.substring(0, i)); } static public boolean isJavaXClassName(String s) { return isJavaXClassName(s, "main$"); } static public boolean isJavaXClassName(String s, String mcDollar) { return startsWithOneOf(s, mcDollar, "main$", "loadableUtils.", "x30", "userCode."); } static public void quoteToPrintWriter(String s, PrintWriter out) { if (s == null) { out.print("null"); return; } out.print('"'); int l = s.length(); for (int i = 0; i < l; i++) { char c = s.charAt(i); if (c == '\\' || c == '"') { out.print('\\'); out.print(c); } else if (c == '\r') out.print("\\r"); else if (c == '\n') out.print("\\n"); else if (c == '\0') out.print("\\0"); else out.print(c); } out.print('"'); } static public boolean isSubClassOf(Class a, Class b) { return isSubclass(a, b); } static public boolean isSyntheticOrAnonymous(Class c) { return c != null && (c.isSynthetic() || isAnonymousClassName(c.getName())); } static public List unwrapSynchronizedList(List l) { if (l instanceof SynchronizedList) return ((SynchronizedList) l).list; if (eqOneOf(className(l), "java.util.Collections$SynchronizedList", "java.util.Collections$SynchronizedRandomAccessList")) return (List) get_raw(l, "list"); return l; } static public String shortDynClassNameForStructure(Object o) { if (o instanceof DynamicObject && ((DynamicObject) o).className != null) return ((DynamicObject) o).className; if (o == null) return null; Class c = o instanceof Class ? (Class) o : o.getClass(); String name = c.getName(); return name.startsWith("dyn.") ? classNameToVM(name) : shortenClassName(name); } static public boolean isPersistableClass(Class c) { String name = c.getName(); if (isSubtypeOf(c, TransientObject.class)) return false; if (isAnonymousClassName(name)) return false; if (isBoxedType(c)) return true; if (isArrayType(c)) return true; if (c == Class.class || c == String.class || c == File.class || c == Color.class) return true; if (name.startsWith("java.util.Collections$Synchronized")) return true; if (hasThisDollarFields(c)) return hasSingleArgumentConstructor(c); else return getDefaultConstructor(c) != null; } static public Constructor getDefaultConstructor(Class c) { if (c != null) for (Constructor m : getDeclaredConstructors_cached(c)) if (empty(m.getParameterTypes())) return m; return null; } static public Object invokeConstructor(Constructor m, Object... args) { try { makeAccessible(m); return m.newInstance(args); } catch (Exception __e) { throw rethrow(__e); } } static public int countDots(String s) { int n = l(s), count = 0; for (int i = 0; i < n; i++) if (s.charAt(i) == '.') ++count; return count; } static public boolean isCIMap_gen(Map map) { return map instanceof TreeMap && className(((TreeMap) map).comparator()).contains("CIComp"); } static public Map unwrapSynchronizedMap(Map map) { if (eqOneOf(shortClassName(map), "SynchronizedMap", "SynchronizedSortedMap", "SynchronizedNavigableMap")) return (Map) get_raw(map, "m"); return map; } static public boolean isCISet_gen(Iterable l) { return l instanceof TreeSet && className(((TreeSet) l).comparator()).contains("CIComp"); } static public String quoteCharacter(char c) { if (c == '\'') return "'\\''"; if (c == '\\') return "'\\\\'"; if (c == '\r') return "'\\r'"; if (c == '\n') return "'\\n'"; if (c == '\t') return "'\\t'"; return "'" + c + "'"; } static public String boolArrayToHex(boolean[] a) { return bytesToHex(boolArrayToBytes(a)); } static public String shortArrayToHex_bigEndian(short[] a) { return bytesToHex(byteArrayFromShorts_bigEndian(a)); } static public String longArrayToHex_bigEndian(long[] a) { return bytesToHex(byteArrayFromLongs_bigEndian(a)); } static public Pair arrayTypeAndDimensions(Object o) { return arrayTypeAndDimensions(_getClass(o)); } static public Pair arrayTypeAndDimensions(Class c) { if (c == null || !c.isArray()) return null; Class elem = c.getComponentType(); if (elem.isArray()) return mapPairB(arrayTypeAndDimensions(elem), dim -> dim + 1); return pair(elem, 1); } static public Map getDeclaredFields_cache = newDangerousWeakHashMap(); static public Field[] getDeclaredFields_cached(Class c) { Field[] fields; synchronized (getDeclaredFields_cache) { fields = getDeclaredFields_cache.get(c); if (fields == null) { getDeclaredFields_cache.put(c, fields = c.getDeclaredFields()); for (Field f : fields) makeAccessible(f); } } return fields; } static public Method findInstanceMethod(Class c, String method, Object... args) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method) && findMethod_checkArgs(m, args, false)) return m; c = c.getSuperclass(); } return null; } static public Set fieldObjectsInFieldOrder(Class c, Set fields) { try { var byName = mapToKey(f -> f.getName(), fields); LinkedHashSet out = new LinkedHashSet(); for (String name : unnullForIteration(getFieldOrder(c))) { Field f = byName.get(name); if (f != null) { byName.remove(name); out.add(f); } } addAll(out, fields); return out; } catch (Throwable __0) { printStackTrace(__0); return fields; } } static public String quoted(Object o) { return quote(o); } static public String quoted(String s) { return quote(s); } static public void ensureDBNotRunning(String name) { if (hasBot(name)) { try { String framesBot = dropSuffix(".", name) + " Frames"; print("Trying to activate frames of running DB: " + framesBot); if (isOK(sendOpt(framesBot, "activate frames")) && isMainProgram()) cleanKill(); } catch (Throwable __e) { pcallFail(__e); } throw fail("Already running: " + name); } } static public void ensureDBNotRunning() { ensureDBNotRunning(dbBotStandardName()); } static public String dbBotStandardName() { String home = userHome(); String name = dbBotName(getDBProgramID()); if (neq(home, actualUserHome())) name += " " + quote(home); return name + "."; } static volatile public Android3 dbBot_instance; static public Android3 dbBot() { return dbBot(true); } static public Android3 dbBot(boolean ensureNotRunning) { return dbBot(dbBotStandardName(), ensureNotRunning); } static public Android3 dbBot(String name) { return dbBot(name, true); } static public Android3 dbBot(String name, boolean ensureNotRunning) { if (ensureNotRunning) ensureDBNotRunning(name); return dbBot_instance = methodsBot2(name, assertNotNull(db_mainConcepts()), db_standardExposedMethods(), db_mainConcepts().lock); } static public boolean isConceptList(Object o) { if (!(o instanceof List)) return false; List l = (List) o; for (Object x : l) if (!(x instanceof Concept)) return false; return true; } static public void dynamicObject_dropRawField(DynamicObject o, Object key) { if (o == null) return; synchronized (o) { o.fieldValues = (LinkedHashMap) syncMapRemove_deleteMapIfEmpty((Map) o.fieldValues, key); } } static public boolean isPersistable(Object o) { return !isInAnonymousClass(o); } static public boolean isTransient(Field f) { return (f.getModifiers() & java.lang.reflect.Modifier.TRANSIENT) != 0; } static public Map> parse3_cachedInput_cache = synchronizedMRUCache(1000); static public List parse3_cachedInput(String s) { List tok = parse3_cachedInput_cache.get(s); if (tok == null) parse3_cachedInput_cache.put(s, tok = parse3(s)); return tok; } static public Map> parse3_cachedPattern_cache = synchronizedMRUCache(1000); static synchronized public List parse3_cachedPattern(String s) { List tok = parse3_cachedPattern_cache.get(s); if (tok == null) parse3_cachedPattern_cache.put(s, tok = parse3(s)); return tok; } static public boolean isLocalhost(String ip) { return isLoopbackIP(ip) || eqic(ip, "localhost"); } static public int vmPort() { return myVMPort(); } static public DialogIO talkToThisVM() { return new talkToThisVM_IO(); } static public class talkToThisVM_IO extends DialogIO { public List answers = ll(thisVMGreeting()); public boolean isLocalConnection() { return true; } public boolean isStillConnected() { return true; } public int getPort() { return vmPort(); } public void sendLine(String line) { answers.add(or2(sendToThisVM_newThread(line), "?")); } public String readLineImpl() { try { return popFirst(answers); } catch (Exception __e) { throw rethrow(__e); } } public void close() { } public Socket getSocket() { return null; } } static public TableWithTooltips tableWithTooltips() { return (TableWithTooltips) swing(new F0() { public Object get() { try { return new TableWithTooltips(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return new TableWithTooltips;"; } }); } static public class TableWithTooltips extends JTable { public String getToolTipText(MouseEvent e) { String tip = null; Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); try { return str(getValueAt(rowIndex, colIndex)); } catch (Throwable _e) { return null; } } } static public Object getTL(Object o, String name) { return getThreadLocal(o, name); } static public A getTL(ThreadLocal tl) { return getThreadLocal(tl); } static public A getTL(ThreadLocal tl, A defaultValue) { return getThreadLocal(tl, defaultValue); } static public Method findMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args); } static public boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } static public Integer rectCenterX(Rect r) { return r == null ? null : r.x + r.w / 2; } static public Integer rectCenterY(Rect r) { return r == null ? null : r.y + r.h / 2; } static public void appendToMechQ_withDate(final String listName, final String text) { mechAppend_noUniq_inQ(listName, "[" + localDateWithMilliseconds() + "] " + text); } static public List nlTok(String s) { return javaTokPlusPeriod(s); } static public void logMechListAppendLocally(String listName, String text) { if (empty(text)) return; logStructureWithDate(mechListAppendLogFile(listName), litorderedmap("list", listName, "text", text)); appendToFile(createLocalMechListFile(listName), assureTrailingNewLine(text)); } static public JButton jImageAndTextButton_defaultPlacement(String imageID, String text, Object action) { return setText(jImageButton(imageID, action), text); } static public JButton jImageAndTextButton_defaultPlacement(String imageID, String text) { return jImageAndTextButton_defaultPlacement(imageID, text, null); } static public BufferedImage imageToBufferedImage(Image img) { if (img == null || img instanceof BufferedImage) return (BufferedImage) img; BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); bimage.createGraphics().drawImage(img, 0, 0, null); return bimage; } static public BufferedImage scaleBufferedImageToMaxWidthOrHeight(WidthAndHeight size, BufferedImage img) { return img == null ? null : scaleBufferedImageToMaxWidthOrHeight(size.w(), size.h(), img); } static public BufferedImage scaleBufferedImageToMaxWidthOrHeight(int maxW, BufferedImage img) { return scaleBufferedImageToMaxWidthOrHeight(maxW, maxW, img); } static public BufferedImage scaleBufferedImageToMaxWidthOrHeight(int maxW, int maxH, BufferedImage img) { if (img == null) return null; int w = img.getWidth(), h = img.getHeight(); if (w <= maxW && h <= maxH) return img; double scale = min(doubleRatio(maxW, w), doubleRatio(maxH, h)); return scaleImage(img, scale); } static public BufferedImage scaleBufferedImageToMaxWidthOrHeight(BufferedImage img, int max) { return scaleBufferedImageToMaxWidthOrHeight(max, img); } static public WeakHasherMap symbol_map = new WeakHasherMap(new Hasher() { public int hashCode(Symbol symbol) { return symbol.text.hashCode(); } public boolean equals(Symbol a, Symbol b) { if (a == null) return b == null; return b != null && eq(a.text, b.text); } }); static public Symbol symbol(String s) { if (s == null) return null; synchronized (symbol_map) { Symbol symbol = new Symbol(s, true); Symbol existingSymbol = symbol_map.findKey(symbol); if (existingSymbol == null) symbol_map.put(existingSymbol = symbol, true); return existingSymbol; } } static public Symbol symbol(CharSequence s) { if (s == null) return null; if (s instanceof Symbol) return (Symbol) s; if (s instanceof String) return symbol((String) s); return symbol(str(s)); } static public Symbol symbol(Object o) { return symbol((CharSequence) o); } static public BufferedReader utf8Reader(InputStream in) { return utf8BufferedReader(in); } static public BufferedReader utf8Reader(File f) { return utf8BufferedReader(f); } static public JFrame handleEscapeKey(final JFrame frame) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); frame.getRootPane().registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { frame.dispose(); } }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); return frame; } static public JFrame minFrameWidth(JFrame frame, int w) { if (frame != null && frame.getWidth() < w) frame.setSize(w, frame.getHeight()); return frame; } static public JFrame minFrameWidth(int w, JFrame frame) { return minFrameWidth(frame, w); } static public MultiSetMap similarEmptyMultiSetMap(MultiSetMap m) { return similarEmptyMultiSetMap(m == null ? null : m.data); } static public MultiSetMap similarEmptyMultiSetMap(Map m) { MultiSetMap mm = new MultiSetMap(); if (m != null) mm.data = similarEmptyMap(m); return mm; } static public ArrayList asList_closeIterator(CloseableIterableIterator it) { AutoCloseable __1 = it; try { return asList(it); } finally { _close(__1); } } static public A[] typedArray(Class c, int n) { return (A[]) Array.newInstance(c, n); } static public Object safeUnstructureGZFile(File f) { try { if (!fileExists(f)) return null; BufferedReader reader = utf8BufferedReader(gzInputStream(f)); return unstructure_tok(javaTokC_noMLS_onReader(reader), true, null); } catch (Exception __e) { throw rethrow(__e); } } static public String dropPrefixSuffix(String prefix, String s) { return dropPrefixSuffix(prefix, prefix, s); } static public String dropPrefixSuffix(String prefix, String suffix, String s) { return dropPrefix(prefix, dropSuffix(suffix, s)); } static public short shortFromBytes(byte[] a, int i) { return (short) (ubyteToInt(a[i]) << 8 | ubyteToInt(a[i + 1])); } static public long longFromBytes_bigEndian(byte[] a, int i) { return twoIntsToLong_bigEndian(intFromBytes_bigEndian(a, i), intFromBytes_bigEndian(a, i + 4)); } static public String firstIntegerString(Iterable c) { Iterator it = c.iterator(); while (it.hasNext()) { String s = it.next(); if (isInteger(s)) return s; } return null; } static public File saveProgramTextFile(String name, String contents) { return saveTextFile(getProgramFile(name), contents); } static public File saveProgramTextFile(String progID, String name, String contents) { return saveTextFile(getProgramFile(progID, name), contents); } static public List platformParseArgs(String s) { List out = new ArrayList(); List tok = javaTok(trim(s)); for (int i = 1; i < l(tok); i += 2) { if (isQuoted(tok.get(i))) { out.add(tok.get(i)); continue; } int j = i; while (j + 2 < l(tok) && empty(tok.get(j + 1))) j += 2; out.add(joinSubList(tok, i, j + 1)); i = j; } return out; } static public String _javaCommand() { String __1 = trim(loadTextFile(javaxDataDir("java-command.txt"))); if (!empty(__1)) return __1; String javaHome = System.getProperty("java.home"); if (nempty(javaHome)) { File f = new File(javaHome); f = oneOfTheFiles(newFile(f, "bin", "java"), newFile(f, "bin", "java.exe")); if (f != null) return platformQuote(f); } if (isOnPATH("java")) return "java"; throw fail("No java command found"); } static public String getFrameTitle(Component c) { JFrame f = getFrame(c); return f == null ? null : f.getTitle(); } static public ThreadLocal pcallPolicyForThread_tl_tl = new ThreadLocal(); static public ThreadLocal pcallPolicyForThread_tl() { return pcallPolicyForThread_tl_tl; } static public IF0 f0ToIF0(F0 f) { return f == null ? null : () -> f.get(); } static public File toFile_nullOnEmpty(String s) { return empty(s) ? null : new File(s); } static public boolean isBoxedType(Class type) { return type == Boolean.class || type == Integer.class || type == Long.class || type == Float.class || type == Short.class || type == Character.class || type == Byte.class || type == Double.class; } static public boolean hasThisDollarFields(Object o) { Matches m = new Matches(); for (var f : allFieldObjects_dontMakeAccessible(o)) if (startsWith(f.getName(), "this$", m) && isInteger(m.rest())) return true; return false; } static public boolean hasSingleArgumentConstructor(Class c) { if (c != null) for (Constructor m : getDeclaredConstructors_cached(c)) if (l(m.getParameterTypes()) == 1) return true; return false; } static public byte[] boolArrayToBytes(boolean[] a) { byte[] b = new byte[(l(a) + 7) / 8]; for (int i = 0; i < l(a); i++) if (a[i]) b[i / 8] |= 1 << (i & 7); return b; } static public byte[] byteArrayFromShorts_bigEndian(short[] a) { return byteArrayFromShorts_bigEndian(a, 0, l(a)); } static public byte[] byteArrayFromShorts_bigEndian(short[] a, int from, int to) { byte[] b = new byte[(to - from) * 2]; for (int i = 0; i < a.length; i++) { short s = a[from + i]; b[i * 2] = (byte) (s >> 8); b[i * 2 + 1] = (byte) s; } return b; } static public byte[] byteArrayFromLongs_bigEndian(long[] a) { return byteArrayFromLongs_bigEndian(a, 0, l(a)); } static public byte[] byteArrayFromLongs_bigEndian(long[] a, int from, int to) { byte[] b = new byte[(to - from) * 8]; for (int i = 0; i < a.length; i++) { long s = a[from + i]; b[i * 8] = (byte) (s >> 56); b[i * 8 + 1] = (byte) (s >> 48); b[i * 8 + 2] = (byte) (s >> 40); b[i * 8 + 3] = (byte) (s >> 32); b[i * 8 + 4] = (byte) (s >> 24); b[i * 8 + 5] = (byte) (s >> 16); b[i * 8 + 6] = (byte) (s >> 8); b[i * 8 + 7] = (byte) s; } return b; } static public List> mapPairB(final Object f, Iterable> l) { return map(l, new F1, Pair>() { public Pair get(Pair p) { try { return p == null ? null : pair(p.a, (C) callF(f, p.b)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "p == null ? null : pair(p.a, (C) callF(f, p.b))"; } }); } static public List> mapPairB(final F1 f, Iterable> l) { return mapPairB((Object) f, l); } static public List> mapPairB(final IF1 f, Iterable> l) { return mapPairB((Object) f, l); } static public List> mapPairB(Iterable> l, IF1 f) { return mapPairB((Object) f, l); } static public Pair mapPairB(IF1 f, Pair p) { return pairMapB(f, p); } static public Pair mapPairB(Pair p, IF1 f) { return pairMapB(f, p); } static public Map mapToKey(Iterable l, IF1 f) { return mapToKeys(l, f); } static public Map mapToKey(IF1 f, Iterable l) { return mapToKeys(f, l); } static public Map> getFieldOrder_cache = weakMap(); static public List getFieldOrder(Object o) { return getFieldOrder(_getClass(o)); } static public List getFieldOrder(Class c) { if (c == null) return null; return getOrCreate(getFieldOrder_cache, c, () -> splitAtSpace(toStringOpt(getOpt(c, "_fieldOrder")))); } static public boolean isOK(String s) { s = trim(s); return swic(s, "ok ") || eqic(s, "ok") || matchStart("ok", s); } static public String sendOpt(String bot, String text, Object... args) { return sendToLocalBotOpt(bot, text, args); } static public void cleanKill() { cleanKillVM(); } static public String dbBotName(String progIDWithCase) { return fsI_flex(progIDWithCase) + " Concepts"; } static public Android3 methodsBot2(String name, final Object receiver, final List exposedMethods) { return methodsBot2(name, receiver, exposedMethods, null); } static public Android3 methodsBot2(String name, final Object receiver, final List exposedMethods, final Lock lock) { Android3 android = new Android3(); android.greeting = name; android.console = false; android.responder = new Responder() { public String answer(String s, List history) { return exposeMethods2(receiver, s, exposedMethods, lock); } }; return makeBot(android); } static public List db_standardExposedMethods_list = ll("xlist", "xnew", "xset", "xdelete", "xget", "xclass", "xfullgrab", "xshutdown", "xchangeCount", "xcount"); static public List db_standardExposedMethods() { return db_standardExposedMethods_list; } static public > C syncMapRemove_deleteMapIfEmpty(C map, A key) { if (map != null && key != null) synchronized (collectionMutex(map)) { map.remove(key); if (map.isEmpty()) return null; } return map; } static public boolean isInAnonymousClass(Object o) { if (o == null) return false; return isAnonymousClassName(className(o)); } static public List parse3(String s) { return dropPunctuation(javaTokPlusPeriod(s)); } static public boolean isLoopbackIP(String ip) { return eq(ip, "127.0.0.1"); } static public int myVMPort() { List records = (List) (get(getJavaX(), "record_list")); Object android = last(records); return or0((Integer) get(android, "port")); } static public String thisVMGreeting() { List record_list = (List) (get(getJavaX(), "record_list")); Object android = first(record_list); return getString(android, "greeting"); } static public String sendToThisVM_newThread(String s, Object... args) { final String _s = format(s, args); try { return (String) evalInNewThread(new F0() { public Object get() { try { return callStaticAnswerMethod(getJavaX(), _s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return callStaticAnswerMethod(getJavaX(), _s);"; } }); } catch (Throwable e) { e = getInnerException(e); printStackTrace(e); return str(e); } } static public void mechAppend_noUniq_inQ(final String listName, final String text) { appendToMechList_noUniq_inQ(listName, text); } static public String localDateWithMilliseconds(Date time) { return localDateWithMilliseconds(time.getTime()); } static public String localDateWithMilliseconds(long time) { SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss''SSSS"); return format.format(time); } static public String localDateWithMilliseconds() { return localDateWithMilliseconds(now()); } static public A logStructureWithDate(File logFile, A o) { logQuoted(logFile, now() + " " + structure(o)); return o; } static public A logStructureWithDate(String fileName, A o) { return logStructureWithDate(getProgramFile(fileName), o); } static public File mechListAppendLogFile(String listName) { return javaxDataDir("Mech List Appends/" + uniqueFileNameUsingMD5_80(listName)); } static public File createLocalMechListFile(String listName) { File nameFile = localMechListNameFile(listName); if (!nameFile.exists()) saveTextFile(nameFile, listName); return localMechListFile(listName); } static public String assureTrailingNewLine(String s) { return addSuffix(s, "\n"); } static public long twoIntsToLong_bigEndian(int a, int b) { return twoIntsToLong(a, b); } static public int intFromBytes_bigEndian(byte[] a, int i) { return intFromBytes(a, i); } static public List allFieldObjects_dontMakeAccessible(Object o) { List fields = new ArrayList(); Class _c = _getClass(o); do { addAll(fields, _c.getDeclaredFields()); _c = _c.getSuperclass(); } while (_c != null); return fields; } static public Pair pairMapB(Object f, Pair p) { return p == null ? null : pair(p.a, callF(f, p.b)); } static public Pair pairMapB(IF1 f, Pair p) { return p == null ? null : pair(p.a, f.get(p.b)); } static public Pair pairMapB(Pair p, Object f) { return pairMap(f, p); } static public Map mapToKeys(Iterable l, IF1 f) { if (l == null) return null; HashMap map = new HashMap(); for (A a : l) map.put(f.get(a), a); return map; } static public Map mapToKeys(IF1 f, A[] l) { return mapToKeys(f, asList(l)); } static public Map mapToKeys(IF1 f, Iterable l) { return mapToKeys(l, f); } static public Map weakMap() { return newWeakHashMap(); } static public boolean matchStart(String pat, String s) { return matchStart(pat, s, null); } static public boolean matchStart(String pat, String s, Matches matches) { if (s == null) return false; return matchStart(pat, parse3_cachedInput(s), matches); } static public boolean matchStart(String pat, List toks, Matches matches) { if (toks == null) return false; List tokpat = parse3_cachedPattern(pat); if (toks.size() < tokpat.size()) return false; String[] m = match2(tokpat, toks.subList(0, tokpat.size())); if (m == null) return false; if (matches != null) { matches.m = new String[m.length + 1]; arraycopy(m, matches.m); matches.m[m.length] = joinSubList(toks, tokpat.size(), toks.size()); } return true; } static public String fsI_flex(String s) { return startsWithDigit(s) ? "#" + s : s; } static public boolean exposeMethods2_debug = false; static public String exposeMethods2(Object receiver, String s, List methodNames) { return exposeMethods2(receiver, s, methodNames, null); } static public String exposeMethods2(Object receiver, String s, List methodNames, Lock lock) { Matches m = new Matches(); if (exposeMethods2_debug) print("Received: " + s); if (match("call *", s, m)) { List l; if (isIdentifier(m.unq(0))) l = ll(m.unq(0)); else l = (List) unstructure(m.unq(0)); String method = getString(l, 0); if (!contains(methodNames, method)) throw fail("Method not allowed: " + method); if (lock != null) lock.lock(); try { if (exposeMethods2_debug) print("Calling: " + method); Object o = call(receiver, method, asObjectArray(subList(l, 1))); if (exposeMethods2_debug) print("Got: " + getClassName(o)); return ok2(structure(o)); } finally { if (lock != null) lock.unlock(); } } if (match("list methods", s)) return ok2(structure(methodNames)); return null; } static public int makeBot(String greeting) { return makeAndroid3(greeting).port; } static public Android3 makeBot(Android3 a) { makeAndroid3(a); return a; } static public Android3 makeBot(String greeting, Object responder) { Android3 a = new Android3(greeting); a.responder = makeResponder(responder); makeBot(a); return a; } static public Android3 makeBot() { return makeAndroid3(defaultBotName()); } static public List dropPunctuation_keep = ll("*", "<", ">"); static public List dropPunctuation(List tok) { tok = new ArrayList(tok); for (int i = 1; i < tok.size(); i += 2) { String t = tok.get(i); if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) { tok.set(i - 1, tok.get(i - 1) + tok.get(i + 1)); tok.remove(i); tok.remove(i); i -= 2; } } return tok; } static public String dropPunctuation(String s) { return join(dropPunctuation(nlTok(s))); } static public int or0(Integer i) { return i == null ? 0 : i; } static public long or0(Long l) { return l == null ? 0L : l; } static public double or0(Double d) { return d == null ? 0.0 : d; } static public Object evalInNewThread(final Object f) { final Flag flag = new Flag(); final Var var = new Var(); final Var exception = new Var(); { startThread(new Runnable() { public void run() { try { try { var.set(callF(f)); } catch (Throwable e) { exception.set(e); } flag.raise(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n var.set(callF(f));\r\n } catch (Throwable e) {\r\n exception..."; } }); } flag.waitUntilUp(); if (exception.has()) throw rethrow(exception.get()); return var.get(); } static public String callStaticAnswerMethod(List bots, String s) { for (Object c : bots) try { String answer = callStaticAnswerMethod(c, s); if (!empty(answer)) return answer; } catch (Throwable e) { print("Error calling " + getProgramID(c)); e.printStackTrace(); } return null; } static public String callStaticAnswerMethod(Object c, String s) { String answer = (String) callOpt(c, "answer", s, litlist(s)); if (answer == null) answer = (String) callOpt(c, "answer", s); return emptyToNull(answer); } static public String callStaticAnswerMethod(String s) { return callStaticAnswerMethod(mc(), s); } static public String callStaticAnswerMethod(String s, List history) { return callStaticAnswerMethod(mc(), s, history); } static public String callStaticAnswerMethod(Object c, String s, List history) { String answer = (String) callOpt(c, "answer", s, history); if (answer == null) answer = (String) callOpt(c, "answer", s); return emptyToNull(answer); } static public void appendToMechList_noUniq_inQ(final String listName, final String text) { mechQ(new Runnable() { public void run() { try { appendToMechList_noUniq_plusLocal(listName, text); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "appendToMechList_noUniq_plusLocal(listName, text)"; } }); } static public String uniqueFileNameUsingMD5_80(String fullName) { return md5(fullName) + " " + takeFirst(80 - 33, fileNameEncode(fullName)); } static public File localMechListNameFile(String listName) { return newFile(localMechListsDir(), uniqueFileNameUsingMD5_80_v2(listName) + ".name"); } static public File localMechListFile(String listName) { return newFile(localMechListsDir(), uniqueFileNameUsingMD5_80_v2(listName) + ".text"); } static public int intFromBytes(byte[] a, int i) { return ubyteToInt(a[i]) << 24 | ubyteToInt(a[i + 1]) << 16 | ubyteToInt(a[i + 2]) << 8 | ubyteToInt(a[i + 3]); } static public Pair pairMap(Object f, Pair p) { return p == null ? null : pair(callF(f, p.a), callF(f, p.b)); } static public Pair pairMap(IF1 f, Pair p) { return p == null ? null : pair(callF(f, p.a), callF(f, p.b)); } static public Pair pairMap(Pair p, Object f) { return pairMap(f, p); } static public String ok2(String s) { return "ok " + s; } static public boolean makeAndroid3_disable = false; static public class Android3 implements AutoCloseable { public String greeting; public boolean publicOverride = false; public int startPort = 5000; public IResponder responder; public boolean console = true; public boolean quiet = false; public boolean daemon = false; public boolean incomingSilent = false; public int incomingPrintLimit = 200; public boolean useMultiPort = true; public boolean recordHistory = false; public boolean verbose = false; public int answerPrintLimit = 500; public boolean newLineAboveAnswer, newLineBelowAnswer; public int port; public long vport; public IDialogHandler handler; public ServerSocket server; public Android3(String greeting) { this.greeting = greeting; } public Android3() { } public void close() { dispose(); } synchronized public void dispose() { if (server != null) { try { server.close(); } catch (IOException e) { print("[internal] " + e); } server = null; } if (vport != 0) { try { print("Disposing " + this); removeFromMultiPort(vport); vport = 0; } catch (Throwable __e) { pcallFail(__e); } } } public String toString() { return "Bot: " + greeting + " [port " + port + (vport == 0 ? "" : ", vport " + vport) + "]"; } } static abstract public class Responder implements IResponder { } public interface IResponder { public String answer(String s, List history); } static public Android3 makeAndroid3(final String greeting) { return makeAndroid3(new Android3(greeting)); } static public Android3 makeAndroid3(final String greeting, Responder responder) { Android3 android = new Android3(greeting); android.responder = responder; return makeAndroid3(android); } static public Android3 makeAndroid3(final Android3 a) { if (makeAndroid3_disable) return a; if (a.responder == null) a.responder = new Responder() { public String answer(String s, List history) { return callStaticAnswerMethod(s, history); } }; if (!a.quiet) print("[bot] " + a.greeting); if (a.console && (readLine_noReadLine || makeAndroid3_consoleInUse())) a.console = false; record(a); if (a.useMultiPort) a.vport = addToMultiPort(a.greeting, makeAndroid3_verboseResponder(a)); if (a.console) makeAndroid3_handleConsole(a); if (a.useMultiPort) return a; a.handler = makeAndroid3_makeDialogHandler(a); if (a.quiet) startDialogServer_quiet.set(true); try { a.port = a.daemon ? startDialogServerOnPortAboveDaemon(a.startPort, a.handler) : startDialogServerOnPortAbove(a.startPort, a.handler); } finally { startDialogServer_quiet.set(null); } a.server = startDialogServer_serverSocket; return a; } static public void makeAndroid3_handleConsole(final Android3 a) { if (!a.quiet) print("You may also type on this console."); { startThread(new Runnable() { public void run() { try { List history = new ArrayList(); while (licensed()) { String line; try { line = readLine(); } catch (Throwable e) { print(getInnerMessage(e)); break; } if (line == null) break; { history.add(line); history.add(makeAndroid3_getAnswer(line, history, a)); } } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "List history = new ArrayList();\r\n while (licensed()) {\r\n Stri..."; } }); } } static public DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) { return new DialogHandler() { public void run(final DialogIO io) { if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) { io.sendLine("Sorry, not allowed"); return; } String dialogID = randomID(8); io.sendLine(a.greeting + " / Your ID: " + dialogID); List history = new ArrayList(); while (io.isStillConnected()) { if (io.waitForLine()) { final String line = io.readLineNoBlock(); String s = dialogID + " at " + now() + ": " + quote(line); if (!a.incomingSilent) print(shorten(s, a.incomingPrintLimit)); if (eq(line, "bye")) { io.sendLine("bye stranger"); return; } Matches m = new Matches(); if (a.recordHistory) history.add(line); String answer; if (match3("this is a continuation of talk *", s, m) || match3("hello bot! this is a continuation of talk *", s, m)) { dialogID = unquote(m.m[0]); answer = "ok"; } else try { makeAndroid3_io.set(io); answer = makeAndroid3_getAnswer(line, history, a); } finally { makeAndroid3_io.set(null); } if (a.recordHistory) history.add(answer); io.sendLine(answer); } } } }; } static public String makeAndroid3_getAnswer(String line, List history, Android3 a) { String answer, originalAnswer; try { originalAnswer = a.responder.answer(line, history); answer = makeAndroid3_fallback(line, history, originalAnswer); } catch (Throwable e) { e = getInnerException(e); printStackTrace(e); originalAnswer = answer = e.toString(); } if (!a.incomingSilent) { if (originalAnswer == null) originalAnswer = "?"; if (a.newLineAboveAnswer) print(); print(">" + dropFirst(indentx(2, shorten(rtrim(originalAnswer), a.answerPrintLimit)))); if (a.newLineBelowAnswer) print(); } return answer; } static public String makeAndroid3_fallback(String s, List history, String answer) { if (answer == null && match3("what is your pid", s)) return getPID(); if (answer == null && match3("what is your program id", s)) return getProgramID(); if (match3("get injection id", s)) return getInjectionID(); if (answer == null) answer = "?"; if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0) answer = quote(answer); return answer; } static public boolean makeAndroid3_consoleInUse() { if (isTrue(vm_generalMap_get("consoleInUse"))) return true; for (Object o : record_list) if (o instanceof Android3 && ((Android3) o).console) return true; return false; } static public Responder makeAndroid3_verboseResponder(final Android3 a) { return new Responder() { public String answer(String s, List history) { if (a.verbose) print("> " + shorten(s, a.incomingPrintLimit)); String answer = a.responder.answer(s, history); if (a.verbose) print("< " + shorten(answer, a.incomingPrintLimit)); return answer; } }; } static public ThreadLocal makeAndroid3_io = new ThreadLocal(); static public Android3 makeAndroid3() { return makeAndroid3(getProgramTitle() + "."); } static public String makeResponder_callAnswerMethod(Object bot, String s, List history) { String answer = (String) callOpt(bot, "answer", s, history); if (answer == null) answer = (String) callOpt(bot, "answer", s); return answer; } static public Responder makeResponder(final Object bot) { if (bot instanceof Responder) return (Responder) bot; if (bot instanceof String) { String f = (String) bot; return new Responder() { public String answer(String s, List history) { String answer = (String) callOptMC((String) bot, s, history); if (answer == null) answer = (String) callOptMC((String) bot, s); return answer; } }; } return new Responder() { public String answer(String s, List history) { return makeResponder_callAnswerMethod(bot, s, history); } }; } static public String defaultBotName() { return getProgramTitle() + "."; } static public String emptyToNull(String s) { return eq(s, "") ? null : s; } static public Map emptyToNull(Map map) { return empty(map) ? null : map; } static public void mechQ(Runnable r) { mechAppendQueue(r); } static public String appendToMechList_noUniq_plusLocal(String name, String text) { logMechListAppendLocally(name, text); return botAppendToMechList(name, text); } static public File localMechListsDir() { return javaxDataDir("Mech Lists"); } static public void removeFromMultiPort(long vport) { if (vport == 0) return; for (Object port : getMultiPorts()) call(port, "removePort", vport); } static public List record_list = synchroList(); static public void record(Object o) { record_list.add(o); } static public Object addToMultiPort_responder; static public long addToMultiPort(final String botName) { return addToMultiPort(botName, new Object() { public String answer(String s, List history) { String answer = (String) (callOpt(getMainClass(), "answer", s, history)); if (answer != null) return answer; answer = (String) callOpt(getMainClass(), "answer", s); if (answer != null) return answer; if (match3("get injection id", s)) return getInjectionID(); return null; } }); } static public long addToMultiPort(final String botName, final Object responder) { addToMultiPort_responder = responder; startMultiPort(); List ports = getMultiPorts(); if (ports == null) return 0; if (ports.isEmpty()) throw fail("No multiports!"); if (ports.size() > 1) print("Multiple multi-ports. Using last one."); Object port = last(ports); Object responder2 = new Object() { public String answer(String s, List history) { if (match3("get injection id", s)) return getInjectionID(); if (match3("your name", s)) return botName; return (String) call(responder, "answer", s, history); } }; record(responder2); return (Long) call(port, "addResponder", botName, responder2); } static public AtomicInteger dialogServer_clients = new AtomicInteger(); static public boolean dialogServer_printConnects = false; static public ThreadLocal startDialogServer_quiet = new ThreadLocal(); static public Set dialogServer_knownClients = synchroTreeSet(); static public int startDialogServerOnPortAbove(int port, IDialogHandler handler) { while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler)) ++port; return port; } static public int startDialogServerOnPortAboveDaemon(int port, IDialogHandler handler) { while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler, true)) ++port; return port; } static public void startDialogServer(int port, IDialogHandler handler) { if (!startDialogServerIfPortAvailable(port, handler)) throw fail("Can't start dialog server on port " + port); } static public boolean startDialogServerIfPortAvailable(int port, final IDialogHandler handler) { return startDialogServerIfPortAvailable(port, handler, false); } static public ServerSocket startDialogServer_serverSocket; static public boolean startDialogServerIfPortAvailable(int port, final IDialogHandler handler, boolean daemon) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); } catch (IOException e) { return false; } final ServerSocket _serverSocket = serverSocket; startDialogServer_serverSocket = serverSocket; Thread thread = new Thread("Socket accept port " + port) { public void run() { try { while (true) { try { final Socket s = _serverSocket.accept(); String client = s.getInetAddress().toString(); if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) { print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet()); dialogServer_knownClients.add(client); } String threadName = "Handling client " + s.getInetAddress(); Thread t2 = new Thread(threadName) { public void run() { try { final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8"); final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8")); DialogIO io = new DialogIO() { public boolean isLocalConnection() { return s.getInetAddress().isLoopbackAddress(); } public boolean isStillConnected() { return !(eos || s.isClosed()); } public void sendLine(String line) { try { w.write(line + "\n"); w.flush(); } catch (Exception __e) { throw rethrow(__e); } } public String readLineImpl() { try { return in.readLine(); } catch (Exception __e) { throw rethrow(__e); } } public void close() { try { s.close(); } catch (IOException e) { } } public Socket getSocket() { return s; } }; try { handler.run(io); } finally { if (!io.noClose) s.close(); } } catch (IOException e) { print("[internal] " + e); } finally { } } }; t2.setDaemon(true); t2.start(); } catch (SocketTimeoutException e) { } } } catch (IOException e) { print("[internal] " + e); } } }; if (daemon) thread.setDaemon(true); thread.start(); if (!isTrue(getAndClearThreadLocal(startDialogServer_quiet))) print("Dialog server on port " + port + " started."); return true; } static public String getInnerMessage(Throwable e) { if (e == null) return null; return getInnerException(e).getMessage(); } static public boolean publicCommOn() { return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication"))); } static public String processID_cached; static public String getPID() { if (processID_cached == null) { String name = ManagementFactory.getRuntimeMXBean().getName(); processID_cached = name.replaceAll("@.*", ""); } return processID_cached; } static public String getInjectionID() { return (String) call(getJavaX(), "getInjectionID", getMainClass()); } static public Object callOptMC(String method, Object... args) { return callOpt(mc(), method, args); } static public Q mechAppendQueue_q; static public Lock mechAppendQueue_lock = lock(); static public Q mechAppendQueue() { Lock __0 = mechAppendQueue_lock; lock(__0); try { if (mechAppendQueue_q == null) mechAppendQueue_q = startQ(); return mechAppendQueue_q; } finally { unlock(__0); } } static public void mechAppendQueue(Runnable r) { mechAppendQueue().add(r); } static public String botAppendToMechList(String name, String text) { return botAppendToMechList_now(name, text); } static public List getMultiPorts() { return (List) callOpt(getJavaX(), "getMultiPorts"); } static public void startMultiPort() { List mp = getMultiPorts(); if (mp != null && mp.isEmpty()) { nohupJavax("#1001639"); throw fail("Upgrading JavaX, please restart this program afterwards."); } } static public Set synchroTreeSet() { return Collections.synchronizedSet(new TreeSet()); } static public Set synchroTreeSet(TreeSet set) { return Collections.synchronizedSet(set); } static public boolean forbiddenPort(int port) { return port == 5037; } static public String botAppendToMechList_now(String name, String text) { return botAppendToMechList_mode(name, text, "noUniq"); } static public String botAppendToMechList_mode(String name, String text, String mode) { if (empty(name) || empty(text)) return ""; String result = postPageSilently("http://butter.botcompany.de:8080/mech/raw/bot-list-append", arrayPlus(muricaCredentials(), "name", name, "text", text, "mode", mode)); if (!swic(result, "No change")) { if (eq(mechMode().readMode, "localCopies")) { print("Appending to local list copy: " + name); appendToLocalMechListCopy(name, text); } mech_notifyBusOfChange(name); mechList_clearCache(name); } return result; } static public String botAppendToMechList_mode(String name, Collection lines, String mode) { if (empty(lines)) return ""; return botAppendToMechList_mode(name, lines(lines), mode); } static public MechMode mechMode_value = new MechMode(); static public MechMode mechMode() { return mechMode_value; } static public TreeSet asCISet(Iterable c) { return toCaseInsensitiveSet(c); } static public TreeSet asCISet(String... x) { return toCaseInsensitiveSet(x); } static public void mech_notifyBusOfChange(String listName) { vmBus_send("mechChange", listName); } static public ThreadLocal mechList_clearCache_inFunction = new ThreadLocal(); static public void mechList_clearCache(String listName) { { AutoCloseable __1 = tempSetTL(mechList_clearCache_inFunction, true); try { print("Sending mech clear: " + listName); vmBus_send("mechList_clearCache", listName); } finally { _close(__1); } } mechList_clearCache_noSend(listName); } static public void mechList_clearCache_noSend(String listName) { for (String field : mcFields()) if (startsWithEndsWith(field, "mech", "_cache")) { Object o = getOptMC(field); if (o instanceof Map) removeFromMapCI_sync((Map) o, listName); } } static public String postPageSilently(String url, Object... params) { return doPostSilently(litmap(params), url); } static public void appendToLocalMechListCopy(String listName, String text) { appendToTextFile(remoteMechListMirrorFile(listName), "\n" + text); } static public TreeSet toCaseInsensitiveSet(Iterable c) { if (isCISet(c)) return (TreeSet) c; TreeSet set = caseInsensitiveSet(); addAll(set, c); return set; } static public TreeSet toCaseInsensitiveSet(String... x) { TreeSet set = caseInsensitiveSet(); addAll(set, x); return set; } static public Set mcFields() { return staticFieldNames(mc()); } static public boolean startsWithEndsWith(String s, String prefix, String suffix) { return startsWith(s, prefix) && endsWith(s, suffix); } static public boolean startsWithEndsWith(String s, String prefixSuffix) { return startsWithEndsWith(s, prefixSuffix, prefixSuffix); } static public void removeFromMapCI_sync(Map map, String key) { if (map == null) return; synchronized (getMutex(map)) { for (String k : cloneList(keys(map))) if (eqic(key, k)) map.remove(k); } } static public String doPostSilently(Map urlParameters, String url) { return doPostSilently(makePostData(urlParameters), url); } static public String doPostSilently(String urlParameters, String url) { doPost_silently.set(true); return doPost(urlParameters, url); } static public File remoteMechListMirrorFile(String listName) { return newFile(remoteMechListMirrorsDir(), uniqueFileNameUsingMD5_80_v2(upper(listName))); } static public Set staticFieldNames(Object o) { TreeSet fields = new TreeSet(); Class _c = _getClass(o); do { for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & Modifier.STATIC) != 0) fields.add(f.getName()); _c = _c.getSuperclass(); } while (_c != null); return fields; } static public Object getMutex(Object o) { return collectionMutex(o); } static public File remoteMechListMirrorsDir() { return javaxDataDir("Remote Mech Lists"); } public interface IVarWithNotify extends IVar, IF0WithChangeListeners { default public IVarWithNotify onChange(IVF1 r) { if (r == null) return this; onChange(() -> r.get(get())); return this; } default public IVarWithNotify onChangeAndNow(IVF1 r) { if (r == null) return this; onChangeAndNow(() -> r.get(get())); return this; } } static public class NotifyingCollection extends AbstractCollection implements Collection { public Collection c; public NotifyingCollection() { } public NotifyingCollection(Collection c) { this.c = c; } public int size() { synchronized (this) { return c.size(); } } public boolean isEmpty() { synchronized (this) { return c.isEmpty(); } } public boolean contains(Object o) { synchronized (this) { return c.contains(o); } } public Object[] toArray() { synchronized (this) { return c.toArray(); } } public T[] toArray(T[] a) { synchronized (this) { return c.toArray(a); } } public Iterator iterator() { return c.iterator(); } public boolean add(E e) { synchronized (this) { beforeChange(); if (!c.add(e)) return false; } change(); return true; } public boolean remove(Object o) { synchronized (this) { beforeChange(); if (!c.remove(o)) return false; } change(); return true; } public boolean containsAll(Collection coll) { synchronized (this) { return c.containsAll(coll); } } public boolean addAll(Collection coll) { synchronized (this) { beforeChange(); if (!c.addAll(coll)) return false; } change(); return true; } public boolean removeAll(Collection coll) { synchronized (this) { beforeChange(); if (!c.removeAll(coll)) return false; } change(); return true; } public boolean retainAll(Collection coll) { synchronized (this) { beforeChange(); if (!c.retainAll(coll)) return false; } change(); return true; } public void clear() { synchronized (this) { beforeChange(); c.clear(); } change(); } public String toString() { synchronized (this) { return c.toString(); } } @Override public Spliterator spliterator() { return c.spliterator(); } public void beforeChange() { } public void change() { } public Collection unwrap() { return c; } } static public class Hi15Image extends WAndHImpl implements MakesBufferedImage { public short[] pixels; public Hi15Image() { } public Hi15Image(int w, int h, short[] pixels) { this.pixels = pixels; this.h = h; this.w = w; } public Hi15Image(BufferedImage img) { this(new RGBImage(img)); } public Hi15Image(RGBImage img) { w = img.getWidth(); h = img.getHeight(); pixels = new short[w * h]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) pixels[y * w + x] = rgbIntToHi15(img.getInt(x, y)); } public Hi15Image(MakesBufferedImage img) { this(toBufferedImage(img)); } public RGBImage toRGB() { RGBImage img = new RGBImage(w, h); int i = 0, w = this.w, h = this.h; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) img.setPixel(x, y, hi15ToRGBInt(pixels[i++])); return img; } public BufferedImage getBufferedImage() { return toRGB().getBufferedImage(); } final public short getHi15Color(int x, int y) { return getHi15Pixel(x, y); } public short getHi15Pixel(int x, int y) { return pixels[y * w + x]; } public short getHi15Pixel_noRangeCheck(int idx) { return pixels[idx]; } static public int perChannelBitCountMask(int bitCount) { int mask = ((~0x1F) >> bitCount) & 0x1F; int mask2 = (mask << 10) | (mask << 5) | mask; return mask2; } public void reducePerChannelBitCount(int bitCount) { if (bitCount >= 5) return; int mask = perChannelBitCountMask(bitCount); short[] pixels = this.pixels; for (int i = 0; i < pixels.length; i++) pixels[i] = (short) (pixels[i] & mask); } public void reduceColorCount(int numColors) { assertPowerOfTwo(numColors); int bits = dualLog(numColors); assertDivisibleBy(3, bits); int bitsPerChannel = bits / 3; reducePerChannelBitCount(bitsPerChannel); } } static public class DummyPosterizer implements IPosterizer { public int get(int brightness) { return brightness; } } static public class StructureStringIndenter { final public StructureStringIndenter setLevels(int levels) { return levels(levels); } public StructureStringIndenter levels(int levels) { this.levels = levels; return this; } final public int getLevels() { return levels(); } public int levels() { return levels; } public int levels = 100; final public StructureStringIndenter setInlineChars(int inlineChars) { return inlineChars(inlineChars); } public StructureStringIndenter inlineChars(int inlineChars) { this.inlineChars = inlineChars; return this; } final public int getInlineChars() { return inlineChars(); } public int inlineChars() { return inlineChars; } public int inlineChars = 40; final public StructureStringIndenter setVerbose(boolean verbose) { return verbose(verbose); } public StructureStringIndenter verbose(boolean verbose) { this.verbose = verbose; return this; } final public boolean getVerbose() { return verbose(); } public boolean verbose() { return verbose; } public boolean verbose = false; public List tok; public Map bracketMap; public String get(String s) { if (s == null) return null; tok = javaTokForStructure(s); int n = l(tok); bracketMap = getBracketMap(tok, __1 -> isOpeningBracket(__1), __2 -> isClosingBracket(__2)); int levels = clampToInt(this.levels * 2L); StringBuilder buf = new StringBuilder(); int indent = 0; for (int i = 0; i < n; i++) { String t = tok.get(i); if (isOpeningBracket(t)) { String prev = _get(tok, i - 2); Integer j = or(bracketMap.get(i), n); if (j != null && (eq(prev, "intarray") || !tokenRangeLongerThanNChars(tok, i + 1, j + 1, inlineChars))) { buf.append(joinSubList(tok, i, j + 1)); i = j; } else { if (verbose) print("Bracket part longer than " + inlineChars + " chars: " + quote(shortenJoinSubList(inlineChars, tok, i, j + 1))); indent += 2; buf.append(t); if (indent <= levels) buf.append("\n").append(spaces(indent)); } } else if (isClosingBracket(t)) { indent -= 2; if (indent < levels) buf.append("\n").append(spaces(indent)); buf.append(t); } else if (indent <= levels && eq(t, ",")) { buf.append(t).append("\n").append(spaces(indent)); i++; } else buf.append(t); } return str(buf); } } public interface IImageRegion extends INumberOfPixels, IPixelSet { public Rect bounds(); public IterableIterator pixelIterator(); public boolean contains(int x, int y); public default Img image() { return null; } public default Object creator() { return null; } public default int indexInCreator() { return 0; } public default Boolean createdWithDiagonals() { return null; } public default int nPixels() { return numberOfPixels(); } public default int numberOfPixels() { return l(pixelIterator()); } public default Pt firstPixel() { return first(pixelIterator()); } public default Color color() { return null; } public default int brightness() { return -1; } public default OnePathWithOrigin outline() { return g22_regionOutline(this); } default public Image2B toImage2B() { return new RegionToImage2B(this).get(); } default public int[] pixelsAsIntArray() { throw unimplemented(); } default public IPixelSet pixelSet() { return this; } } static public class SnPSettings extends MetaWithChangeListeners implements IFieldsToList { static final public String _fieldOrder = "pixelRows colors decolorizer"; public int pixelRows; public int colors; public SnPSettings(int pixelRows, int colors) { this.colors = colors; this.pixelRows = pixelRows; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + pixelRows + ", " + colors + ")"; } public boolean equals(Object o) { if (!(o instanceof SnPSettings)) return false; SnPSettings __1 = (SnPSettings) o; return pixelRows == __1.pixelRows && colors == __1.colors; } public int hashCode() { int h = -327917448; h = boostHashCombine(h, _hashCode(pixelRows)); h = boostHashCombine(h, _hashCode(colors)); return h; } public Object[] _fieldsToList() { return new Object[] { pixelRows, colors }; } public SnPSettings() { pixelRows = 128; colors = 8; } public SnPSettings(BufferedImage image, int colors) { pixelRows = image.getHeight(); this.colors = colors; } public SnPSettings cloneMe() { return shallowClone(this); } public transient FieldVar varDecolorizer_cache; public FieldVar varDecolorizer() { if (varDecolorizer_cache == null) varDecolorizer_cache = varDecolorizer_load(); return varDecolorizer_cache; } public FieldVar varDecolorizer_load() { return new FieldVar(this, "decolorizer", () -> decolorizer(), decolorizer -> decolorizer(decolorizer)); } final public SnPSettings setDecolorizer(Decolorizer decolorizer) { return decolorizer(decolorizer); } public SnPSettings decolorizer(Decolorizer decolorizer) { if (!eq(this.decolorizer, decolorizer)) { this.decolorizer = decolorizer; change(); } return this; } final public Decolorizer getDecolorizer() { return decolorizer(); } public Decolorizer decolorizer() { return decolorizer; } public Decolorizer decolorizer; public int pixelRowsForImage(WidthAndHeight img) { return pixelRows < 0 ? img.getHeight() : pixelRows; } static public SnPSettings allColors(int pixelRows) { return new SnPSettings(pixelRows, 255); } } static public class ImageSurface extends Surface { public BufferedImage image; public double zoomX = 1, zoomY = 1, zoomFactor = 1.5; public Rectangle selection; public List tools = new ArrayList(); public Object overlay; public List overlays = syncL(); public Runnable onSelectionChange; final public ImageSurface setVerbose(boolean verbose) { return verbose(verbose); } public ImageSurface verbose(boolean verbose) { this.verbose = verbose; return this; } final public boolean getVerbose() { return verbose(); } public boolean verbose() { return verbose; } public boolean verbose = false; public boolean noMinimumSize = true; public String titleForUpload; public Object onZoom; public boolean specialPurposed = false; final public ImageSurface setAllowPaste(boolean allowPaste) { return allowPaste(allowPaste); } public ImageSurface allowPaste(boolean allowPaste) { this.allowPaste = allowPaste; return this; } final public boolean getAllowPaste() { return allowPaste(); } public boolean allowPaste() { return allowPaste; } public boolean allowPaste = false; final public ImageSurface setZoomable(boolean zoomable) { return zoomable(zoomable); } public ImageSurface zoomable(boolean zoomable) { this.zoomable = zoomable; return this; } final public boolean getZoomable() { return zoomable(); } public boolean zoomable() { return zoomable; } public boolean zoomable = true; public boolean noAlpha = false; public Object interpolationMode = RenderingHints.VALUE_INTERPOLATION_BILINEAR; public Object onNewImage; public BufferedImage imageToDraw; public File file; public boolean autoZoomToDisplay = false; final public ImageSurface setRepaintInThread(boolean repaintInThread) { return repaintInThread(repaintInThread); } public ImageSurface repaintInThread(boolean repaintInThread) { this.repaintInThread = repaintInThread; return this; } final public boolean getRepaintInThread() { return repaintInThread(); } public boolean repaintInThread() { return repaintInThread; } public boolean repaintInThread = false; public BoolVar showingVar; public Pt mousePosition; transient public Set onMousePositionChanged; public ImageSurface onMousePositionChanged(Runnable r) { onMousePositionChanged = createOrAddToSyncLinkedHashSet(onMousePositionChanged, r); return this; } public ImageSurface removeMousePositionChangedListener(Runnable r) { utils.remove(onMousePositionChanged, r); return this; } public void mousePositionChanged() { if (onMousePositionChanged != null) for (var listener : onMousePositionChanged) pcallF_typed(listener); } transient public Set onImageChanged; public ImageSurface onImageChanged(Runnable r) { onImageChanged = createOrAddToSyncLinkedHashSet(onImageChanged, r); return this; } public ImageSurface removeImageChangedListener(Runnable r) { utils.remove(onImageChanged, r); return this; } public void imageChanged() { if (onImageChanged != null) for (var listener : onImageChanged) pcallF_typed(listener); } transient public Set> onUserModifiedImage; public ImageSurface onUserModifiedImage(IVF1 f) { onUserModifiedImage = createOrAddToSyncLinkedHashSet(onUserModifiedImage, f); return this; } public ImageSurface removeUserModifiedImageListener(IVF1 f) { utils.remove(onUserModifiedImage, f); return this; } public void userModifiedImage(BufferedImage image) { if (onUserModifiedImage != null) for (var listener : onUserModifiedImage) pcallF_typed(listener, image); } public ImageSurface() { this(dummyImage()); } static public BufferedImage dummyImage() { return whiteImage(1); } public ImageSurface(File file) { setImage(file); } public ImageSurface(MakesBufferedImage image) { this(image != null ? image.getBufferedImage() : dummyImage()); } public ImageSurface(BufferedImage image) { setImage(image); clearSurface = false; bindToComponent(this, () -> performAutoZoom(), null); onResize(this, () -> performAutoZoom()); onEnclosingScrollPaneResize(this, () -> performAutoZoom()); componentPopupMenu2(this, ImageSurface_popupMenuMaker()); new ImageSurfaceSelector(this); jHandleFileDrop(this, new VF1() { public void get(File f) { try { setImage(loadBufferedImage(f)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setImage(loadBufferedImage(f))"; } }); imageSurfaceOnHover(this, p -> { mousePosition = p; mousePositionChanged(); }); } public ImageSurface(RGBImage image, double zoom) { this(image); setZoom(zoom); } public void fillPopupMenu(JPopupMenu menu, Point point) { if (zoomable) { JMenuItem miZoomReset = new JMenuItem("Zoom 100%"); miZoomReset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { setZoom(1.0); centerPoint(point); } }); menu.add(miZoomReset); JMenuItem miZoomIn = new JMenuItem("Zoom in"); miZoomIn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { zoomIn(zoomFactor); centerPoint(point); } }); menu.add(miZoomIn); JMenuItem miZoomOut = new JMenuItem("Zoom out"); miZoomOut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { zoomOut(zoomFactor); centerPoint(point); } }); menu.add(miZoomOut); menu.add(jMenuItemStayCheckedOnClick("Zoom to window", () -> autoZoomToDisplay, () -> setAutoZoomToDisplay(true))); addMenuItem(menu, "Show full screen", new Runnable() { public void run() { try { showFullScreen(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showFullScreen()"; } }); String col = ""; if (hasImage()) { try { int rgb = getPixel(getImage(), point.x, point.y); col = " #" + takeLast(6, intToHex(rgb)); } catch (Throwable __e) { pcallFail(__e); } } addMenuItem(menu, "Point: " + point.x + "," + point.y + col + " (image: " + w() + "*" + h() + ")", null); menu.addSeparator(); } if (!specialPurposed) addMenuItem(menu, "Load image...", new Runnable() { public void run() { try { selectFile("Load image", new VF1() { public void get(File f) { try { setImage(loadImage2(f)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setImage(loadImage2(f))"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "selectFile(\"Load image\",\r\n new VF1() { public void get(File f) c..."; } }); addMenuItem(menu, "Save image...", new Runnable() { public void run() { try { saveImage(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "saveImage()"; } }); addMenuItem(menu, "Upload image...", new Runnable() { public void run() { try { uploadTheImage(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "uploadTheImage()"; } }); addMenuItem(menu, "Copy image to clipboard", new Runnable() { public void run() { try { copyImageToClipboard(getImage()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyImageToClipboard(getImage())"; } }); if (!specialPurposed || allowPaste) addMenuItem(menu, "Paste image from clipboard", new Runnable() { public void run() { try { loadFromClipboard(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "loadFromClipboard()"; } }); if (!specialPurposed) addMenuItem(menu, "Load image snippet...", new Runnable() { public void run() { try { selectImageSnippet(new VF1() { public void get(String imageID) { try { setImage(loadImage2(imageID)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setImage(loadImage2(imageID))"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "selectImageSnippet(new VF1() { public void get(String imageID) ctex {..."; } }); if (selection != null) addMenuItem(menu, "Crop", new Runnable() { public void run() { try { crop(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "crop()"; } }); if (!specialPurposed) addMenuItem(menu, "No image", new Runnable() { public void run() { try { noImage(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "noImage()"; } }); } public void noImage() { setImage((BufferedImage) null); } public void crop() { if (selection == null) return; BufferedImage img = cloneClipBufferedImage(getImage(), selection); selection = null; setUserModifiedImage(img); } public void setUserModifiedImage(BufferedImage img) { setImage(img); userModifiedImage(img); } public void loadFromClipboard() { BufferedImage img = getImageFromClipboard(); if (img != null) setUserModifiedImage(img); } transient public IF0 defaultImageDir; public File defaultImageDir() { return defaultImageDir != null ? defaultImageDir.get() : defaultImageDir_base(); } final public File defaultImageDir_fallback(IF0 _f) { return _f != null ? _f.get() : defaultImageDir_base(); } public File defaultImageDir_base() { return getProgramDir(); } public void saveImage() { var image = getImage(); JFileChooser fileChooser = new JFileChooser(defaultImageDir()); if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { try { utils.saveImage(image, file = fileChooser.getSelectedFile()); } catch (Throwable e) { popup(e); } } } public void drawImageItself(int w, int h, Graphics2D g) { int iw = getZoomedWidth(), ih = getZoomedHeight(); if (interpolationMode == RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR || zoomX >= 1 || zoomY >= 1) { g.drawImage(image, 0, 0, iw, ih, null); } else g.drawImage(resizeImage(image, iw, ih), 0, 0, null); } transient public IVF3 drawBackground; public void drawBackground(int w, int h, Graphics2D g) { if (drawBackground != null) drawBackground.get(w, h, g); else drawBackground_base(w, h, g); } final public void drawBackground_fallback(IVF3 _f, int w, int h, Graphics2D g) { if (_f != null) _f.get(w, h, g); else drawBackground_base(w, h, g); } public void drawBackground_base(int w, int h, Graphics2D g) { g.setColor(or(getBackground(), Color.white)); g.fillRect(0, 0, w, h); } public void render(int w, int h, Graphics2D g) { if (verbose) _print("render"); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolationMode); drawBackground(w, h, g); BufferedImage image = or(imageToDraw, this.image); if (!hasImage()) drawBackground(w, h, g); else { boolean alpha = !noAlpha && hasTransparency(image); if (alpha) drawBackground(w, h, g); drawImageItself(w, h, g); int iw = getZoomedWidth(), ih = getZoomedHeight(); if (!alpha) { g.fillRect(iw, 0, w - iw, h); g.fillRect(0, ih, iw, h - ih); } } if (overlay != null) { if (verbose) _print("render overlay"); pcallF(overlay, g); } for (var overlay : cloneList(overlays)) { try { overlay.drawOn(cloneGraphics(g)); } catch (Throwable __e) { pcallFail(__e); } } if (selection != null) { if (verbose) _print("render selection"); drawSelectionRect(g, selection, Color.green, Color.white); } } public void drawSelectionRect(Graphics2D g, Rectangle selection, Color green, Color white) { drawSelectionRect(g, selection, green, white, zoomX, zoomY); } public void drawSelectionRect(Graphics2D g, Rectangle selection, Color green, Color white, double zoomX, double zoomY) { g.setColor(green); int top = (int) (selection.y * zoomY); int bottom = (int) ((selection.y + selection.height) * zoomY); int left = (int) (selection.x * zoomX); int right = (int) ((selection.x + selection.width) * zoomX); g.drawRect(left - 1, top - 1, right - left + 1, bottom - top + 1); g.setColor(white); g.drawRect(left - 2, top - 2, right - left + 3, bottom - top + 3); } public ImageSurface setZoom(double zoom) { setZoom(zoom, zoom); return this; } public void setZoom(double zoomX, double zoomY) { autoZoomToDisplay = false; setZoom_dontChangeAutoZoom(zoomX, zoomY); } public void setZoom_dontChangeAutoZoom(double zoomX) { setZoom_dontChangeAutoZoom(zoomX, zoomX); } public void setZoom_dontChangeAutoZoom(double zoomX, double zoomY) { if (this.zoomX == zoomX && this.zoomY == zoomY) return; if (verbose) _print("Setting zoom"); this.zoomX = zoomX; this.zoomY = zoomY; revalidateMe(); repaint(); centerPoint(new Point(getImage().getWidth() / 2, getImage().getHeight() / 2)); pcallF(onZoom); } public Dimension getMinimumSize() { if (metaGet("scaffolding") != null) scaffoldCalled(this, "getMinimumSize"); if (noMinimumSize) return new Dimension(1, 1); int w = getZoomedWidth(); int h = getZoomedHeight(); Dimension min = super.getMinimumSize(); return printIfScaffoldingEnabled(this, new Dimension(Math.max(w, min.width), Math.max(h, min.height))); } public int getZoomedHeight() { return (int) (h() * zoomY); } public int getZoomedWidth() { return (int) (w() * zoomX); } public boolean isShowing_quick() { if (showingVar == null) { swing(() -> { if (showingVar == null) showingVar = componentShowingVar(ImageSurface.this); }); } return showingVar.get(); } public void setImageIfShowing_thisThread(MakesBufferedImage image) { setImageIfShowing_thisThread(toBufferedImage(image)); } public void setImageIfShowing_thisThread(BufferedImage image) { if (isShowing_quick()) setImage_thisThread(image); } public void setImage(File file) { setFile(file); setImage(loadImage2(file)); } public void setImage(MakesBufferedImage image) { swing(() -> { setImage_thisThread(image); }); } public void setImage(BufferedImage img) { swing(() -> { setImage_thisThread(img); }); } public void setImage_thisThread(MakesBufferedImage img) { setImage_thisThread(toBufferedImage(img)); } public void setImage_thisThread(BufferedImage img) { BufferedImage newImage = img != null ? img : dummyImage(); BufferedImage oldImage = image; image = newImage; if (verbose) print("Old image size:" + imageSize(oldImage) + ", new image size: " + imageSize(newImage)); boolean sameSize = imagesHaveSameSize(oldImage, newImage); if (!sameSize) { if (verbose) _print("New image size"); revalidateMe(); } quickRepaint(); pcallF(onNewImage); if (!sameSize && autoZoomToDisplay) zoomToDisplaySize(); imageChanged(); } public void setImageAndZoomToDisplay(BufferedImage img) { setImage(img); zoomToDisplaySize(); } public BufferedImage getImage() { return image; } public double getZoomX() { return zoomX; } public double getZoomY() { return zoomY; } public Dimension getPreferredSize() { if (metaGet("scaffolding") != null) scaffoldCalled(this, "getPreferredSize"); return printIfScaffoldingEnabled(this, new Dimension(getZoomedWidth(), getZoomedHeight())); } public JScrollPane makeScrollPane() { JScrollPane scrollPane = new JScrollPane(this); scrollPane.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE); return scrollPane; } public void zoomToWindow() { zoomToDisplaySize(); } public void zoomToDisplaySize() { swing(() -> { if (!hasImage()) return; Dimension display = getDisplaySize(); if (display.width == 0 || display.height == 0) return; int w = w(), h = h(); double xRatio = (display.width - 5) / (double) w; double yRatio = (display.height - 5) / (double) h; if (scaffoldingEnabled(this)) printVars("zoomToDisplaySize", "display", display, "w", w, "h", h, "xRatio", xRatio, "yRatio", yRatio); setZoom_dontChangeAutoZoom(min(xRatio, yRatio)); revalidateMe(); }); } private Dimension getDisplaySize() { if (metaGet("scaffolding") != null) scaffoldCalled(this, "getDisplaySize"); Container c = getParent(); while (c != null) { if (c instanceof JScrollPane) return c.getSize(); c = c.getParent(); } return getSize(); } public void setSelection(Rect r) { setSelection(toRectangle(r)); } public void setSelection(Rectangle r) { if (neq(selection, r)) { selection = r; pcallF(onSelectionChange); quickRepaint(); } } public Rectangle getSelection() { return selection; } public RGBImage getRGBImage() { return new RGBImage(getImage()); } public void centerPoint(Point p) { JScrollPane sp = enclosingScrollPane(this); if (sp == null) return; p = new Point((int) (p.x * getZoomX()), (int) (p.y * getZoomY())); final JViewport viewport = sp.getViewport(); Dimension viewSize = viewport.getExtentSize(); int x = max(0, p.x - viewSize.width / 2); int y = max(0, p.y - viewSize.height / 2); p = new Point(x, y); final Point _p = p; awtLater(new Runnable() { public void run() { try { viewport.setViewPosition(_p); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "viewport.setViewPosition(_p);"; } }); } public Pt pointFromEvent(MouseEvent e) { return pointFromComponentCoordinates(new Pt(e.getX(), e.getY())); } public Pt pointFromComponentCoordinates(Pt p) { return new Pt((int) (p.x / zoomX), (int) (p.y / zoomY)); } public Pt pointToComponentCoordinates(double x, double y) { return new Pt((int) (x * zoomX), (int) (y * zoomY)); } public void uploadTheImage() { var img = getImage(); JTextField tf = jTextField(titleForUpload); showFormTitled("Upload Image (PNG)", "Image title (optional)", tf, new F0() { public Object get() { try { disableSubmitButton(getFrame(tf)); startThread("Upload Image", new Runnable() { public void run() { try { try { messageBox("Image uploaded as " + uploadPNGToImageServer(img, titleForUpload = getTextTrim(tf))); disposeFrame(tf); } catch (Throwable e) { enableSubmitButton(getFrame(tf)); messageBox(e); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n messageBox(\"Image uploaded as \" + uploadPNGToImageServer..."; } }); return false; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disableSubmitButton(getFrame(tf));\r\n thread \"Upload Image\" {\r\n ..."; } }); } public void showFullScreen() { showFullScreenImageSurface(getImage()); } public void zoomIn(double f) { setZoom(getZoomX() * f, getZoomY() * f); } public void zoomOut(double f) { setZoom(getZoomX() / f, getZoomY() / f); } public ImageSurface setFile(File f) { file = f; return this; } public void setOverlay(IVF1 overlay) { this.overlay = overlay; } public boolean hasImage() { return image != null; } public int w() { return image.getWidth(); } public int h() { return image.getHeight(); } final public void pixelate(boolean b) { setPixelated(b); } public void setPixelated(boolean b) { assertTrue(b); imageSurface_pixelated(this); } final public ImageSurface autoZoomToDisplay(boolean b) { return setAutoZoomToDisplay(b); } public ImageSurface setAutoZoomToDisplay(boolean b) { if (autoZoomToDisplay = b) zoomToDisplaySize(); return this; } public void quickRepaint() { if (repaintInThread) paintImmediately(0, 0, getWidth(), getHeight()); else repaint(); } public void setTool(ImageSurfaceMouseHandler tool) { swing(() -> { removeAllTools(); addTool(tool); }); } public boolean hasTool(AutoCloseable tool) { return swing(() -> tools.contains(tool)); } public void addTool(ImageSurfaceMouseHandler tool) { swing(() -> { if (!tools.contains(tool)) tool.register(this); }); } public void removeTool(AutoCloseable tool) { swing(() -> { if (tools.contains(tool)) { close(tool); tools.remove(tool); } }); } final public void clearTools() { removeAllTools(); } public void removeAllTools() { closeAllAndClear(tools); } public void performAutoZoom() { if (autoZoomToDisplay) zoomToDisplaySize(); } public void revalidateMe() { revalidateIncludingFullCenterContainer(this); } public void addOverlay(G2Drawable overlay) { overlays.add(overlay); repaint(); } public void clearOverlays() { if (nempty(overlays)) { overlays.clear(); repaint(); } } public void setOverlay(G2Drawable overlay) { clearOverlays(); if (overlay != null) addOverlay(overlay); } public void loadImage(File f) { setImage(loadImage2(f)); } public JComponent visualize() { return jscroll_center_borderless(this); } public void standardZoom() { setZoom(1.0); } public A print(A a) { return print("", a); } public A print(String msg, A a) { return _print(msg, a); } } static public VF2 ImageSurface_popupMenuMaker() { return new VF2() { public void get(ImageSurface is, JPopupMenu menu) { try { Point p = is.pointFromEvent(componentPopupMenu_mouseEvent.get()).getPoint(); is.fillPopupMenu(menu, p); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Point p = is.pointFromEvent(componentPopupMenu_mouseEvent.get()).getPoint();\r..."; } }; } static public class JOnScreenKeyboard extends JPanel { public JPanel[] panel; public JButton[][] button; transient public Set> onKeyPressed; public JOnScreenKeyboard onKeyPressed(IVF1 f) { onKeyPressed = createOrAddToSyncLinkedHashSet(onKeyPressed, f); return this; } public JOnScreenKeyboard removeKeyPressedListener(IVF1 f) { utils.remove(onKeyPressed, f); return this; } public void keyPressed(String key) { if (onKeyPressed != null) for (var listener : onKeyPressed) pcallF_typed(listener, key); } static final public String[][] key = { { "Esc", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "PrtSc", "Insert", "Delete", "Home", "End", "PgUp", "PgDn" }, { "3\n2", "&", "é", "\"", "'", "(", "§", "è", "!", "ç", "à", ")", "-", "BkSpc", "NumLock", "/", "*", "-" }, { "Tab", "A", "Z", "E", "R", "T", "Y", "U", "I", "O", "P", "^", "$", "Enter", "7", "8", "9", "+" }, { "ShiftLock", "Q", "S", "D", "F", "G", "H", "J", "K", "L", "M", "ù", "µ", "4", "5", "6" }, { "Shift", "<", "W", "X", "C", "V", "B", "N", ",", ";", ":", "=", "Shift", "Up", "1", "2", "3", "Enter" }, { "Ctrl", "Fn", "Win", "Alt", "Space", "AltGr", "Context", "Ctrl", "Left", "Down", "Right", "0", "." } }; public JOnScreenKeyboard() { init(); } public void init() { setLayout(new GridLayout(0, 1)); panel = new JPanel[6]; for (int row = 0; row < key.length; row++) { panel[row] = new JPanel(); button = new JButton[20][20]; for (int column = 0; column < key[row].length; column++) { button[row][column] = new JButton(key[row][column]); button[row][column].putClientProperty("key", key[row][column]); button[row][column].addActionListener(e -> { JButton btn = (JButton) (e.getSource()); String key = (String) (btn.getClientProperty("key")); _print("JOnScreenKeyboard key pressed: " + key); keyPressed(key); }); panel[row].add(button[row][column]); } add(panel[row]); } } public JScrollPane withScrollPane() { var sp = jscroll_borderless_center(this); onFirstResize(sp, () -> scrollToCenter(sp)); return sp; } } static public class ScreenShotMeta implements IFieldsToList { public TimestampRange takenWhen; public Rect bounds; public BufferedImage image; public ScreenShotMeta() { } public ScreenShotMeta(TimestampRange takenWhen, Rect bounds, BufferedImage image) { this.image = image; this.bounds = bounds; this.takenWhen = takenWhen; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + takenWhen + ", " + bounds + ", " + image + ")"; } public Object[] _fieldsToList() { return new Object[] { takenWhen, bounds, image }; } } static public class ArrayMatrix extends AbstractMatrix { public ArrayMatrix() { } public A[] data; public ArrayMatrix(int w, int h) { this.h = h; this.w = w; data = (A[]) new Object[w * h]; } public ArrayMatrix(int w, int h, A[] data) { this.data = data; this.h = h; this.w = w; } public A get(int x, int y) { return data[y * w + x]; } public void set(int x, int y, A a) { data[y * w + x] = a; } } static public int concepts_internStringsLongerThan = 10; static public ThreadLocal concepts_unlisted = new ThreadLocal(); static public boolean concepts_unlistedByDefault = true; public interface IConceptIndex { public void update(Concept c); public void remove(Concept c); } public interface IFieldIndex { public Collection getAll(Val val); public List allValues(); public MultiSet allValues_multiSet(); public IterableIterator objectIterator(); } static public class ConceptsChange { } static public class ConceptCreate extends ConceptsChange implements IFieldsToList { public Concept c; public ConceptCreate() { } public ConceptCreate(Concept c) { this.c = c; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + c + ")"; } public boolean equals(Object o) { if (!(o instanceof ConceptCreate)) return false; ConceptCreate __3 = (ConceptCreate) o; return eq(c, __3.c); } public int hashCode() { int h = -1751266972; h = boostHashCombine(h, _hashCode(c)); return h; } public Object[] _fieldsToList() { return new Object[] { c }; } } static public class ConceptChange extends ConceptsChange implements IFieldsToList { public Concept c; public ConceptChange() { } public ConceptChange(Concept c) { this.c = c; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + c + ")"; } public boolean equals(Object o) { if (!(o instanceof ConceptChange)) return false; ConceptChange __4 = (ConceptChange) o; return eq(c, __4.c); } public int hashCode() { int h = -1760609256; h = boostHashCombine(h, _hashCode(c)); return h; } public Object[] _fieldsToList() { return new Object[] { c }; } } static public class ConceptDelete extends ConceptsChange implements IFieldsToList { static final public String _fieldOrder = "id c"; public long id; public Concept c; public ConceptDelete() { } public ConceptDelete(long id, Concept c) { this.c = c; this.id = id; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + id + ", " + c + ")"; } public boolean equals(Object o) { if (!(o instanceof ConceptDelete)) return false; ConceptDelete __5 = (ConceptDelete) o; return id == __5.id && eq(c, __5.c); } public int hashCode() { int h = -1734431213; h = boostHashCombine(h, _hashCode(id)); h = boostHashCombine(h, _hashCode(c)); return h; } public Object[] _fieldsToList() { return new Object[] { id, c }; } } static public class FullChange extends ConceptsChange implements IFieldsToList { public FullChange() { } public String toString() { return shortClassName_dropNumberPrefix(this); } public boolean equals(Object o) { return o instanceof FullChange; } public int hashCode() { int h = 733452095; return h; } public Object[] _fieldsToList() { return null; } } static public class Concepts implements AutoCloseable { public NavigableMap concepts = synchroTreeMap(); final public long getIdCounter() { return idCounter(); } public long idCounter() { return idCounter; } public long idCounter; transient public HashMap perClassData; transient public Map miscMap; transient public String programID; transient public File conceptsFile; transient public Concepts parent; transient volatile public long changes, changesWritten, lastChange; transient volatile public java.util.Timer autoSaver; transient volatile public boolean dontSave = false; transient volatile public boolean savingConcepts, noXFullGrab; transient public boolean vmBusSend = true; transient public boolean initialSave = false; transient public int autoSaveInterval = -1000; transient public boolean useGZIP = true, quietSave; transient public ReentrantLock lock = new ReentrantLock(true); transient public ReentrantLock saverLock = new ReentrantLock(true); transient public long lastSaveTook = -1, lastSaveWas, loadTook, uncompressedSize; transient public float maxAutoSavePercentage = 10; transient public List conceptIndices; transient public Map, Map> fieldIndices; transient public Map, Map> ciFieldIndices; transient public List preSave; transient public Object classFinder = _defaultClassFinder(); transient public List onAllChanged = synchroList(); transient public Set onChange = new HashSet(); transient public Object saveWrapper; final public Concepts setModifyOnCreate(boolean modifyOnCreate) { return modifyOnCreate(modifyOnCreate); } public Concepts modifyOnCreate(boolean modifyOnCreate) { this.modifyOnCreate = modifyOnCreate; return this; } final public boolean getModifyOnCreate() { return modifyOnCreate(); } public boolean modifyOnCreate() { return modifyOnCreate; } transient public boolean modifyOnCreate = false; transient public boolean modifyOnBackRef = false; transient public boolean useFileLock = true; final public Concepts setGrabThroughSocket(boolean grabThroughSocket) { return grabThroughSocket(grabThroughSocket); } public Concepts grabThroughSocket(boolean grabThroughSocket) { this.grabThroughSocket = grabThroughSocket; return this; } final public boolean getGrabThroughSocket() { return grabThroughSocket(); } public boolean grabThroughSocket() { return grabThroughSocket; } transient public boolean grabThroughSocket = true; transient public FileBasedLock fileLock; transient public boolean storeBaseClassesInStructure = false; transient public boolean useBackRefsForSearches = false; transient public boolean defunct = false; transient public int newBackupEveryXMinutes = 60; final public Concepts setCloseConceptsOnExit(boolean closeConceptsOnExit) { return closeConceptsOnExit(closeConceptsOnExit); } public Concepts closeConceptsOnExit(boolean closeConceptsOnExit) { this.closeConceptsOnExit = closeConceptsOnExit; return this; } final public boolean getCloseConceptsOnExit() { return closeConceptsOnExit(); } public boolean closeConceptsOnExit() { return closeConceptsOnExit; } transient public boolean closeConceptsOnExit = false; final public Concepts setSaveError(Throwable saveError) { return saveError(saveError); } public Concepts saveError(Throwable saveError) { this.saveError = saveError; return this; } final public Throwable getSaveError() { return saveError(); } public Throwable saveError() { return saveError; } transient public Throwable saveError; transient public Set> onSaveError; public Concepts onSaveError(IVF1 f) { onSaveError = createOrAddToSyncLinkedHashSet(onSaveError, f); return this; } public Concepts removeSaveErrorListener(IVF1 f) { utils.remove(onSaveError, f); return this; } public void fireSaveError(Throwable error) { if (onSaveError != null) for (var listener : onSaveError) pcallF_typed(listener, error); } public Concepts() { } public Concepts(String programID) { this.programID = programID; } public Concepts(File conceptsFile) { this.conceptsFile = conceptsFile; } synchronized public long internalID() { do { ++idCounter; } while (hasConcept(idCounter)); return idCounter; } synchronized public HashMap perClassData() { if (perClassData == null) perClassData = new HashMap(); return perClassData; } public void initProgramID() { if (programID == null) programID = getDBProgramID(); } public Concepts load(String structure) { return load(structure, false); } public Concepts load(String structure, boolean allDynamic) { clearConcepts(); Map map = unstructureMap(structure, allDynamic, classFinder); concepts.putAll(map); assignConceptsToUs(); calcIdCounter(); return this; } public Concepts load() { initProgramID(); Object dbGrabber = miscMapGet("dbGrabber"); if (dbGrabber != null && !isFalse(callF(dbGrabber))) return this; try { if (grabThroughSocket && tryToGrab()) return this; } catch (Throwable e) { if (!exceptionMessageContains(e, "no xfullgrab")) printShortException(e); print("xfullgrab failed - loading DB of " + programID + " from disk"); } return loadFromDisk(); } public Concepts loadFromDisk() { if (nempty(concepts)) clearConcepts(); long time = now(); Map _concepts = (Map) (unstructureGZFile(conceptsFile(), toIF1(classFinder))); putAll(concepts, _concepts); assignConceptsToUs(); loadTook = now() - time; done("Loaded " + n2(l(concepts), "concept"), time); calcIdCounter(); return this; } public Concepts loadConcepts() { return load(); } public boolean tryToGrab() { if (sameSnippetID(programID, getDBProgramID())) return false; RemoteDB db = connectToDBOpt(programID); try { if (db != null) { loadGrab(db.fullgrab()); return true; } return false; } finally { _close(db); } } public Concepts loadGrab(String grab) { clearConcepts(); DynamicObject_loading.set(true); try { Map map = (Map) unstructure(grab, false, classFinder); concepts.putAll(map); assignConceptsToUs(); for (long l : map.keySet()) idCounter = max(idCounter, l); } finally { DynamicObject_loading.set(null); } return this; } public void assignConceptsToUs() { for (Pair p : mapToPairs((Map) (Map) concepts)) if (!(p.b instanceof Concept)) { print("DROPPING non-existant concept " + p.a + ": " + dynShortName(p.b)); concepts.remove(p.a); } for (Concept c : values(concepts)) c._concepts = this; for (Concept c : values(concepts)) c._doneLoading2(); } public String progID() { return programID == null ? getDBProgramID() : programID; } public Concept getConcept(String id) { return empty(id) ? null : getConcept(parseLong(id)); } public Concept getConcept(long id) { return (Concept) concepts.get((long) id); } public Concept getConcept(RC ref) { return ref == null ? null : getConcept(ref.longID()); } public boolean hasConcept(long id) { return concepts.containsKey((long) id); } public void deleteConcept(long id) { Concept c = getConcept(id); if (c == null) print("Concept " + id + " not found"); else c.delete(); } public void calcIdCounter() { Long lastID = lastKey(concepts); idCounter = lastID == null ? 1 : lastID + 1; } public File conceptsDir() { return dirOfFile(conceptsFile()); } public Concepts conceptsFile(File conceptsFile) { this.conceptsFile = conceptsFile; return this; } public File conceptsFile() { if (conceptsFile != null) return conceptsFile; return getProgramFile(programID, useGZIP ? "concepts.structure.gz" : "concepts.structure"); } public File lockFile() { return newFile(conceptsDir(), "concepts.lock"); } public FileBasedLock fileLock() { if (fileLock == null) fileLock = new FileBasedLock(lockFile()); return fileLock; } public void saveConceptsIfDirty() { saveConcepts(); } public void save() { saveConcepts(); } public void saveConcepts() { vmBus_send("saveConceptsCalled", Concepts.this); if (dontSave) return; initProgramID(); saverLock.lock(); savingConcepts = true; long start = now(), time; try { String s = null; long _changes = changes; if (_changes == changesWritten) return; File f = conceptsFile(); lock.lock(); long fullTime = now(); try { if (useGZIP) { vmBus_send("callingSaveWrapper", Concepts.this, saveWrapper); callRunnableWithWrapper(saveWrapper, new Runnable() { public void run() { try { vmBus_send("callingPreSave", Concepts.this, preSave); callFAll(preSave); vmBus_send("writingFile", Concepts.this, f); uncompressedSize = saveGZStructureToFile(f, cloneMap(concepts), makeStructureData()); vmBus_send("gzFileSaved", Concepts.this, f, uncompressedSize); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "vmBus_send callingPreSave(Concepts.this, preSave);\r\n callFAll(preS..."; } }); newFile(conceptsDir(), "concepts.structure").delete(); } else s = fullStructure(); } finally { lock.unlock(); } changesWritten = _changes; if (!useGZIP) { time = now() - start; if (!quietSave) print("Saving " + toM(l(s)) + "M chars (" + time + " ms)"); start = now(); saveTextFile(f, javaTokWordWrap(s)); newFile(conceptsDir(), "concepts.structure.gz").delete(); } File conceptsFile = conceptsFile(); File backupFile = newFile(conceptsDir(), "backups/" + fileName(conceptsFile) + ".backup" + ymd() + "-" + formatInt(hours(), 2) + (newBackupEveryXMinutes >= 60 ? "" : formatInt(roundDownTo_rev(minutes(), newBackupEveryXMinutes), 2))); copyFile(f, backupFile); time = now() - start; if (!quietSave) print("Saved " + toK(f.length()) + " K, " + n(concepts, "concepts") + " (" + time + " ms)"); lastSaveWas = fullTime; lastSaveTook = now() - fullTime; saveError(null); } finally { savingConcepts = false; saverLock.unlock(); } } public void _autoSaveConcepts() { if (autoSaveInterval < 0 && maxAutoSavePercentage != 0) { long pivotTime = Math.round(lastSaveWas + lastSaveTook * 100.0 / maxAutoSavePercentage); if (now() < pivotTime) { return; } } try { saveConcepts(); } catch (Throwable e) { saveError(e); print("Concept save failed, will try again"); printStackTrace(e); fireSaveError(e); } } public String fullStructure() { return structure(cloneMap(concepts), makeStructureData()); } transient public IF0 makeStructureData; public structure_Data makeStructureData() { return makeStructureData != null ? makeStructureData.get() : makeStructureData_base(); } final public structure_Data makeStructureData_fallback(IF0 _f) { return _f != null ? _f.get() : makeStructureData_base(); } public structure_Data makeStructureData_base() { return finishStructureData(new structure_Data()); } public structure_Data finishStructureData(structure_Data data) { if (storeBaseClassesInStructure) data.storeBaseClasses = true; return data; } public void clearConcepts() { for (Concept c : allConcepts()) c.delete(); } public void fireLegacyChangeEvent() { synchronized (this) { ++changes; lastChange = sysNow(); } if (vmBusSend) vmBus_send("conceptsChanged", this); pcallFAll(onAllChanged); } synchronized public void autoSaveConcepts() { if (autoSaver == null) { if (isTransient()) throw fail("Can't persist transient database"); autoSaver = doEvery_daemon("Concepts Saver for " + conceptsDir(), abs(autoSaveInterval), new Runnable() { public void run() { try { _autoSaveConcepts(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_autoSaveConcepts()"; } }); } } public void close() { cleanMeUp(); } public void cleanMeUp() { try { if (closeConceptsOnExit) closeAllOpt(allConcepts()); defunct = true; boolean shouldSave = autoSaver != null; if (autoSaver != null) { autoSaver.cancel(); autoSaver = null; } while (savingConcepts) sleepInCleanUp(10); if (shouldSave) saveConceptsIfDirty(); } catch (Throwable __e) { pcallFail(__e); } { cleanUp(fileLock); fileLock = null; } } public Map getIDsAndNames() { Map map = new HashMap(); Map cloned = cloneMap(concepts); for (long id : keys(cloned)) map.put(id, cloned.get(id).className); return map; } public void deleteConcepts(List l) { ping(); if (l != null) for (Object o : cloneList(l)) if (o instanceof Long) { Concept c = concepts.get(o); if (c != null) c.delete(); } else if (o instanceof Concept) ((Concept) o).delete(); else warn("Can't delete " + getClassName(o)); } public A conceptOfType(Class type) { IConceptCounter counter = conceptCounterForClass(type); if (counter != null) return (A) first(counter.allConcepts()); return firstOfType(allConcepts(), type); } public List conceptsOfType(Class type) { List l = conceptsOfType_noParent(type); if (parent == null) return l; return concatLists_conservative(l, parent.conceptsOfType(type)); } public List conceptsOfType_noParent(Class type) { ping(); IConceptCounter counter = conceptCounterForClass(type); if (counter != null) return (List) cloneList(counter.allConcepts()); return filterByType(allConcepts(), type); } public List listConcepts(Class type) { return conceptsOfType(type); } public List list(Class type) { return conceptsOfType(type); } public List list_noParent(Class type) { return conceptsOfType_noParent(type); } public List list(String type) { return conceptsOfType(type); } public List conceptsOfType(String type) { return filterByDynamicType(allConcepts(), "main$" + type); } public boolean hasConceptOfType(Class type) { return hasType(allConcepts(), type); } public void persistConcepts() { loadConcepts(); autoSaveConcepts(); } public void conceptPersistence() { persistConcepts(); } public Concepts persist() { persistConcepts(); return this; } public void persist(Integer interval) { if (interval != null) autoSaveInterval = interval; persist(); } public A ensureHas(Class c, Runnable r) { A a = conceptOfType(c); if (a == null) { r.run(); a = conceptOfType(c); if (a == null) throw fail("Concept not made by " + r + ": " + shortClassName(c)); } return a; } public void ensureHas(Class c1, Class c2, Object func) { for (Concept a : conceptsOfType(c1)) { Concept b = findBackRef(a, c2); if (b == null) { callF(func, a); b = findBackRef(a, c2); if (b == null) throw fail("Concept not made by " + func + ": " + shortClassName(c2)); } } } public void forEvery(Class type, Object func) { for (Concept c : conceptsOfType(type)) callF(func, c); } public int deleteAll(Class type) { List l = (List) conceptsOfType(type); for (Concept c : l) c.delete(); return l(l); } public Collection allConcepts() { synchronized (concepts) { return new ArrayList(values(concepts)); } } public IConceptCounter conceptCounterForClass(Class c) { for (IFieldIndex idx : values(mapGet(fieldIndices, c))) if (idx instanceof IConceptCounter) return ((IConceptCounter) idx); for (IFieldIndex idx : values(mapGet(ciFieldIndices, c))) if (idx instanceof IConceptCounter) return ((IConceptCounter) idx); return null; } public int countConcepts(Class c, Object... params) { int n = countConcepts_noParent(c, params); if (parent == null) return n; return n + parent.countConcepts(c, params); } public int countConcepts_noParent(Class c, Object... params) { ping(); if (empty(params)) { IConceptCounter counter = conceptCounterForClass(c); if (counter != null) return counter.countConcepts(); return l(list_noParent(c)); } int n = 0; for (A x : list_noParent(c)) if (checkConceptFields(x, params)) ++n; return n; } public int countConcepts(String c, Object... params) { ping(); if (empty(params)) return l(list(c)); int n = 0; for (Concept x : list(c)) if (checkConceptFields(x, params)) ++n; return n; } public int countConcepts() { return l(concepts); } synchronized public List clonedConceptIndices() { return cloneList(conceptIndices); } synchronized public void addConceptIndex(IConceptIndex index) { if (conceptIndices == null) conceptIndices = new ArrayList(); conceptIndices.add(index); } synchronized public void removeConceptIndex(IConceptIndex index) { if (conceptIndices == null) return; conceptIndices.remove(index); if (empty(conceptIndices)) conceptIndices = null; } synchronized public void addFieldIndex(Class c, String field, IFieldIndex index) { if (fieldIndices == null) fieldIndices = new HashMap(); Map map = fieldIndices.get(c); if (map == null) fieldIndices.put(c, map = new HashMap()); map.put(field, index); } synchronized public void removeFieldIndex(Class c, String field, IFieldIndex index) { Map map = mapGet(fieldIndices, c); mapRemove(map, field); } synchronized public IFieldIndex getFieldIndex(Class c, String field) { if (fieldIndices == null) return null; Map map = fieldIndices.get(c); return map == null ? null : map.get(field); } synchronized public IFieldIndex getAnyIndexForClass(Class c) { return first(allIndicesForClass(c)); } synchronized public Collection allIndicesForClass(Class c) { return concatLists(values(fieldIndices == null ? null : fieldIndices.get(c)), values(ciFieldIndices == null ? null : ciFieldIndices.get(c))); } synchronized public void addCIFieldIndex(Class c, String field, IFieldIndex index) { if (ciFieldIndices == null) ciFieldIndices = new HashMap(); Map map = ciFieldIndices.get(c); if (map == null) ciFieldIndices.put(c, map = new HashMap()); map.put(field, index); } synchronized public void removeCIFieldIndex(Class c, String field) { Map map = mapGet(ciFieldIndices, c); mapRemove(map, field); } synchronized public IFieldIndex getCIFieldIndex(Class c, String field) { if (ciFieldIndices == null) return null; Map map = ciFieldIndices.get(c); return map == null ? null : map.get(field); } public RC xnew(String name, Object... values) { return new RC(cnew(name, values)); } public void xset(long id, String field, Object value) { xset(new RC(id), field, value); } public void xset(RC c, String field, Object value) { if (value instanceof RC) value = getConcept((RC) value); cset(getConcept(c), field, value); } public Object xget(long id, String field) { return xget(new RC(id), field); } public Object xget(RC c, String field) { return xgetPost(cget(getConcept(c), field)); } public Object xgetPost(Object o) { o = deref(o); if (o instanceof Concept) return new RC((Concept) o); return o; } public void xdelete(long id) { xdelete(new RC(id)); } public void xdelete(RC c) { getConcept(c).delete(); } public void xdelete(List l) { for (RC c : l) xdelete(c); } public List xlist() { return map("toPassRef", allConcepts()); } public List xlist(String className) { return map("toPassRef", conceptsOfType(className)); } public boolean isTransient() { return eq(programID, "-"); } public String xfullgrab() { if (noXFullGrab) throw fail("no xfullgrab (DB too large)"); Lock __1 = lock(); lock(__1); try { if (changes == changesWritten && !isTransient()) return loadConceptsStructure(programID); return fullStructure(); } finally { unlock(__1); } } public void xshutdown() { cleanKillVM(); } public long xchangeCount() { return changes; } public int xcount() { return countConcepts(); } public void register(Concept c) { ping(); if (c._concepts == this) return; if (c._concepts != null) throw fail("Can't re-register"); c.id = internalID(); c.created = now(); if (modifyOnCreate) c._setModified(c.created); register_phase2(c); vmBus_send("conceptCreated", c); fireChange(new ConceptCreate(c)); } public void register_phase2(Concept c) { c._concepts = this; concepts.put((long) c.id, c); for (Concept.Ref r : c._refs()) r.index(); c.change(); c._onRegistered(); } public void registerKeepingID(Concept c) { if (c._concepts == this) return; if (c._concepts != null) throw fail("Can't re-register"); c._concepts = this; concepts.put((long) c.id, c); c.change(); } public void conceptChanged(Concept c) { fireChange(new ConceptChange(c)); if (conceptIndices != null) for (IConceptIndex index : clonedConceptIndices()) index.update(c); } public boolean hasUnsavedData() { return changes != changesWritten || savingConcepts; } synchronized public Object miscMapGet(Object key) { return mapGet(miscMap, key); } synchronized public Object miscMapPut(Object key, Object value) { if (miscMap == null) miscMap = new HashMap(); return miscMap.put(key, value); } synchronized public void miscMapRemove(Object key) { mapRemove(miscMap, key); } synchronized public A miscMapGetOrCreate(Object key, IF0 create) { if (containsKey(miscMap, key)) return (A) miscMap.get(key); A value = create.get(); miscMapPut(key, value); return value; } public void setParent(Concepts parent) { this.parent = parent; } public void fireChange(ConceptsChange change) { if (change == null) return; pcallFAll(onChange, change); fireLegacyChangeEvent(); } final public void onChange(IVF1 l) { addChangeListener(l); } public void addChangeListener(IVF1 l) { syncAdd(onChange, l); } public void removeChangeListener(IVF1 l) { syncRemove(onChange, l); } public void addPreSave(Runnable r) { preSave = syncAddOrCreate(preSave, r); } public String toString() { return nConcepts(concepts) + " (" + conceptsDir() + ", hash: " + identityHashCode(this) + ")"; } } public interface IConcept { public long _conceptID(); public Concepts concepts(); } static public class Concept extends DynamicObject implements IConcept, ChangeTriggerable { transient public Concepts _concepts; public long id; public long created, _modified; public List backRefs; public Concept(String className) { super(className); _created(); } public Concept() { if (!_loading()) { _created(); } } public Concept(boolean unlisted) { if (!unlisted) _created(); } public boolean includeZeroIDInToString() { return false; } public String toString() { String s = shortDynamicClassName(this); long id = this.id; if (id != 0 || includeZeroIDInToString()) s += " " + id; return s; } static public boolean loading() { return _loading(); } static public boolean _loading() { return dynamicObjectIsLoading(); } public void _created() { if (!concepts_unlistedByDefault && !eq(concepts_unlisted.get(), true)) db_mainConcepts().register(this); } public class TypedRef extends Ref { public TypedRef() { } public Class bType; public TypedRef(Class bType) { this.bType = bType; } public TypedRef(Class bType, B value) { this.bType = bType; set((A) value); } public TypedRef(B value) { set((A) value); } public boolean set(A a) { return super.set(checkValue(a)); } public void check() { checkValue(get()); } public C checkValue(C a) { if (bType != null && a != null) assertIsInstance(a, bType); return a; } public B b() { return (B) value; } } public class Ref implements IRef { public A value; public Ref() { if (!dynamicObjectIsLoading()) registerRef(); } public void registerRef() { vmBus_send("registeringConceptRef", this); } public Ref(A value) { this.value = value; registerRef(); index(); } public Concept concept() { return Concept.this; } public A get() { return value; } public boolean has() { return value != null; } public boolean set(A a) { if (a == value) return false; unindex(); value = a; index(); change(); return true; } public void setIfEmpty(A a) { if (!has()) set(a); } public void set(Ref ref) { set(ref.get()); } public void clear() { set((A) null); } public boolean validRef() { return value != null && _concepts != null && _concepts == value._concepts; } public void index() { if (validRef()) { value._addBackRef(this); change(); } } public Ref unindex() { if (validRef()) { value._removeBackRef(this); change(); } return this; } public void unindexAndDrop() { unindex(); _removeRef(this); } public void change() { Concept.this.change(); } public String toString() { return str(value); } } public class RefL extends AbstractList { public List> l = new ArrayList(); public RefL() { } public RefL(List l) { replaceWithList(l); } public void clear() { while (!isEmpty()) utils.removeLast(this); } public void replaceWithList(List l) { clear(); for (A a : unnullForIteration(l)) add(a); } public A set(int i, A o) { Ref ref = syncGet(l, i); A prev = ref.get(); ref.set(o); return prev; } public void add(int i, A o) { syncAdd(l, i, new Ref(o)); } public A get(int i) { return syncGet(l, i).get(); } public A remove(int i) { return syncRemove(l, i).get(); } public int size() { return syncL(l); } public boolean contains(Object o) { if (o instanceof Concept) for (Ref r : l) if (eq(r.get(), o)) return true; return super.contains(o); } } public void delete() { for (Ref r : unnullForIteration(_refs())) r.unindex(); for (Ref r : cloneList(backRefs)) r.set((Concept) null); backRefs = null; var _concepts = this._concepts; if (_concepts != null) { _concepts.concepts.remove(id); _concepts.fireChange(new ConceptDelete(id, this)); if (_concepts.conceptIndices != null) for (IConceptIndex index : _concepts.conceptIndices) index.remove(this); this._concepts = null; } id = 0; } public BaseXRef export() { return new BaseXRef(_concepts.progID(), id); } final public void _change() { change(); } public void change() { _setModified(now()); _change_withoutUpdatingModifiedField(); } public void _setModified(long modified) { _modified = modified; } final public void _change_withoutUpdatingModifiedField() { _onChange(); if (_concepts != null) _concepts.conceptChanged(this); } public void _onChange() { } public String _programID() { return _concepts == null ? getDBProgramID() : _concepts.progID(); } public void _addBackRef(Concept.Ref ref) { backRefs = addDyn_quickSync(backRefs, ref); _backRefsModified(); } public void _backRefsModified() { if (_concepts != null && _concepts.modifyOnBackRef) change(); } public void _removeBackRef(Concept.Ref ref) { backRefs = removeDyn_quickSync(backRefs, ref); _backRefsModified(); } public void _removeRef(Concept.Ref ref) { } public int _backRefCount() { return syncL(backRefs); } final public void setField(String field, Object value) { _setField(field, value); } public void _setField(String field, Object value) { cset(this, field, value); } public boolean setField_trueIfChanged(String field, Object value) { return cset(this, field, value) != 0; } public A setFieldAndReturn(String field, A value) { setField(field, value); return value; } final public void setFields(Object... values) { _setFields(values); } public void _setFields(Object... values) { cset(this, values); } public Concepts concepts() { return _concepts; } public boolean isDeleted() { return id == 0; } public void _doneLoading() { } public void _doneLoading2() { Map map = _fieldMigrations(); if (map != null) for (Map.Entry __0 : _entrySet(map)) { String oldField = __0.getKey(); FieldMigration m = __0.getValue(); crenameField_noOverwrite(this, oldField, m.newField); } } static public class FieldMigration implements IFieldsToList { public String newField; public FieldMigration() { } public FieldMigration(String newField) { this.newField = newField; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + newField + ")"; } public boolean equals(Object o) { if (!(o instanceof FieldMigration)) return false; FieldMigration __6 = (FieldMigration) o; return eq(newField, __6.newField); } public int hashCode() { int h = 558692372; h = boostHashCombine(h, _hashCode(newField)); return h; } public Object[] _fieldsToList() { return new Object[] { newField }; } } public Map _fieldMigrations() { return null; } public Collection _refs() { return scanConceptForRefs(this); } public Concepts _concepts() { return _concepts; } public boolean _conceptsDefunct() { return _concepts != null && _concepts.defunct; } public boolean _conceptsDefunctOrUnregistered() { return _concepts == null || _concepts.defunct; } public void _onRegistered() { } public boolean addAndChange(Collection cl, A a) { if (cl == null || !cl.add(a)) return false; change(); return true; } public void clearAndChange(Collection cl) { if (cl == null) return; cl.clear(); change(); } public void addAndChange(LongBuffer buf, long a) { if (buf == null) return; buf.add(a); change(); } public void clearAndChange(LongBuffer buf) { if (buf == null) return; buf.clear(); change(); } public File conceptsDir() { var concepts = concepts(); return concepts == null ? null : concepts.conceptsDir(); } public File fileInConceptsDir(String name) { var dir = conceptsDir(); return dir == null ? null : newFile(dir, name); } public long _conceptID() { return id; } } static public class RC { transient public Object owner; public String id; public RC() { } public RC(long id) { this.id = str(id); } public RC(Object owner, long id) { this.id = str(id); this.owner = owner; } public RC(Concept c) { this(c.id); } public long longID() { return parseLong(id); } public String toString() { return id; } transient public RemoteDB db; public String getString(String field) { return db.xS(this, field); } public Object get(String field) { return db.xget(this, field); } public void set(String field, Object value) { db.xset(this, field, value); } } static public class BaseXRef { public String programID; public long id; public BaseXRef() { } public BaseXRef(String programID, long id) { this.id = id; this.programID = programID; } public boolean equals(Object o) { if (!(o instanceof BaseXRef)) return false; BaseXRef r = (BaseXRef) o; return eq(programID, r.programID) && eq(id, r.id); } public int hashCode() { return programID.hashCode() + (int) id; } } static public class XRef extends Concept { public BaseXRef ref; public XRef() { } public XRef(BaseXRef ref) { this.ref = ref; _doneLoading2(); } public void _doneLoading2() { getIndex().put(ref, this); } public HashMap getIndex() { return getXRefIndex(_concepts); } } static synchronized public HashMap getXRefIndex(Concepts concepts) { HashMap cache = (HashMap) concepts.perClassData().get(XRef.class); if (cache == null) concepts.perClassData.put(XRef.class, cache = new HashMap()); return cache; } static public XRef lookupOrCreateXRef(BaseXRef ref) { XRef xref = getXRefIndex(db_mainConcepts()).get(ref); if (xref == null) xref = new XRef(ref); return xref; } static public void loadAndAutoSaveConcepts() { db_mainConcepts().persist(); } static public void loadAndAutoSaveConcepts(int interval) { db_mainConcepts().persist(interval); } static public RC toPassRef(Concept c) { return new RC(c); } static public void concepts_setUnlistedByDefault(boolean b) { concepts_unlistedByDefault = b; } static public class AnimatedLine extends Animation { public int maxSpeed = 1; public int y, speed; public void start() { y = random(h); newSpeed(); } public void newSpeed() { speed = random_incl(-maxSpeed, maxSpeed); } public void paint() { fillRect(g, 0, 0, w, h, Color.white); drawLine(g, 0, y, w, y, Color.black); } public void nextFrame() { if (oneIn(20)) newSpeed(); y = clamp(y + speed, 0, h - 1); } } static public class SimpleLiveValue extends LiveValue implements IVarWithNotify { transient public Set onChange; public SimpleLiveValue onChange(Runnable r) { onChange = createOrAddToSyncLinkedHashSet(onChange, r); return this; } public SimpleLiveValue removeChangeListener(Runnable r) { utils.remove(onChange, r); return this; } public void change() { if (onChange != null) for (var listener : onChange) pcallF_typed(listener); } public Class type; volatile public A value; public SimpleLiveValue(Class type) { this.type = type; } public SimpleLiveValue(Class type, A value) { this.value = value; this.type = type; } public Class getType() { return type; } public A get() { return value; } public void fireChanged() { change(); } public void set(A a) { if (neq(value, a)) { value = a; fireChanged(); } } } static public class GazellePresenceListener implements IFieldsToList { public StefansOS_ConnectToServer connector; public GazellePresenceListener() { } public GazellePresenceListener(StefansOS_ConnectToServer connector) { this.connector = connector; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + connector + ")"; } public Object[] _fieldsToList() { return new Object[] { connector }; } public VarWithNotify userCount = new VarWithNotify(); final public GazellePresenceListener setVerbose(boolean verbose) { return verbose(verbose); } public GazellePresenceListener verbose(boolean verbose) { this.verbose = verbose; return this; } final public boolean getVerbose() { return verbose(); } public boolean verbose() { return verbose; } public boolean verbose = false; public void init() { connector.onNewLine(line -> { Matches m = new Matches(); if (swic(line, "gazellePresence:", m)) { userCount.set(parseInt(m.rest())); if (verbose) print("Gazelle presence count: " + get()); } }); connector.sub("gazellePresence"); } public Integer get() { return userCount.get(); } } static public class WebRequest implements IWebRequest { public NanoHTTPD.IHTTPSession httpSession; public String uri, subURI; public Map params, files; public String cookie, clientIP; public boolean isHttps, noSpam; public WebRequest(NanoHTTPD.IHTTPSession httpSession, String uri, Map params) { this.params = params; this.uri = uri; this.httpSession = httpSession; files = httpSession.getFiles(); clientIP = getClientIPFromHeaders(httpSession.getHeaders()); } public String uri() { return uri; } public Map params() { return params; } public Map files() { return files; } public Map headers() { return httpSession.getHeaders(); } public String cookie() { return cookie; } public boolean isHttps() { return isHttps; } public boolean isPost() { return httpSession.getMethod() == NanoHTTPD.Method.POST; } public String googleClientID() { String domain = lower(domain()); File jsonFile = googleClientSecretFileForDomain(domain); if (!fileExists(jsonFile)) return null; Map map = decodeJSONMap(loadTextFile(jsonFile)); map = (Map) map.get("web"); return (String) map.get("client_id"); } public void noSpam() { if (noSpam) return; noSpam = true; } } static public class WeakIdentityHashMap implements Map { final public ReferenceQueue queue = new ReferenceQueue(); public Map backingStore = new HashMap(); public WeakIdentityHashMap() { _registerWeakMap(this); } public synchronized void clear() { backingStore.clear(); reap(); } public synchronized boolean containsKey(Object key) { reap(); return backingStore.containsKey(new IdentityWeakReference(key)); } public synchronized boolean containsValue(Object value) { reap(); return backingStore.containsValue(value); } public synchronized Set> entrySet() { reap(); Set> ret = new HashSet>(); for (Map.Entry ref : backingStore.entrySet()) { final K key = ref.getKey().get(); final V value = ref.getValue(); Map.Entry entry = new Map.Entry() { public synchronized K getKey() { return key; } public synchronized V getValue() { return value; } public synchronized V setValue(V value) { throw new UnsupportedOperationException(); } }; ret.add(entry); } return Collections.unmodifiableSet(ret); } public synchronized Set keySet() { reap(); IdentityHashMap map = new IdentityHashMap(); for (IdentityWeakReference ref : backingStore.keySet()) { K k = ref.get(); if (k != null) map.put(k, Boolean.TRUE); } return map.keySet(); } public synchronized boolean equals(Object o) { if (!(o instanceof WeakIdentityHashMap)) { return false; } return backingStore.equals(((WeakIdentityHashMap) o).backingStore); } public synchronized V get(Object key) { reap(); return backingStore.get(new IdentityWeakReference(key)); } public synchronized V put(K key, V value) { reap(); return backingStore.put(new IdentityWeakReference(key), value); } public synchronized int hashCode() { reap(); return backingStore.hashCode(); } public synchronized boolean isEmpty() { reap(); return backingStore.isEmpty(); } public synchronized void putAll(Map t) { throw new UnsupportedOperationException(); } public synchronized V remove(Object key) { reap(); return backingStore.remove(new IdentityWeakReference(key)); } public synchronized int size() { reap(); return backingStore.size(); } public synchronized Collection values() { reap(); return backingStore.values(); } private synchronized void reap() { Object zombie = queue.poll(); while (zombie != null) { IdentityWeakReference victim = (IdentityWeakReference) zombie; backingStore.remove(victim); zombie = queue.poll(); } } public class IdentityWeakReference extends WeakReference { public int hash; @SuppressWarnings("unchecked") public IdentityWeakReference(Object obj) { super((K) obj, queue); hash = System.identityHashCode(obj); } public synchronized int hashCode() { return hash; } public synchronized boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof WeakIdentityHashMap.IdentityWeakReference)) { return false; } IdentityWeakReference ref = (IdentityWeakReference) o; if (this.get() == ref.get()) { return true; } return false; } } } static public class JForm implements Swingable { public List parts = new ArrayList(); public FormLayout1 layout = new FormLayout1(); public JPanel panel; final public JForm setScrollable(boolean scrollable) { return scrollable(scrollable); } public JForm scrollable(boolean scrollable) { this.scrollable = scrollable; return this; } final public boolean getScrollable() { return scrollable(); } public boolean scrollable() { return scrollable; } public boolean scrollable = false; final public JForm setFrameCloser(IVF1 frameCloser) { return frameCloser(frameCloser); } public JForm frameCloser(IVF1 frameCloser) { this.frameCloser = frameCloser; return this; } final public IVF1 getFrameCloser() { return frameCloser(); } public IVF1 frameCloser() { return frameCloser; } public IVF1 frameCloser; public JForm(Object... parts) { this.parts = asList(parts); } public JForm addRow(String label, Swingable component) { return addRow(label, toComponent(component)); } public JForm addRow(String label, Component component) { addAll(parts, label, component); return this; } public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { panel = jpanel(layout, showForm_arrange1(showForm_makeComponents(c -> { { if (frameCloser != null) frameCloser.get(c); } }, flattenToArray(parts)))); return scrollable ? jscroll_vertical(panel) : panel; } public JForm closeInternalFrameOnSubmit() { frameCloser(__1 -> disposeInternalFrame(__1)); return this; } final public JForm disposeFrameOnSubmit() { return closeFrameOnSubmit(); } public JForm closeFrameOnSubmit() { frameCloser(__2 -> disposeFrame(__2)); return this; } public JForm closeNothingOnSubmit() { frameCloser(null); return this; } } static public class PosterizeBWImage implements PixelPreservingImageOpResult, IFieldsToList { public int brightnessLevels; public BWImage img; public PosterizeBWImage() { } public PosterizeBWImage(int brightnessLevels, BWImage img) { this.img = img; this.brightnessLevels = brightnessLevels; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + brightnessLevels + ", " + img + ")"; } public Object[] _fieldsToList() { return new Object[] { brightnessLevels, img }; } public BWImage result; public void run() { try { if (brightnessLevels >= 256 || img == null) { result = img; return; } byte[] pixels = img.getBytes(); int w = img.getWidth(), h = img.getHeight(), n = pixels.length; byte[] pixels2 = new byte[n]; var posterizer = cachePosterizer(new SinglePixelPosterizer(brightnessLevels)); for (int i = 0; i < n; i++) pixels2[i] = (byte) posterizer.get(ubyteToInt(pixels[i])); result = new BWImage(w, h, pixels2); } catch (Exception __e) { throw rethrow(__e); } } public BWImage pixelPreservingSrcImage() { return img; } public BWImage get() { if (result == null) run(); return result; } } static public interface IWebRequest { public String uri(); public Map params(); public Map headers(); public Map files(); default public String clientIP() { return unnull(getClientIPFromHeaders(headers())); } default public String getHeader(String name) { return mapGet(headers(), name); } default public String domain() { return getHeader("host"); } public String cookie(); public boolean isHttps(); public boolean isPost(); default public String protocol() { return isHttps() ? "https://" : "http://"; } default public void noSpam() { } default public String getOpt(String param) { return get(param); } default public String get(String param) { return mapGet(params(), param); } default public String userAgent() { return getHeader("user-agent"); } default public Object proxy(String url, boolean rewriteHost, boolean rewritePort) { throw unimplemented(); } default public boolean uriIs(String uri) { return eq(uri(), uri); } default public boolean uriIsIC(String uri) { return eqic(uri(), uri); } default public String postData() { return mapGet(files(), "postData"); } } abstract static public class RenamedLongIterator extends IterableIterator { abstract public long nextLong(); @Override public Long next() { return nextLong(); } } static public class NumberPt implements IDoublePt { public Number x, y; public NumberPt() { } public NumberPt(Point p) { x = p.x; y = p.y; } public NumberPt(Pt p) { x = p.x; y = p.y; } public NumberPt(double x, double y) { this.y = y; this.x = x; } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } public String toString() { return x + ", " + y; } public double length() { return sqrt(sqr(x_dbl()) + sqr(y_dbl())); } final public double x_dbl() { return x_double(); } public double x_double() { return x.doubleValue(); } final public double y_dbl() { return y_double(); } public double y_double() { return y.doubleValue(); } } static public class HashBufferedImage implements IFieldsToList { public BufferedImage img; public HashBufferedImage() { } public HashBufferedImage(BufferedImage img) { this.img = img; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + img + ")"; } public Object[] _fieldsToList() { return new Object[] { img }; } public long hash; public long get() { if (img == null) return hash; var gp = grabbableIntPixels_fastOrSlow(img); boolean hasAlpha = hasAlpha(img); var ping = pingSource(); int[] pixelsIn = gp.data; int w = gp.w, h = gp.h; int scanlineExtra = gp.scanlineStride - w; int iIn = gp.offset; addToHash(w); addToHash(h); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int packed = pixelsIn[iIn++]; if (!hasAlpha) packed |= 0xFF000000; addToHash(packed); } iIn += scanlineExtra; { if (ping != null) ping.get(); } } return hash; } public void addToHash(long x) { hash = boostHashCombine64(hash, x); } } abstract static public class AbstractLayoutManager implements LayoutManager { final public AbstractLayoutManager setPreferredSize(Dimension preferredSize) { return preferredSize(preferredSize); } public AbstractLayoutManager preferredSize(Dimension preferredSize) { this.preferredSize = preferredSize; return this; } final public Dimension getPreferredSize() { return preferredSize(); } public Dimension preferredSize() { return preferredSize; } public Dimension preferredSize = new Dimension(100, 100); final public AbstractLayoutManager setMinimumSize(Dimension minimumSize) { return minimumSize(minimumSize); } public AbstractLayoutManager minimumSize(Dimension minimumSize) { this.minimumSize = minimumSize; return this; } final public Dimension getMinimumSize() { return minimumSize(); } public Dimension minimumSize() { return minimumSize; } public Dimension minimumSize = new Dimension(10, 10); public void addLayoutComponent(String name, Component comp) { } public void removeLayoutComponent(Component comp) { } public AbstractLayoutManager preferredSize(int w, int h) { return preferredSize(new Dimension(w, h)); } public Dimension preferredLayoutSize(Container parent) { layoutContainer(parent); return preferredSize; } public Dimension minimumLayoutSize(Container parent) { return minimumSize; } } static public class TrayIconLastPosition { public TrayIcon trayIcon; public WithTimestamp lastPosition; public TrayIconLastPosition(TrayIcon trayIcon) { this.trayIcon = trayIcon; { if (trayIcon != null) trayIcon.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { lastPosition = withTimestamp(pt(e.getX(), e.getY())); } }); } } } static abstract public class IterableIterator implements Iterator, Iterable { public Iterator iterator() { return this; } public void remove() { unsupportedOperation(); } } static public class SynchronizedArrayList extends SynchronizedArrayList_Base implements RandomAccess, Cloneable { static final public int DEFAULT_CAPACITY = 10; static final public Object[] EMPTY_ELEMENTDATA = {}; static final public Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; transient public Object[] elementData; public int size; public SynchronizedArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; } else { throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); } } public SynchronizedArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } public SynchronizedArrayList(Collection c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { this.elementData = EMPTY_ELEMENTDATA; } } public synchronized void trimToSize() { modCount++; if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } } public synchronized void ensureCapacity(int minCapacity) { int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY; if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; if (minCapacity - elementData.length > 0) grow(minCapacity); } static final public int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } public synchronized int size() { return size; } public synchronized boolean isEmpty() { return size == 0; } public boolean contains(Object o) { return indexOf(o) >= 0; } public synchronized int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i] == null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; } public synchronized int lastIndexOf(Object o) { if (o == null) { for (int i = size - 1; i >= 0; i--) if (elementData[i] == null) return i; } else { for (int i = size - 1; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; } public synchronized Object clone() { return new SynchronizedArrayList(this); } public synchronized Object[] toArray() { return Arrays.copyOf(elementData, size); } @SuppressWarnings("unchecked") public synchronized T[] toArray(T[] a) { if (a.length < size) return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } @SuppressWarnings("unchecked") public A elementData(int index) { return (A) elementData[index]; } public synchronized A get(int index) { rangeCheck(index); return elementData(index); } public synchronized A set(int index, A element) { rangeCheck(index); A oldValue = elementData(index); elementData[index] = element; return oldValue; } public synchronized boolean add(A e) { ensureCapacityInternal(size + 1); elementData[size++] = e; return true; } public synchronized void add(int index, A element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } public synchronized A remove(int index) { rangeCheck(index); modCount++; A oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index + 1, elementData, index, numMoved); elementData[--size] = null; return oldValue; } public synchronized boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index + 1, elementData, index, numMoved); elementData[--size] = null; } public synchronized void clear() { modCount++; for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } public synchronized boolean addAll(Collection c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; } public synchronized boolean addAll(int index, Collection c) { rangeCheckForAdd(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); int numMoved = size - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; } public synchronized void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); int newSize = size - (toIndex - fromIndex); for (int i = newSize; i < size; i++) { elementData[i] = null; } size = newSize; } private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: " + index + ", Size: " + size; } public synchronized boolean removeAll(Collection c) { Objects.requireNonNull(c); return batchRemove(c, false); } public synchronized boolean retainAll(Collection c) { Objects.requireNonNull(c); return batchRemove(c, true); } private boolean batchRemove(Collection c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; } private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { int expectedModCount = modCount; s.defaultWriteObject(); s.writeInt(size); for (int i = 0; i < size; i++) { s.writeObject(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { elementData = EMPTY_ELEMENTDATA; s.defaultReadObject(); s.readInt(); if (size > 0) { ensureCapacityInternal(size); Object[] a = elementData; for (int i = 0; i < size; i++) { a[i] = s.readObject(); } } } public synchronized ListIterator listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: " + index); return new ListItr(index); } public ListIterator listIterator() { return new ListItr(0); } public Iterator iterator() { return concurrentlyIterateList(this); } public class Itr implements Iterator { public int cursor; public int lastRet = -1; public int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public A next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = SynchronizedArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (A) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { SynchronizedArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final public void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } public class ListItr extends Itr implements ListIterator { public ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } @SuppressWarnings("unchecked") public A previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = SynchronizedArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (A) elementData[lastRet = i]; } public void set(A e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { SynchronizedArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(A e) { checkForComodification(); try { int i = cursor; SynchronizedArrayList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } public List subList(int fromIndex, int toIndex) { _subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex); } public class SubList extends SynchronizedArrayList_Base implements RandomAccess { final public SynchronizedArrayList_Base parent; final public int parentOffset; final public int offset; public int size; public SubList(SynchronizedArrayList_Base parent, int offset, int fromIndex, int toIndex) { this.parent = parent; this.parentOffset = fromIndex; this.offset = offset + fromIndex; this.size = toIndex - fromIndex; this.modCount = SynchronizedArrayList.this.modCount; } public A set(int index, A e) { synchronized (SynchronizedArrayList.this) { rangeCheck(index); checkForComodification(); A oldValue = SynchronizedArrayList.this.elementData(offset + index); SynchronizedArrayList.this.elementData[offset + index] = e; return oldValue; } } public A get(int index) { synchronized (SynchronizedArrayList.this) { rangeCheck(index); checkForComodification(); return SynchronizedArrayList.this.elementData(offset + index); } } public int size() { synchronized (SynchronizedArrayList.this) { checkForComodification(); return this.size; } } public void add(int index, A e) { synchronized (SynchronizedArrayList.this) { rangeCheckForAdd(index); checkForComodification(); parent.add(parentOffset + index, e); this.modCount = parent.modCount(); this.size++; } } public A remove(int index) { synchronized (SynchronizedArrayList.this) { rangeCheck(index); checkForComodification(); A result = parent.remove(parentOffset + index); this.modCount = parent.modCount(); this.size--; return result; } } public void removeRange(int fromIndex, int toIndex) { synchronized (SynchronizedArrayList.this) { checkForComodification(); parent.removeRange(parentOffset + fromIndex, parentOffset + toIndex); this.modCount = parent.modCount(); this.size -= toIndex - fromIndex; } } public boolean addAll(Collection c) { return addAll(this.size, c); } public boolean addAll(int index, Collection c) { synchronized (SynchronizedArrayList.this) { rangeCheckForAdd(index); int cSize = c.size(); if (cSize == 0) return false; checkForComodification(); parent.addAll(parentOffset + index, c); this.modCount = parent.modCount(); this.size += cSize; return true; } } public Iterator iterator() { return listIterator(); } public ListIterator listIterator(final int index) { synchronized (SynchronizedArrayList.this) { checkForComodification(); rangeCheckForAdd(index); final int offset = this.offset; return new ListIterator() { public int cursor = index; public int lastRet = -1; public int expectedModCount = SynchronizedArrayList.this.modCount; public boolean hasNext() { return cursor != SubList.this.size; } @SuppressWarnings("unchecked") public A next() { checkForComodification(); int i = cursor; if (i >= SubList.this.size) throw new NoSuchElementException(); Object[] elementData = SynchronizedArrayList.this.elementData; if (offset + i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (A) elementData[offset + (lastRet = i)]; } public boolean hasPrevious() { return cursor != 0; } @SuppressWarnings("unchecked") public A previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = SynchronizedArrayList.this.elementData; if (offset + i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (A) elementData[offset + (lastRet = i)]; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { SubList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = SynchronizedArrayList.this.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void set(A e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { SynchronizedArrayList.this.set(offset + lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(A e) { checkForComodification(); try { int i = cursor; SubList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = SynchronizedArrayList.this.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final public void checkForComodification() { if (expectedModCount != SynchronizedArrayList.this.modCount) throw new ConcurrentModificationException(); } }; } } public List subList(int fromIndex, int toIndex) { synchronized (SynchronizedArrayList.this) { _subListRangeCheck(fromIndex, toIndex, size); return new SubList(parent, offset, fromIndex, toIndex); } } private void rangeCheck(int index) { if (index < 0 || index >= this.size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void rangeCheckForAdd(int index) { if (index < 0 || index > this.size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: " + index + ", Size: " + this.size; } private void checkForComodification() { if (SynchronizedArrayList.this.modCount != this.modCount) throw new ConcurrentModificationException(); } } @Override @SuppressWarnings("unchecked") public synchronized void sort(Comparator c) { final int expectedModCount = modCount; Arrays.sort((A[]) elementData, 0, size, c); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } } static public interface MakesBufferedImage extends WidthAndHeight { public BufferedImage getBufferedImage(); public default void drawAt(Graphics2D g, int x, int y) { g.drawImage(getBufferedImage(), x, y, null); } default public int getWidth() { return getBufferedImage().getWidth(); } default public int getHeight() { return getBufferedImage().getHeight(); } } static public class DeleteFilesDialog { final public DeleteFilesDialog setTitle(String title) { return title(title); } public DeleteFilesDialog title(String title) { this.title = title; return this; } final public String getTitle() { return title(); } public String title() { return title; } public String title = "Delete files"; public LinkedHashSet filesToDelete = new LinkedHashSet(); public DeleteFilesDialog() { } public DeleteFilesDialog(String title) { this.title = title; } public DeleteFilesDialog wholeDirectory(File dir) { if (!isDirectory(dir)) return this; filesToDelete.addAll(reversed(findAllFiles(dir))); filesToDelete.add(dir); return this; } public void show() { renameSubmitButton("DELETE " + upper(nFiles(filesToDelete)), showFormTitled3(title, "Files to delete", jscroll(uneditableTextArea(lines(filesToDelete))), null, runnableThread(new Runnable() { public void run() { try { doIt(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "doIt();"; } })).visualize()); } public void doIt() { int successes = 0; for (File f : filesToDelete) if (deleteFile(f)) { print("DELETED: " + f); ++successes; } else print("COULDN'T DELETE: " + f); int failures = l(filesToDelete) - successes; String msg = "Deleted " + nFiles(successes); if (failures == 0) infoBox(msg); else messageBox(msg + ", but couldn't delete " + n2(failures)); } } static public interface IProbabilisticScheduler extends Steppable { public void at(double probability, Runnable action); default public void schedule(double probability, Runnable action) { atRelative(probability, action); } default public void atRelative(double probability, Runnable action) { at(currentProbability() * probability, action); } public double currentProbability(); public long stepCount(); public double lastExecutedProbability(); default public void schedule(Runnable x) { run(x); } default public void at(Runnable x) { run(x); } default public void run(Runnable x) { if (x == null) return; initAction(x); x.run(); } default public void scheduleAll(Iterable> l) { for (var x : unnullForIteration(l)) at(x.probability(), x.get()); } default public void initAction(Object action) { if (action instanceof IProbabilistic) ((IProbabilistic) action).setScheduler(this); } } static public class TextImageAction { public String text; public String imageID; public Object action; public String toolTip; public VF1 popupMenuMaker; public Map more; public File file; public TextImageAction() { } public TextImageAction(String text, String imageID, Object action) { this.action = action; this.imageID = imageID; this.text = text; } } static abstract public class CloseableIterableIterator extends IterableIterator implements AutoCloseable { public void close() throws Exception { } } abstract static public class AbstractSSIList extends NotifyingList implements StringIO { public AbstractSSIList() { init(); } public AbstractSSIList(Collection l) { initAndAddAll(importSSIs(l)); } public List importSSIs(Collection l) { return map(__139 -> importSSI(__139), l); } abstract public MySSI importSSI(AbstractSSI ssi); public BufferedImage render(WidthAndHeight size) { return renderAll(this, size); } public BufferedImage render(BufferedImage canvas) { return renderAll(this, canvas); } public BufferedImage renderOutlines(WidthAndHeight size) { return toSSIList().renderOutlines(size); } public SSIList toSSIList() { return new SSIList(map(this, __1 -> __1.toSSI())); } public void readWrite(StringHead head) { head.exchangeAll(this); } public List vectorSSIs() { return instancesOf(VectorSSI.class, this); } final public List literalSSIs() { return directSSIs(); } public List directSSIs() { return instancesOf(SSI.class, this); } public Percent percentageVectorized() { return Percent.ratio(l(vectorSSIs()), l(this)); } } static public class HuffmanTreeMaker { final public HuffmanTree getTree() { return tree(); } public HuffmanTree tree() { return tree; } public HuffmanTree tree = new HuffmanTree(); public TreeSet pool = new TreeSet(); public int indexCounter; public class Head implements Comparable { public int index = indexCounter++; final public Head setNode(HuffmanTree.Node node) { return node(node); } public Head node(HuffmanTree.Node node) { this.node = node; return this; } final public HuffmanTree.Node getNode() { return node(); } public HuffmanTree.Node node() { return node; } public HuffmanTree.Node node; final public Head setFreq(double freq) { return freq(freq); } public Head freq(double freq) { this.freq = freq; return this; } final public double getFreq() { return freq(); } public double freq() { return freq; } public double freq; public int compareTo(Head h) { if (this == h) return 0; var c = cmp(freq, h.freq); if (c != 0) return c; return cmp(index, h.index); } public String toString() { return freq + "x " + node; } } public HuffmanTreeMaker importByteHistogram(int[] histogram) { int n = l(histogram); for (int i = 0; i < n; i++) { double freq = histogram[i]; if (freq != 0) pool.add(new Head().freq(freq).node(tree.new Leaf(i))); } return this; } public void run() { try { while (l(pool) > 1) { ping(); var it = iterator(pool); var a = it.next(); it.remove(); var b = it.next(); it.remove(); var newHead = new Head().freq(a.freq + b.freq).node(tree.new Branch().zero(b.node).one(a.node)); pool.add(newHead); } } catch (Exception __e) { throw rethrow(__e); } } public HuffmanTree get() { run(); if (nempty(pool)) tree.root(popFirst(pool).node()); return tree; } } public interface PixelPreservingImageOpResult { public Img pixelPreservingSrcImage(); } static public class ShortBuffer implements Iterable { public short[] data; public int size; public ShortBuffer() { } public ShortBuffer(int size) { if (size != 0) data = new short[size]; } public ShortBuffer(Iterable l) { if (l instanceof Collection) allocate(((Collection) l).size()); addAll(l); } public void add(short i) { if (size >= lShortArray(data)) { data = resizeShortArray(data, Math.max(1, toShort(Math.min(maximumSafeArraySize(), lShortArray(data) * 2L)))); if (size >= data.length) throw fail("ShortBuffer too large: " + size); } data[size++] = i; } public void allocate(int n) { data = resizeShortArray(data, max(n, size())); } public void setSize(int n) { data = resizeShortArray(data, n); size = min(l(data), size); } public void addAll(Iterable l) { if (l != null) for (var i : l) add(i); } public void addAll(short... l) { if (l != null) for (short i : l) add(i); } final public short[] toShortArray() { return toArray(); } public short[] toArray() { return size == 0 ? null : resizeShortArray(data, size); } final public List asList() { return toList(); } final public List asVirtualList() { return toList(); } public List toList() { return new RandomAccessAbstractList() { public int size() { return size; } public Short get(int i) { return ShortBuffer.this.get(i); } public Short set(int i, Short val) { Short a = get(i); data[i] = val; return a; } }; } public void reset() { size = 0; } public void clear() { reset(); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public short get(int idx) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); return data[idx]; } public void set(int idx, short value) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); data[idx] = value; } public short popLast() { if (size == 0) throw fail("empty buffer"); return data[--size]; } public short last() { return data[size - 1]; } public short nextToLast() { return data[size - 2]; } public String toString() { return squareBracket(joinWithSpace(toList())); } public Iterator iterator() { return new IterableIterator() { public int i = 0; public boolean hasNext() { return i < size; } public Short next() { return data[i++]; } }; } public ShortIterator shortIterator() { return new ShortIterator() { public int i = 0; public boolean hasNext() { return i < size; } public short next() { return data[i++]; } public String toString() { return "Iterator@" + i + " over " + ShortBuffer.this; } }; } public void trimToSize() { data = resizeShortArray(data, size); } } public interface HasBounds extends WidthAndHeight { public Rect bounds(); default public int getWidth() { return bounds().h; } default public int getHeight() { return bounds().w; } } public interface Enterable { public AutoCloseable enter(); } static public class Matches { public String[] m; public Matches() { } public Matches(String... m) { this.m = m; } public String get(int i) { return i < m.length ? m[i] : null; } public String unq(int i) { return unquote(get(i)); } public String tlc(int i) { return unq(i).toLowerCase(); } public boolean bool(int i) { return "true".equals(unq(i)); } public String rest() { return m[m.length - 1]; } public int psi(int i) { return Integer.parseInt(unq(i)); } public String toString() { return "Matches(" + joinWithComma(quoteAll(asList(m))) + ")"; } public int hashCode() { return _hashCode(toList(m)); } public boolean equals(Object o) { return o instanceof Matches && arraysEqual(m, ((Matches) o).m); } } static public class WithTimestamp extends Var { public long timestamp; final public Timestamp timestamp() { return getTimestamp(); } final public Timestamp timeStamp() { return getTimestamp(); } public Timestamp getTimestamp() { return timestamp == 0 ? null : new Timestamp(timestamp); } public WithTimestamp() { } public WithTimestamp(long timestamp, A value) { super(value); this.timestamp = timestamp; } public WithTimestamp(A value) { this(now(), value); } public Timestamp timestampObj() { return timestamp == 0 ? null : new Timestamp(timestamp); } public long unixDate() { return timestamp; } public String toString() { return toStringWithTimestamp(super.toString()); } public String toStringQuoted() { return toStringWithTimestamp(quote(super.toString())); } public String toStringWithTimestamp(String s) { return s + " at " + localDateWithSeconds(timestamp); } public boolean olderThanMinutes(double minutes) { return elapsedMinutes_timestamp(timestamp) >= minutes; } public boolean olderThanSeconds(double seconds) { return elapsedSeconds_timestamp(timestamp) >= seconds; } } static public class SynchronizedLongBuffer implements ILongBuffer { public long[] data; public int size; public SynchronizedLongBuffer() { } public SynchronizedLongBuffer(int size) { if (size != 0) data = new long[size]; } public SynchronizedLongBuffer(Iterable l) { if (l instanceof Collection) allocate(((Collection) l).size()); addAll(l); } public synchronized void add(long i) { if (size >= lLongArray(data)) { data = resizeLongArray(data, Math.max(1, toInt(Math.min(maximumSafeArraySize(), lLongArray(data) * 2L)))); if (size >= data.length) throw fail("LongBuffer too large: " + size); } data[size++] = i; } synchronized public void allocate(int n) { data = resizeLongArray(data, max(n, size())); } public synchronized void addAll(Iterable l) { if (l != null) for (long i : l) add(i); } public synchronized long[] toArray() { return size == 0 ? null : resizeLongArray(data, size); } synchronized public List toList() { return longArrayToList(data, 0, size); } public synchronized List asVirtualList() { return listFromFunction(__140 -> get(__140), size); } synchronized public void reset() { size = 0; } public void clear() { reset(); } synchronized public int size() { return size; } public synchronized boolean isEmpty() { return size == 0; } public synchronized long get(int idx) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); return data[idx]; } synchronized public void set(int idx, long value) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); data[idx] = value; } public synchronized long popLast() { if (size == 0) throw fail("empty buffer"); return data[--size]; } public synchronized long last() { return data[size - 1]; } synchronized public long nextToLast() { return data[size - 2]; } public String toString() { return squareBracket(joinWithSpace(toList())); } public synchronized Iterator iterator() { return new IterableIterator() { public int i = 0; public boolean hasNext() { return i < size(); } public Long next() { synchronized (SynchronizedLongBuffer.this) { if (!hasNext()) throw fail("Index out of bounds: " + i); return data[i++]; } } }; } public synchronized void trimToSize() { data = resizeLongArray(data, size); } synchronized public void remove(int idx) { arraycopy(data, idx + 1, data, idx, size - 1 - idx); --size; } public synchronized long poll() { return size == 0 ? -1 : data[--size]; } public synchronized void insertAt(int idx, long[] l) { int n = l(l); if (n == 0) return; long[] newData = new long[size + n]; arraycopy(data, 0, newData, 0, idx); arraycopy(l, 0, newData, idx, n); arraycopy(data, idx, newData, idx + n, size - idx); data = newData; size = newData.length; } public void integrityCheck() { assertTrue("Size positive", size >= 0); assertTrue("Data length", l(data) >= size); } } static public class Dyn_FieldWatcher implements AutoCloseable { public DynModule module; public String field; public Object value; public Runnable action; public Runnable changeListener = new Runnable() { public void run() { try { check(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "check();"; } }; public VF1 fieldChangeListener = new VF1() { public void get(String f) { try { if (eq(f, field)) check(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(f, field))\r\n check();"; } }; transient public IF1 cloneValue; public Object cloneValue(Object o) { return cloneValue != null ? cloneValue.get(o) : cloneValue_base(o); } final public Object cloneValue_fallback(IF1 _f, Object o) { return _f != null ? _f.get(o) : cloneValue_base(o); } public Object cloneValue_base(Object o) { return o; } public Dyn_FieldWatcher(DynModule module, String field, Runnable action) { this(module, field, action, null); } public Dyn_FieldWatcher(DynModule module, String field, Runnable action, IF1 cloneValue) { this.cloneValue = cloneValue; this.action = action; this.field = field; this.module = module; value = cloneValue(get(module, field)); module.onChange(changeListener); module.onFieldChange(fieldChangeListener); } public void check() { Object newValue = cloneValue(get(module, field)); if (eq(value, newValue)) return; value = newValue; dm_q(module, action); } public void close() { try { module.removeChangeListener(changeListener); module.removeFieldChangeListener(fieldChangeListener); } catch (Exception __e) { throw rethrow(__e); } } } static public class DoubleRect { public double x, y, w, h; public DoubleRect() { } public DoubleRect(Rectangle r) { x = r.x; y = r.y; w = r.width; h = r.height; } public DoubleRect(double x, double y, double w, double h) { this.h = h; this.w = w; this.y = y; this.x = x; } public boolean eq(Object o) { if (!(o instanceof DoubleRect)) return false; if (o == this) return true; DoubleRect r = (DoubleRect) o; return x == r.x && y == r.y && w == r.w && h == r.h; } public String toString() { return x + "," + y + " / " + w + "," + h; } public double x1() { return x; } public double y1() { return y; } public double x2() { return x + w; } public double y2() { return y + h; } public boolean contains(Pt p) { return contains(p.x, p.y); } public boolean contains(double _x, double _y) { return _x >= x && _y >= y && _x < x + w && _y < y + h; } public boolean empty() { return w <= 0 || h <= 0; } } abstract static public class Surface extends JPanel implements IMeta { public boolean clearSurface = true; public boolean clearOnce = false; volatile public Object meta; public void _setMeta(Object meta) { this.meta = meta; } public Object _getMeta() { return meta; } final public boolean scaffolding() { return scaffoldingEnabled(); } final public boolean scaffolded() { return scaffoldingEnabled(); } public boolean scaffoldingEnabled() { return utils.scaffoldingEnabled(this); } public boolean scaffoldingEnabled(Object o) { return utils.scaffoldingEnabled(o); } public String toString_base() { return super.toString(); } public String toString() { Object o = metaGet("toString", this); if (o instanceof String) return ((String) o); if (o instanceof IF1) return str(((IF1) o).get(this)); return toString_base(); } public Surface() { setDoubleBuffered(false); } public Graphics2D createGraphics2D(int width, int height, Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setBackground(getBackground()); if (clearSurface || clearOnce) { g2.clearRect(0, 0, width, height); clearOnce = false; } return g2; } public abstract void render(int w, int h, Graphics2D g); public void paintImmediately(int x, int y, int w, int h) { RepaintManager repaintManager = null; boolean save = true; if (!isDoubleBuffered()) { repaintManager = RepaintManager.currentManager(this); save = repaintManager.isDoubleBufferingEnabled(); repaintManager.setDoubleBufferingEnabled(false); } super.paintImmediately(x, y, w, h); if (repaintManager != null) repaintManager.setDoubleBufferingEnabled(save); } public void paint(Graphics g) { Dimension d = getSize(); Graphics2D g2 = createGraphics2D(d.width, d.height, g); render(d.width, d.height, g2); g2.dispose(); } } static public class WeakVar implements IVar { public WeakReference ref; public synchronized void set(A a) { ref = weakRef(a); } public synchronized A get() { if (ref == null) return null; A value = ref.get(); if (value == null) ref = null; return value; } } abstract static public class NotifyingList extends NotifyingCollection implements List, RandomAccess { public NotifyingList() { } public List list; public NotifyingList(List list) { super(list); this.list = list; } public List subList(int i, int j) { throw todo(); } public void setInnerList(List list) { c = this.list = list; } public void init() { setInnerList(new ArrayList()); } public void initAndAddAll(Collection l) { init(); addAll(l); } public boolean equals(Object o) { if (this == o) return true; synchronized (this) { return list.equals(o); } } public int hashCode() { synchronized (this) { return list.hashCode(); } } public A get(int index) { synchronized (this) { return list.get(index); } } public A set(int index, A element) { synchronized (this) { beforeChange(); A a = list.set(index, element); change(); return a; } } public void add(int index, A element) { synchronized (this) { beforeChange(); list.add(index, element); } change(); } public A remove(int index) { A e; synchronized (this) { beforeChange(); e = list.remove(index); } change(); return e; } public int indexOf(Object o) { synchronized (this) { return list.indexOf(o); } } public int lastIndexOf(Object o) { synchronized (this) { return list.lastIndexOf(o); } } public boolean addAll(int index, Collection c) { synchronized (this) { beforeChange(); if (!list.addAll(index, c)) return false; } change(); return true; } public ListIterator listIterator() { return list.listIterator(); } public ListIterator listIterator(int index) { return list.listIterator(index); } public void sort(Comparator c) { synchronized (this) { beforeChange(); list.sort(c); } change(); } } static public class Q implements AutoCloseable { public String name = "Unnamed Queue"; public List q = synchroLinkedList(); public ReliableSingleThread rst = new ReliableSingleThread(new Runnable() { public void run() { try { _run(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_run()"; } }); final public boolean getRetired() { return retired(); } public boolean retired() { return retired; } volatile public boolean retired = false; final public Runnable getCurrentJob() { return currentJob(); } public Runnable currentJob() { return currentJob; } volatile public Runnable currentJob; public AtomicLong jobsDone = new AtomicLong(); public Q() { } public Q(String name) { this.name = name; } public void add(Runnable r) { assertNotRetired(); q.add(r); _trigger(); } public void addInFront(Runnable r) { assertNotRetired(); q.add(0, r); _trigger(); } public void _trigger() { rst.name = name; rst.go(); } public void add(Object r) { add(toRunnable(r)); } public void _run() { Runnable r; while (licensed() && !retired && (r = syncPopFirst(q)) != null) { currentJob = r; inc(jobsDone); try { r.run(); } catch (Throwable __e) { pcallFail(__e); } currentJob = null; } onIdle(); } public void close() { retired = true; } public void done() { } public boolean isEmpty() { return q.isEmpty(); } public int size() { return q.size(); } public Object mutex() { return q; } public List snapshot() { return cloneList(q); } public void onIdle() { } public boolean busy() { return currentJob != null; } public void assertNotRetired() { assertFalse("Queue is retired", retired()); } public boolean hasThread() { return rst.hasThread(); } public long nJobsDone() { return jobsDone.get(); } public String toString() { return (retired ? "Retired " : "") + "Q " + systemHashCodeHex(this) + " (" + (isEmpty() ? "empty" : nEntries(size()) + ", current job: " + currentJob) + ")"; } } static public class VectorSSIList extends AbstractSSIList { public VectorSSIList() { init(); } public VectorSSIList(Collection l) { super(l); } public VectorSSI importSSI(AbstractSSI ssi) { return toVectorSSI(ssi); } } static public class TailFile implements AutoCloseable { public File file; public int interval; public Object onData; final public TailFile setSleeper(ISleeper_v2 sleeper) { return sleeper(sleeper); } public TailFile sleeper(ISleeper_v2 sleeper) { this.sleeper = sleeper; return this; } final public ISleeper_v2 getSleeper() { return sleeper(); } public ISleeper_v2 sleeper() { return sleeper; } public ISleeper_v2 sleeper = defaultSleeper(); public long l; final public long getCurrentFileSize() { return currentFileSize(); } public long currentFileSize() { return currentFileSize; } public long currentFileSize; public Flag stopped = new Flag(); public FlexibleRateTimer timer; public ReliableSingleThread thread; volatile public boolean hasIdled, debug; public TailFile() { } public TailFile(final File file, int interval, Object onData) { this.onData = onData; this.interval = interval; this.file = file; thread = new ReliableSingleThread(new Runnable() { public void run() { try { update(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "update()"; } }); } public void update() { long l2 = currentFileSize = l(file); if (l2 < l) l = 0; if (l2 == l) hasIdled = true; else try { if (debug) print("New data in " + f2s(file) + ": " + n2(l2 - l, "byte")); for (String s : loadTextFilePart_iterator(file, l, l2)) pcallF(onData, s); l = l2; } catch (Throwable __e) { pcallFail(__e); } } public void start() { timer = new FlexibleRateTimer(msIntervalToHertz(interval), () -> { if (!stopped.isUp()) thread.trigger(); }); timer.sleeper(sleeper); timer.start(); } public void stop() { timer.cancel(); timer = null; if (stopped.raise()) thread.triggerAndWait(); } public void close() { stop(); } public boolean started() { return timer != null; } public void debugOn() { if (debug) return; debug = true; print("Watching file: " + f2s(file)); } public String toString() { return "Tailing file " + file; } } static public class RenderRecognizedBox implements Renderable, IFieldsToList { static final public String _fieldOrder = "box outerColor innerColor"; public IRecognizedBox box; public RenderRecognizedBox() { } public RenderRecognizedBox(IRecognizedBox box) { this.box = box; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + box + ")"; } public boolean equals(Object o) { if (!(o instanceof RenderRecognizedBox)) return false; RenderRecognizedBox __1 = (RenderRecognizedBox) o; return eq(box, __1.box); } public int hashCode() { int h = -26540481; h = boostHashCombine(h, _hashCode(box)); return h; } public Object[] _fieldsToList() { return new Object[] { box }; } final public RenderRecognizedBox setOuterColor(Color outerColor) { return outerColor(outerColor); } public RenderRecognizedBox outerColor(Color outerColor) { this.outerColor = outerColor; return this; } final public Color getOuterColor() { return outerColor(); } public Color outerColor() { return outerColor; } public Color outerColor = Color.red; final public RenderRecognizedBox setInnerColor(Color innerColor) { return innerColor(innerColor); } public RenderRecognizedBox innerColor(Color innerColor) { this.innerColor = innerColor; return this; } final public Color getInnerColor() { return innerColor(); } public Color innerColor() { return innerColor; } public Color innerColor = Color.green; public void renderOn(Graphics2D g, int w, int h) { Rect r = box.bounds(); r = growRect(r); drawRect(g, innerColor, r); r = growRect(r); drawRect(g, outerColor, r); } } static public class RestartableCountdown implements AutoCloseable { public java.util.Timer timer; public long targetTime; public long totalSleepTime; synchronized public void setTargetTime(long targetTime, Runnable action) { if (targetTime <= 0) stop(); else if (targetTime != this.targetTime) { start(targetTime - sysNow(), action); this.targetTime = targetTime; } } synchronized public void start(long delayMS, Object action) { stop(); if (delayMS <= 0) { startThread(new Runnable() { public void run() { try { callF(action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(action);"; } }); } else { totalSleepTime += delayMS; timer = doLater_daemon(delayMS, action); targetTime = sysNow() + delayMS; } } public void start(double delaySeconds, Object action) { start(toMS(delaySeconds), action); } synchronized public void stop() { cancelTimer(timer); timer = null; targetTime = 0; } public void close() { stop(); } } static public class VStack implements Steppable, IVStack { public List stack = new ArrayList(); public Object latestResult; transient public Object newResult; static public class NullSentinel { } static public NullSentinel nullSentinel = new NullSentinel(); public VStack() { } public VStack(Computable computation) { push(computation); } public VStack(Iterable l) { pushAll(l); } public interface Computable { public void step(VStack stack, Object subComputationResult); } private Object deSentinel(Object o) { return o instanceof NullSentinel ? null : o; } private Object sentinel(Object o) { return o == null ? nullSentinel : o; } public void push(Computable computation) { stack.add(assertNotNull(computation)); } public boolean step() { if (empty(stack)) return false; newResult = null; last(stack).step(this, result()); latestResult = newResult; newResult = null; return true; } public void _return(Object value) { newResult = sentinel(value); pop(); } final public void replace(Computable computation) { tailCall(computation); } public void tailCall(Computable computation) { pop(); stack.add(computation); } public A compute(Computable computation) { if (computation == null) return null; push(computation); stepAll(this); return (A) latestResult; } final public Object subResult() { return result(); } public Object result() { return deSentinel(latestResult); } public boolean hasSubResult() { return latestResult != null; } public void pushAll(Iterable l) { for (Computable c : unnullForIteration(l)) push(c); } public void add(Runnable r) { if (r == null) return; push((stack, subComputationResult) -> r.run()); } public Computable caller() { return nextToLast(stack); } public void pop() { removeLast(stack); } public boolean isEmpty() { return empty(stack); } } public interface TransientObject { } static public class FixedVarContext extends VarContext { public String[] names; public Object[] values; public FixedVarContext() { } public FixedVarContext(String[] names) { this(null, names); this.names = names; } public FixedVarContext(VarContext parent, String[] names) { super(parent); this.names = names; if (names != null) values = new Object[names.length]; } public int indexOfVar(String name) { return indexOfInSortedArray(names, name); } public int indexOfVarMandatory(String name) { int idx = indexOfVar(name); if (idx < 0) throw fail("Variable not found: " + name + ", known: " + joinWithComma(names)); return idx; } public Object get(int idx) { return values[idx]; } public Object get(String name) { int idx = indexOfVar(name); if (idx >= 0) return values[idx]; if (parent != null) return parent.get(name); return null; } public void set(int idx, Object value) { values[idx] = value; } public void set(String name, Object value) { int idx = indexOfVar(name); if (idx >= 0) values[idx] = value; else throw fail("Variable " + name + " not defined in context"); } public AutoCloseable tempSet(String name, Object value) { int idx = indexOfVar(name); if (idx >= 0) { Object old = values[idx]; values[idx] = value; return () -> values[idx] = old; } else throw fail("Variable " + name + " not defined in context"); } public void unset(String name) { set(name, null); } public Map varMap() { Map map = new HashMap(); int n = l(names); for (int i = 0; i < n; i++) map.put(names[i], values[i]); return map; } } static public class ConceptsComboBox extends JComboBox { public Concepts concepts; public Class conceptClass; public AWTOnConceptChanges updater; final public ConceptsComboBox setAllowNull(boolean allowNull) { return allowNull(allowNull); } public ConceptsComboBox allowNull(boolean allowNull) { this.allowNull = allowNull; return this; } final public boolean getAllowNull() { return allowNull(); } public boolean allowNull() { return allowNull; } public boolean allowNull = false; final public ConceptsComboBox setItemFilter(IF1 itemFilter) { return itemFilter(itemFilter); } public ConceptsComboBox itemFilter(IF1 itemFilter) { this.itemFilter = itemFilter; return this; } final public IF1 getItemFilter() { return itemFilter(); } public IF1 itemFilter() { return itemFilter; } public IF1 itemFilter; public ConceptsComboBox(Concepts concepts, Class conceptClass) { this.conceptClass = conceptClass; this.concepts = concepts; updateItems(); updater = new AWTOnConceptChanges(concepts, this, () -> updateItems()); updater.install(); } public void updateItems() { var l = sortTheList(filterTheList(freshList())); if (allowNull) l = nullPlus(l); setComboBoxItems_notifyListeners(this, l); } transient public IF0> freshList; public Collection freshList() { return freshList != null ? freshList.get() : freshList_base(); } final public Collection freshList_fallback(IF0> _f) { return _f != null ? _f.get() : freshList_base(); } public Collection freshList_base() { return utils.list(concepts, conceptClass); } public List filterTheList(Collection l) { return itemFilter == null ? asList(l) : filter(itemFilter, l); } transient public IF1, List> sortTheList; public List sortTheList(List l) { return sortTheList != null ? sortTheList.get(l) : sortTheList_base(l); } final public List sortTheList_fallback(IF1, List> _f, List l) { return _f != null ? _f.get(l) : sortTheList_base(l); } public List sortTheList_base(List l) { return sortConceptsByID(l); } public ConceptsComboBox sorter(IF1, List> sorter) { sortTheList = sorter; return this; } public A get() { return getSelectedItem_typed(this); } public void select(long conceptID) { utils.setSelectedItem(this, getConcept(concepts, conceptClass, conceptID)); } } static public class HuffmanByteArray implements BitIO { public HuffmanByteArray() { } final public HuffmanByteArray setData(byte[] data) { return data(data); } public HuffmanByteArray data(byte[] data) { this.data = data; return this; } final public byte[] getData() { return data(); } public byte[] data() { return data; } public byte[] data; final public int[] getHistogram() { return histogram(); } public int[] histogram() { return histogram; } public int[] histogram; final public HuffmanTreeMaker getTm() { return tm(); } public HuffmanTreeMaker tm() { return tm; } public HuffmanTreeMaker tm; final public HuffmanTree getTree() { return tree(); } public HuffmanTree tree() { return tree; } public HuffmanTree tree = new HuffmanTree(); final public HuffmanByteArray setStartWithMagicCode(boolean startWithMagicCode) { return startWithMagicCode(startWithMagicCode); } public HuffmanByteArray startWithMagicCode(boolean startWithMagicCode) { this.startWithMagicCode = startWithMagicCode; return this; } final public boolean getStartWithMagicCode() { return startWithMagicCode(); } public boolean startWithMagicCode() { return startWithMagicCode; } public boolean startWithMagicCode = false; final public HuffmanByteArray setMagicCode(String magicCode) { return magicCode(magicCode); } public HuffmanByteArray magicCode(String magicCode) { this.magicCode = magicCode; return this; } final public String getMagicCode() { return magicCode(); } public String magicCode() { return magicCode; } public String magicCode = "HUF1"; public HuffmanByteArray(byte[] data) { this.data = data; } public void readWrite(BitHead head) { if (head.writeMode() && histogram == null) { histogram = byteHistogramArray(data); tm = new HuffmanTreeMaker(); tm.importByteHistogram(histogram); tree = tm.get(); } if (startWithMagicCode) head.exchangeASCII(magicCode); tree.readWrite(head); new VariableSizeUIntForBitHead().chunkSize(3).readWrite(head, () -> data.length, size -> data = new byte[size]); if (head.writeMode()) { for (var b : unnullForIteration(data)) tree.writeCharacter(b, head); } if (head.readMode()) { for (int i = 0; i < l(data); i++) { if (head.isEOF()) break; data[i] = toUByte(tree.readSymbol(head)); } } } public byte[] get() { return data; } public HuffmanByteArray fromByteArray(byte[] data) { BitIO.super.fromByteArray(data); return this; } public HuffmanByteArray load(byte[] data) { BitIO.super.load(data); return this; } } abstract static public class VarContext { final public VarContext getParent() { return parent(); } public VarContext parent() { return parent; } public VarContext parent; public VarContext() { } public VarContext(VarContext parent) { this.parent = parent; } abstract public Object get(String name); final public void put(String name, Object value) { set(name, value); } abstract public void set(String name, Object value); final public AutoCloseable tempPut(String name, Object value) { return tempSet(name, value); } abstract public AutoCloseable tempSet(String name, Object value); abstract public void unset(String name); abstract public Map varMap(); public void printMe() { pnl(varMap()); print("parent", parent); } final public VarContext setExitFromScript(Object exitFromScript) { return exitFromScript(exitFromScript); } public VarContext exitFromScript(Object exitFromScript) { this.exitFromScript = exitFromScript; return this; } final public Object getExitFromScript() { return exitFromScript(); } public Object exitFromScript() { return exitFromScript; } public Object exitFromScript; final public VarContext setReturnValue(Object returnValue) { return returnValue(returnValue); } public VarContext returnValue(Object returnValue) { this.returnValue = returnValue; return this; } final public Object getReturnValue() { return returnValue(); } public Object returnValue() { return returnValue; } public Object returnValue; public boolean exiting() { ping(); return exitFromScript != null; } } static public class Average { final public double getSum() { return sum(); } public double sum() { return sum; } public double sum; final public double getN() { return n(); } public double n() { return n; } public double n; final public void addSample(double d) { add(d); } public void add(double d) { ++n; sum += d; } public void add(double d, double weight) { n += weight; sum += d * weight; } public void remove(double d) { add(d, -1); } final public double avg() { return get(); } final public double average() { return get(); } final public double getAverage() { return get(); } public double get() { return doubleRatio(sum, n); } public boolean isEmpty() { return n == 0; } public String toString() { return get() + " (n=" + n + ")"; } public void clear() { n = 0; sum = 0; } final public double count() { return size(); } public double size() { return n; } } static public class OpenGL_DemoObjects implements GLEventListener, IFieldsToList { public Animator animator; public OpenGL_DemoObjects() { } public OpenGL_DemoObjects(Animator animator) { this.animator = animator; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + animator + ")"; } public Object[] _fieldsToList() { return new Object[] { animator }; } public OutlineShape outlineShape; public RenderState renderState; public RegionRenderer regionRenderer; public GLRegion glRegion; public OutlineShape dynamicOutlineShape; public RenderState dynamicRenderState; public RegionRenderer dynamicRegionRenderer; public GLRegion dynamicGlRegion; volatile public float weight = 1.0f; final public float zNear = 0.1f, zFar = 7000f; final public int[] sampleCount = new int[] { 4 }; public float xTranslate = -40f; public float yTranslate = 0f; public float zTranslate = -100f; public float angleRotate = 0f; final public int renderModes = Region.VARWEIGHT_RENDERING_BIT; @Override public void init(GLAutoDrawable drawable) { final GL2ES2 gl = drawable.getGL().getGL2ES2(); gl.setSwapInterval(1); gl.glEnable(GL.GL_DEPTH_TEST); gl.glEnable(GL.GL_BLEND); gl.glClearColor(1.0f, 0.0f, 1.0f, 1.0f); renderState = RenderState.createRenderState(SVertex.factory()); renderState.setColorStatic(1.0f, 1.0f, 1.0f, 1.0f); renderState.setHintMask(RenderState.BITHINT_GLOBAL_DEPTH_TEST_ENABLED); outlineShape = new OutlineShape(renderState.getVertexFactory()); outlineShape.addEmptyOutline(); outlineShape.addVertex(0.0f, -10.0f, true); outlineShape.addVertex(17.0f, -10.0f, true); outlineShape.addVertex(11.0f, 5.0f, false); outlineShape.addVertex(17.0f, 10.0f, true); outlineShape.addVertex(7.0f, 15.0f, false); outlineShape.addVertex(6.0f, 8.0f, false); outlineShape.addVertex(0.0f, 10.0f, true); outlineShape.closeLastOutline(true); float offset = 30; outlineShape.addEmptyOutline(); outlineShape.addVertex(offset + 0.0f, -10.0f, true); outlineShape.addVertex(offset + 17.0f, -10.0f, true); outlineShape.addVertex(offset + 11.0f, 5.0f, true); outlineShape.addVertex(offset + 16.0f, 10.0f, true); outlineShape.addVertex(offset + 7.0f, 15.0f, true); outlineShape.addVertex(offset + 6.0f, 8.0f, true); outlineShape.addVertex(offset + 0.0f, 10.0f, true); outlineShape.closeLastOutline(true); regionRenderer = RegionRenderer.create(renderState, RegionRenderer.defaultBlendEnable, RegionRenderer.defaultBlendDisable); glRegion = GLRegion.create(renderModes, null); glRegion.addOutlineShape(outlineShape, null, glRegion.hasColorChannel() ? renderState.getColorStatic(new float[4]) : null); dynamicRenderState = RenderState.createRenderState(SVertex.factory()); dynamicRenderState.setColorStatic(1.0f, 0.0f, 0.0f, 1.0f); dynamicRenderState.setHintMask(RenderState.BITHINT_GLOBAL_DEPTH_TEST_ENABLED); dynamicRegionRenderer = RegionRenderer.create(dynamicRenderState, RegionRenderer.defaultBlendEnable, RegionRenderer.defaultBlendDisable); dynamicOutlineShape = new OutlineShape(dynamicRenderState.getVertexFactory()); dynamicGlRegion = GLRegion.create(renderModes, null); } @Override public void dispose(GLAutoDrawable drawable) { final GL2ES2 gl = drawable.getGL().getGL2ES2(); { if (animator != null) animator.stop(); } regionRenderer.destroy(gl); glRegion.destroy(gl); dynamicGlRegion.destroy(gl); } @Override public void display(GLAutoDrawable drawable) { final GL2ES2 gl = drawable.getGL().getGL2ES2(); double time = com.jogamp.common.os.Platform.currentTimeMicros(); float sinusAnimation = (float) (Math.sin(time / 100000f)); float sinusAnimationRotate = (float) (Math.sin(time / 1000000f)); gl.glClearColor(0.2f, 0.2f, 0.2f, 1.0f); gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); final PMVMatrix pmv = regionRenderer.getMatrix(); pmv.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); pmv.glLoadIdentity(); pmv.glTranslatef(xTranslate, yTranslate, zTranslate); pmv.glRotatef(angleRotate + 10f * sinusAnimationRotate, 0, 0, 1); if (weight != regionRenderer.getRenderState().getWeight()) { regionRenderer.getRenderState().setWeight(weight); } regionRenderer.enable(gl, true); glRegion.draw(gl, regionRenderer, sampleCount); regionRenderer.enable(gl, false); float offset = 60; dynamicOutlineShape.clear(); dynamicOutlineShape.addVertex(offset + 0.0f, -10.0f, true); dynamicOutlineShape.addVertex(offset + 17.0f, -10.0f, true); dynamicOutlineShape.addVertex(offset + 11.0f + 5 * sinusAnimation, 5.0f + 5 * sinusAnimation, false); dynamicOutlineShape.addVertex(offset + 17.0f, 10.0f, true); dynamicOutlineShape.addVertex(offset + 7.0f + 5 * sinusAnimation, 15.0f + 5 * sinusAnimation, false); dynamicOutlineShape.addVertex(offset + 6.0f, 8.0f, true); dynamicOutlineShape.addVertex(offset + 0.0f, 10.0f, true); dynamicOutlineShape.closeLastOutline(true); final PMVMatrix dynamicPmv = dynamicRegionRenderer.getMatrix(); dynamicPmv.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); dynamicPmv.glLoadIdentity(); dynamicPmv.glTranslatef(xTranslate, yTranslate, zTranslate); dynamicPmv.glRotatef(angleRotate + 10f * sinusAnimationRotate, 0, 0, 1); if (weight != dynamicRegionRenderer.getRenderState().getWeight()) { dynamicRegionRenderer.getRenderState().setWeight(weight); } dynamicGlRegion.clear(gl); dynamicGlRegion.addOutlineShape(dynamicOutlineShape, null, glRegion.hasColorChannel() ? renderState.getColorStatic(new float[4]) : null); dynamicRegionRenderer.enable(gl, true); dynamicGlRegion.draw(gl, dynamicRegionRenderer, sampleCount); dynamicRegionRenderer.enable(gl, false); } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { final PMVMatrix pmv = regionRenderer.getMatrix(); regionRenderer.reshapePerspective(45.0f, width, height, zNear, zFar); pmv.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); pmv.glLoadIdentity(); final PMVMatrix dynamicPmv = dynamicRegionRenderer.getMatrix(); dynamicRegionRenderer.reshapePerspective(45.0f, width, height, zNear, zFar); dynamicPmv.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); dynamicPmv.glLoadIdentity(); } } static public class BWIntegralImage extends Meta implements IBWIntegralImage, IIntegralImage { public int w, h; public int[] data; public BWIntegralImage() { } public BWIntegralImage(File f) { this(loadImage2(f)); } public BWIntegralImage(MakesBufferedImage img) { this(toBufferedImage(img)); } public BWIntegralImage(BufferedImage image) { grab(image); } public BWIntegralImage(BufferedImage image, Decolorizer decolorizer) { grab(image, decolorizer); } public BWIntegralImage(GrabbableIntPixels gp) { grab(gp); } public BWIntegralImage(GrabbableRGBBytePixels gp) { grab(gp, new Decolorizer.Simple()); } public BWIntegralImage(GrabbableGrayPixels gp) { grab(gp); } public BWIntegralImage(BWImage img) { grab(new GrabbableGrayPixels(img.pixels, img.width, img.height, 0, img.width)); } public void grab(BufferedImage image) { grab(image, null); } public void grab(BufferedImage image, Decolorizer decolorizer) { if (image.getType() == BufferedImage.TYPE_BYTE_GRAY) grab(grabbableGrayPixels(image)); else { var gp = grabbableRGBBytePixels(image); if (gp != null) grab(gp, decolorizer); else grab(grabbableIntPixels_fastOrSlow(image), decolorizer); } } public void grab(GrabbableRGBBytePixels gp, Decolorizer decolorizer) { if (decolorizer == null) decolorizer = new Decolorizer.Simple(); alloc(gp.w, gp.h); int w = this.w, h = this.h; int iImage = gp.offset, sum = 0, pixelStride = gp.pixelStride; byte[] image = gp.data; for (int x = 0; x < w; x++) { int packed = rgbInt(image[iImage], image[iImage + 1], image[iImage + 2]); iImage += pixelStride; int brightness = decolorizer.toGrayScale(packed); data[x] = (sum += brightness); } var ping = pingSource(); int scanlineExtra = gp.scanlineStride - w * pixelStride; iImage = gp.offset + gp.scanlineStride; int i = w; for (int y = 1; y < h; y++) { sum = 0; for (int x = 0; x < w; x++) { int packed = rgbInt(image[iImage], image[iImage + 1], image[iImage + 2]); iImage += pixelStride; int brightness = decolorizer.toGrayScale(packed); sum += brightness; data[i] = sum + data[i - w]; i++; } iImage += scanlineExtra; { if (ping != null) ping.get(); } } } public void grab(GrabbableIntPixels gp, Decolorizer decolorizer) { if (isDefaultDecolorizer(decolorizer)) { grab(gp); return; } alloc(gp.w, gp.h); int w = this.w, h = this.h; int offset = gp.offset, sum = 0; int[] image = gp.data; for (int x = 0; x < w; x++) { int packed = image[offset + x]; int brightness = decolorizer.toGrayScale(packed); data[x] = (sum += brightness); } var ping = pingSource(); int scanlineExtra = gp.scanlineStride - w; int iImage = offset + gp.scanlineStride, i = w; for (int y = 1; y < h; y++) { sum = 0; for (int x = 0; x < w; x++) { int packed = image[iImage]; int brightness = decolorizer.toGrayScale(packed); sum += brightness; data[i] = sum + data[i - w]; iImage++; i++; } iImage += scanlineExtra; { if (ping != null) ping.get(); } } } public void grab(GrabbableIntPixels gp) { alloc(gp.w, gp.h); int w = this.w, h = this.h; int offset = gp.offset, sum = 0; int[] image = gp.data; for (int x = 0; x < w; x++) { int packed = image[offset + x]; int brightness = packedToBrightness(packed); data[x] = (sum += brightness); } var ping = pingSource(); int scanlineExtra = gp.scanlineStride - w; int iImage = offset + gp.scanlineStride, i = w; for (int y = 1; y < h; y++) { sum = 0; for (int x = 0; x < w; x++) { int packed = image[iImage]; int brightness = packedToBrightness(packed); sum += brightness; data[i] = sum + data[i - w]; iImage++; i++; } iImage += scanlineExtra; { if (ping != null) ping.get(); } } } public void grab(GrabbableGrayPixels gp) { alloc(gp.w, gp.h); int offset = gp.offset, sum = 0; byte[] image = gp.data; for (int x = 0; x < w; x++) { int brightness = image[offset + x]; data[x] = (sum += brightness); } var ping = pingSource(); int scanlineExtra = gp.scanlineStride - w; int iImage = offset + gp.scanlineStride, i = w; for (int y = 1; y < h; y++) { sum = 0; for (int x = 0; x < w; x++) { int brightness = image[iImage]; sum += brightness; data[i] = sum + data[i - w]; iImage++; i++; } iImage += scanlineExtra; { if (ping != null) ping.get(); } } } private void alloc(int w, int h) { this.w = w; this.h = h; if (w * h > 8 * 1024 * 1024) throw fail("Image too large (more than 8 MP): " + w + "*" + h); data = new int[w * h]; } public int get(int x, int y) { return x < 0 || y < 0 ? 0 : data[min(y, h - 1) * w + min(x, w - 1)]; } public double getIIValue(double x, double y) { int xFloor = ifloor(x), yFloor = ifloor(y); double val = getIIValue(xFloor, yFloor); if (xFloor == x && yFloor == y) return val; double val2 = getIIValue(xFloor + 1, yFloor); double val3 = getIIValue(xFloor, yFloor + 1); double val4 = getIIValue(xFloor + 1, yFloor + 1); return blend2D(val, val2, val3, val4, x - xFloor, y - yFloor); } public int getIIValue(int x, int y) { return get(x, y); } public double getIntegralValue(int x, int y, int channel) { return get(x, y); } public double getPixelAverage(int x1, int y1, int x2, int y2) { int area = (x2 - x1) * (y2 - y1); return doubleRatio(bwIntegralImage_sumRect(this, x1, y1, x2, y2), area); } public int getWidth() { return w; } public int getHeight() { return h; } public int packedToBrightness(int packed) { int b = (packed & 0xFF); int r = ((packed >> 16) & 0xFF); int g = ((packed >> 8) & 0xFF); return (r + g + b + 1) / 3; } public int getInt(int x, int y) { return iround(rectSum(x, y, x + 1, y + 1, 0)); } public int getPixel(int x, int y) { return rgbIntFromGrayscale(getInt(x, y)); } public BufferedImage getBufferedImage() { Object src = metaGet("src", this); if (src instanceof BufferedImage) return ((BufferedImage) src); return grayImageFromIBWIntegralImage(this); } } static public class CompressToInterpolatedDoubleArray { public int[] data; public InterpolatedDoubleArray result; final public CompressToInterpolatedDoubleArray setSlopeTolerance(double slopeTolerance) { return slopeTolerance(slopeTolerance); } public CompressToInterpolatedDoubleArray slopeTolerance(double slopeTolerance) { this.slopeTolerance = slopeTolerance; return this; } final public double getSlopeTolerance() { return slopeTolerance(); } public double slopeTolerance() { return slopeTolerance; } public double slopeTolerance = 0.01; public IntBuffer indices = new IntBuffer(); public DoubleBuffer values = new DoubleBuffer(); public CompressToInterpolatedDoubleArray(int[] data) { this.data = data; } public InterpolatedDoubleArray get() { int iData = 0; while (iData < data.length) { int startValue = data[iData]; DoubleRange startValueRange = doubleRange(startValue - 0.5, startValue + 0.5); DoubleRange totalSlopeRange = null; int jData; for (jData = iData + 1; jData < data.length; jData++) { double x = data[jData], h = jData - iData; DoubleRange xRange = doubleRange(x - 0.5, x + 0.5); DoubleRange slopeRange = doubleRange((xRange.start - startValueRange.end) / h, (xRange.end - startValueRange.start) / h); slopeRange = growRange(slopeTolerance, slopeRange); if (totalSlopeRange == null) totalSlopeRange = slopeRange; else { slopeRange = intersectRanges(slopeRange, totalSlopeRange); if (empty(slopeRange)) break; else totalSlopeRange = slopeRange; } } indices.add(iData); values.add(data[iData]); iData = max(iData + 1, jData - 1); } return result = new InterpolatedDoubleArray(indices.toArrayNonNull(), values.toArrayNonNull()); } } public interface IVStack { default public void call(VStack.Computable f) { push(f); } public void push(VStack.Computable f); public void tailCall(VStack.Computable f); default public void _return() { _return(null); } public void _return(Object value); public Object subResult(); } public interface IF0_Pair extends IF0> { public Pair get(); } public interface IHasTokenRangeWithSrc { public IHasTokenRangeWithSrc setTokenRangeWithSrc(TokenRangeWithSrc src); public TokenRangeWithSrc tokenRangeWithSrc(); default public String srcText() { var src = tokenRangeWithSrc(); return src == null ? null : src.text(); } } public interface IF0_Bool { public boolean get(); } static public interface IBinaryImage extends MakesBufferedImage { public boolean getBoolPixel(int x, int y); default public void setPixel(int x, int y, boolean b) { throw unimplemented(); } default public boolean getBoolPixel(Pt p) { return getBoolPixel(p.x, p.y); } default public boolean getBoolPixel_noRangeCheck(int x, int y) { return getBoolPixel(x, y); } public default BufferedImage getBufferedImage() { return toImage2B().getBufferedImage(); } default public Image2B toImage2B() { return this instanceof Image2B ? (Image2B) this : iBinaryImageToImage2B(this); } } public interface IImageRegions { public List> regions(); public int[] regionMatrix(); public Img image(); public int nRegions(); public IImageRegion getRegion(int i); } static public class StefansOS_ConnectToServer implements AutoCloseable { public DialogIO io; volatile public boolean on, verbose; public Set subs = synchroLinkedHashSet(); public VF1 onLine; public String server = "botcompany.de"; public List onConnected = syncList(); transient public Set> onNewLine; public StefansOS_ConnectToServer onNewLine(IVF1 f) { onNewLine = createOrAddToSyncLinkedHashSet(onNewLine, f); return this; } public StefansOS_ConnectToServer removeNewLineListener(IVF1 f) { utils.remove(onNewLine, f); return this; } public void newLine(String text) { if (onNewLine != null) for (var listener : onNewLine) pcallF_typed(listener, text); } public void start() { if (on) return; on = true; _connect(); doEvery_daemon_highPriority(30000, new Runnable() { public void run() { try { if (io != null) sendLine(""); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (io != null) sendLine(\"\")"; } }); } public void cleanMeUp() { on = false; closeIO(); } public void close() { cleanMeUp(); } public void _connect() { startThread("Connect", new Runnable() { public void run() { try { while (licensed() && on) { if (!tryToConnect()) { sleepSeconds(1); continue; } try { var io = talkTo(server, 6000); io.getSocket().setSoTimeout(30000 + 10000); print("Connected."); pcallFAll(onConnected); AutoCloseable __1 = tempAfterwards(new Runnable() { public void run() { try { print("Disconnected."); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "print(\"Disconnected.\")"; } }); try { sendLine(io, format("computerID=*", computerID())); StefansOS_ConnectToServer.this.io = io; for (String channel : cloneList(subs)) sendLine(format("sub *", channel)); print("Sent computer ID: " + computerID()); String line; while ((line = io.readLine()) != null) { if (verbose) print("Server said: " + line); pcallF(onLine, line); newLine(line); } } finally { _close(__1); } } catch (Throwable e) { printShortException(e); } closeIO(); sleepSeconds(5); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "while (licensed() && on) {\r\n if (!tryToConnect()) { sleepSeconds(1); c..."; } }); } public void closeIO() { if (io != null) { try { io.close(); } catch (Throwable __e) { pcallFail(__e); } io = null; } } public boolean connected() { return io != null; } public void sub(String channel) { if (subs.add(channel) && io != null) { try { sendLine(format("sub *", channel)); } catch (Throwable __e) { pcallFail(__e); } } } public void startWithSubs(String... channels) { for (String channel : channels) sub(channel); start(); } public void sendLine(String line) { sendLine(io, line); } public void sendLine(DialogIO io, String line) { if (io != null) { if (verbose) print("Sending to server: " + line); io.sendLine(line); } else print("Can't send, not connected: " + line); } transient public IF0 tryToConnect; public boolean tryToConnect() { return tryToConnect != null ? tryToConnect.get() : tryToConnect_base(); } final public boolean tryToConnect_fallback(IF0 _f) { return _f != null ? _f.get() : tryToConnect_base(); } public boolean tryToConnect_base() { return true; } } static public class LineThroughPoint implements G2Drawable, IFieldsToList { static final public String _fieldOrder = "x y angle"; public double x; public double y; public double angle; public LineThroughPoint() { } public LineThroughPoint(double x, double y, double angle) { this.angle = angle; this.y = y; this.x = x; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + x + ", " + y + ", " + angle + ")"; } public boolean equals(Object o) { if (!(o instanceof LineThroughPoint)) return false; LineThroughPoint __1 = (LineThroughPoint) o; return x == __1.x && y == __1.y && angle == __1.angle; } public int hashCode() { int h = -2021865473; h = boostHashCombine(h, _hashCode(x)); h = boostHashCombine(h, _hashCode(y)); h = boostHashCombine(h, _hashCode(angle)); return h; } public Object[] _fieldsToList() { return new Object[] { x, y, angle }; } public LineThroughPoint(IDoublePt p, double angle) { this.angle = angle; x = p.x_double(); y = p.y_double(); } public DoublePt pointOnLine(double distance) { return doublePt(x + sin(angle) * distance, y + cos(angle) * distance); } public void drawOn(Graphics2D g) { int distance = 200; DoublePt p1 = pointOnLine(-distance); DoublePt p2 = pointOnLine(distance); g.drawLine(iround(p1.x_double()), iround(p1.y_double()), iround(p2.x_double()), iround(p2.y_double())); } } static public class JSection extends SingleComponentPanel { public JSection(Component c) { super(c); } public String getTitle() { Border border = getBorder(); if (border instanceof TitledBorder) return ((TitledBorder) border).getTitle(); return null; } } static public class RecognizedRegion implements IRecognizedRegion, IFieldsToList { public IImageRegion region; public RecognizedRegion() { } public RecognizedRegion(IImageRegion region) { this.region = region; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + region + ")"; } public boolean equals(Object o) { if (!(o instanceof RecognizedRegion)) return false; RecognizedRegion __1 = (RecognizedRegion) o; return eq(region, __1.region); } public int hashCode() { int h = -1664329654; h = boostHashCombine(h, _hashCode(region)); return h; } public Object[] _fieldsToList() { return new Object[] { region }; } public IImageRegion region() { return region; } } static public class CollapsibleLeftPanel extends MetaWithChangeListeners implements Swingable { public transient FieldVar varSidePanelName_cache; public FieldVar varSidePanelName() { if (varSidePanelName_cache == null) varSidePanelName_cache = varSidePanelName_load(); return varSidePanelName_cache; } public FieldVar varSidePanelName_load() { return new FieldVar(this, "sidePanelName", () -> sidePanelName(), sidePanelName -> sidePanelName(sidePanelName)); } final public CollapsibleLeftPanel setSidePanelName(String sidePanelName) { return sidePanelName(sidePanelName); } public CollapsibleLeftPanel sidePanelName(String sidePanelName) { if (!eq(this.sidePanelName, sidePanelName)) { this.sidePanelName = sidePanelName; change(); } return this; } final public String getSidePanelName() { return sidePanelName(); } public String sidePanelName() { return sidePanelName; } volatile public String sidePanelName; public JComponent sideComponent, mainComponent; public JSplitPane splitPane; public transient FieldVar varExpanded_cache; public FieldVar varExpanded() { if (varExpanded_cache == null) varExpanded_cache = varExpanded_load(); return varExpanded_cache; } public FieldVar varExpanded_load() { return new FieldVar(this, "expanded", () -> expanded(), expanded -> expanded(expanded)); } final public CollapsibleLeftPanel setExpanded(boolean expanded) { return expanded(expanded); } public CollapsibleLeftPanel expanded(boolean expanded) { if (!eq(this.expanded, expanded)) { this.expanded = expanded; change(); } return this; } final public boolean getExpanded() { return expanded(); } public boolean expanded() { return expanded; } volatile public boolean expanded = false; public SingleComponentPanel scp = singleComponentPanel(); public CollapsibleLeftPanel(boolean expanded, String sidePanelName, JComponent sideComponent, JComponent mainComponent) { this.mainComponent = mainComponent; this.sideComponent = sideComponent; this.sidePanelName = sidePanelName; this.expanded = expanded; } public void expand() { if (scaffolding()) print("CollapsibleLeftPanel.expand"); setExpanded(true); } public void collapse() { setExpanded(false); } public void updateScp() { swing(() -> { if (metaGet("scaffolding") != null) scaffoldCalled(this, "updateScp"); if (expanded) { splitPane().setRightComponent(jMinWidth0(mainComponent)); scp.set(splitPane()); } else { splitPane().setRightComponent(jMinWidth0(jpanel())); scp.set(westAndCenterWithMargin(sidePanelMargins(vstack(expandButton())), mainComponent)); } }); } public JComponent expandButton() { return jClickableImage_instantToolTip("#1103075", "Expand " + sidePanelName, new Runnable() { public void run() { try { expand(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "expand();"; } }); } public JComponent collapseButton() { return jClickableImage_instantToolTip("#1103076", "Collapse " + sidePanelName, new Runnable() { public void run() { try { collapse(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "collapse();"; } }); } public JComponent wrappedSideComponent() { return sidePanelMargins(northAndCenterWithMargin(westAndCenterWithMargin(collapseButton(), liveValueLabel(varSidePanelName())), sideComponent)); } public JSplitPane splitPane() { if (scaffolding()) print("splitPane " + splitPane); if (splitPane == null) { splitPane = jhsplit_minZero(0.25, wrappedSideComponent(), null); varExpanded().onChangeAndNow(new Runnable() { public void run() { try { updateScp(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "updateScp();"; } }); } return splitPane; } transient public IF1 sidePanelMargins; public JComponent sidePanelMargins(JComponent c) { return sidePanelMargins != null ? sidePanelMargins.get(c) : sidePanelMargins_base(c); } final public JComponent sidePanelMargins_fallback(IF1 _f, JComponent c) { return _f != null ? _f.get(c) : sidePanelMargins_base(c); } public JComponent sidePanelMargins_base(JComponent c) { return c; } public JComponent visualize() { splitPane(); return scp; } } public interface IF0WithChangeListeners extends IF0, IHasChangeListeners { } static public class GeneralSSIList extends AbstractSSIList { public GeneralSSIList() { init(); } public GeneralSSIList(Collection l) { super(l); } @Override public AbstractSSI importSSI(AbstractSSI ssi) { return ssi; } } static public class JECompressionRegime implements CompressionRegime_AnyType> { final public JECompressionRegime setQuickEval(boolean quickEval) { return quickEval(quickEval); } public JECompressionRegime quickEval(boolean quickEval) { this.quickEval = quickEval; return this; } final public boolean getQuickEval() { return quickEval(); } public boolean quickEval() { return quickEval; } public boolean quickEval = true; final public JECompressionRegime setFullEval(boolean fullEval) { return fullEval(fullEval); } public JECompressionRegime fullEval(boolean fullEval) { this.fullEval = fullEval; return this; } final public boolean getFullEval() { return fullEval(); } public boolean fullEval() { return fullEval; } public boolean fullEval = false; public byte[] metaCompress(byte[] c) { return c; } public byte[] decompressorToBytes(ICachedJavaXExpr decompressor) { return metaCompress(toUtf8(str(decompressor))); } public ICachedJavaXExpr decompressorFromBytes(byte[] compressed) { print("decompressorFromBytes"); return javaExpr(fromUtf8(gunzipBytes(compressed))); } public Object runDecompressor(ICachedJavaXExpr code) { if (code == null) return null; if (quickEval) try { return code.quickEval(); } catch (Throwable e) { if (!fullEval) rethrow(e); else printStackTrace(e); } if (fullEval) { print("*** FULL JAVA EVAL ***"); return dm_javaEval(str(code)); } throw fail("No way to eval " + shorten(100, sfu(code))); } public transient IF0 fullRegime; public CompressionRegime_AnyType fullRegime() { return fullRegime != null ? fullRegime.get() : fullRegime_base(); } final public CompressionRegime_AnyType fullRegime_fallback(IF0 _f) { return _f != null ? _f.get() : fullRegime_base(); } public CompressionRegime_AnyType fullRegime_base() { return null; } } static public class WithSideValue extends Var implements IWithSideValue { public A sideValue; public WithSideValue() { } public WithSideValue(A sideValue, B value) { super(value); this.sideValue = sideValue; } public WithSideValue(B value) { super(value); } public A sideValue() { return sideValue; } public String toString() { return prependSquareBracketed(sideValue) + super.toString(); } } abstract static public class IntegerIterator { abstract public boolean hasNext(); abstract public int next(); } public interface IStringifier { public String toString(A o); } static public class CombinedStringifier implements IStringifier { public CopyOnWriteArrayList> stringifiers = new CopyOnWriteArrayList(); public IStringifier defaultStringifier = new Stringifier_ToString(); public CombinedStringifier(IPartialStringifier... stringifiers) { addAll(this.stringifiers, stringifiers); } public String toString(A o) { for (var stringifier : stringifiers) { String s = stringifier.toStringOpt(o); if (s != null) return s; } return defaultStringifier.toString(o); } public String toString() { return formatFunctionCall("CombinedStringifier", listPlus((List) stringifiers, defaultStringifier)); } } static public class JFilePathLabel implements Swingable, IFieldsToList { public File file; public JFilePathLabel() { } public JFilePathLabel(File file) { this.file = file; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + file + ")"; } public Object[] _fieldsToList() { return new Object[] { file }; } transient public JLabel label; transient public JFilePathButton button; transient public JPanel buttons = jline(); public boolean nameOnly = false; final public JFilePathLabel setIconOnTheLeft(boolean iconOnTheLeft) { return iconOnTheLeft(iconOnTheLeft); } public JFilePathLabel iconOnTheLeft(boolean iconOnTheLeft) { this.iconOnTheLeft = iconOnTheLeft; return this; } final public boolean getIconOnTheLeft() { return iconOnTheLeft(); } public boolean iconOnTheLeft() { return iconOnTheLeft; } public boolean iconOnTheLeft = false; final public JFilePathLabel setMinWidth(boolean minWidth) { return minWidth(minWidth); } public JFilePathLabel minWidth(boolean minWidth) { this.minWidth = minWidth; return this; } final public boolean getMinWidth() { return minWidth(); } public boolean minWidth() { return minWidth; } public boolean minWidth = false; public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { label = jlabel(); if (minWidth) jnarrowLabel(label); makeButtons(); update(); return layout(); } public void makeButtons() { button = new JFilePathButton(file); buttons.add(button.visualize()); } public void setFile(File file) { this.file = file; update(); } final public File get() { return file(); } public File file() { return file; } public void update() { setText(label, file == null ? "-" : nameOnly ? fileName(file) : f2s(file)); if (nameOnly) toolTip(file == null ? "No file" : f2s(file), label); button.setFile(file); } public JComponent layout() { var a = buttons; var b = label; return iconOnTheLeft ? minWidth ? westAndCenterWithMargin(a, b) : jline(a, b) : minWidth ? centerAndEastWithMargin(b, a) : jline(b, a); } public void showInExplorer() { button.showInExplorer(); } public JFilePathLabel nameOnly() { nameOnly = true; return this; } } static public class UTF8Processor { public byte[] buffer = new byte[5]; public int count = 0; public String processByte(byte nextByte) { try { buffer[count++] = nextByte; if (count == expectedBytes()) { String result = new String(buffer, 0, count, "UTF-8"); count = 0; return result; } return ""; } catch (Exception __e) { throw rethrow(__e); } } public int expectedBytes() { int num = buffer[0] & 255; if (num < 0x80) return 1; if (num < 0xe0) return 2; if (num < 0xf0) return 3; if (num < 0xf8) return 4; return 5; } } static public class ReliableSingleThread implements Runnable { public boolean _isTransient() { return true; } public Object runnable; public String name = "Single Thread"; public boolean cancelBeforeTrigger = false; public boolean waitBetweenCancelAndTrigger = false; public F0 enter; public int cancelTimeOut = 10000; public boolean trigger = false; public Thread thread; public WeakReference threadBeingCancelled; public List inserts = syncL(); public ReliableSingleThread() { } public ReliableSingleThread(Object runnable) { this.runnable = runnable; } public ReliableSingleThread(Runnable runnable) { this.runnable = runnable; } public void trigger() { go(); } synchronized public void go() { if (cancelBeforeTrigger) cancelAndPossiblyWait(); trigger = true; if (!running()) { AutoCloseable __1 = callF(enter); try { thread = startThread(name, new Runnable() { public void run() { try { AutoCloseable __2 = callF(enter); try { _run(); } finally { _close(__2); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp callF(enter);\r\n _run();"; } }); } finally { _close(__1); } } } public void run() { go(); } public void get() { go(); } synchronized public boolean running() { return thread != null; } public void triggerAndWait() { trigger(); waitUntilDone(); } public void waitUntilDone() { while (running()) sleep(1); } transient public Runnable preSleep; public void preSleep() { if (preSleep != null) preSleep.run(); else preSleep_base(); } final public void preSleep_fallback(Runnable _f) { if (_f != null) _f.run(); else preSleep_base(); } public void preSleep_base() { } public void _run() { try { while (licensed()) { preSleep(); Thread oldThread; synchronized (this) { var currentInserts = syncGetAndClear(inserts); pcallFAll(currentInserts); if (!trigger) { thread = null; break; } oldThread = getWeakRef(threadBeingCancelled); trigger = false; } if (oldThread != null && oldThread != currentThread()) oldThread.join(cancelTimeOut); pcallF(runnable); } } catch (Exception __e) { throw rethrow(__e); } } synchronized public void cancel() { if (thread == null) return; threadBeingCancelled = new WeakReference(thread); cancelAndInterruptThread(thread); thread = null; } public void cancelAndWait() { Thread _thread; synchronized (this) { if (thread == null) return; _thread = thread; threadBeingCancelled = new WeakReference(thread); thread = null; } cancelAndInterruptThread(_thread); } public void cancelAndTrigger() { cancelAndPossiblyWait(); trigger(); } synchronized public boolean triggered() { return trigger; } public void cleanMeUp() { cancel(); } public ReliableSingleThread cancelBeforeTrigger() { cancelBeforeTrigger = true; return this; } public void cancelAndPossiblyWait() { if (waitBetweenCancelAndTrigger) cancel(); } public void insert(Runnable r) { inserts.add(r); trigger(); } synchronized public boolean hasThread() { return thread != null; } public ReliableSingleThread action(Runnable r) { runnable = r; return this; } } static public class JVideoLibDownloader extends JForwardingLibDownloader { public JVideoLibDownloader() { libraryName("Video extension"); libID(ffmpegLibraryIDForPlatform()); } } static public class WindowResizeDragger extends MouseAdapter { public int cornerSize = 10; public boolean debug = false; public Pt minWindowSize = pt(20, 20); public MouseEvent mouseDownEvent; public JComponent src; public Window window; public Rect originalPosition, srcBounds; public int dragX, dragY; public Cursor originalCursor, ourCursor; public WindowResizeDragger(JComponent src) { this.src = src; addMouseAndMotionListener(src, this); } public boolean engaged() { return mouseDownEvent != null; } public void start(MouseEvent e) { this.mouseDownEvent = e; window = getWindow(src); if (window == null) return; originalPosition = toRect(getBounds(window)); cursorCalc(e, true); } public void cursorCalc(MouseEvent e, boolean inside) { srcBounds = toRect(boundsOnScreen(src)); Pt mouse = pt(e.getXOnScreen(), e.getYOnScreen()); if (distance(mouse.y, srcBounds.y2()) <= cornerSize) dragY = 1; else if (distance(mouse.y, srcBounds.y1()) <= cornerSize) dragY = -1; else dragY = 0; if (distance(mouse.x, srcBounds.x2()) <= cornerSize) dragX = 1; else if (distance(mouse.x, srcBounds.x1()) <= cornerSize) dragX = -1; else dragX = 0; originalCursor = src.getCursor(); int iCursor = dragY * 3 + dragX + 4; int cursor = new int[] { Cursor.NW_RESIZE_CURSOR, Cursor.N_RESIZE_CURSOR, Cursor.NE_RESIZE_CURSOR, Cursor.W_RESIZE_CURSOR, -1, Cursor.E_RESIZE_CURSOR, Cursor.SW_RESIZE_CURSOR, Cursor.S_RESIZE_CURSOR, Cursor.SE_RESIZE_CURSOR }[iCursor]; Cursor newCursor = cursor >= 0 && inside ? Cursor.getPredefinedCursor(cursor) : null; if (debug) printVars(iCursor, "ourCursor", ourCursor, "newCursor", newCursor); if (newCursor != ourCursor) { ourCursor = newCursor; src.setCursor(newCursor); } } @Override public void mouseEntered(MouseEvent e) { if (debug) print("mouseEntered"); if (!engaged()) cursorCalc(e, true); } @Override public void mouseExited(MouseEvent e) { if (debug) print("mouseExited"); if (!engaged()) cursorCalc(e, false); } public void mousePressed(MouseEvent e) { if (e.getButton() != MouseEvent.BUTTON1) return; if (engaged()) return; start(e); } public void mouseDragged(MouseEvent e) { if (!engaged()) return; updatePosition(e); } public void mouseMoved(MouseEvent e) { cursorCalc(e, true); } public void mouseReleased(MouseEvent e) { if (e.getButton() != mouseDownEvent.getButton()) return; updatePosition(e); if (debug) print("drag done"); if (src.getCursor() == ourCursor) src.setCursor(originalCursor); mouseDownEvent = null; dragDone(); } public void updatePosition(MouseEvent e) { Rect w = toRect(window.getBounds()); Pt a = topLeftCorner(w), b = bottomRightCorner(w); Pt mouse = pt(e.getXOnScreen(), e.getYOnScreen()); if (dragX < 0) a.x = min(b.x - minWindowSize.x, mouse.x + originalPosition.x - mouseDownEvent.getXOnScreen()); else if (dragX > 0) b.x = max(a.x + minWindowSize.x, mouse.x + originalPosition.x2() - mouseDownEvent.getXOnScreen()); if (dragY < 0) a.y = min(b.y - minWindowSize.y, mouse.y + originalPosition.y - mouseDownEvent.getYOnScreen()); else if (dragY > 0) b.y = max(a.y + minWindowSize.y, mouse.y + originalPosition.y2() - mouseDownEvent.getYOnScreen()); Rect r = rectFromPoints(a, b); if (debug) printVars("updatePosition", "w", w, "mouse", mouse, "a", a, "b", b, "dragX", dragX, "dragY", dragY); window.setBounds(toRectangle(r)); } public void dragDone() { } } static public class TranspileWithErrorWindow { final public TranspileWithErrorWindow setSnippetID(String snippetID) { return snippetID(snippetID); } public TranspileWithErrorWindow snippetID(String snippetID) { this.snippetID = snippetID; return this; } final public String getSnippetID() { return snippetID(); } public String snippetID() { return snippetID; } public String snippetID; public JFastLogView_noWrap transpilationErrorBox; final public TranspileWithErrorWindow setTranspileAction(Runnable transpileAction) { return transpileAction(transpileAction); } public TranspileWithErrorWindow transpileAction(Runnable transpileAction) { this.transpileAction = transpileAction; return this; } final public Runnable getTranspileAction() { return transpileAction(); } public Runnable transpileAction() { return transpileAction; } public Runnable transpileAction; transient public Set onSuccess; public TranspileWithErrorWindow onSuccess(Runnable r) { onSuccess = createOrAddToSyncLinkedHashSet(onSuccess, r); return this; } public TranspileWithErrorWindow removeSuccessListener(Runnable r) { utils.remove(onSuccess, r); return this; } public void success() { if (onSuccess != null) for (var listener : onSuccess) pcallF_typed(listener); } transient public Set> onError; public TranspileWithErrorWindow onError(IVF1 f) { onError = createOrAddToSyncLinkedHashSet(onError, f); return this; } public TranspileWithErrorWindow removeErrorListener(IVF1 f) { utils.remove(onError, f); return this; } public void error(Throwable error) { if (onError != null) for (var listener : onError) pcallF_typed(listener, error); } final public void runMe() { run(); } public void run() { infoBox("Transpiling " + snippetID); try { transpileAction.run(); } catch (Throwable e) { infoBox("Transpilation error. " + e); swingLater(new Runnable() { public void run() { try { boolean first = transpilationErrorBox == null; transpilationErrorBox = maximizeFrame(scrollAllTheWayDown(showText_fast_noWrap(transpilationErrorBox, "Transpilation Error", renderStackTrace(e)))); if (first) { setFrameIcon("#1101268", transpilationErrorBox); addButtonsToWindow(transpilationErrorBox, jbuttonWithDisable("Medium transpile", new Runnable() { public void run() { try { runMe(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "runMe();"; } })); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "boolean first = transpilationErrorBox == null;\r\n transpilationErrorBox..."; } }); error(e); return; } infoBox("Transpiled OK!"); hideWindow(transpilationErrorBox); transpilationErrorBox = null; success(); } } public enum NESWDirection { north(0, -1), east(1, 0), south(0, 1), west(-1, 0); static final public NESWDirection[] values = values(); final public int getX() { return x(); } public int x() { return x; } final public int x; final public int getY() { return y(); } public int y() { return y; } final public int y; NESWDirection(int x, int y) { this.y = y; this.x = x; } public int index() { return ordinal(); } public NESWDirection plus(int i) { return getNESWDirection(index() + i); } } static public class DoubleBuffer implements Iterable, IntSize { public double[] data; public int size; public DoubleBuffer() { } public DoubleBuffer(int size) { if (size != 0) data = new double[size]; } public DoubleBuffer(Iterable l) { addAll(l); } public DoubleBuffer(Collection l) { this(l(l)); addAll(l); } public DoubleBuffer(double... data) { this.data = data; size = l(data); } public void add(double i) { if (size >= lDoubleArray(data)) { data = resizeDoubleArray(data, Math.max(1, toInt(Math.min(maximumSafeArraySize(), lDoubleArray(data) * 2L)))); if (size >= data.length) throw fail("DoubleBuffer too large: " + size); } data[size++] = i; } public void addAll(Iterable l) { if (l != null) for (double i : l) add(i); } public double[] toArray() { return size == 0 ? null : resizeDoubleArray(data, size); } public double[] toArrayNonNull() { return unnull(toArray()); } public List toList() { return doubleArrayToList(data, 0, size); } public List asVirtualList() { return new RandomAccessAbstractList() { public int size() { return size; } public Double get(int i) { return DoubleBuffer.this.get(i); } public Double set(int i, Double val) { Double a = get(i); data[i] = val; return a; } }; } public void reset() { size = 0; } public void clear() { reset(); } public int size() { return size; } public double get(int idx) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); return data[idx]; } public void set(int idx, double value) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); data[idx] = value; } public double popLast() { if (size == 0) throw fail("empty buffer"); return data[--size]; } public double last() { return data[size - 1]; } public double nextToLast() { return data[size - 2]; } public String toString() { return squareBracket(joinWithSpace(toList())); } public Iterator iterator() { return new IterableIterator() { public int i = 0; public boolean hasNext() { return i < size; } public Double next() { return data[i++]; } }; } public void trimToSize() { data = resizeDoubleArray(data, size); } public int indexOf(double b) { for (int i = 0; i < size; i++) if (data[i] == b) return i; return -1; } public double[] subArray(int start, int end) { return subDoubleArray(data, start, min(end, size)); } } static public class ProgramScan { static public int threads = isWindows() ? 500 : 10; static public int timeout = 5000; static public String ip = "127.0.0.1"; static public int quickScanFrom = 10000, quickScanTo = 10999; static public int maxNumberOfVMs_android = 4; static public int maxNumberOfVMs_nonAndroid = 50; static public int maxNumberOfVMs; static public boolean verbose = false; static public class Program { public int port; public String helloString; public Program(int port, String helloString) { this.helloString = helloString; this.port = port; } } static public List scan() { try { return scan(1, 65535); } catch (Exception __e) { throw rethrow(__e); } } static public List scan(int fromPort, int toPort) { return scan(fromPort, toPort, new int[0]); } static public List scan(int fromPort, int toPort, int[] preferredPorts) { try { Set preferredPortsSet = new HashSet(asList(preferredPorts)); int scanSize = toPort - fromPort + 1; String name = toPort < 10000 ? "bot" : "program"; int threads = isWindows() ? min(500, scanSize) : min(scanSize, 10); final ExecutorService es = Executors.newFixedThreadPool(threads); if (verbose) print(firstToUpper(name) + "-scanning " + ip + " with timeout " + timeout + " ms in " + threads + " threads."); startTiming(); List> futures = new ArrayList(); List ports = new ArrayList(); for (int port : preferredPorts) { futures.add(checkPort(es, ip, port, timeout)); ports.add(port); } for (int port = fromPort; port <= toPort; port++) if (!preferredPortsSet.contains(port) && !forbiddenPort(port)) { futures.add(checkPort(es, ip, port, timeout)); ports.add(port); } es.shutdown(); List programs = new ArrayList(); long time = now(); int i = 0; for (final Future f : futures) { if (verbose) print("Waiting for port " + get(ports, i++) + " at time " + (now() - time)); Program p = f.get(); if (p != null) programs.add(p); } if (verbose) print("Found " + programs.size() + " " + name + "(s) on " + ip); return programs; } catch (Exception __e) { throw rethrow(__e); } } static public Future checkPort(final ExecutorService es, final String ip, final int port, final int timeout) { return es.submit(new Callable() { @Override public Program call() { try { Socket socket = new Socket(); try { socket.setSoTimeout(timeout); socket.connect(new InetSocketAddress(ip, port), timeout); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); String hello = or(in.readLine(), "?"); return new Program(port, hello); } finally { socket.close(); } } catch (Exception ex) { return null; } } }); } static public List quickScan() { return scan(quickScanFrom, quickScanTo); } static public List quickBotScan() { return quickBotScan(new int[0]); } static public List quickBotScan(int[] preferredPorts) { if (maxNumberOfVMs == 0) maxNumberOfVMs = isAndroid() ? maxNumberOfVMs_android : maxNumberOfVMs_nonAndroid; return scan(4999, 5000 + maxNumberOfVMs - 1, preferredPorts); } } static public class RegExp implements IFieldsToList { static final public String _fieldOrder = "pattern caseInsensitive compiled error"; public String pattern; public boolean caseInsensitive = false; public RegExp() { } public RegExp(String pattern, boolean caseInsensitive) { this.caseInsensitive = caseInsensitive; this.pattern = pattern; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + pattern + ", " + caseInsensitive + ")"; } public boolean equals(Object o) { if (!(o instanceof RegExp)) return false; RegExp __1 = (RegExp) o; return eq(pattern, __1.pattern) && eq(caseInsensitive, __1.caseInsensitive); } public int hashCode() { int h = -1850962679; h = boostHashCombine(h, _hashCode(pattern)); h = boostHashCombine(h, _hashCode(caseInsensitive)); return h; } public Object[] _fieldsToList() { return new Object[] { pattern, caseInsensitive }; } transient public Pattern compiled; public String error; public RegExp(String pattern) { this.pattern = pattern; } final public java.util.regex.Pattern get() { return compile(); } public java.util.regex.Pattern compile() { try { if (compiled == null) compiled = compileRegexpPossiblyIC(pattern, caseInsensitive); error = null; return compiled; } catch (Throwable e) { error = exceptionToStringShort(e); return null; } } public boolean valid() { return compile() != null; } public boolean containsSpecialChars() { return containsRegExpSpecialChars(pattern); } public boolean containedIn(String s) { return regexpContains(getForce(), s); } public java.util.regex.Pattern getForce() { var pattern = get(); if (error != null) throw fail(error, pattern); return pattern; } } static public class PersistableOKOrError implements IF0 { public A value; final public PersistableThrowable getError() { return error(); } public PersistableThrowable error() { return error; } public PersistableThrowable error; public PersistableOKOrError() { } public PersistableOKOrError(A value) { this.value = value; } public PersistableOKOrError(boolean dummy, PersistableThrowable error) { this.error = error; assertNotNull(error); } final public boolean isOK() { return ok(); } public boolean ok() { return error == null; } public String toString() { return ok() ? str(value) : "Error: " + str(error); } public A get() { return !ok() ? null : value; } public A getMandatory() { if (!ok()) throw error.asRuntimeException(); return value; } static public PersistableOKOrError ok(A a) { return new PersistableOKOrError(a); } static public PersistableOKOrError error(PersistableThrowable error) { return new PersistableOKOrError(false, error); } } static public class JustCountingOutputStream extends OutputStream { public long counter; @Override public void write(int b) throws IOException { ++counter; } @Override public void write(byte[] b) throws IOException { counter += b.length; } @Override public void write(byte[] b, int off, int len) throws IOException { counter += len; } final public long get() { return getFilePointer(); } public long getFilePointer() { return counter; } } static public class DefaultButtonBorder extends JPanel { public JButton button; public DefaultButtonBorder(JButton button) { super(new BorderLayout()); this.button = button; setBorder(makeBorder()); add(button); onEnabledChanged(button, () -> setBorder(makeBorder())); } public Border makeBorder() { return BorderFactory.createLineBorder(utils.isEnabled(button) ? Color.black : Color.lightGray); } } static abstract public class F0 { abstract public A get(); } static abstract public class F1 { abstract public B get(A a); } abstract static public class RandomAccessAbstractList extends AbstractList implements RandomAccess { } static abstract public class F2 { abstract public C get(A a, B b); } static public class RGB { public float r, g, b; public RGB() { } public RGB(float brightness) { r = g = b = brightness; } public RGB(float r, float g, float b) { this.r = r; this.g = g; this.b = b; } public RGB(double r, double g, double b) { this.r = (float) r; this.g = (float) g; this.b = (float) b; } public RGB(double[] rgb) { this(rgb[0], rgb[1], rgb[2]); } public RGB(int rgb) { r = rgbRed(rgb) / 255f; g = rgbGreen(rgb) / 255f; b = rgbBlue(rgb) / 255f; } public RGB(double brightness) { this((float) brightness); } public RGB(Color color) { r = color.getRed() / 255f; g = color.getGreen() / 255f; b = color.getBlue() / 255f; } public RGB(String hex) { int i = l(hex) - 6; r = Integer.parseInt(hex.substring(i, i + 2), 16) / 255f; g = Integer.parseInt(hex.substring(i + 2, i + 4), 16) / 255f; b = Integer.parseInt(hex.substring(i + 4, i + 6), 16) / 255f; } public float getComponent(int i) { return i == 0 ? r : i == 1 ? g : b; } public int getInt(int i) { return i == 0 ? redInt() : i == 1 ? greenInt() : blueInt(); } public Color getColor() { return new Color(clampZeroToOne(r), clampZeroToOne(g), clampZeroToOne(b)); } public static RGB newSafe(float r, float g, float b) { return new RGB(Math.max(0, Math.min(1, r)), Math.max(0, Math.min(1, g)), Math.max(0, Math.min(1, b))); } public int asInt() { return getColor().getRGB() & 0xFFFFFF; } public int getInt() { return getColor().getRGB() & 0xFFFFFF; } public int asIntWithAlpha() { return rgbInt(redInt(), greenInt(), blueInt()) | 0xFF000000; } final public float brightness() { return getBrightness(); } public float getBrightness() { return (r + g + b) / 3.0f; } public String getHexString() { return Integer.toHexString(asInt() | 0xFF000000).substring(2).toUpperCase(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RGB)) return false; RGB rgb = (RGB) o; if (Float.compare(rgb.b, b) != 0) return false; if (Float.compare(rgb.g, g) != 0) return false; if (Float.compare(rgb.r, r) != 0) return false; return true; } @Override public int hashCode() { int result = (r != +0.0f ? Float.floatToIntBits(r) : 0); result = 31 * result + (g != +0.0f ? Float.floatToIntBits(g) : 0); result = 31 * result + (b != +0.0f ? Float.floatToIntBits(b) : 0); return result; } public boolean isBlack() { return r == 0f && g == 0f && b == 0f; } public boolean isWhite() { return r == 1f && g == 1f && b == 1f; } public boolean isGrayscale() { return r == g && g == b; } public String toString() { return isGrayscale() ? formatChannel(r) : spaceCombine("RGB", formatChannel(r), formatChannel(g), formatChannel(b)); } public String formatChannel(float value) { return formatDouble(value, 2); } public int redInt() { return iround(r * 255); } public int greenInt() { return iround(g * 255); } public int blueInt() { return iround(b * 255); } static public float brightnessToFloat(int brightness) { return brightness / 255f; } public RGB cloneMe() { return new RGB(r, g, b); } } static final public class IntPair implements Comparable, IFieldsToList { public int a; public int b; public IntPair() { } public IntPair(int a, int b) { this.b = b; this.a = a; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + a + ", " + b + ")"; } public Object[] _fieldsToList() { return new Object[] { a, b }; } public boolean equals(Object o) { if (!(o instanceof IntPair)) return false; IntPair x = (IntPair) o; return a == x.a && b == x.b; } public int hashCode() { int h = -672893111; h = boostHashCombine(h, _hashCode(a)); h = boostHashCombine(h, _hashCode(b)); return h; } public int compareTo(IntPair p) { if (p == null) return 1; int pa = p.a; if (a < pa) return -1; if (a > pa) return 1; return Integer.compare(b, p.b); } } static public class HasChangeListeners implements IHasChangeListeners, ChangeTriggerable { transient public Set onChange; public HasChangeListeners onChange(Runnable r) { onChange = createOrAddToSyncLinkedHashSet(onChange, r); return this; } public HasChangeListeners removeChangeListener(Runnable r) { utils.remove(onChange, r); return this; } public void change() { if (onChange != null) for (var listener : onChange) pcallF_typed(listener); } } static abstract public class F3 { abstract public D get(A a, B b, C c); } static public class BoolVar { public boolean a = false; public BoolVar() { } public BoolVar(boolean a) { this.a = a; } public synchronized void set() { set(true); } public synchronized void set(boolean v) { if (v != a) { a = v; notifyAll(); } } public synchronized boolean get() { return a; } final public void unset() { clear(); } public void clear() { set(false); } public boolean waitUntilTrue() { return waitForValue(true); } public boolean waitUntilFalse() { return waitForValue(false); } public boolean waitUntilTrue(double timeoutSeconds) { return waitForValue(timeoutSeconds, true); } public boolean waitUntilFalse(double timeoutSeconds) { return waitForValue(timeoutSeconds, false); } synchronized public boolean waitForValue(boolean wantedValue) { try { while (a != wantedValue) wait(); return a; } catch (Exception __e) { throw rethrow(__e); } } synchronized public boolean waitForValue(double timeoutSeconds, boolean wantedValue) { try { if (timeoutSeconds == infinity()) return waitForValue(wantedValue); long destTime = sysNowPlusSeconds_noPing(timeoutSeconds), remainingTime; while (a != wantedValue && (remainingTime = destTime - sysNow_noPing()) > 0) wait(remainingTime); return a; } catch (Exception __e) { throw rethrow(__e); } } public synchronized boolean getAndSet(boolean b) { var value = a; set(b); return value; } public synchronized boolean waitUntilTrueAndClear() { if (!waitUntilTrue()) return false; set(false); return true; } public synchronized boolean waitUntilTrueAndClear(double timeoutSeconds) { if (!waitUntilTrue(timeoutSeconds)) return false; set(false); return true; } public Object mutex() { return this; } } static final public class WidthAndHeightFinal extends Meta implements WidthAndHeight, ByteIO, IFieldsToList { static final public String _fieldOrder = "width height"; public int width; public int height; public WidthAndHeightFinal() { } public WidthAndHeightFinal(int width, int height) { this.height = height; this.width = width; } public boolean equals(Object o) { if (!(o instanceof WidthAndHeightFinal)) return false; WidthAndHeightFinal __0 = (WidthAndHeightFinal) o; return width == __0.width && height == __0.height; } public int hashCode() { int h = -1177452162; h = boostHashCombine(h, _hashCode(width)); h = boostHashCombine(h, _hashCode(height)); return h; } public Object[] _fieldsToList() { return new Object[] { width, height }; } public int getWidth() { return width; } public int getHeight() { return height; } public WidthAndHeightFinal(int wAndH) { this(wAndH, wAndH); } public String toString() { return n2(width) + "*" + n2(height) + " px"; } public void readWrite(ByteHead head) { head.exchangeInt(() -> width(), w -> width = w); head.exchangeInt(() -> height(), h -> height = h); } } static public interface IHasGlobalID { public GlobalID globalID(); } static public class ConceptFieldIndexCI extends ConceptFieldIndexBase { public ConceptFieldIndexCI(Class cc, String field) { super(cc, field); } public ConceptFieldIndexCI(Concepts concepts, Class cc, String field) { super(concepts, cc, field); } public void init() { valueToObject = generalizedCIMultiSetMap(); } public void register() { concepts.addCIFieldIndex(cc, field, this); } } static public class FormLayout1 extends AbstractLayoutManager { public void layoutContainer(Container parent) { List l = getComponents(parent); BitSet bigOnes = new BitSet(); for (int i = 0; i < l(l); i++) if (containsATextArea(l.get(i))) add(bigOnes, i); int nBigOnes = bigOnes.cardinality(); int mandatoryHeight = totalPreferredHeight(listWithoutIndicesInBitSet(l, bigOnes)); int gap = 4, outerSpacing = 5; Dimension size = parent.getSize(); int gapsAndMargins = outerSpacing * 2 + (l(l) - 1) * gap; int totalSpace = size.height - gapsAndMargins; int liberalSpace = totalSpace - mandatoryHeight; double perBigOne = doubleRatio(liberalSpace, nBigOnes); double y = outerSpacing; for (int i = 0; i < l(l); i++) { Component c = l.get(i); boolean big = contains(bigOnes, i); double h = big ? perBigOne : c.getPreferredSize().height; int actualY = iround(y); c.setBounds(outerSpacing, actualY, size.width - outerSpacing * 2, iround(y + h) - actualY); y += h + gap; } Dimension pref = componentsBoundingSize(parent, outerSpacing); if (parent.getHeight() <= 0) { int tph = totalPreferredHeight(l); pref.height = tph + gapsAndMargins; } preferredSize(pref); } } public interface IRecognizedBox { default public Rect bounds() { return null; } default public String label() { return null; } default public double confidence() { return 1.0; } } static public class StringHead implements Closeable { final public StringHead setReadMode(boolean readMode) { return readMode(readMode); } public StringHead readMode(boolean readMode) { this.readMode = readMode; return this; } final public boolean getReadMode() { return readMode(); } public boolean readMode() { return readMode; } public boolean readMode = false; final public StringHead setWriteMode(boolean writeMode) { return writeMode(writeMode); } public StringHead writeMode(boolean writeMode) { this.writeMode = writeMode; return this; } final public boolean getWriteMode() { return writeMode(); } public boolean writeMode() { return writeMode; } public boolean writeMode = false; final public BufferedReader getReader() { return reader(); } public BufferedReader reader() { return reader; } public BufferedReader reader; final public Writer getWriter() { return writer(); } public Writer writer() { return writer; } public Writer writer; public StringHead() { } public StringHead(Reader reader) { reader(reader); } public StringHead(Writer writer) { writer(writer); } public StringHead reader(Reader reader) { this.reader = bufferedReader(reader); readMode(true); return this; } public StringHead writer(Writer writer) { this.writer = writer; writeMode(true); return this; } public void finish() { } public String readLine() { String line = readLineFromReader(reader); if (line == null) close(); return line; } public void writeLine(String line) { try { writer.write(line); writer.write('\n'); } catch (Exception __e) { throw rethrow(__e); } } public void exchangeLine(IF0 getter, IVF1 setter) { if (writeMode()) writeLine(getter.get()); if (readMode()) setter.get(readLine()); } public void close() { try { { cleanUp(reader); reader = null; } { cleanUp(writer); writer = null; } } catch (Exception __e) { throw rethrow(__e); } } public void exchange(StringIO writable) { if (writable != null) writable.readWrite(this); } public void exchangeAll(Iterable writables) { if (writables != null) for (var writable : writables) exchange(writable); } } public interface MakesBWImage { public BWImage getBWImage(); } static public class CenteredComboBoxRenderer implements ListCellRenderer, IFieldsToList { public ListCellRenderer baseRenderer; public CenteredComboBoxRenderer() { } public CenteredComboBoxRenderer(ListCellRenderer baseRenderer) { this.baseRenderer = baseRenderer; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + baseRenderer + ")"; } public Object[] _fieldsToList() { return new Object[] { baseRenderer }; } final public CenteredComboBoxRenderer setCenterItems(boolean centerItems) { return centerItems(centerItems); } public CenteredComboBoxRenderer centerItems(boolean centerItems) { this.centerItems = centerItems; return this; } final public boolean getCenterItems() { return centerItems(); } public boolean centerItems() { return centerItems; } public boolean centerItems = false; public Component getListCellRendererComponent(JList list, A value, int index, boolean isSelected, boolean cellHasFocus) { var c = baseRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (c instanceof JLabel) { if (centerItems() || index < 0) centerLabel((JLabel) c); else leftAlignLabel((JLabel) c); } return c; } } static public class VirtualVar extends HasChangeListeners implements IVarWithNotify, IFieldsToList { public IF0 getter; public IVF1 setter; public VirtualVar() { } public VirtualVar(IF0 getter, IVF1 setter) { this.setter = setter; this.getter = getter; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + getter + ", " + setter + ")"; } public boolean equals(Object o) { if (!(o instanceof VirtualVar)) return false; VirtualVar __1 = (VirtualVar) o; return eq(getter, __1.getter) && eq(setter, __1.setter); } public int hashCode() { int h = -393827268; h = boostHashCombine(h, _hashCode(getter)); h = boostHashCombine(h, _hashCode(setter)); return h; } public Object[] _fieldsToList() { return new Object[] { getter, setter }; } public void set(A a) { { if (setter != null) setter.get(a); } } public A get() { return getter == null ? null : getter.get(); } } static public class SynchronizedList extends SynchronizedCollection implements List { public SynchronizedList() { } public List list; public SynchronizedList(List list) { super(list); this.list = list; } public SynchronizedList(List list, Object mutex) { super(list, mutex); this.list = list; } public boolean equals(Object o) { if (this == o) return true; synchronized (mutex) { return list.equals(o); } } public int hashCode() { synchronized (mutex) { return list.hashCode(); } } public E get(int index) { synchronized (mutex) { return list.get(index); } } public E set(int index, E element) { synchronized (mutex) { return list.set(index, element); } } public void add(int index, E element) { synchronized (mutex) { list.add(index, element); } } public E remove(int index) { synchronized (mutex) { return list.remove(index); } } public int indexOf(Object o) { synchronized (mutex) { return list.indexOf(o); } } public int lastIndexOf(Object o) { synchronized (mutex) { return list.lastIndexOf(o); } } public boolean addAll(int index, Collection c) { synchronized (mutex) { return list.addAll(index, c); } } public ListIterator listIterator() { return list.listIterator(); } public ListIterator listIterator(int index) { return list.listIterator(index); } public List subList(int fromIndex, int toIndex) { synchronized (mutex) { return new SynchronizedList<>(list.subList(fromIndex, toIndex), mutex); } } @Override public void replaceAll(java.util.function.UnaryOperator operator) { synchronized (mutex) { list.replaceAll(operator); } } @Override public void sort(Comparator c) { synchronized (mutex) { list.sort(c); } } @java.io.Serial private Object readResolve() { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list) : this); } } final static public class _MethodCache { final public Class c; final public HashMap> cache = new HashMap(); public _MethodCache(Class c) { this.c = c; _init(); } public void _init() { Class _c = c; java.lang.Module myModule = getClass().getModule(); boolean anyHiddenClasses = false; while (_c != null) { boolean exported = classIsExportedTo(_c, myModule); if (!exported) anyHiddenClasses = true; else for (Method m : _c.getDeclaredMethods()) if ((anyHiddenClasses || !isAbstract(m)) && !reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); _c = _c.getSuperclass(); } for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if ((anyHiddenClasses || m.isDefault()) && !reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); } public Method findMethod(String method, Object[] args) { try { List m = cache.get(method); if (m == null) return null; int n = m.size(); for (int i = 0; i < n; i++) { Method me = m.get(i); if (call_checkArgs(me, args, false)) return me; } return null; } catch (Exception __e) { throw rethrow(__e); } } public Method findStaticMethod(String method, Object[] args) { try { List m = cache.get(method); if (m == null) return null; int n = m.size(); for (int i = 0; i < n; i++) { Method me = m.get(i); if (isStaticMethod(me) && call_checkArgs(me, args, false)) return me; } return null; } catch (Exception __e) { throw rethrow(__e); } } } static abstract public class LiveValue implements IF0WithChangeListeners { abstract public Class getType(); public abstract A get(); } abstract static public class AbstractHasHi15Color { public AbstractHasHi15Color() { } final public AbstractHasHi15Color setHi15color(short hi15color) { return hi15color(hi15color); } public AbstractHasHi15Color hi15color(short hi15color) { this.hi15color = hi15color; return this; } final public short getHi15color() { return hi15color(); } public short hi15color() { return hi15color; } public short hi15color; public Color color() { return utils.hi15color(hi15color); } public AbstractHasHi15Color color(Color color) { return hi15color(colorToHi15(color)); } public String colorToString() { return lower(colorToHex(color())); } } static public class proxy_InvocationHandler implements InvocationHandler { public Object target; public proxy_InvocationHandler() { } public proxy_InvocationHandler(Object target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) { return call(target, method.getName(), unnull(args)); } } static public class MethodMaker { public ClassGen cg; public MethodGen mg; public InstructionList il = new InstructionList(); public ConstantPoolGen cp; public InstructionFactory factory; public int frameSize; public org.apache.bcel.generic.Type[] argTypes; public int[] argStackIndex; final public MethodMaker setVerboseAdd(boolean verboseAdd) { return verboseAdd(verboseAdd); } public MethodMaker verboseAdd(boolean verboseAdd) { this.verboseAdd = verboseAdd; return this; } final public boolean getVerboseAdd() { return verboseAdd(); } public boolean verboseAdd() { return verboseAdd; } public boolean verboseAdd = false; public boolean classConstantWorkaround = false; public MethodMaker(ClassMaker classMaker, Class returnType, String methodName, Class... argumentTypes) { this(classMaker.cg, returnType, methodName, argumentTypes); } public MethodMaker(ClassGen cg, Class returnType, String methodName, Class... argumentTypes) { this(cg, Const.ACC_PUBLIC, returnType, methodName, argumentTypes); } public MethodMaker(ClassGen cg, short modifiers, Object returnType, String methodName, Object... argumentTypes) { this.cg = cg; cp = cg.getConstantPool(); factory = new InstructionFactory(cg); argTypes = wrapTypes(argumentTypes); mg = new MethodGen(modifiers, wrapType(returnType), argTypes, null, methodName, cg.getClassName(), il, cp); layoutStack(); } public MethodMaker(ClassGen cg, short modifiers, Class returnType, String methodName, Class... argumentTypes) { this.cg = cg; cp = cg.getConstantPool(); factory = new InstructionFactory(cg); argTypes = wrapTypes(argumentTypes); mg = new MethodGen(modifiers, wrapType(returnType), argTypes, null, methodName, cg.getClassName(), il, cp); layoutStack(); } public void layoutStack() { frameSize = 1; argStackIndex = new int[l(argTypes)]; for (int i = 0; i < l(argTypes); i++) { argStackIndex[i] = frameSize; frameSize += eqOneOf(argTypes[i], org.apache.bcel.generic.Type.LONG, org.apache.bcel.generic.Type.DOUBLE) ? 2 : 1; } } static public org.apache.bcel.generic.Type[] wrapTypes(Object[] classes) { org.apache.bcel.generic.Type[] types = new org.apache.bcel.generic.Type[l(classes)]; for (int i = 0; i < l(classes); i++) types[i] = wrapType(classes[i]); return types; } static public org.apache.bcel.generic.Type wrapType(Object o) { if (o instanceof Class) return classToBCELType((Class) o); if (o instanceof String) { Class c = parsePrimitiveType((String) o); if (c != null) return classToBCELType(c); return new ObjectType((String) o); } return null; } public int newLocalVar() { return frameSize++; } public MethodMaker newObject(Class c, Class... argTypes) { il.append(factory.createNew(className(c))); il.append(InstructionConst.DUP); invokeConstructor(c, argTypes); return this; } public MethodMaker invokeConstructor(Class c, Class... argTypes) { Constructor ctor = findConstructor_precise_onTypes(c, argTypes); il.append(factory.createInvoke(className(c), "", org.apache.bcel.generic.Type.VOID, wrapTypes(ctor.getParameterTypes()), Const.INVOKESPECIAL)); return this; } public MethodMaker dup() { il.append(InstructionConst.DUP); return this; } public MethodMaker astore(int var) { il.append(new ASTORE(var)); return this; } public int argIdx(int iArg) { return argStackIndex[iArg]; } public MethodMaker aloadArgWithAutoboxing(int iArg) { var type = argTypes[iArg]; int stackIdx = argStackIndex[iArg]; if (type == org.apache.bcel.generic.Type.BYTE) { il.append(new ILOAD(stackIdx)); invokeStatic(Byte.class, Byte.class, "valueOf", byte.class); return this; } if (type == org.apache.bcel.generic.Type.BOOLEAN) { il.append(new ILOAD(stackIdx)); invokeStatic(Boolean.class, Boolean.class, "valueOf", boolean.class); return this; } if (type == org.apache.bcel.generic.Type.CHAR) { il.append(new ILOAD(stackIdx)); invokeStatic(Character.class, Character.class, "valueOf", char.class); return this; } if (type == org.apache.bcel.generic.Type.SHORT) { il.append(new ILOAD(stackIdx)); invokeStatic(Short.class, Short.class, "valueOf", short.class); return this; } if (type == org.apache.bcel.generic.Type.INT) { il.append(new ILOAD(stackIdx)); invokeStatic(Integer.class, Integer.class, "valueOf", int.class); return this; } if (type == org.apache.bcel.generic.Type.LONG) { il.append(new LLOAD(stackIdx)); invokeStatic(Long.class, Long.class, "valueOf", long.class); return this; } if (type == org.apache.bcel.generic.Type.FLOAT) { il.append(new LLOAD(stackIdx)); invokeStatic(Float.class, Float.class, "valueOf", float.class); return this; } if (type == org.apache.bcel.generic.Type.DOUBLE) { il.append(new DLOAD(stackIdx)); invokeStatic(Double.class, Double.class, "valueOf", double.class); return this; } return aload(stackIdx); } public MethodMaker aload(int stackIdx) { il.append(new ALOAD(stackIdx)); return this; } public MethodMaker stringConstant(String s) { il.append(new PUSH(cp, s)); return this; } public MethodMaker classConstant(Class c) { if (classConstantWorkaround) { stringConstant(c.getName()); invokeStatic(Class.class, Class.class, "forName", String.class); } else { var ldc = new LDC(classRef(c)); assertEquals("classConstant", ldc.getValue(cp), wrapType(c)); il.append(ldc); } return this; } final public MethodMaker intConst(int i) { return intConstant(i); } public MethodMaker intConstant(int i) { if (i >= -1 && i <= 5) return add(new ICONST(i)); if (i == (byte) i) return add(new BIPUSH((byte) i)); if (i == (short) i) return add(new SIPUSH((short) i)); return add(new LDC(cp.addInteger(i))); } final public MethodMaker doubleConst(double d) { return doubleConstant(d); } public MethodMaker doubleConstant(double d) { return add(new LDC2_W(cp.addDouble(d))); } public MethodMaker boolConstant(boolean b) { return intConstant(b ? 1 : 0); } public MethodMaker invokeVirtual(Class c, Class returnType, String methodName, Class... argTypes) { Method m = findNonStaticMethod_precise_onTypes(c, methodName, argTypes); if (m == null) throw fail("Method not found: " + className(c) + "." + formatFunctionCall(methodName, argTypes) + " returning " + className(returnType)); il.append(factory.createInvoke(className(c), methodName, wrapType(m.getReturnType()), wrapTypes(m.getParameterTypes()), Const.INVOKEVIRTUAL)); return this; } public MethodMaker invokeInterface(Class c, Class returnType, String methodName, Class... argTypes) { Method m = mostApplicableMethod_onTypes(filter(nonDefaultInterfaceMethods(c), _m -> _m.getName().equals(methodName)), argTypes); if (m == null) throw fail("Method not found: " + className(c) + "." + formatFunctionCall(methodName, argTypes) + " returning " + className(returnType)); il.append(factory.createInvoke(className(c), methodName, wrapType(m.getReturnType()), wrapTypes(m.getParameterTypes()), Const.INVOKEINTERFACE)); return this; } public MethodMaker invokeStatic(Class c, Class returnType, String methodName, Class... argTypes) { Method m = findMethod_precise_onTypes(c, methodName, argTypes); if (m == null) throw fail("Method not found: " + className(c) + "." + formatFunctionCall(methodName, argTypes) + " returning " + className(returnType)); il.append(factory.createInvoke(className(c), methodName, wrapType(m.getReturnType()), wrapTypes(m.getParameterTypes()), Const.INVOKESTATIC)); return this; } public MethodMaker areturn() { il.append(InstructionConst.ARETURN); return this; } public MethodMaker _return() { il.append(InstructionConst.RETURN); return this; } public MethodMaker returnPrimitive(Class type) { il.append(primitiveReturnInstruction(type)); return this; } public ReturnInstruction primitiveReturnInstruction(Class type) { assertTrue(isPrimitiveType(type)); if (type == long.class) return InstructionConst.LRETURN; if (type == float.class) return InstructionConst.FRETURN; if (type == double.class) return InstructionConst.DRETURN; return InstructionConst.IRETURN; } public MethodMaker add(Instruction i) { il.append(i); if (verboseAdd) print("> " + i); return this; } public A addAndReturn(A i) { add(i); return i; } public MethodMaker add(BranchInstruction i) { il.append(i); if (verboseAdd) print("> " + i); return this; } public A addAndReturn(A i) { add(i); return i; } public void done() { mg.stripAttributes(true); mg.setMaxStack(); mg.setMaxLocals(); cg.addMethod(mg.getMethod()); } public JVMStackCellType convertToObject(JVMStackCellType stackTop) { if (stackTop == JVMStackCellType.objValue) { } else if (stackTop == JVMStackCellType.intValue) invokeStatic(Integer.class, Integer.class, "valueOf", int.class); else if (stackTop == JVMStackCellType.doubleValue) invokeStatic(Double.class, Double.class, "valueOf", double.class); else if (stackTop == JVMStackCellType.none) add(new ACONST_NULL()); else throw fail("TODO: add conversion for stack cell type: " + stackTop); return JVMStackCellType.objValue; } public void discardStackTop(JVMStackCellType stackTop) { if (stackTop == JVMStackCellType.none) { } else if (stackTop == JVMStackCellType.doubleValue || stackTop == JVMStackCellType.longValue) add(new POP2()); else add(new POP()); } public int classRef(Object c) { return cp.addClass((ObjectType) wrapType(assertNotNull(c))); } public MethodMaker checkCast(Object c) { return add(new CHECKCAST(classRef(c))); } public MethodMaker loadNull() { return add(new ACONST_NULL()); } public InstructionHandle here() { return il.append(new NOP()); } public GOTO forwardGoto() { return addAndReturn(new GOTO(null)); } public void returnWithType(JVMStackCellType stackTop) { if (stackTop == JVMStackCellType.objValue) areturn(); else if (stackTop == JVMStackCellType.intValue) add(new IRETURN()); else if (stackTop == JVMStackCellType.doubleValue) add(new DRETURN()); else if (stackTop == JVMStackCellType.none) _return(); else throw fail("TODO: add return for stack cell type: " + stackTop); } public void getStaticField(String className, String fieldName, Class type) { il.append(factory.createGetStatic(className, fieldName, wrapType(type))); } } public interface RunnableWithExceptions { public void run() throws Exception; } static public class EphemeralObjectIDs { public long idCounter; public WeakValueMap idToObject = new WeakValueMap(); public Map objectToID = weakIdentityMap(); public EphemeralObjectIDs runnablesReferenceQueue(RunnablesReferenceQueue queue) { idToObject.queue(queue); return this; } synchronized public long remember(Object o) { if (o == null) return 0; { var __1 = objectToID.get(o); if (__1 != null) return __1; } long id = ++idCounter; idToObject.put(id, o); objectToID.put(o, id); return id; } synchronized public Object get(long id) { if (id == 0) return null; return idToObject.get(id); } synchronized public boolean wasGarbageCollected(long id) { return id > 0 && id <= idCounter && get(id) == null; } } static public class JavaXClassLoader extends URLClassLoader { public String progID; public Set files = syncLinkedHashSet(); public Set libraryIDs = syncLinkedHashSet(); public Set triedToLoad = synchroSet(); public Set loadedClasses = synchroSet(); public boolean retired = false; public Object retiredMarker; public IF1 findClass_extension; public String mainClassName; public boolean verbose = false; public JavaXClassLoader(String progID, List files) { this(progID, files, getSystemClassLoader()); } public JavaXClassLoader(String progID, List files, ClassLoader parent) { super(new URL[0], parent); this.progID = progID; for (File f : unnullForIteration(files)) addFile(f); fixACCInClassLoader(this); } public Class super_findClass(String name) throws ClassNotFoundException { return super.findClass(name); } public Class findClass(String name) throws ClassNotFoundException { if (verbose) System.out.println(this + " findClass: " + name); if (findClass_extension != null) { Class c = findClass_extension.get(name); if (verbose) System.out.println("extension returned: " + c); if (c != null) return c; } boolean triedBefore = !triedToLoad.add(name); try { Class c = super.findClass(name); if (verbose) System.out.println("super.findClass returned: " + c); loadedClasses.add(c); if (eq(name, mainClassName())) callOpt(javax(), "registerAMainClass", c); return c; } catch (ClassNotFoundException e) { if (verbose) System.out.println(getStackTrace(e)); throw new ClassNotFoundException("Class " + name + " not found in " + joinWithComma(map(__141 -> f2s(__141), files)) + " (progID=" + progID + ")" + (triedBefore ? ", tried to load before" : ""), e); } } public String toString() { return shortClassName(this) + "[" + systemHashCodeHex(this) + "] - " + progID; } public String mainClassName() { if (mainClassName == null) { mainClassName = "main"; try { mainClassName = or2(trim(loadTextFileResource(this, "main-class")), mainClassName); } catch (Throwable __e) { pcallFail(__e); } } return mainClassName; } public boolean addFile(File f, String libraryID) { if (nempty(libraryID)) if (!libraryIDs.add(libraryID)) return false; return addFile(f); } public boolean addFile(File f) { try { if (!files.add(f)) return false; addURL(f.toURI().toURL()); mainClassName(); return true; } catch (Exception __e) { throw rethrow(__e); } } public Set libraryIDs() { return libraryIDs; } public boolean hasLibraryID(String libraryID) { return libraryIDs.contains(libraryID); } transient public IF1 findLibrary; public String findLibrary(String libname) { return findLibrary != null ? findLibrary.get(libname) : findLibrary_base(libname); } final public String findLibrary_fallback(IF1 _f, String libname) { return _f != null ? _f.get(libname) : findLibrary_base(libname); } public String findLibrary_base(String libname) { return super.findLibrary(libname); } public void addURL(URL url) { super.addURL(url); } } abstract static public class Probabilistic extends Meta implements IProbabilistic, Steppable { public IProbabilisticScheduler ps; public void initScheduler() { if (ps == null) setScheduler(new ProbabilisticScheduler()); } public void setScheduler(IProbabilisticScheduler ps) { this.ps = ps; } public IProbabilisticScheduler scheduler() { initScheduler(); return ps; } final public void at(Runnable action) { schedule(action); } public void schedule(Runnable action) { scheduleRelative(1.0, action); } final public void at(double probability, Runnable action) { schedule(probability, action); } public void schedule(double probability, Runnable action) { initScheduler(); ps.at(probability, action); } final public void atRelative(double probability, Runnable action) { scheduleRelative(probability, action); } public void scheduleRelative(double probability, Runnable action) { initScheduler(); ps.atRelative(probability, action); } public void scheduleAll(Iterable actions) { forEach(__142 -> schedule(__142), actions); } public void scheduleAll(double probability, Iterable actions) { forEach(actions, a -> schedule(probability, a)); } public void scheduleAllRelative(double probability, Iterable actions) { forEach(actions, a -> scheduleRelative(probability, a)); } public void stepAll() { utils.stepAll(scheduler()); } public boolean step() { return scheduler().step(); } public void runFor(double seconds) { stepForNSeconds(seconds, scheduler()); } } static public class Flattener { public List out = new ArrayList(); public Flattener() { } public Flattener(Object... l) { add(l); } public void add(Object o) { if (o instanceof Object[]) for (var x : ((Object[]) o)) add(x); else if (o instanceof Iterable) for (var x : ((Iterable) o)) add(x); else if (o != null) out.add(o); } public void add(Object... l) { add((Object) l); } public List toList() { return out; } public Object[] toArray() { return toObjectArray(out); } } static public class FlexibleRateTimer implements AutoCloseable { public double hertz; transient public Runnable action; transient public double timestamp; transient public DoLater doLater; transient public Flag started = new Flag(); transient volatile public boolean disposed = false; transient public long delay; transient public List onFrequencyChanged; transient public boolean verbose = false; final public FlexibleRateTimer setSleeper(ISleeper_v2 sleeper) { return sleeper(sleeper); } public FlexibleRateTimer sleeper(ISleeper_v2 sleeper) { this.sleeper = sleeper; return this; } final public ISleeper_v2 getSleeper() { return sleeper(); } public ISleeper_v2 sleeper() { return sleeper; } public ISleeper_v2 sleeper = defaultSleeper(); final public FlexibleRateTimer setPileUp(boolean pileUp) { return pileUp(pileUp); } public FlexibleRateTimer pileUp(boolean pileUp) { this.pileUp = pileUp; return this; } final public boolean getPileUp() { return pileUp(); } public boolean pileUp() { return pileUp; } public boolean pileUp = true; static public double minHertz = 0, actualMinHertz = 1e-8, maxHertz = 1000; public FlexibleRateTimer() { } public FlexibleRateTimer(double hertz) { this.hertz = hertz; } public FlexibleRateTimer(double hertz, Runnable action) { this.action = action; this.hertz = hertz; } public void start() { if (!started.raise()) return; if (verbose) print("Starting timer with " + hertz + " Hz"); vmBus_timerStarted(this); _kaboom(); } synchronized public void _kaboom() { try { if (verbose) print(disposed ? "Timer kaboom (disposed)" : "Timer kaboom"); if (disposed) return; { cleanUp(doLater); doLater = null; } if (hertz <= actualMinHertz) { timestamp = 0; return; } if (timestamp == 0) timestamp = sysNow(); timestamp += 1000 / getFrequency(); if (!pileUp) timestamp = max(sysNow(), timestamp); long _timestamp = lround(timestamp); doLater = new DoLater(_timestamp, new Runnable() { public void run() { try { delay = sysNow() - _timestamp; if (verbose) print("Timer action"); pcallF(action); _kaboom(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "delay = sysNow()-_timestamp;\r\n if (verbose) print(\"Timer action\");\r\n ..."; } }); doLater.sleeper(sleeper); if (verbose) print("Timer scheduled for: " + (_timestamp - sysNow())); doLater.enable(); } catch (Throwable __e) { pcallFail(__e); } } public void cancel() { close(); } public synchronized void close() { disposed = true; { cleanUp(doLater); doLater = null; } } public void setRunnableAndStart(Runnable action) { this.action = action; start(); } public void setFrequency(double hertz) { synchronized (this) { if (disposed) return; hertz = clamp(hertz, minHertz, maxHertz); if (hertz == this.hertz) return; this.hertz = hertz; } pcallFAll(onFrequencyChanged); } public void setFrequencyImmediately(double hertz) { synchronized (this) { if (disposed) return; hertz = clamp(hertz, minHertz, maxHertz); if (hertz == this.hertz) return; double oldHertz = this.hertz; this.hertz = hertz; if (!started.isUp()) return; if (verbose) print("Timer setFreq doLater=" + doLater); boolean b = doLater == null || doLater.cancel(); if (verbose) print("Timer cancel result: " + b + " (" + oldHertz + " -> " + hertz + ")"); timestamp = sysNow(); if (b) _kaboom(); } pcallFAll(onFrequencyChanged); } synchronized public double getFrequency() { return hertz; } public long currentDelay() { return delay; } synchronized public void onFrequencyChanged(Runnable r) { onFrequencyChanged = addOrCreate(onFrequencyChanged, r); } public void onFrequencyChangedAndNow(Runnable r) { onFrequencyChanged(runAndReturn(r)); } } static public class CachedPosterizer implements IPosterizer { public IPosterizer posterizer; public int[] cache; public CachedPosterizer(IPosterizer posterizer) { this.posterizer = posterizer; makeCache(); } public int get(int brightness) { return cache[brightness]; } public void makeCache() { cache = new int[256]; for (int brightness = 0; brightness < 256; brightness++) cache[brightness] = posterizer.get(brightness); } } static public class ByteBuffer implements Iterable { public byte[] data; public int size; public ByteBuffer() { } public ByteBuffer(int size) { if (size != 0) data = new byte[size]; } public ByteBuffer(Iterable l) { if (l instanceof Collection) allocate(((Collection) l).size()); addAll(l); } public ByteBuffer(byte[] data) { this.data = data; size = l(data); } public void add(int idx, int i) { add(0); arraycopy(data, idx, data, idx + 1, size - (idx + 1)); data[idx] = (byte) i; } public void add(int i) { add((byte) i); } public void add(byte i) { if (size >= lByteArray(data)) { allocate(Math.max(1, toInt(Math.min(maximumSafeArraySize(), lByteArray(data) * 2L)))); if (size >= data.length) throw fail("ByteBuffer too large: " + size); } data[size++] = i; } public void allocate(int n) { data = resizeByteArray(data, max(n, size())); } public void addAll(Iterable l) { if (l != null) for (byte i : l) add(i); } final public byte[] toByteArray() { return toArray(); } public byte[] toArray() { return size == 0 ? null : resizeByteArray(data, size); } public List toList() { return byteArrayToList(data, 0, size); } public List asVirtualList() { return new RandomAccessAbstractList() { public int size() { return size; } public Byte get(int i) { return ByteBuffer.this.get(i); } public Byte set(int i, Byte val) { Byte a = get(i); data[i] = val; return a; } }; } public void reset() { size = 0; } public void clear() { reset(); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public byte get(int idx) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); return data[idx]; } public void set(int idx, byte value) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); data[idx] = value; } public byte popLast() { if (size == 0) throw fail("empty buffer"); return data[--size]; } public byte popFirst() { if (size == 0) throw fail("empty buffer"); byte b = data[0]; arraycopy(data, 1, 0, --size); return b; } public byte last() { return data[size - 1]; } public byte nextToLast() { return data[size - 2]; } public String toString() { return squareBracket(joinWithSpace(toList())); } public Iterator iterator() { return new IterableIterator() { public int i = 0; public boolean hasNext() { return i < size; } public Byte next() { return data[i++]; } }; } public void trimToSize() { data = resizeByteArray(data, size); } public int indexOf(byte b) { for (int i = 0; i < size; i++) if (data[i] == b) return i; return -1; } public byte[] subArray(int start, int end) { return subByteArray(data, start, min(end, size)); } } static public class RangeSlider extends JSlider { public RangeSlider() { initSlider(); } public RangeSlider(int min, int max) { super(min, max); initSlider(); } private void initSlider() { setOrientation(HORIZONTAL); } @Override public void updateUI() { setUI(new RangeSliderUI(this)); updateLabelUIs(); } @Override public int getValue() { return super.getValue(); } @Override public void setValue(int value) { int oldValue = getValue(); if (oldValue == value) { return; } int oldExtent = getExtent(); int newValue = Math.min(Math.max(getMinimum(), value), oldValue + oldExtent); int newExtent = oldExtent + oldValue - newValue; getModel().setRangeProperties(newValue, newExtent, getMinimum(), getMaximum(), getValueIsAdjusting()); } public int getUpperValue() { return getValue() + getExtent(); } public void setUpperValue(int value) { int lowerValue = getValue(); int newExtent = Math.min(Math.max(0, value - lowerValue), getMaximum() - lowerValue); setExtent(newExtent); } public void setValues(int value, int upper) { setValue(value); setUpperValue(upper); } } static public class RangeSliderUI extends BasicSliderUI { public Color rangeColor = Color.GREEN; public Rectangle upperThumbRect; public boolean upperThumbSelected = false; transient public boolean lowerDragging = false; transient public boolean upperDragging = false; public RangeSliderUI(RangeSlider b) { super(b); } @Override public void installUI(JComponent c) { upperThumbRect = new Rectangle(); super.installUI(c); } @Override public TrackListener createTrackListener(JSlider slider) { return new RangeTrackListener(); } @Override public ChangeListener createChangeListener(JSlider slider) { return new ChangeHandler(); } @Override public void calculateThumbSize() { super.calculateThumbSize(); upperThumbRect.setSize(thumbRect.width, thumbRect.height); } @Override public void calculateThumbLocation() { super.calculateThumbLocation(); if (slider.getSnapToTicks()) { int upperValue = slider.getValue() + slider.getExtent(); int snappedValue = upperValue; int majorTickSpacing = slider.getMajorTickSpacing(); int minorTickSpacing = slider.getMinorTickSpacing(); int tickSpacing = 0; if (minorTickSpacing > 0) { tickSpacing = minorTickSpacing; } else if (majorTickSpacing > 0) { tickSpacing = majorTickSpacing; } if (tickSpacing != 0) { if ((upperValue - slider.getMinimum()) % tickSpacing != 0) { float temp = (float) (upperValue - slider.getMinimum()) / (float) tickSpacing; int whichTick = Math.round(temp); snappedValue = slider.getMinimum() + (whichTick * tickSpacing); } if (snappedValue != upperValue) { slider.setExtent(snappedValue - slider.getValue()); } } } if (slider.getOrientation() == JSlider.HORIZONTAL) { int upperPosition = xPositionForValue(slider.getValue() + slider.getExtent()); upperThumbRect.x = upperPosition - (upperThumbRect.width / 2); upperThumbRect.y = trackRect.y; } else { int upperPosition = yPositionForValue(slider.getValue() + slider.getExtent()); upperThumbRect.x = trackRect.x; upperThumbRect.y = upperPosition - (upperThumbRect.height / 2); } } @Override public Dimension getThumbSize() { return new Dimension(12, 12); } @Override public void paint(Graphics g, JComponent c) { super.paint(g, c); Rectangle clipRect = g.getClipBounds(); if (upperThumbSelected) { if (clipRect.intersects(thumbRect)) { paintLowerThumb(g); } if (clipRect.intersects(upperThumbRect)) { paintUpperThumb(g); } } else { if (clipRect.intersects(upperThumbRect)) { paintUpperThumb(g); } if (clipRect.intersects(thumbRect)) { paintLowerThumb(g); } } } @Override public void paintTrack(Graphics g) { super.paintTrack(g); Rectangle trackBounds = trackRect; if (slider.getOrientation() == JSlider.HORIZONTAL) { int lowerX = thumbRect.x + (thumbRect.width / 2); int upperX = upperThumbRect.x + (upperThumbRect.width / 2); int cy = (trackBounds.height / 2) - 2; Color oldColor = g.getColor(); g.translate(trackBounds.x, trackBounds.y + cy); g.setColor(rangeColor); for (int y = 0; y <= 3; y++) { g.drawLine(lowerX - trackBounds.x, y, upperX - trackBounds.x, y); } g.translate(-trackBounds.x, -(trackBounds.y + cy)); g.setColor(oldColor); } else { int lowerY = thumbRect.x + (thumbRect.width / 2); int upperY = upperThumbRect.x + (upperThumbRect.width / 2); int cx = (trackBounds.width / 2) - 2; Color oldColor = g.getColor(); g.translate(trackBounds.x + cx, trackBounds.y); g.setColor(rangeColor); for (int x = 0; x <= 3; x++) { g.drawLine(x, lowerY - trackBounds.y, x, upperY - trackBounds.y); } g.translate(-(trackBounds.x + cx), -trackBounds.y); g.setColor(oldColor); } } @Override public void paintThumb(Graphics g) { } private void paintLowerThumb(Graphics g) { Rectangle knobBounds = thumbRect; int w = knobBounds.width; int h = knobBounds.height; Graphics2D g2d = (Graphics2D) g.create(); Shape thumbShape = createThumbShape(w - 1, h - 1); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.translate(knobBounds.x, knobBounds.y); g2d.setColor(Color.CYAN); g2d.fill(thumbShape); g2d.setColor(Color.BLUE); g2d.draw(thumbShape); g2d.dispose(); } private void paintUpperThumb(Graphics g) { Rectangle knobBounds = upperThumbRect; int w = knobBounds.width; int h = knobBounds.height; Graphics2D g2d = (Graphics2D) g.create(); Shape thumbShape = createThumbShape(w - 1, h - 1); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.translate(knobBounds.x, knobBounds.y); g2d.setColor(Color.PINK); g2d.fill(thumbShape); g2d.setColor(Color.RED); g2d.draw(thumbShape); g2d.dispose(); } private Shape createThumbShape(int width, int height) { Ellipse2D shape = new Ellipse2D.Double(0, 0, width, height); return shape; } private void setUpperThumbLocation(int x, int y) { Rectangle upperUnionRect = new Rectangle(); upperUnionRect.setBounds(upperThumbRect); upperThumbRect.setLocation(x, y); SwingUtilities.computeUnion(upperThumbRect.x, upperThumbRect.y, upperThumbRect.width, upperThumbRect.height, upperUnionRect); slider.repaint(upperUnionRect.x, upperUnionRect.y, upperUnionRect.width, upperUnionRect.height); } public void scrollByBlock(int direction) { synchronized (slider) { int blockIncrement = (slider.getMaximum() - slider.getMinimum()) / 10; if (blockIncrement <= 0 && slider.getMaximum() > slider.getMinimum()) { blockIncrement = 1; } int delta = blockIncrement * ((direction > 0) ? POSITIVE_SCROLL : NEGATIVE_SCROLL); if (upperThumbSelected) { int oldValue = ((RangeSlider) slider).getUpperValue(); ((RangeSlider) slider).setUpperValue(oldValue + delta); } else { int oldValue = slider.getValue(); slider.setValue(oldValue + delta); } } } public void scrollByUnit(int direction) { synchronized (slider) { int delta = 1 * ((direction > 0) ? POSITIVE_SCROLL : NEGATIVE_SCROLL); if (upperThumbSelected) { int oldValue = ((RangeSlider) slider).getUpperValue(); ((RangeSlider) slider).setUpperValue(oldValue + delta); } else { int oldValue = slider.getValue(); slider.setValue(oldValue + delta); } } } public class ChangeHandler implements ChangeListener { public void stateChanged(ChangeEvent arg0) { if (!lowerDragging && !upperDragging) { calculateThumbLocation(); slider.repaint(); } } } public class RangeTrackListener extends TrackListener { @Override public void mousePressed(MouseEvent e) { if (!slider.isEnabled()) { return; } currentMouseX = e.getX(); currentMouseY = e.getY(); if (slider.isRequestFocusEnabled()) { slider.requestFocus(); } boolean lowerPressed = false; boolean upperPressed = false; if (upperThumbSelected || slider.getMinimum() == slider.getValue()) { if (upperThumbRect.contains(currentMouseX, currentMouseY)) { upperPressed = true; } else if (thumbRect.contains(currentMouseX, currentMouseY)) { lowerPressed = true; } } else { if (thumbRect.contains(currentMouseX, currentMouseY)) { lowerPressed = true; } else if (upperThumbRect.contains(currentMouseX, currentMouseY)) { upperPressed = true; } } if (lowerPressed) { switch(slider.getOrientation()) { case JSlider.VERTICAL: offset = currentMouseY - thumbRect.y; break; case JSlider.HORIZONTAL: offset = currentMouseX - thumbRect.x; break; } upperThumbSelected = false; lowerDragging = true; return; } lowerDragging = false; if (upperPressed) { switch(slider.getOrientation()) { case JSlider.VERTICAL: offset = currentMouseY - upperThumbRect.y; break; case JSlider.HORIZONTAL: offset = currentMouseX - upperThumbRect.x; break; } upperThumbSelected = true; upperDragging = true; return; } upperDragging = false; } @Override public void mouseReleased(MouseEvent e) { lowerDragging = false; upperDragging = false; slider.setValueIsAdjusting(false); super.mouseReleased(e); } @Override public void mouseDragged(MouseEvent e) { if (!slider.isEnabled()) { return; } currentMouseX = e.getX(); currentMouseY = e.getY(); if (lowerDragging) { slider.setValueIsAdjusting(true); moveLowerThumb(); } else if (upperDragging) { slider.setValueIsAdjusting(true); moveUpperThumb(); } } @Override public boolean shouldScroll(int direction) { return false; } private void moveLowerThumb() { int thumbMiddle = 0; switch(slider.getOrientation()) { case JSlider.VERTICAL: int halfThumbHeight = thumbRect.height / 2; int thumbTop = currentMouseY - offset; int trackTop = trackRect.y; int trackBottom = trackRect.y + (trackRect.height - 1); int vMax = yPositionForValue(slider.getValue() + slider.getExtent()); if (drawInverted()) { trackBottom = vMax; } else { trackTop = vMax; } thumbTop = Math.max(thumbTop, trackTop - halfThumbHeight); thumbTop = Math.min(thumbTop, trackBottom - halfThumbHeight); setThumbLocation(thumbRect.x, thumbTop); thumbMiddle = thumbTop + halfThumbHeight; slider.setValue(valueForYPosition(thumbMiddle)); break; case JSlider.HORIZONTAL: int halfThumbWidth = thumbRect.width / 2; int thumbLeft = currentMouseX - offset; int trackLeft = trackRect.x; int trackRight = trackRect.x + (trackRect.width - 1); int hMax = xPositionForValue(slider.getValue() + slider.getExtent()); if (drawInverted()) { trackLeft = hMax; } else { trackRight = hMax; } thumbLeft = Math.max(thumbLeft, trackLeft - halfThumbWidth); thumbLeft = Math.min(thumbLeft, trackRight - halfThumbWidth); setThumbLocation(thumbLeft, thumbRect.y); thumbMiddle = thumbLeft + halfThumbWidth; slider.setValue(valueForXPosition(thumbMiddle)); break; default: return; } } private void moveUpperThumb() { int thumbMiddle = 0; switch(slider.getOrientation()) { case JSlider.VERTICAL: int halfThumbHeight = thumbRect.height / 2; int thumbTop = currentMouseY - offset; int trackTop = trackRect.y; int trackBottom = trackRect.y + (trackRect.height - 1); int vMin = yPositionForValue(slider.getValue()); if (drawInverted()) { trackTop = vMin; } else { trackBottom = vMin; } thumbTop = Math.max(thumbTop, trackTop - halfThumbHeight); thumbTop = Math.min(thumbTop, trackBottom - halfThumbHeight); setUpperThumbLocation(thumbRect.x, thumbTop); thumbMiddle = thumbTop + halfThumbHeight; slider.setExtent(valueForYPosition(thumbMiddle) - slider.getValue()); break; case JSlider.HORIZONTAL: int halfThumbWidth = thumbRect.width / 2; int thumbLeft = currentMouseX - offset; int trackLeft = trackRect.x; int trackRight = trackRect.x + (trackRect.width - 1); int hMin = xPositionForValue(slider.getValue()); if (drawInverted()) { trackRight = hMin; } else { trackLeft = hMin; } thumbLeft = Math.max(thumbLeft, trackLeft - halfThumbWidth); thumbLeft = Math.min(thumbLeft, trackRight - halfThumbWidth); setUpperThumbLocation(thumbLeft, thumbRect.y); thumbMiddle = thumbLeft + halfThumbWidth; slider.setExtent(valueForXPosition(thumbMiddle) - slider.getValue()); break; default: return; } } } } static public class TransferableImage implements Transferable { public Image i; public TransferableImage(Image i) { this.i = i; } public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (flavor.equals(DataFlavor.imageFlavor) && i != null) { return i; } else { throw new UnsupportedFlavorException(flavor); } } public DataFlavor[] getTransferDataFlavors() { DataFlavor[] flavors = new DataFlavor[1]; flavors[0] = DataFlavor.imageFlavor; return flavors; } public boolean isDataFlavorSupported(DataFlavor flavor) { DataFlavor[] flavors = getTransferDataFlavors(); for (int i = 0; i < flavors.length; i++) { if (flavor.equals(flavors[i])) { return true; } } return false; } } public interface Updateable { public void update(); } static public class WithProbability extends Var implements Comparable> { public double probability; public WithProbability() { } public WithProbability(A a) { this(1, a); } public WithProbability(double probability, A a) { super(a); this.probability = probability; } public String toString() { return "p=" + renderedProbability() + ": " + str(get()); } public String renderedProbability() { return formatDouble_noLeadingZero(probability, 2); } public double probability() { return probability; } public int hashCode() { return boostHashCombine(utils.hashCode(probability), utils.hashCode(get())); } public boolean equals(Object o) { if (o instanceof WithProbability) { return probability == ((WithProbability) o).probability && eq(get(), ((WithProbability) o).get()); } return false; } public int compareTo(WithProbability wp) { return wp == null ? 1 : cmp(wp.probability, probability); } } public interface BitIO { public void readWrite(BitHead head); default public byte[] saveAsByteArray() { return saveToByteArray(); } default public byte[] toByteArray() { return saveToByteArray(); } default public byte[] saveToByteArray() { return saveToByteArray(new BitHead()); } default public byte[] saveAsByteArray(BitHead head) { return saveToByteArray(head); } default public byte[] toByteArray(BitHead head) { return saveToByteArray(head); } default public byte[] saveToByteArray(BitHead head) { var baos = byteArrayOutputStream(); head.outputStream(baos); readWrite(head); head.finish(); return baos.toByteArray(); } default public String toHexString() { return utils.toHexString(toByteArray()); } default public File saveToFile(File file) { OutputStream out = bufferedFileOutputStream(file); try { var head = new BitHead(out); readWrite(head); head.finish(); return file; } finally { _close(out); } } default public BitIO fromByteArray(byte[] data) { return load(data); } default public BitIO load(byte[] data) { readWrite(new BitHead(new ByteArrayInputStream(data))); return this; } default public BitIO load(File file) { InputStream in = bufferedInputStream(file); try { readWrite(new BitHead(in)); return this; } finally { _close(in); } } default public long byteIOLength() { JustCountingOutputStream out = new JustCountingOutputStream(); var head = new BitHead(out); readWrite(head); head.finish(); return out.get(); } } static public class SecretValue extends Var { public SecretValue() { } public SecretValue(A a) { super(a); } public String toString() { return "Secret value"; } } static public class GenericArrayTypeImpl implements GenericArrayType { final public Type genericComponentType; public GenericArrayTypeImpl(Type ct) { genericComponentType = ct; } public static GenericArrayTypeImpl make(Type ct) { return new GenericArrayTypeImpl(ct); } public Type getGenericComponentType() { return genericComponentType; } public String toString() { return getGenericComponentType().getTypeName() + "[]"; } @Override public boolean equals(Object o) { if (o instanceof GenericArrayType) { GenericArrayType that = (GenericArrayType) o; return Objects.equals(genericComponentType, that.getGenericComponentType()); } else return false; } @Override public int hashCode() { return Objects.hashCode(genericComponentType); } } static public class JSelectableDirLabel extends JFilePathLabel { transient public JButton selectButton; public JSelectableDirLabel() { } public JSelectableDirLabel(File dir) { super(dir); } public void makeButtons() { super.makeButtons(); selectButton = toolTip("Select a directory", jbutton("Choose...", () -> showSelectDialog())); buttons.add(selectButton); } public void showSelectDialog() { showDirChooser(file(), __1 -> setFile(__1)); } } static public class AppendableChain extends MinimalChain implements Iterable, IntSize { public MinimalChain last; final public int getSize() { return size(); } public int size() { return size; } public int size; public AppendableChain() { } public AppendableChain(A element) { this.element = element; size = 1; last = this; } public AppendableChain(A element, AppendableChain next) { this.next = next; this.element = element; if (next == null) return; MinimalChain b = new MinimalChain(); b.element = next.element; b.next = next.next; this.next = b; last = next.last; size = next.size + 1; } public String toString() { return str(toList()); } public boolean add(A a) { MinimalChain newLast = new MinimalChain(a); last.next = newLast; last = newLast; ++size; return true; } public AppendableChain popFirst() { if (next == null) return null; element = next.element; if (last == next) last = this; next = next.next; --size; return this; } public ArrayList toList() { ArrayList l = emptyList(size); MinimalChain c = this; while (c != null) { l.add(c.element); c = c.next; } return l; } public class ACIt extends IterableIterator { public MinimalChain c = AppendableChain.this; public boolean hasNext() { return c != null; } public A next() { var a = c.element; c = c.next; return a; } } public IterableIterator iterator() { return new ACIt(); } } static public class CompactLinkedHashSet extends AbstractSet { public UnsynchronizedCompactHashSet> entries = new UnsynchronizedCompactHashSet(); public Entry head, tail; static public class Entry { public A value; public Entry prev, next; public int hashCode() { return _hashCode(value); } public boolean equals(Object o) { return o == this || eq(value, o); } } public boolean add(A a) { if (entries.contains(a)) return false; Entry n = new Entry(); n.value = a; n.prev = tail; if (tail != null) tail.next = n; tail = n; if (head == null) head = n; entries.add(n); return true; } public boolean remove(Object a) { return remove(entries.find(a)); } public boolean remove(Entry node) { if (node == null) return false; if (node.next != null) node.next.prev = node.prev; else tail = node.prev; if (node.prev != null) node.prev.next = node.next; else head = node.next; entries.remove(node); return true; } public int size() { return entries.size(); } public IterableIterator iterator() { return new IterableIterator() { public Entry entry = head, prev = null; public boolean hasNext() { return entry != null; } public A next() { A a = entry.value; prev = entry; entry = entry.next; return a; } public void remove() { if (prev == null) throw new IllegalStateException(); CompactLinkedHashSet.this.remove(prev); prev = null; } }; } public void clear() { entries.clear(); head = tail = null; } public boolean contains(Object a) { return entries.contains(a); } public A find(Object o) { Entry e = entries.find(o); return e == null ? null : e.value; } public A prevElement(A a) { Entry e = entries.find(a); if (e == null || e.prev == null) return null; return e.prev.value; } public A nextElement(A a) { Entry e = entries.find(a); if (e == null || e.next == null) return null; return e.next.value; } public A first() { return head == null ? null : head.value; } public A last() { return tail == null ? null : tail.value; } public boolean removeIfSame(Object o) { A value = find(o); if (value == o) { remove(value); return true; } return false; } } static public class LoggingBitHead extends BitHead { public class Event { public long byteCounter = LoggingBitHead.this.byteCounter; public int align = LoggingBitHead.this.align; public int currentByte = LoggingBitHead.this.currentByte; } public class WritingBit extends Event implements IFieldsToList { public boolean b = false; public WritingBit() { } public WritingBit(boolean b) { this.b = b; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + b + ")"; } public boolean equals(Object o) { if (!(o instanceof WritingBit)) return false; WritingBit __0 = (WritingBit) o; return b == __0.b; } public int hashCode() { int h = 1485302449; h = boostHashCombine(h, _hashCode(b)); return h; } public Object[] _fieldsToList() { return new Object[] { b }; } } public class WritingByte extends Event implements IFieldsToList { public int i; public WritingByte() { } public WritingByte(int i) { this.i = i; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + i + ")"; } public boolean equals(Object o) { if (!(o instanceof WritingByte)) return false; WritingByte __1 = (WritingByte) o; return i == __1.i; } public int hashCode() { int h = -1200248860; h = boostHashCombine(h, _hashCode(i)); return h; } public Object[] _fieldsToList() { return new Object[] { i }; } } transient public Set> onLog; public LoggingBitHead onLog(IVF1 f) { onLog = createOrAddToSyncLinkedHashSet(onLog, f); return this; } public LoggingBitHead removeLogListener(IVF1 f) { utils.remove(onLog, f); return this; } public void log(Event event) { if (onLog != null) for (var listener : onLog) pcallF_typed(listener, event); } public boolean writeArraysSlowly() { return true; } public void writeBit(boolean b) { log(new WritingBit(b)); super.writeBit(b); } public void writeByte(int i) { log(new WritingByte(i)); super.writeByte(i); } } static public class FixedRateTimer extends java.util.Timer implements AutoCloseable { public FixedRateTimer() { this(false); } public FixedRateTimer(boolean daemon) { this(defaultTimerName(), daemon); } public FixedRateTimer(String name) { this(name, false); } public FixedRateTimer(String name, boolean daemon) { super(name, daemon); _registerTimer(this); } public List entries = synchroList(); static public class Entry implements IFieldsToList { public TimerTask task; public long firstTime; public long period; public Entry() { } public Entry(TimerTask task, long firstTime, long period) { this.period = period; this.firstTime = firstTime; this.task = task; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + task + ", " + firstTime + ", " + period + ")"; } public Object[] _fieldsToList() { return new Object[] { task, firstTime, period }; } } public void scheduleAtFixedRate(TimerTask task, long delay, long period) { entries.add(new Entry(task, now() + delay, period)); super.scheduleAtFixedRate(task, delay, period); } public void cancel() { entries.clear(); super.cancel(); } public int purge() { entries.clear(); return super.purge(); } public FixedRateTimer changeRate(int newPeriod) { Object r = ((SmartTimerTask) first(entries).task).r; cancel(); return doEvery(newPeriod, r); } public void close() { try { cancel(); } catch (Exception __e) { throw rethrow(__e); } } } static abstract public class WholeImageFilter extends AbstractBufferedImageOp implements IF1 { public Rectangle transformedSpace; public Rectangle originalSpace; public WholeImageFilter() { } public BufferedImage get(BufferedImage src) { return filter(src, null); } public BufferedImage filter(BufferedImage src, BufferedImage dst) { int width = src.getWidth(); int height = src.getHeight(); int type = src.getType(); WritableRaster srcRaster = src.getRaster(); originalSpace = new Rectangle(0, 0, width, height); transformedSpace = new Rectangle(0, 0, width, height); transformSpace(transformedSpace); if (dst == null) { ColorModel dstCM = src.getColorModel(); dst = new BufferedImage(dstCM, dstCM.createCompatibleWritableRaster(transformedSpace.width, transformedSpace.height), dstCM.isAlphaPremultiplied(), null); } WritableRaster dstRaster = dst.getRaster(); int[] inPixels = getRGB(src, 0, 0, width, height, null); inPixels = filterPixels(width, height, inPixels, transformedSpace); setRGB(dst, 0, 0, transformedSpace.width, transformedSpace.height, inPixels); return dst; } public void transformSpace(Rectangle rect) { } abstract public int[] filterPixels(int width, int height, int[] inPixels, Rectangle transformedSpace); } static public class CompactLongSet extends java.util.AbstractSet { final static public int INITIAL_SIZE = 3; public final static double LOAD_FACTOR = 0.75; final static public long deletedObject = Long.MIN_VALUE; public boolean containsZero, containsDeletedObject; public int elements; public int freecells; public long[] objects; public int modCount; public CompactLongSet() { this(0); } public CompactLongSet(int expectedElements) { int size = max(INITIAL_SIZE, iceil(expectedElements / LOAD_FACTOR)); objects = new long[size]; freecells = objects.length; } public CompactLongSet(Collection c) { this(c.size()); addAll(c); } @Override public RenamedLongIterator iterator() { return new CompactHashIterator(); } @Override public int size() { return elements; } @Override public boolean isEmpty() { return elements == 0; } @Override public boolean contains(Object o) { return contains((long) o); } public boolean contains(long o) { if (o == 0) return containsZero; if (o == deletedObject) return containsDeletedObject; int hash = hash(o); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; while (objects[index] != 0) { if (objects[index] == o) return true; index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset * 2 + 1; if (offset == -1) offset = 2; } return false; } @Override public boolean add(Long o) { return add((long) o); } public boolean add(long o) { if (o == 0) { if (containsZero) return false; containsZero = true; elements++; return true; } if (o == deletedObject) { if (containsDeletedObject) return false; containsDeletedObject = true; elements++; return true; } int hash = hash(o); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; int deletedix = -1; while (objects[index] != 0 && objects[index] != o) { if (objects[index] == deletedObject) deletedix = index; index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset * 2 + 1; if (offset == -1) offset = 2; } if (objects[index] == 0) { if (deletedix != -1) index = deletedix; else freecells--; modCount++; elements++; objects[index] = o; if (1 - (freecells / (double) objects.length) > LOAD_FACTOR) rehash(); return true; } else return false; } @Override public boolean remove(Object o) { return remove((long) o); } public boolean remove(long o) { if (o == 0) { if (!containsZero) return false; containsZero = false; --elements; return true; } if (o == deletedObject) { if (!containsDeletedObject) return false; containsDeletedObject = false; --elements; return true; } int hash = hash(o); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; while (objects[index] != 0 && objects[index] != o) { index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset * 2 + 1; if (offset == -1) offset = 2; } if (objects[index] != 0) { objects[index] = deletedObject; modCount++; elements--; return true; } else return false; } @Override public void clear() { elements = 0; for (int ix = 0; ix < objects.length; ix++) objects[ix] = 0; containsZero = containsDeletedObject = false; freecells = objects.length; modCount++; } public void rehash() { int garbagecells = objects.length - (elements + freecells); if (garbagecells / (double) objects.length > 0.05) rehash(objects.length); else rehash(objects.length * 2 + 1); } public void rehash(int newCapacity) { int oldCapacity = objects.length; @SuppressWarnings("unchecked") long[] newObjects = new long[newCapacity]; for (int ix = 0; ix < oldCapacity; ix++) { long o = objects[ix]; if (o == 0 || o == deletedObject) continue; int hash = hash(o); int index = (hash & 0x7FFFFFFF) % newCapacity; int offset = 1; while (newObjects[index] != 0) { index = ((index + offset) & 0x7FFFFFFF) % newCapacity; offset = offset * 2 + 1; if (offset == -1) offset = 2; } newObjects[index] = o; } objects = newObjects; freecells = objects.length - elements; } public class CompactHashIterator extends RenamedLongIterator { public int index; public int lastReturned = -1; public boolean sendZero, sendDeletedObject; public int expectedModCount; @SuppressWarnings("empty-statement") public CompactHashIterator() { for (index = 0; index < objects.length && (objects[index] == 0 || objects[index] == deletedObject); index++) ; expectedModCount = modCount; sendZero = containsZero; sendDeletedObject = containsDeletedObject; } @Override public boolean hasNext() { return index < objects.length || sendZero || sendDeletedObject; } @Override public long nextLong() { int length = objects.length; if (index >= length) { if (sendZero) { sendZero = false; return 0L; } if (sendDeletedObject) { sendDeletedObject = false; return deletedObject; } throw new NoSuchElementException(); } lastReturned = index; for (index += 1; index < length && (objects[index] == 0 || objects[index] == deletedObject); index++) ; return objects[lastReturned]; } @Override public void remove() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (lastReturned == -1 || lastReturned == -2) throw new IllegalStateException(); if (objects[lastReturned] != 0 && objects[lastReturned] != deletedObject) { objects[lastReturned] = deletedObject; elements--; modCount++; expectedModCount = modCount; } } } public int capacity() { return objects.length; } public boolean shrinkToFactor(double factor) { if (factor > LOAD_FACTOR) throw fail("Shrink factor must be equal to or smaller than load factor: " + factor + " / " + LOAD_FACTOR); int newCapacity = max(INITIAL_SIZE, iround(size() / factor)); if (newCapacity >= capacity()) return false; rehash(newCapacity); return true; } public int hash(long l) { return utils.hashCode(l); } } static public class GridCodec1 implements JavaCodec, IFieldsToList { public BufferedImage stage0_image; public GridCodec1() { } public GridCodec1(BufferedImage stage0_image) { this.stage0_image = stage0_image; } public Object[] _fieldsToList() { return new Object[] { stage0_image }; } final public GridCodec1 setRows(int rows) { return rows(rows); } public GridCodec1 rows(int rows) { this.rows = rows; return this; } final public int getRows() { return rows(); } public int rows() { return rows; } public int rows = 20; static public GridCodec1 demo() { return new GridCodec1(defaultScreenshot()); } public Matrix stage1_matrix; public long dataBytes, dataChars; public Matrix> stage2_grid; public JE_CompressEachElementIndividually> strat; public JECompressionSearch>> search; public JECompressionSearch>> forward() { assertNotNull(stage0_image); var m = stage1_matrix = imageToMatrix(stage0_image); dataBytes = m.nCells() * 4 + 2; dataChars = dataBytes * 2 + l("lInt(\"\")"); print("Matrix ~ " + shorten_str(60, m)); print("Trivial comp ~ " + (m.nCells() * 8)); stage2_grid = matrixToMNGrid_rows(m, rows); List> stage3_cells = matrixOfMatricesToListOfLists(stage2_grid); search = jeCompressionSearch(stage3_cells, dataChars); strat = new JE_CompressEachElementIndividually>().elementCompressionStrategy(() -> new JE_RepElement()).onCompressionFail(ints -> javaObjectToIJavaExpr(ints)); search.addStrategy(strat); return search; } public String stats() { return strat == null ? null : strat.stats(); } public JECompressionSearch>>.Submission winner() { return search == null ? null : search.bestSubmission(); } public ICachedJavaXExpr>> winnerCodeWithoutPostProcessing() { return rCallF(winner(), __1 -> __1 == null ? null : __1.decompressor()); } public ICachedJavaXExpr winnerCode() { var innerWinner = winnerCodeWithoutPostProcessing(); if (innerWinner == null) return null; return addPostProcessing(innerWinner); } public List cellWidths() { return lambdaMapMethod(__156 -> __156.getWidth(), rowToList(stage2_grid, 0)); } public List cellHeights() { return lambdaMapMethod(__157 -> __157.getHeight(), colToList(stage2_grid, 0)); } public ICachedJavaXExpr addPostProcessing(ICachedJavaXExpr>> inner) { List cellWidths = cellWidths(); List cellHeights = cellHeights(); return new AbstractJavaXExpr() { public FunctionCall javaConstruct() { return functionCall("gridLOLToImage", toJava(cellWidths), toJava(cellHeights), inner); } public String toString() { return str(javaConstruct()); } public BufferedImage quickEval() { return gridLOLToImage(cellWidths, cellHeights, inner.quickEval()); } }; } public BufferedImage renderCellsLinearly() { return mergeBufferedImagesHorizontally(map(__143 -> intMatrixToImage(__143), matrixToList(stage2_grid))); } public void drawOverlay(ImageSurface is, Graphics2D g) { try { double zoom = is.getZoomX(); List cellWidths = cellWidths(); List cellHeights = cellHeights(); List cellX1s = partialSums_firstIs0(cellWidths); List cellY1s = partialSums_firstIs0(cellHeights); for (int y = 0; y < l(cellHeights); y++) for (int x = 0; x < l(cellWidths); x++) if (strat.isElementCompressed(y * l(cellWidths) + x)) { Rect r = rectFromPoints(cellX1s.get(x), cellY1s.get(y), cellX1s.get(x + 1), cellY1s.get(y + 1)); r = scaleRect(r, zoom); fillRect(g, r, colorWithAlpha(Color.GREEN, .5)); } } catch (Throwable __e) { pcallFail(__e); } } } public interface IndexIterator { public int nextIndex(); } static public class MethodOnObject implements IFieldsToList { static final public String _fieldOrder = "object method"; transient public Object object; public String method; public MethodOnObject() { } public MethodOnObject(Object object, String method) { this.method = method; this.object = object; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + object + ", " + method + ")"; } public boolean equals(Object o) { if (!(o instanceof MethodOnObject)) return false; MethodOnObject __1 = (MethodOnObject) o; return eq(object, __1.object) && eq(method, __1.method); } public int hashCode() { int h = 791808543; h = boostHashCombine(h, _hashCode(object)); h = boostHashCombine(h, _hashCode(method)); return h; } public Object[] _fieldsToList() { return new Object[] { object, method }; } } static public class MinimumFilter extends WholeImageFilter { public int hRadius; public int vRadius; public MinimumFilter() { this(1); } public MinimumFilter(int radius) { hRadius = vRadius = radius; } public MinimumFilter(int hRadius, int vRadius) { this.vRadius = vRadius; this.hRadius = hRadius; } public int[] filterPixels(int width, int height, int[] inPixels, Rectangle transformedSpace) { int index = 0; int[] outPixels = new int[width * height]; int y1 = -vRadius / 2, y2 = y1 + vRadius; int x1 = -hRadius / 2, x2 = x1 + hRadius; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int pixel = 0xffffffff; for (int dy = y1; dy <= y2; dy++) { int iy = y + dy; int ioffset; if (0 <= iy && iy < height) { ioffset = iy * width; for (int dx = x1; dx <= x2; dx++) { int ix = x + dx; if (0 <= ix && ix < width) { pixel = PixelUtils.combinePixels(pixel, inPixels[ioffset + ix], PixelUtils.MIN); } } } } outPixels[index++] = pixel; } } return outPixels; } } static public class JGallery extends MetaWithChangeListeners implements Swingable { public boolean _isTransient() { return true; } public transient FieldVar> varFiles_cache; public FieldVar> varFiles() { if (varFiles_cache == null) varFiles_cache = varFiles_load(); return varFiles_cache; } public FieldVar> varFiles_load() { return new FieldVar>(this, "files", () -> files(), files -> files(files)); } final public JGallery setFiles(List files) { return files(files); } public JGallery files(List files) { if (!eq(this.files, files)) { this.files = files; change(); } return this; } final public List getFiles() { return files(); } public List files() { return files; } public List files; final public File getSelectedFile() { return selectedFile(); } public File selectedFile() { return selectedFile; } public File selectedFile; final public JGallery setHorizontal(boolean horizontal) { return horizontal(horizontal); } public JGallery horizontal(boolean horizontal) { this.horizontal = horizontal; return this; } final public boolean getHorizontal() { return horizontal(); } public boolean horizontal() { return horizontal; } public boolean horizontal = true; transient public Set> onAdaptingButton; public JGallery onAdaptingButton(IVF2 f) { onAdaptingButton = createOrAddToSyncLinkedHashSet(onAdaptingButton, f); return this; } public JGallery removeAdaptingButtonListener(IVF2 f) { utils.remove(onAdaptingButton, f); return this; } public void adaptingButton(JButton button, File file) { if (onAdaptingButton != null) for (var listener : onAdaptingButton) pcallF_typed(listener, button, file); } public DynamicStack buttons_cache; public DynamicStack buttons() { if (buttons_cache == null) buttons_cache = buttons_load(); return buttons_cache; } public DynamicStack buttons_load() { return horizontal ? makeNiceButtons() : verticalNiceButtons(); } public ButtonImageLoader imageLoader_cache; public ButtonImageLoader imageLoader() { if (imageLoader_cache == null) imageLoader_cache = imageLoader_load(); return imageLoader_cache; } public ButtonImageLoader imageLoader_load() { return new ButtonImageLoader(buttons()); } public void setImageFiles(Collection filesCollection) { swing(() -> { var files = asList(filesCollection); if (eq(this.files, files)) return; setFiles(files); List l = filesForNiceButtons(files, __3 -> openImage(__3)); replaceNiceButtons(buttons(), l); for (var __1 : zip(allButtons(buttons()), files)) { var btn = pairA(__1); var file = pairB(__1); adaptingButton(btn, file); } File selectedFile = selectedFile(); selectFile(selectedFile); imageLoader().update(); }); } public void selectFile(File file) { swing(() -> { selectedFile = file; int idx = indexOf(files, file); for (Pair __0 : iterateWithIndex(allButtons(buttons()))) { int i = pairA(__0); JButton btn = pairB(__0); boolean selected = i == idx; setSelected(btn, selected); if (selected) { print("Selected button: " + btn); scrollIntoView(btn); } } }); } public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { return jHigherScrollPane(jfullcenter(buttons())); } transient public IVF1 openImage; public void openImage(File f) { if (openImage != null) openImage.get(f); else openImage_base(f); } final public void openImage_fallback(IVF1 _f, File f) { if (_f != null) _f.get(f); else openImage_base(f); } public void openImage_base(File f) { showImage(f); } } public interface IUnstructured { default public void _doneLoading() { } } final static public class IntegralImage implements IIntegralImage { public int w, h; public int[] data; public IntegralImage(RGBImage img) { init(img); } public void init(RGBImage img) { w = img.w(); h = img.h(); if (longMul(w, h) > 8000000) throw fail("Image too big: " + w + "*" + h); data = new int[w * h * 3]; int i = 0; for (int y = 0; y < h; y++) { int sumR = 0, sumG = 0, sumB = 0; for (int x = 0; x < w; x++) { int rgb = img.getInt(x, y); sumR += (rgb >> 16) & 0xFF; sumG += (rgb >> 8) & 0xFF; sumB += rgb & 0xFF; data[i] = y > 0 ? sumR + data[i - w * 3] : sumR; data[i + 1] = y > 0 ? sumG + data[i - w * 3 + 1] : sumG; data[i + 2] = y > 0 ? sumB + data[i - w * 3 + 2] : sumB; i += 3; } } } public IntegralImage(MakesBufferedImage img) { if (img instanceof RGBImage) init((RGBImage) img); else init(toBufferedImage(img)); } public IntegralImage(BufferedImage img) { init(img); } public void init(BufferedImage img) { w = img.getWidth(); h = img.getHeight(); if (longMul(w, h) > 8000000) throw fail("Image too big: " + w + "*" + h); int[] pixels = pixelsOfBufferedImage(img); data = new int[w * h * 3]; int i = 0, j = 0, sumR = 0, sumG = 0, sumB = 0; for (int x = 0; x < w; x++) { int rgb = pixels[j++]; data[i++] = (sumR += (rgb >> 16) & 0xFF); data[i++] = (sumG += (rgb >> 8) & 0xFF); data[i++] = (sumB += rgb & 0xFF); } for (int y = 1; y < h; y++) { sumR = sumG = sumB = 0; for (int x = 0; x < w; x++) { int rgb = pixels[j++]; sumR += (rgb >> 16) & 0xFF; sumG += (rgb >> 8) & 0xFF; sumB += rgb & 0xFF; data[i] = sumR + data[i - w * 3]; data[i + 1] = sumG + data[i - w * 3 + 1]; data[i + 2] = sumB + data[i - w * 3 + 2]; i += 3; } } } public double getIntegralValue(double x, double y, int channel) { int xFloor = ifloor(x), yFloor = ifloor(y); double val = getIntegralValue(xFloor, yFloor, channel); if (xFloor == x && yFloor == y) return val; double val2 = getIntegralValue(xFloor + 1, yFloor, channel); double val3 = getIntegralValue(xFloor, yFloor + 1, channel); double val4 = getIntegralValue(xFloor + 1, yFloor + 1, channel); return blend2D(val, val2, val3, val4, x - xFloor, y - yFloor); } final public double get(int x, int y, int channel) { return getIntegralValue(x, y, channel); } public double getIntegralValue(int x, int y, int channel) { return x < 0 || y < 0 ? 0 : data[(min(y, h - 1) * w + min(x, w - 1)) * 3 + channel]; } final public double get(int x, int y) { return getIntegralValue(x, y); } public double getIntegralValue(int x, int y) { if (x < 0 || y < 0) return 0; int i = (min(y, h - 1) * w + min(x, w - 1)) * 3; return data[i] + data[i + 1] + data[i + 2]; } public String toString() { return "IntegralImage " + w + "*" + h + ", brightness: " + averageBrightness(); } public BufferedImage getBufferedImage() { return integralImageToBufferedImage(this); } public int getWidth() { return w; } public int getHeight() { return h; } public Object _serialize() { return litobjectarray(w, h, data); } static public IntegralImage _deserialize(Object[] l) { return new IntegralImage((int) l[0], (int) l[1], (int[]) l[2]); } public IntegralImage(int w, int h, int[] data) { this.data = data; this.h = h; this.w = w; } } static public class IntBuffer implements Iterable { public int[] data; public int size; public IntBuffer() { } public IntBuffer(int size) { if (size != 0) data = new int[size]; } public IntBuffer(Iterable l) { if (l instanceof Collection) allocate(((Collection) l).size()); addAll(l); } public void add(int i) { if (size >= lIntArray(data)) { data = resizeIntArray(data, Math.max(1, toInt(Math.min(maximumSafeArraySize(), lIntArray(data) * 2L)))); if (size >= data.length) throw fail("IntBuffer too large: " + size); } data[size++] = i; } public void allocate(int n) { data = resizeIntArray(data, max(n, size())); } public void setSize(int n) { data = resizeIntArray(data, n); size = min(l(data), size); } public void addAll(Iterable l) { if (l != null) for (int i : l) add(i); } public void addAll(int... l) { if (l != null) for (int i : l) add(i); } final public int[] toIntArray() { return toArray(); } public int[] toArray() { return size == 0 ? null : resizeIntArray(data, size); } public int[] subArray(int from, int to) { return subIntArray(data, from, min(to, size)); } public int[] toArrayNonNull() { return unnull(toArray()); } final public List asList() { return toList(); } final public List asVirtualList() { return toList(); } public List toList() { return new RandomAccessAbstractList() { public int size() { return size; } public Integer get(int i) { return IntBuffer.this.get(i); } public Integer set(int i, Integer val) { Integer a = get(i); data[i] = val; return a; } }; } public void reset() { size = 0; } public void clear() { reset(); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public int get(int idx) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); return data[idx]; } public void set(int idx, int value) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); data[idx] = value; } public int popLast() { if (size == 0) throw fail("empty buffer"); return data[--size]; } public int last() { return data[size - 1]; } public int nextToLast() { return data[size - 2]; } public String toString() { return squareBracket(joinWithSpace(toList())); } public Iterator iterator() { return new IterableIterator() { public int i = 0; public boolean hasNext() { return i < size; } public Integer next() { return data[i++]; } }; } public IntegerIterator integerIterator() { return new IntegerIterator() { public int i = 0; public boolean hasNext() { return i < size; } public int next() { return data[i++]; } public String toString() { return "Iterator@" + i + " over " + IntBuffer.this; } }; } public void trimToSize() { data = resizeIntArray(data, size); } } static public class DoublePt implements IDoublePt { public double x, y; public DoublePt() { } public DoublePt(Point p) { x = p.x; y = p.y; } public DoublePt(double x, double y) { this.y = y; this.x = x; } public boolean equals(Object p) { if (p instanceof DoublePt) { return x == ((DoublePt) p).x && y == ((DoublePt) p).y; } return false; } public int hashCode() { return boostHashCombine(utils.hashCode(x), utils.hashCode(y)); } public String toString() { return x + ", " + y; } public double length() { return sqrt(x * x + y * y); } public double x_double() { return x; } public double y_double() { return y; } } static public interface IIntPred { public boolean get(int a); } static public class SynchronizedNavigableSet extends SynchronizedSortedSet implements NavigableSet { public SynchronizedNavigableSet() { } @java.io.Serial static final public long serialVersionUID = -5505529816273629798L; @SuppressWarnings("serial") public NavigableSet ns; public SynchronizedNavigableSet(NavigableSet s) { super(s); ns = s; } public SynchronizedNavigableSet(NavigableSet s, Object mutex) { super(s, mutex); ns = s; } public E lower(E e) { synchronized (mutex) { return ns.lower(e); } } public E floor(E e) { synchronized (mutex) { return ns.floor(e); } } public E ceiling(E e) { synchronized (mutex) { return ns.ceiling(e); } } public E higher(E e) { synchronized (mutex) { return ns.higher(e); } } public E pollFirst() { synchronized (mutex) { return ns.pollFirst(); } } public E pollLast() { synchronized (mutex) { return ns.pollLast(); } } public NavigableSet descendingSet() { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex); } } public Iterator descendingIterator() { synchronized (mutex) { return descendingSet().iterator(); } } public NavigableSet subSet(E fromElement, E toElement) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex); } } public NavigableSet headSet(E toElement) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex); } } public NavigableSet tailSet(E fromElement) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, true), mutex); } } public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex); } } public NavigableSet headSet(E toElement, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex); } } public NavigableSet tailSet(E fromElement, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive), mutex); } } } static public class SynchronizedCircularFifoBuffer implements Iterable, IntSize { public int capacity; public long base; public ArrayDeque coreStorage; public Collection storage; public SynchronizedCircularFifoBuffer(int capacity) { this.capacity = capacity; coreStorage = new ArrayDeque(capacity); storage = synchronizedCollection(coreStorage); } public void add(E e) { synchronized (storage) { if (isFull()) remove(); coreStorage.addLast(e); } } public E remove() { synchronized (storage) { ++base; return coreStorage.removeFirst(); } } public boolean isFull() { return storage.size() == capacity; } public boolean isEmpty() { return storage.isEmpty(); } public int size() { return storage.size(); } public Object[] toArray() { return storage.toArray(); } public T[] toArray(T[] a) { return storage.toArray(a); } public List asList() { return new ArrayList(storage); } public Collection getBackingStore() { return storage; } public Iterator iterator() { return storage.iterator(); } public E last() { synchronized (storage) { return coreStorage.peekLast(); } } public void clear() { synchronized (storage) { coreStorage.clear(); base = 0; } } synchronized public long getBase() { return base; } synchronized public int getCapacity() { return capacity; } } abstract static public class AbstractMatrix implements Matrix { public AbstractMatrix() { } public int w, h; public AbstractMatrix(int w, int h) { this.h = h; this.w = w; } public int getWidth() { return w; } public int getHeight() { return h; } public String toString() { return flexLines(roundBracket(w + "x" + h), countIteratorToList(y -> str(getLine(y)), getHeight())); } public void set(int x, int y, A a) { throw unimplemented(); } } static public class RegionToBWImage implements IFieldsToList { public IImageRegion region; public RegionToBWImage() { } public RegionToBWImage(IImageRegion region) { this.region = region; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + region + ")"; } public Object[] _fieldsToList() { return new Object[] { region }; } final public RegionToBWImage setBounds(Rect bounds) { return bounds(bounds); } public RegionToBWImage bounds(Rect bounds) { this.bounds = bounds; return this; } final public Rect getBounds() { return bounds(); } public Rect bounds() { return bounds; } public Rect bounds; public BWImage image; final public RegionToBWImage setBgColor(int bgColor) { return bgColor(bgColor); } public RegionToBWImage bgColor(int bgColor) { this.bgColor = bgColor; return this; } final public int getBgColor() { return bgColor(); } public int bgColor() { return bgColor; } public int bgColor = 0xFF; final public RegionToBWImage setColor(int color) { return color(color); } public RegionToBWImage color(int color) { this.color = color; return this; } final public int getColor() { return color(); } public int color() { return color; } public int color = 0x00; public void run() { try { if (bounds == null) bounds = region.bounds(); int x1 = bounds.x, y1 = bounds.y, w = bounds.w, h = bounds.h, i = 0; byte[] pixels = new byte[w * h]; if (bgColor != 0) fillArray(pixels, (byte) bgColor); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { if (region.contains(x1 + x, y1 + y)) pixels[i] = (byte) color; i++; } image = new BWImage(w, h, pixels); } catch (Exception __e) { throw rethrow(__e); } } public BWImage get() { if (image == null) run(); return image; } } static public class ComputerCountListener implements IFieldsToList { public StefansOS_ConnectToServer connector; public ComputerCountListener() { } public ComputerCountListener(StefansOS_ConnectToServer connector) { this.connector = connector; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + connector + ")"; } public Object[] _fieldsToList() { return new Object[] { connector }; } public VarWithNotify computerCount = new VarWithNotify(); public boolean verbose = false; public void init() { connector.onNewLine(line -> { Matches m = new Matches(); if (swic(line, "ComputerCount = ", m)) { computerCount.set(parseInt(m.rest())); if (verbose) print("Computer count: " + get()); } }); connector.sub("computerCount"); } public LiveValue liveValue() { return varWithNotifyToLiveValue(Integer.class, computerCount); } public Integer get() { return computerCount.get(); } } static public class WidthAndHeightImpl extends Meta implements WidthAndHeight, ByteIO, IFieldsToList { public int width; public int height; public WidthAndHeightImpl() { } public WidthAndHeightImpl(int width, int height) { this.height = height; this.width = width; } public Object[] _fieldsToList() { return new Object[] { width, height }; } public int getWidth() { return width; } public int getHeight() { return height; } public WidthAndHeightImpl(int wAndH) { this(wAndH, wAndH); } public String toString() { return n2(width) + "*" + n2(height) + " px"; } public void readWrite(ByteHead head) { head.exchangeInt(() -> width(), w -> width = w); head.exchangeInt(() -> height(), h -> height = h); } } static public class RunnablesReferenceQueue implements AutoCloseable { public ReferenceQueue queue = new ReferenceQueue(); volatile public Thread thread; public Flag closed = new Flag(); final public RunnablesReferenceQueue setTimeout(int timeout) { return timeout(timeout); } public RunnablesReferenceQueue timeout(int timeout) { this.timeout = timeout; return this; } final public int getTimeout() { return timeout(); } public int timeout() { return timeout; } public int timeout = 60000; public RunnablesReferenceQueue() { thread = startThread("RunnablesReferenceQueue", () -> _run()); } public void _run() { try { try { while (ping() && !closed.get()) { Reference ref = queue.remove(timeout); if (ref != null) { if (ref instanceof Runnable) pcallF((Runnable) ref); else warn("RunnablesReferenceQueue: Reference not runnable - " + className(ref)); } } } catch (InterruptedException e) { } finally { thread = null; } } catch (Exception __e) { throw rethrow(__e); } } public void close() { try { closed.raise(); interruptThread(thread); } catch (Exception __e) { throw rethrow(__e); } } final public ReferenceQueue get() { return queue(); } public ReferenceQueue queue() { return queue; } } static public class JPopDownButton extends JButton { public String menuPosition = "left"; public JPopDownButton() { this(""); } public JPopDownButton(String text) { super(joinNemptiesWithSpace(text, unicode_downPointingTriangle())); utils.addActionListener(this, new Runnable() { public void run() { try { openMenu(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "openMenu();"; } }); } public JPopDownButton(IVF1 fillMenu) { this(); this.fillMenu = fillMenu; } public JPopDownButton content(Object... items) { onFillingMenu(menu -> fillJPopupMenu(menu, items)); return this; } transient public Set> onFillingMenu; public JPopDownButton onFillingMenu(IVF1 f) { onFillingMenu = createOrAddToSyncLinkedHashSet(onFillingMenu, f); return this; } public JPopDownButton removeFillingMenuListener(IVF1 f) { utils.remove(onFillingMenu, f); return this; } public void fillingMenu(JPopupMenu menu) { if (onFillingMenu != null) for (var listener : onFillingMenu) pcallF_typed(listener, menu); } transient public IVF1 fillMenu; public void fillMenu(JPopupMenu menu) { if (fillMenu != null) fillMenu.get(menu); else fillMenu_base(menu); } final public void fillMenu_fallback(IVF1 _f, JPopupMenu menu) { if (_f != null) _f.get(menu); else fillMenu_base(menu); } public void fillMenu_base(JPopupMenu menu) { fillingMenu(menu); } public void openMenu() { JPopupMenu menu = new JPopupMenu(); int emptyCount = menu.getComponentCount(); fillMenu(menu); if (menu.getComponentCount() == emptyCount) return; int x = 0; if (eq(menuPosition, "center")) x = (getWidth() - getPreferredWidth(menu)) / 2; else if (eq(menuPosition, "right")) x = getWidth() - getPreferredWidth(menu); menu.show(this, x, getHeight()); } public JComponent visualize() { return this; } } abstract static public class AbstractJavaXExpr extends Meta implements ICachedJavaXExpr { } static public class SSIListFrame extends MetaWithChangeListeners implements ByteIO, MakesBufferedImage { final public SSIListFrame setMagicMarker(int magicMarker) { return magicMarker(magicMarker); } public SSIListFrame magicMarker(int magicMarker) { this.magicMarker = magicMarker; return this; } final public int getMagicMarker() { return magicMarker(); } public int magicMarker() { return magicMarker; } public int magicMarker = 0xFFFFBABE; public transient FieldVar varTimestampInMS_cache; public FieldVar varTimestampInMS() { if (varTimestampInMS_cache == null) varTimestampInMS_cache = varTimestampInMS_load(); return varTimestampInMS_cache; } public FieldVar varTimestampInMS_load() { return new FieldVar(this, "timestampInMS", () -> timestampInMS(), timestampInMS -> timestampInMS(timestampInMS)); } final public SSIListFrame setTimestampInMS(long timestampInMS) { return timestampInMS(timestampInMS); } public SSIListFrame timestampInMS(long timestampInMS) { if (!eq(this.timestampInMS, timestampInMS)) { this.timestampInMS = timestampInMS; change(); } return this; } final public long getTimestampInMS() { return timestampInMS(); } public long timestampInMS() { return timestampInMS; } public long timestampInMS; public transient FieldVar varResolution_cache; public FieldVar varResolution() { if (varResolution_cache == null) varResolution_cache = varResolution_load(); return varResolution_cache; } public FieldVar varResolution_load() { return new FieldVar(this, "resolution", () -> resolution(), resolution -> resolution(resolution)); } final public SSIListFrame setResolution(WidthAndHeightImpl resolution) { return resolution(resolution); } public SSIListFrame resolution(WidthAndHeightImpl resolution) { if (!eq(this.resolution, resolution)) { this.resolution = resolution; change(); } return this; } final public WidthAndHeightImpl getResolution() { return resolution(); } public WidthAndHeightImpl resolution() { return resolution; } public WidthAndHeightImpl resolution = new WidthAndHeightImpl(); public transient FieldVar varContent_cache; public FieldVar varContent() { if (varContent_cache == null) varContent_cache = varContent_load(); return varContent_cache; } public FieldVar varContent_load() { return new FieldVar(this, "content", () -> content(), content -> content(content)); } final public SSIListFrame setContent(SSIList content) { return content(content); } public SSIListFrame content(SSIList content) { if (!eq(this.content, content)) { this.content = content; change(); } return this; } final public SSIList getContent() { return content(); } public SSIList content() { return content; } public SSIList content = new SSIList(); public void readWrite(ByteHead head) { head.exchangeInt(magicMarker); head.exchangeLong(varTimestampInMS()); head.exchange(resolution); head.exchangeWithSize(content); } public int getWidth() { return resolution.w(); } public int getHeight() { return resolution.h(); } final public BufferedImage render() { return getBufferedImage(); } public BufferedImage getBufferedImage() { return content.render(resolution); } } static abstract public class DialogIO implements AutoCloseable { public String line; public boolean eos, loud, noClose; public Lock lock = lock(); abstract public String readLineImpl(); abstract public boolean isStillConnected(); abstract public void sendLine(String line); abstract public boolean isLocalConnection(); abstract public Socket getSocket(); public int getPort() { Socket s = getSocket(); return s == null ? 0 : s.getPort(); } public boolean helloRead = false; public int shortenOutputTo = 500; public String readLineNoBlock() { String l = line; line = null; return l; } public boolean waitForLine() { try { ping(); if (line != null) return true; line = readLineImpl(); if (line == null) eos = true; return line != null; } catch (Exception __e) { throw rethrow(__e); } } public String readLine() { waitForLine(); helloRead = true; return readLineNoBlock(); } public String ask(String s, Object... args) { if (loud) return askLoudly(s, args); if (!helloRead) readLine(); if (args.length != 0) s = format3(s, args); sendLine(s); return readLine(); } public String askLoudly(String s, Object... args) { if (!helloRead) readLine(); if (args.length != 0) s = format3(s, args); print("> " + shorten(s, shortenOutputTo)); sendLine(s); String answer = readLine(); print("< " + shorten(answer, shortenOutputTo)); return answer; } public void pushback(String l) { if (line != null) throw fail(); line = l; helloRead = false; } } static abstract public class DialogHandler implements IDialogHandler { } public interface IDialogHandler { public void run(DialogIO io); } static public class AWTOnConceptChanges implements AutoCloseable { final public AWTOnConceptChanges setComponent(JComponent component) { return component(component); } public AWTOnConceptChanges component(JComponent component) { this.component = component; return this; } final public JComponent getComponent() { return component(); } public JComponent component() { return component; } public JComponent component; final public AWTOnConceptChanges setAction(Runnable action) { return action(action); } public AWTOnConceptChanges action(Runnable action) { this.action = action; return this; } final public Runnable getAction() { return action(); } public Runnable action() { return action; } public Runnable action; final public AWTOnConceptChanges setConcepts(Concepts concepts) { return concepts(concepts); } public AWTOnConceptChanges concepts(Concepts concepts) { this.concepts = concepts; return this; } final public Concepts getConcepts() { return concepts(); } public Concepts concepts() { return concepts; } public Concepts concepts; final public AWTOnConceptChanges setFirstDelay(int firstDelay) { return firstDelay(firstDelay); } public AWTOnConceptChanges firstDelay(int firstDelay) { this.firstDelay = firstDelay; return this; } final public int getFirstDelay() { return firstDelay(); } public int firstDelay() { return firstDelay; } public int firstDelay; final public AWTOnConceptChanges setDelay(int delay) { return delay(delay); } public AWTOnConceptChanges delay(int delay) { this.delay = delay; return this; } final public int getDelay() { return delay(); } public int delay() { return delay; } public int delay = 500; public long changes = -1; public javax.swing.Timer timer; public AWTOnConceptChanges(Concepts concepts, JComponent component, Runnable action) { this.action = action; this.component = component; this.concepts = concepts; } public void install() { assertNotNull(concepts); timer = installTimer(component, delay, firstDelay, new Runnable() { public void run() { try { _trigger(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_trigger();"; } }); } public void _trigger() { long c = concepts.changes; if (changes != c) { changes = c; { if (action != null) action.run(); } } } public void close() { try { { cleanUp(timer); timer = null; } } catch (Exception __e) { throw rethrow(__e); } } } static public class VariableSizeUIntForBitHead implements BitIO { final public VariableSizeUIntForBitHead setChunkSize(int chunkSize) { return chunkSize(chunkSize); } public VariableSizeUIntForBitHead chunkSize(int chunkSize) { this.chunkSize = chunkSize; return this; } final public int getChunkSize() { return chunkSize(); } public int chunkSize() { return chunkSize; } public int chunkSize = 3; final public VariableSizeUIntForBitHead setValue(int value) { return value(value); } public VariableSizeUIntForBitHead value(int value) { this.value = value; return this; } final public int getValue() { return value(); } public int value() { return value; } public int value; final public int getBitCount() { return bitCount(); } public int bitCount() { return bitCount; } public int bitCount; public void readWrite(BitHead head) { if (head.writeMode()) { bitCount = max(1, numberOfBits(value)); int value = this.value; head.writePartialByte(value, chunkSize); value >>>= chunkSize; while (value != 0) { head.writeBit(1); head.writePartialByte(value, chunkSize); value >>>= chunkSize; } head.writeBit(0); } if (head.readMode()) { int value = head.readPartialByte(chunkSize); int shift = 0; bitCount = chunkSize; while (!head.isEOF() && head.readBit()) { value |= head.readPartialByte(chunkSize) << bitCount; bitCount += chunkSize; } value(value); } } public void readWrite(BitHead head, IF0 getter, IVF1 setter) { if (head.writeMode()) value(getter.get()); readWrite(head); if (head.readMode()) setter.get(value()); } } public interface IHasChangeListeners { public IHasChangeListeners onChange(Runnable r); public IHasChangeListeners removeChangeListener(Runnable r); default public IHasChangeListeners onChangeAndNow(Runnable l) { onChange(l); callF(l); return this; } } public interface JavaCodec { } static public class ImageSurface_PositionToolTip extends ImageSurfaceMouseHandler { public ImageSurface_PositionToolTip(ImageSurface is) { if (containsInstance(is.tools, ImageSurface_PositionToolTip.class)) return; register(is); } final public void mouseDragged(MouseEvent e) { mouseMoved(e); } public void mouseMoved(MouseEvent e) { try { Pt p = getPt(e); String s = str(p); var img = is.getImage(); if (img != null && p.x >= 0 && p.y >= 0 && p.x < img.getWidth() && p.y < img.getHeight()) { IToolTipMaker toolTipMaker = lookupDynamicInterface_v2(IToolTipMaker.class, img); if (toolTipMaker != null) s = toolTipMaker.getToolTip(p); else s += " - " + intToHex_fullLength(img.getRGB(p.x, p.y)); } setToolTip(is, s); } catch (Throwable __e) { pcallFail(__e); } } } static public class TranslucentWindowTest { public List windows = new ArrayList(); public void run() { try { var screens = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); System.out.println("Detected " + screens.length + " screen(s)"); for (int iScreen = 0; iScreen < screens.length; iScreen++) { var screen = screens[iScreen].getDefaultConfiguration().getBounds(); JWindow window = new JWindow(); window.setBounds(screen.x + screen.width / 4, screen.y + screen.height / 4, screen.width / 2, screen.height / 2); window.setBackground(new Color(0, 0, 255, 64)); window.setAlwaysOnTop(true); var label = new JLabel("Screen " + (iScreen + 1) + " of " + screens.length); label.setHorizontalAlignment(JLabel.CENTER); window.add(label); window.setVisible(true); windows.add(window); } doAfter(10.0, new Runnable() { public void run() { try { disposeWindows(windows); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disposeWindows(windows);"; } }); } catch (Exception __e) { throw rethrow(__e); } } } static public class FlexWebSocket extends WebSocket { public FlexWebSocket(NanoHTTPD.IHTTPSession handshake) { super(handshake); } transient public Set> onGotMessage; public FlexWebSocket onGotMessage(IVF1 f) { onGotMessage = createOrAddToSyncLinkedHashSet(onGotMessage, f); return this; } public FlexWebSocket removeGotMessageListener(IVF1 f) { utils.remove(onGotMessage, f); return this; } public void gotMessage(WebSocketFrame messageFrame) { if (onGotMessage != null) for (var listener : onGotMessage) pcallF_typed(listener, messageFrame); } transient public Set onClosed; public FlexWebSocket onClosed(Runnable r) { onClosed = createOrAddToSyncLinkedHashSet(onClosed, r); return this; } public FlexWebSocket removeClosedListener(Runnable r) { utils.remove(onClosed, r); return this; } public void closed() { if (onClosed != null) for (var listener : onClosed) pcallF_typed(listener); } public void send(WebSocketFrame frame) { try { frame.write(out); } catch (Exception __e) { throw rethrow(__e); } } public void onException(IOException e) { pcall_fail(e); } public void onMessage(WebSocketFrame messageFrame) { gotMessage(messageFrame); } public void onClose(WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote) { closed(); } public void close() { try { try { close(WebSocketFrame.CloseCode.NormalClosure, ""); } catch (Throwable __e) { pcallFail(__e); } } catch (Exception __e) { throw rethrow(__e); } } } static public interface IIntegralImage extends MakesBufferedImage { public int getWidth(); public int getHeight(); default public Pt getSize() { return pt(getWidth(), getHeight()); } default public int defaultChannel() { return 0; } default public int nChannels() { return 3; } public double getIntegralValue(int x, int y, int channel); default public double getIntegralValue(double x, double y, int channel) { return getIntegralValue(ifloor(x), ifloor(y), channel); } default public double getIntegralValue(int x, int y) { return getIntegralValue(x, y, 0) + getIntegralValue(x, y, 1) + getIntegralValue(x, y, 2); } default public double rectSum(int x1, int y1, int x2, int y2, int channel) { double bottomLeft = getIntegralValue(x1 - 1, y2 - 1, channel); double bottomRight = getIntegralValue(x2 - 1, y2 - 1, channel); double topLeft = getIntegralValue(x1 - 1, y1 - 1, channel); double topRight = getIntegralValue(x2 - 1, y1 - 1, channel); return bottomRight + topLeft - topRight - bottomLeft; } default public double rectSum(double x1, double y1, double x2, double y2, int channel) { double bottomLeft = getIntegralValue(x1 - 1, y2 - 1, channel); double bottomRight = getIntegralValue(x2 - 1, y2 - 1, channel); double topLeft = getIntegralValue(x1 - 1, y1 - 1, channel); double topRight = getIntegralValue(x2 - 1, y1 - 1, channel); return bottomRight + topLeft - topRight - bottomLeft; } default public double rectSum(int x1, int y1, int x2, int y2) { double bottomLeft = getIntegralValue(x1 - 1, y2 - 1); double bottomRight = getIntegralValue(x2 - 1, y2 - 1); double topLeft = getIntegralValue(x1 - 1, y1 - 1); double topRight = getIntegralValue(x2 - 1, y1 - 1); return bottomRight + topLeft - topRight - bottomLeft; } default public double rectAverage(int x1, int y1, int x2, int y2, int channel) { return doubleRatio(rectSum(x1, y1, x2, y2, channel), areaFromPoints(x1, y1, x2, y2)); } default public double rectAverage(Rect r, int channel) { return doubleRatio(rectSum(r, channel), rectArea(r)); } default public double rectSum(Rect r) { return rectSum(r.x, r.y, r.x2(), r.y2()); } default public double rectSum(Rect r, int channel) { return rectSum(r.x, r.y, r.x2(), r.y2(), channel); } default public double pixelSum(DoubleRect r) { return rectSum(toRect_floor(r), defaultChannel()); } default public IIntegralImage clip(int x, int y, int w, int h) { return new IIVirtualClip(this, x, y, w, h); } default public double averageBrightness() { int w = getWidth(), h = getHeight(); return doubleRatio(getIntegralValue(w - 1, h - 1), w * h * 3 * 255.0); } default public RGB averageRGB() { int w = getWidth(), h = getHeight(); double factor = 1 / (255.0 * (w * h)); return new RGB(rectSum(0, 0, w, h, 0) * factor, rectSum(0, 0, w, h, 1) * factor, rectSum(0, 0, w, h, 2) * factor); } default public double getPixel(int x, int y, int channel) { return rectSum(x, y, x + 1, y + 1, channel); } default public int getPixel(int x, int y) { int r = iround(rectSum(x, y, x + 1, y + 1, 0)); int g = iround(rectSum(x, y, x + 1, y + 1, 1)); int b = iround(rectSum(x, y, x + 1, y + 1, 2)); return rgbInt(r, g, b); } default public int nPixels() { return getWidth() * getHeight(); } default public BufferedImage getBufferedImage() { int w = getWidth(), h = getHeight(); int[] pixels = new int[w * h]; int i = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) pixels[i++] = getPixel(x, y) | fullAlphaMask(); return intArrayToBufferedImage(pixels, w, h); } } abstract static public class AbstractCompressor_AnyType extends Probabilistic { public CompressionSearch_AnyType search; public AbstractCompressor_AnyType() { } public AbstractCompressor_AnyType(CompressionSearch_AnyType search) { this.search = search; } public void setSearch(CompressionSearch_AnyType search) { if (this.search != null && this.search != search) throw fail(); this.search = search; } public CompressionRegime_AnyType regime() { return search == null ? null : search.regime(); } public Data inputData() { return search.inputData(); } public void flush() { } public CompressionSearch_AnyType.Submission submit(A a) { return submit(a, null); } public CompressionSearch_AnyType.Submission submit(A a, Object notes) { return search.submit(a, notes); } } static public class Stages implements Steppable, Runnable, IFieldsToList { static final public String _fieldOrder = "stages iStage stage"; public List stages = new ArrayList(); public Stages() { } public Stages(List stages) { this.stages = stages; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + stages + ")"; } public boolean equals(Object o) { if (!(o instanceof Stages)) return false; Stages __1 = (Stages) o; return eq(stages, __1.stages); } public int hashCode() { int h = -1808627371; h = boostHashCombine(h, _hashCode(stages)); return h; } public Object[] _fieldsToList() { return new Object[] { stages }; } public int iStage; public Runnable stage; public boolean step() { return iStage <= l(stages) && trueBecause(callF(stage = _get(stages, iStage++))); } public Runnable stage(Runnable stage) { stages.add(stage); return stage; } public Runnable stage(String name, Runnable stage) { return stage(runnableWithCustomToString(name, stage)); } public void run() { try { stepAll(this); } catch (Exception __e) { throw rethrow(__e); } } public int indexOfStage(Runnable stage) { return stages.indexOf(stage); } public void stepUntilStage(Runnable stage) { int index = indexOfStage(stage); while (iStage <= index && step()) { } } } static public class Scribble implements IFieldsToList { static final public String _fieldOrder = "color strokeWidth points"; public Color color; public Number strokeWidth; public List points; public Scribble() { } public Scribble(Color color, Number strokeWidth, List points) { this.points = points; this.strokeWidth = strokeWidth; this.color = color; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + color + ", " + strokeWidth + ", " + points + ")"; } public boolean equals(Object o) { if (!(o instanceof Scribble)) return false; Scribble __1 = (Scribble) o; return eq(color, __1.color) && eq(strokeWidth, __1.strokeWidth) && eq(points, __1.points); } public int hashCode() { int h = -343368992; h = boostHashCombine(h, _hashCode(color)); h = boostHashCombine(h, _hashCode(strokeWidth)); h = boostHashCombine(h, _hashCode(points)); return h; } public Object[] _fieldsToList() { return new Object[] { color, strokeWidth, points }; } public void addPoint(Pt p) { points.add(new NumberPt(p)); } } static public interface IAutoCloseableF0 extends IF0, AutoCloseable { } public interface IPartialStringifier { public String toStringOpt(A o); } static public class BitIOWrapper implements BitIO, IFieldsToList { public BitIO io; public BitIOWrapper() { } public BitIOWrapper(BitIO io) { this.io = io; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + io + ")"; } public boolean equals(Object o) { if (!(o instanceof BitIOWrapper)) return false; BitIOWrapper __1 = (BitIOWrapper) o; return eq(io, __1.io); } public int hashCode() { int h = -684469696; h = boostHashCombine(h, _hashCode(io)); return h; } public Object[] _fieldsToList() { return new Object[] { io }; } public void readWrite(BitHead head) { io.readWrite(head); } } static public class AlphanumComparator implements Comparator { public boolean ignoreCase = false; private final boolean isDigit(char ch) { return ((ch >= 48) && (ch <= 57)); } private final String getChunk(String s, int slength, int marker) { StringBuilder chunk = new StringBuilder(); char c = s.charAt(marker); chunk.append(c); marker++; if (isDigit(c)) while (marker < slength) { c = s.charAt(marker); if (!isDigit(c)) break; chunk.append(c); marker++; } else while (marker < slength) { c = s.charAt(marker); if (isDigit(c)) break; chunk.append(c); marker++; } return chunk.toString(); } public int compare(String s1, String s2) { if (s1 == null) return s2 == null ? 0 : -1; if (s2 == null) return 1; int thisMarker = 0; int thatMarker = 0; int s1Length = s1.length(); int s2Length = s2.length(); while (thisMarker < s1Length && thatMarker < s2Length) { String thisChunk = getChunk(s1, s1Length, thisMarker); thisMarker += thisChunk.length(); String thatChunk = getChunk(s2, s2Length, thatMarker); thatMarker += thatChunk.length(); int result = 0; if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { int thisChunkLength = thisChunk.length(); result = thisChunkLength - thatChunk.length(); if (result == 0) { for (int i = 0; i < thisChunkLength; i++) { result = thisChunk.charAt(i) - thatChunk.charAt(i); if (result != 0) { return result; } } } } else { result = thisChunk.compareTo(thatChunk); } if (result != 0) return result; } return s1Length - s2Length; } } static public class JExtendedTabbedPane implements Swingable { public JTabbedPane tabs; public List components = new ArrayList(); public SingleComponentPanel scpBesideTabs = scp(); public SingleComponentPanel scpPage = scp(); final public JExtendedTabbedPane setVerbose(boolean verbose) { return verbose(verbose); } public JExtendedTabbedPane verbose(boolean verbose) { this.verbose = verbose; return this; } final public boolean getVerbose() { return verbose(); } public boolean verbose() { return verbose; } public boolean verbose = false; public JExtendedTabbedPane(JTabbedPane _tabs) { swing(() -> { tabs = _tabs != null ? _tabs : jtabs(); int n = tabCount(tabs); for (int i = 0; i < n; i++) { var c = tabs.getComponentAt(i); c.setVisible(true); components.add(c); tabs.setComponentAt(i, emptyPage()); } onTabSelectedAndNow(tabs, () -> updatePage()); }); } public void updatePage() { int idx = getSelectedIndex(); var c = get(components, idx); if (verbose) printVars("JExtendedTabbedPane.updateTabs", "idx", idx, "c", c); scpPage.set(c); } public Component emptyPage() { return verticalStrut(0); } public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { return vertical() ? westAndCenter(centerAndSouthWithMargin(tabs, scpBesideTabs), wrapPage(scpPage)) : northAndCenter(centerAndEastWithMargin(tabs, scpBesideTabs), wrapPage(scpPage)); } transient public IF1 wrapPage; public JComponent wrapPage(JComponent page) { return wrapPage != null ? wrapPage.get(page) : wrapPage_base(page); } final public JComponent wrapPage_fallback(IF1 _f, JComponent page) { return _f != null ? _f.get(page) : wrapPage_base(page); } public JComponent wrapPage_base(JComponent page) { return page; } final public JExtendedTabbedPane setComponentBelowTabs(Component c) { return setComponentBesideTabs(c); } public JExtendedTabbedPane setComponentBesideTabs(Component c) { scpBesideTabs.set(c); return this; } public int getSelectedIndex() { return tabs.getSelectedIndex(); } public void setComponentAt(int i, Component c) { components.set(i, c); if (getSelectedIndex() == i) updatePage(); } public Component getComponentAt(int i) { return components.get(i); } public Component getTabComponentAt(int i) { return tabs.getTabComponentAt(i); } public void add(String title, Component c) { components.add(c); tabs.add(title, emptyPage()); } public int getTabCount() { return tabs.getTabCount(); } public void setTitleAt(int i, String title) { tabs.setTitleAt(i, title); } public void setSelectedIndex(int i) { tabs.setSelectedIndex(i); } public boolean vertical() { return tabs.getTabPlacement() == JTabbedPane.LEFT; } } static public class PersistableThrowable extends DynamicObject { public String className; public String msg; public String stacktrace; final public PersistableThrowable setActualThrowable(Throwable actualThrowable) { return actualThrowable(actualThrowable); } public PersistableThrowable actualThrowable(Throwable actualThrowable) { this.actualThrowable = actualThrowable; return this; } final public Throwable getActualThrowable() { return actualThrowable(); } public Throwable actualThrowable() { return actualThrowable; } transient public Throwable actualThrowable; public PersistableThrowable() { } public PersistableThrowable(Throwable e) { actualThrowable = e; if (e == null) className = "Crazy Null Error"; else { className = getClassName(e).replace('/', '.'); msg = e.getMessage(); stacktrace = getStackTrace_noRecord(e); } } public String toString() { return nempty(msg) ? className + ": " + msg : className; } public RuntimeException asRuntimeException() { if (actualThrowable != null) return utils.asRuntimeException(actualThrowable); return new Fail(this); } } abstract static public class Animation { public int w = 128, h = 128; public double fps = 20; public Graphics2D g; public Animation() { } public Animation(int w, int h) { this.h = h; this.w = w; } public void setSize(int w, int h) { this.w = w; this.h = h; } public void setGraphics(Graphics2D g) { this.g = g; } public void start() { } public void paint() { } public void nextFrame() { } public BufferedImage toImage() { var img = whiteImage(w, h); setGraphics(createGraphics(img)); paint(); return img; } } public interface IDoublePt { public double x_double(); public double y_double(); } static public class NumPadFixingInputMap extends InputMap { public void put(KeyStroke keyStroke, Object actionMapKey) { super.put(keyStroke, actionMapKey); Integer code = rsyntaxTextArea_fixNumPad_map.get(keyStroke.getKeyCode()); if (code != null) put(KeyStroke.getKeyStroke(code, keyStroke.getModifiers()), actionMapKey); } public void replaceOn(JComponent c) { InputMap im = c.getInputMap(); setParent(im.getParent()); for (KeyStroke key : im.keys()) put(key, im.get(key)); c.setInputMap(JComponent.WHEN_FOCUSED, this); } } static public class PixelUtils { public final static int REPLACE = 0; public final static int NORMAL = 1; public final static int MIN = 2; public final static int MAX = 3; public final static int ADD = 4; public final static int SUBTRACT = 5; public final static int DIFFERENCE = 6; public final static int MULTIPLY = 7; public final static int HUE = 8; public final static int SATURATION = 9; public final static int VALUE = 10; public final static int COLOR = 11; public final static int SCREEN = 12; public final static int AVERAGE = 13; public final static int OVERLAY = 14; public final static int CLEAR = 15; public final static int EXCHANGE = 16; public final static int DISSOLVE = 17; public final static int DST_IN = 18; public final static int ALPHA = 19; public final static int ALPHA_TO_GRAY = 20; static public Random randomGenerator = new Random(); static public int _clamp(int c) { if (c < 0) return 0; if (c > 255) return 255; return c; } public static int interpolate(int v1, int v2, float f) { return _clamp((int) (v1 + f * (v2 - v1))); } public static int brightness(int rgb) { int r = (rgb >> 16) & 0xff; int g = (rgb >> 8) & 0xff; int b = rgb & 0xff; return (r + g + b) / 3; } public static boolean nearColors(int rgb1, int rgb2, int tolerance) { int r1 = (rgb1 >> 16) & 0xff; int g1 = (rgb1 >> 8) & 0xff; int b1 = rgb1 & 0xff; int r2 = (rgb2 >> 16) & 0xff; int g2 = (rgb2 >> 8) & 0xff; int b2 = rgb2 & 0xff; return Math.abs(r1 - r2) <= tolerance && Math.abs(g1 - g2) <= tolerance && Math.abs(b1 - b2) <= tolerance; } final static public float[] hsb1 = new float[3]; final static public float[] hsb2 = new float[3]; public static int combinePixels(int rgb1, int rgb2, int op) { return combinePixels(rgb1, rgb2, op, 0xff); } public static int combinePixels(int rgb1, int rgb2, int op, int extraAlpha, int channelMask) { return (rgb2 & ~channelMask) | combinePixels(rgb1 & channelMask, rgb2, op, extraAlpha); } public static int combinePixels(int rgb1, int rgb2, int op, int extraAlpha) { if (op == REPLACE) return rgb1; int a1 = (rgb1 >> 24) & 0xff; int r1 = (rgb1 >> 16) & 0xff; int g1 = (rgb1 >> 8) & 0xff; int b1 = rgb1 & 0xff; int a2 = (rgb2 >> 24) & 0xff; int r2 = (rgb2 >> 16) & 0xff; int g2 = (rgb2 >> 8) & 0xff; int b2 = rgb2 & 0xff; switch(op) { case NORMAL: break; case MIN: r1 = Math.min(r1, r2); g1 = Math.min(g1, g2); b1 = Math.min(b1, b2); break; case MAX: r1 = Math.max(r1, r2); g1 = Math.max(g1, g2); b1 = Math.max(b1, b2); break; case ADD: r1 = _clamp(r1 + r2); g1 = _clamp(g1 + g2); b1 = _clamp(b1 + b2); break; case SUBTRACT: r1 = _clamp(r2 - r1); g1 = _clamp(g2 - g1); b1 = _clamp(b2 - b1); break; case DIFFERENCE: r1 = _clamp(Math.abs(r1 - r2)); g1 = _clamp(Math.abs(g1 - g2)); b1 = _clamp(Math.abs(b1 - b2)); break; case MULTIPLY: r1 = _clamp(r1 * r2 / 255); g1 = _clamp(g1 * g2 / 255); b1 = _clamp(b1 * b2 / 255); break; case DISSOLVE: if ((randomGenerator.nextInt() & 0xff) <= a1) { r1 = r2; g1 = g2; b1 = b2; } break; case AVERAGE: r1 = (r1 + r2) / 2; g1 = (g1 + g2) / 2; b1 = (b1 + b2) / 2; break; case HUE: case SATURATION: case VALUE: case COLOR: Color.RGBtoHSB(r1, g1, b1, hsb1); Color.RGBtoHSB(r2, g2, b2, hsb2); switch(op) { case HUE: hsb2[0] = hsb1[0]; break; case SATURATION: hsb2[1] = hsb1[1]; break; case VALUE: hsb2[2] = hsb1[2]; break; case COLOR: hsb2[0] = hsb1[0]; hsb2[1] = hsb1[1]; break; } rgb1 = Color.HSBtoRGB(hsb2[0], hsb2[1], hsb2[2]); r1 = (rgb1 >> 16) & 0xff; g1 = (rgb1 >> 8) & 0xff; b1 = rgb1 & 0xff; break; case SCREEN: r1 = 255 - ((255 - r1) * (255 - r2)) / 255; g1 = 255 - ((255 - g1) * (255 - g2)) / 255; b1 = 255 - ((255 - b1) * (255 - b2)) / 255; break; case OVERLAY: int m, s; s = 255 - ((255 - r1) * (255 - r2)) / 255; m = r1 * r2 / 255; r1 = (s * r1 + m * (255 - r1)) / 255; s = 255 - ((255 - g1) * (255 - g2)) / 255; m = g1 * g2 / 255; g1 = (s * g1 + m * (255 - g1)) / 255; s = 255 - ((255 - b1) * (255 - b2)) / 255; m = b1 * b2 / 255; b1 = (s * b1 + m * (255 - b1)) / 255; break; case CLEAR: r1 = g1 = b1 = 0xff; break; case DST_IN: r1 = _clamp((r2 * a1) / 255); g1 = _clamp((g2 * a1) / 255); b1 = _clamp((b2 * a1) / 255); a1 = _clamp((a2 * a1) / 255); return (a1 << 24) | (r1 << 16) | (g1 << 8) | b1; case ALPHA: a1 = a1 * a2 / 255; return (a1 << 24) | (r2 << 16) | (g2 << 8) | b2; case ALPHA_TO_GRAY: int na = 255 - a1; return (a1 << 24) | (na << 16) | (na << 8) | na; } if (extraAlpha != 0xff || a1 != 0xff) { a1 = a1 * extraAlpha / 255; int a3 = (255 - a1) * a2 / 255; r1 = _clamp((r1 * a1 + r2 * a3) / 255); g1 = _clamp((g1 * a1 + g2 * a3) / 255); b1 = _clamp((b1 * a1 + b2 * a3) / 255); a1 = _clamp(a1 + a3); } return (a1 << 24) | (r1 << 16) | (g1 << 8) | b1; } } static public class HasIndex implements Comparable { public int idx; public HasIndex() { } public HasIndex(int idx) { this.idx = idx; } public int compareTo(HasIndex h) { return idx - h.idx; } final public int get() { return idx; } } static public interface WidthAndHeight { default public int w() { return getWidth(); } default public int width() { return getWidth(); } public int getWidth(); default public int h() { return getHeight(); } default public int height() { return getHeight(); } public int getHeight(); public default Rect bounds() { return rect(0, 0, getWidth(), getHeight()); } default public int area() { return toInt(areaAsLong()); } default public long areaAsLong() { return longMul(w(), h()); } } static public class WithToolTip extends Var { final public WithToolTip setToolTip(String toolTip) { return toolTip(toolTip); } public WithToolTip toolTip(String toolTip) { this.toolTip = toolTip; return this; } final public String getToolTip() { return toolTip(); } public String toolTip() { return toolTip; } public String toolTip; public WithToolTip() { } public WithToolTip(A value, String toolTip) { super(value); this.toolTip = toolTip; } public String toString() { return formatFunctionCall("WithToolTip", toolTip, get()); } } static public class VectorSSI extends AbstractSSI { public VectorSSI() { } final public VectorSSI setX1(short x1) { return x1(x1); } public VectorSSI x1(short x1) { this.x1 = x1; return this; } final public short getX1() { return x1(); } public short x1() { return x1; } public short x1; final public VectorSSI setY1(short y1) { return y1(y1); } public VectorSSI y1(short y1) { this.y1 = y1; return this; } final public short getY1() { return y1(); } public short y1() { return y1; } public short y1; final public VectorSSI setLeftCurve(InterpolatedDoubleArray leftCurve) { return leftCurve(leftCurve); } public VectorSSI leftCurve(InterpolatedDoubleArray leftCurve) { this.leftCurve = leftCurve; return this; } final public InterpolatedDoubleArray getLeftCurve() { return leftCurve(); } public InterpolatedDoubleArray leftCurve() { return leftCurve; } public InterpolatedDoubleArray leftCurve; final public VectorSSI setRightCurve(InterpolatedDoubleArray rightCurve) { return rightCurve(rightCurve); } public VectorSSI rightCurve(InterpolatedDoubleArray rightCurve) { this.rightCurve = rightCurve; return this; } final public InterpolatedDoubleArray getRightCurve() { return rightCurve(); } public InterpolatedDoubleArray rightCurve() { return rightCurve; } public InterpolatedDoubleArray rightCurve; public VectorSSI(SSI ssi) { ssi.copyAbstractSSI(this); Rect r = ssi.bounds(); x1(toShort_enforce(r.x1())); y1(toShort_enforce(r.y1())); int h = r.h(); int[] left = new int[h], right = new int[h]; for (int y = 0; y < h; y++) { left[y] = ssi.getLeft(y1 + y) - x1; right[y] = ssi.getRight(y1 + y) - x1; } leftCurve(new CompressToInterpolatedDoubleArray(left).get()); rightCurve(new CompressToInterpolatedDoubleArray(right).get()); } final public int h() { return height(); } public int height() { return leftCurve.length(); } public int y2() { return y1 + h(); } final public SSI get() { return toSSI(); } public SSI toSSI() { int h = h(); var ssi = new SSI(y1, y2()); copyAbstractSSI(ssi); int[] left = leftCurve.rounded(); int[] right = rightCurve.rounded(); for (int y = 0; y < h; y++) ssi.set(y1 + y, x1 + left[y], x1 + right[y]); return ssi; } public void drawOn(Graphics2D g) { toSSI().drawOn(g); } public int nPoints() { return leftCurve.nPillars() + rightCurve.nPillars(); } public long sizeInInts() { return 5 + leftCurve.nInts() + rightCurve.nInts(); } public Rect bounds_cache; public Rect bounds() { if (bounds_cache == null) bounds_cache = bounds_load(); return bounds_cache; } public Rect bounds_load() { return toSSI().bounds(); } public Integer numberOfPixels_cache; public int numberOfPixels() { if (numberOfPixels_cache == null) numberOfPixels_cache = numberOfPixels_load(); return numberOfPixels_cache; } public int numberOfPixels_load() { return toSSI().numberOfPixels(); } public void readWrite(StringHead head) { head.exchangeLine(() -> toLine(), __1 -> fromLine(__1)); } public String toLine() { List elements = ll("v", colorToString(), x1, y1, height()); addAll(elements, asList(iroundAll(leftCurve.indicesAndValues()))); addAll(elements, asList(iroundAll(rightCurve.indicesAndValues()))); return spaceCombine(elements); } public void fromLine(String line) { Iterator it = splitAtSpaceIterator(line); assertEquals("v", nextFromIterator(it)); x1 = toShort_enforce(parseInt(nextFromIterator(it))); y1 = toShort_enforce(parseInt(nextFromIterator(it))); } } static public class JFilePathButton implements Swingable, IFieldsToList { public File file; public JFilePathButton() { } public JFilePathButton(File file) { this.file = file; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + file + ")"; } public Object[] _fieldsToList() { return new Object[] { file }; } transient public JButton button; public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { if (button == null) { button = jimageButtonScaledToWidth(16, "#1101292", "", () -> showInExplorer()); componentPopupMenuItem(button, "Copy path", () -> copyToClipboard(f2s(file))); } updateToolTip(); return button; } public void showInExplorer() { { startThread(new Runnable() { public void run() { try { File dirToShow = isFile(file) ? dirOfFile(file) : file; desktopOpen(dirToShow); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "File dirToShow = isFile(file) ? dirOfFile(file) : file;\r\n //startPlatfor..."; } }); } } public void setFile(File file) { this.file = file; updateToolTip(); } public void updateToolTip() { setEnabled(button, file != null); toolTip(file == null ? "No file" : f2s(file) + " [click to show in file explorer]", button); } } static abstract public class TokCondition implements ITokCondition { public abstract boolean get(List tok, int i); } static public class HashRefTokenMaker extends TokenMakerBase { @Override public org.fife.ui.rsyntaxtextarea.Token getTokenList(Segment text, int startTokenType, final int startOffset) { resetTokenList(); char[] array = text.array; int offset = text.offset; int count = text.count; int end = offset + count; int newStartOffset = startOffset - offset; String src = str(array, offset, count); List tok = hashRefTok(src); int ofs = offset; for (int i = 0; i < l(tok); i++) { var t = tok.get(i); if (empty(t)) continue; boolean isHyperlink = odd(i); for (var part : singlePredTok(c -> isSpaceEtc(c), t)) { if (nempty(part)) { var tokenType = isHyperlink ? org.fife.ui.rsyntaxtextarea.Token.VARIABLE : startsWithSpaceEtc(part) ? org.fife.ui.rsyntaxtextarea.Token.WHITESPACE : org.fife.ui.rsyntaxtextarea.Token.IDENTIFIER; int l = l(part); addToken(array, ofs, ofs + l - 1, tokenType, ofs + newStartOffset, isHyperlink); ofs += l; } } } addNullToken(); return firstToken; } } static public class JSyntaxTextFileEditor extends JTextFileEditor { public JSyntaxTextFileEditor(File file) { super(file); } public RSyntaxTextAreaWithSearch textAreaWithSearch; @Override public RSyntaxTextArea textArea() { return (RSyntaxTextArea) textArea; } @Override public JTextArea makeTextArea() { textAreaWithSearch = makeSyntaxTextAreaWithSearch(); textAreaWithSearch.menuLessOperation(); var ta = textAreaWithSearch.textArea(); adaptSyntaxTextArea(ta); return ta; } @Override public JComponent textAreaLayoutComponent() { return textAreaWithSearch.visualize(); } transient public IF0 makeSyntaxTextAreaWithSearch; public RSyntaxTextAreaWithSearch makeSyntaxTextAreaWithSearch() { return makeSyntaxTextAreaWithSearch != null ? makeSyntaxTextAreaWithSearch.get() : makeSyntaxTextAreaWithSearch_base(); } final public RSyntaxTextAreaWithSearch makeSyntaxTextAreaWithSearch_fallback(IF0 _f) { return _f != null ? _f.get() : makeSyntaxTextAreaWithSearch_base(); } public RSyntaxTextAreaWithSearch makeSyntaxTextAreaWithSearch_base() { return rSyntaxTextAreaWithSearch(); } transient public IVF1 adaptSyntaxTextArea; public void adaptSyntaxTextArea(RSyntaxTextArea textArea) { if (adaptSyntaxTextArea != null) adaptSyntaxTextArea.get(textArea); else adaptSyntaxTextArea_base(textArea); } final public void adaptSyntaxTextArea_fallback(IVF1 _f, RSyntaxTextArea textArea) { if (_f != null) _f.get(textArea); else adaptSyntaxTextArea_base(textArea); } public void adaptSyntaxTextArea_base(RSyntaxTextArea textArea) { } public JSyntaxTextFileEditor autoSave(boolean b) { super.autoSave(b); return this; } public JSyntaxTextFileEditor uneditable(boolean b) { super.uneditable(b); return this; } } static public class WAndHImpl extends Meta implements WidthAndHeight, IFieldsToList { public int w; public int h; public WAndHImpl() { } public WAndHImpl(int w, int h) { this.h = h; this.w = w; } public Object[] _fieldsToList() { return new Object[] { w, h }; } public int getWidth() { return w; } public int getHeight() { return h; } public String toString() { return n2(w) + "*" + n2(h) + " px"; } public void setSize(int w, int h) { this.w = w; this.h = h; } } static public class ConceptWithChangeListeners extends Concept implements IHasChangeListeners, ChangeTriggerable { transient public Set onChange; public ConceptWithChangeListeners onChange(Runnable r) { onChange = createOrAddToSyncLinkedHashSet(onChange, r); return this; } public ConceptWithChangeListeners removeChangeListener(Runnable r) { utils.remove(onChange, r); return this; } public void fireChange() { if (onChange != null) for (var listener : onChange) pcallF_typed(listener); } public void _onChange() { super._onChange(); fireChange(); } public void change() { super.change(); } } static public class SynchronizedCollection implements Collection, Serializable { public SynchronizedCollection() { } @java.io.Serial static final public long serialVersionUID = 3053995032091335093L; @SuppressWarnings("serial") public Collection c; @SuppressWarnings("serial") public Object mutex; public SynchronizedCollection(Collection c) { this.c = Objects.requireNonNull(c); mutex = this; } public SynchronizedCollection(Collection c, Object mutex) { this.c = Objects.requireNonNull(c); this.mutex = Objects.requireNonNull(mutex); } public int size() { synchronized (mutex) { return c.size(); } } public boolean isEmpty() { synchronized (mutex) { return c.isEmpty(); } } public boolean contains(Object o) { synchronized (mutex) { return c.contains(o); } } public Object[] toArray() { synchronized (mutex) { return c.toArray(); } } public T[] toArray(T[] a) { synchronized (mutex) { return c.toArray(a); } } public T[] toArray(java.util.function.IntFunction f) { synchronized (mutex) { return c.toArray(f); } } public Iterator iterator() { return c.iterator(); } public boolean add(E e) { synchronized (mutex) { return c.add(e); } } public boolean remove(Object o) { synchronized (mutex) { return c.remove(o); } } public boolean containsAll(Collection coll) { synchronized (mutex) { return c.containsAll(coll); } } public boolean addAll(Collection coll) { synchronized (mutex) { return c.addAll(coll); } } public boolean removeAll(Collection coll) { synchronized (mutex) { return c.removeAll(coll); } } public boolean retainAll(Collection coll) { synchronized (mutex) { return c.retainAll(coll); } } public void clear() { synchronized (mutex) { c.clear(); } } public String toString() { synchronized (mutex) { return c.toString(); } } @Override public void forEach(java.util.function.Consumer consumer) { synchronized (mutex) { c.forEach(consumer); } } @Override public boolean removeIf(java.util.function.Predicate filter) { synchronized (mutex) { return c.removeIf(filter); } } @Override public Spliterator spliterator() { return c.spliterator(); } @Override public java.util.stream.Stream stream() { return c.stream(); } @Override public java.util.stream.Stream parallelStream() { return c.parallelStream(); } @java.io.Serial private void writeObject(ObjectOutputStream s) throws IOException { synchronized (mutex) { s.defaultWriteObject(); } } } static public class OnePathWithOrigin extends OnePath { final public OnePathWithOrigin setOrigin(Pt origin) { return origin(origin); } public OnePathWithOrigin origin(Pt origin) { this.origin = origin; return this; } final public Pt getOrigin() { return origin(); } public Pt origin() { return origin; } public Pt origin = pt(0, 0); public OnePathWithOrigin() { } public OnePathWithOrigin(String path) { super(path); } public OnePathWithOrigin(Pt origin, String path) { super(path); this.origin = origin; } public OnePathWithOrigin(int originX, int originY, String path) { super(path); origin = pt(originX, originY); } public OnePathWithOrigin(Iterable points, boolean close) { var l = asList(points); origin = first(l); fromPoints(l, close); } public OnePathWithOrigin(OnePathWithOrigin path) { super(path); origin = path.origin; } public String toString() { return "Origin (" + origin + "), path: " + super.toString(); } public OnePathWithOrigin reversed() { return new OnePathWithOrigin(reversedList(pointList()), false); } } static public class TargetAndActual extends MetaWithChangeListeners { public TargetAndActual() { } public transient FieldVar varTarget_cache; public FieldVar varTarget() { if (varTarget_cache == null) varTarget_cache = varTarget_load(); return varTarget_cache; } public FieldVar varTarget_load() { return new FieldVar(this, "target", () -> target(), target -> target(target)); } final public TargetAndActual setTarget(A target) { return target(target); } public TargetAndActual target(A target) { if (!eq(this.target, target)) { this.target = target; change(); } return this; } final public A getTarget() { return target(); } public A target() { return target; } public A target; public transient FieldVar varActual_cache; public FieldVar varActual() { if (varActual_cache == null) varActual_cache = varActual_load(); return varActual_cache; } public FieldVar varActual_load() { return new FieldVar(this, "actual", () -> actual(), actual -> actual(actual)); } final public TargetAndActual setActual(A actual) { return actual(actual); } public TargetAndActual actual(A actual) { if (!eq(this.actual, actual)) { this.actual = actual; change(); } return this; } final public A getActual() { return actual(); } public A actual() { return actual; } public A actual; public TargetAndActual(A target, A actual) { this.actual = actual; this.target = target; } public TargetAndActual(A target) { this.target = target; } public String toString() { return commaCombine(target == null ? null : "Target: " + target, actual == null ? null : "Actual: " + actual); } final public A get() { return value(); } public A value() { return actual; } public boolean hasTarget() { return target != null; } final public void value(A actual) { set(actual); } public void set(A actual) { actual(actual); } } static public class CleanExit extends RuntimeException { public CleanExit() { } public CleanExit(String msg) { super(msg); } } static public interface IIntIntPred { public boolean get(int a, int b); } static public class IntMinMax { public int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; public void add(int i) { if (i < min) min = i; if (i > max) max = i; } public int rangeLength() { return max - min; } } static public class ImageSurfaceSelector extends ImageSurfaceMouseHandler { public Point startingPoint; public boolean enabled = true; static public boolean verbose = false; public ImageSurfaceSelector() { } public ImageSurfaceSelector(ImageSurface is) { if (containsInstance(is.tools, ImageSurfaceSelector.class)) return; this.register(is); } public void mousePressed(MouseEvent evt) { if (verbose) print("mousePressed"); if (evt.getButton() != MouseEvent.BUTTON1) return; if (enabled) startingPoint = getPoint(evt); } public void mouseDragged(MouseEvent e) { if (verbose) print("mouseDragged"); if (startingPoint != null) { Point endPoint = getPoint(e); Rectangle r = new Rectangle(startingPoint, new Dimension(endPoint.x - startingPoint.x + 1, endPoint.y - startingPoint.y + 1)); normalize(r); r.width = min(r.width, is.getImage().getWidth() - r.x); r.height = min(r.height, is.getImage().getHeight() - r.y); is.setSelection(r); } if (verbose) print("mouseDragged done"); } public static void normalize(Rectangle r) { if (r.width < 0) { r.x += r.width; r.width = -r.width; } if (r.height < 0) { r.y += r.height; r.height = -r.height; } } public void mouseReleased(MouseEvent e) { if (verbose) print("mouseReleased"); mouseDragged(e); if (getPoint(e).equals(startingPoint)) is.setSelection((Rectangle) null); startingPoint = null; } } static public class ScreenCamStream extends SourceTriggeredStream implements Steppable { final public ScreenCamStream setArea(Rect area) { return area(area); } public ScreenCamStream area(Rect area) { this.area = area; return this; } final public Rect getArea() { return area(); } public Rect area() { return area; } volatile public Rect area = screenBounds(0); public boolean step() { if (ended()) return false; catchError(() -> shootImpl()); return true; } public long frameCount() { return elementCount(); } public void shootImpl() { var img = shootScreenWithMeta(area).image; assertInstanceOf(ScreenShotMeta.class, getMetaSrc(img)); newElement(img); } public void useScreen(int iScreen) { area = screenBounds_safe(iScreen); } } static public class HashedBWImage implements IBWImage, MakesBWImage { public BWImage image; public long hash; public boolean hashComputed = false; public HashedBWImage(BufferedImage image) { this(bwImage(image)); } public HashedBWImage(BWImage image) { this.image = image; assertNotNull(image); } public long hash() { while (!hashComputed) { synchronized (this) { if (!hashComputed) { hash = hashBWImage(image); hashComputed = true; } } } return hash; } public boolean equals(Object o) { if (o instanceof HashedBWImage) { if (hash() != ((HashedBWImage) o).hash()) return false; if (!bwImagesIdentical(image, ((HashedBWImage) o).image)) { reportHashCollision(this, ((HashedBWImage) o)); return false; } return true; } return false; } public int hashCode() { return (int) hash(); } final public BWImage getBWImage() { return get(); } public BWImage get() { return image; } public int getWidth() { return image.getWidth(); } public int getHeight() { return image.getHeight(); } public BufferedImage getBufferedImage() { return image.getBufferedImage(); } public void verify() { if (hash != 0) assertEquals(hash, hashBWImage(image)); } public String classNameForPrinting() { return cnfp(this, HashedBWImage.class, "HashedBWImage"); } public String toString() { return formatFunctionCall(classNameForPrinting(), w() + "*" + h() + "px", "hash " + longToHex(hash())); } public float getFloatPixel(int x, int y) { return image.getFloatPixel(x, y); } public int getInt(int x, int y) { return image.getInt(x, y); } } static public class RectAsRecognizedBox implements IRecognizedBox, IFieldsToList { public Rect bounds; public RectAsRecognizedBox() { } public RectAsRecognizedBox(Rect bounds) { this.bounds = bounds; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + bounds + ")"; } public boolean equals(Object o) { if (!(o instanceof RectAsRecognizedBox)) return false; RectAsRecognizedBox __1 = (RectAsRecognizedBox) o; return eq(bounds, __1.bounds); } public int hashCode() { int h = -549506401; h = boostHashCombine(h, _hashCode(bounds)); return h; } public Object[] _fieldsToList() { return new Object[] { bounds }; } public Rect bounds() { return bounds; } } static public class WeightlessShuffledIterator extends IterableIterator implements IndexIterator { final public List list; final public int n; final public int bits, cycleLength, a, b, c; public int i; public int value; public WeightlessShuffledIterator(int n) { this((List) iotaZeroList(n)); } public WeightlessShuffledIterator(List list) { this.list = list; n = l(list); if (n == 0) { a = b = c = bits = cycleLength = 0; return; } bits = numberOfBitsNeededToRepresentNOptions(n + 1); var lsfr = new TripletLSFR(bits); a = lsfr.a; b = lsfr.b; c = lsfr.c; value = lsfr.value; cycleLength = lsfr.cycleLength; } public boolean hasNext() { return i < n; } public A next() { return list.get(nextIndex()); } public int nextIndex() { if (i >= n) return -1; ++i; int raw; do { int x = value; x ^= (x << a) & cycleLength; x ^= x >>> b; x ^= (x << c) & cycleLength; value = x; raw = postProcessLSFRValue(x - 1); } while (raw >= n); return raw; } public int bits() { return bits; } public int postProcessLSFRValue(int i) { return i; } } static public ThreadLocal> MyHTTPD_headers = new ThreadLocal(); static public ThreadLocal MyHTTPD_current = new ThreadLocal(); static public class MyHTTPD extends NanoHTTPD { public MyHTTPD(int port) { super(port); } public Object onServe, onEndServe; volatile public long requests; transient public IF0 enter; public Object serveFunction = new F2, Object>() { public Object get(String uri, Map parms) { try { return callHtmlMethod2(getMainClass(), uri, parms); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callHtmlMethod2(getMainClass(), uri, parms)"; } }; static public class Serving { public String uri; public Map header, parms, files; } public Set currentlyServing = synchroSet(); public Response serve(String uri, Method method, Map header, Map parms, Map files) { try { AutoCloseable __1 = callF(enter); try { ++requests; AutoCloseable __2 = tempSetThreadLocal(MyHTTPD_current, this); try { Serving serving = nu(Serving.class, "uri", uri, "header", header, "parms", parms, "files", files); currentlyServing.add(serving); pcallF(onServe, serving); try { String remoteAddr = getClientIPFromHeaders(header); String host = header.get("host"); print(formatDateAndTime() + " Serving URI: " + quote((nempty(host) ? "//" + host : "") + uri) + " to: " + remoteAddr); try { Response response = (Response) (callOpt(getMainClass(), "serve", uri, method, header, parms, files)); if (response != null) return response; Object html; MyHTTPD_headers.set(header); try { html = callF(serveFunction, uri, parms); } finally { MyHTTPD_headers.set(null); } if (html != null) return html instanceof String ? serveHTML((String) html) : (NanoHTTPD.Response) html; return serve404(); } catch (Throwable e) { printStackTrace(e); return serveHTML("ERROR."); } } finally { pcallF(onEndServe, serving); currentlyServing.remove(serving); } } finally { _close(__2); } } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } } static public class RegisteredReference implements IRef { public Meta owner; public A value; public RegisteredReference() { } public RegisteredReference(Meta owner) { this(owner, null); } public RegisteredReference(Meta owner, A value) { this.value = value; this.owner = owner; index(); } public Meta owner() { return owner; } public A get() { return value; } public boolean has() { return value != null; } public boolean set_trueIfChanged(A a) { if (eq(a, value)) return false; unindex(); value = a; index(); return true; } public void set(A a) { set_trueIfChanged(a); } public void setIfEmpty(A a) { if (!has()) set(a); } public void set(IRef ref) { set(ref == null ? null : ref.get()); } public void clear() { set((A) null); } public boolean validRef() { return true; } public void index() { if (!validRef()) return; var br = lookupInterface(IHasBackRefs.class, get()); { if (br != null) br._registerBackRef(this); } } public void unindex() { if (!validRef()) return; var br = lookupInterface(IHasBackRefs.class, get()); { if (br != null) br._unregisterBackRef(this); } } public void change() { } public String toString() { return str(value); } } static public class TreeMultiMap extends MultiMap { public TreeMultiMap() { super(true); } public TreeMultiMap(MultiMap map) { this(); putAll(map); } public NavigableMap> innerMap() { return (NavigableMap) data; } } static public class Range { public float min = 1f, max = 0f; public Range() { } public Range(float x) { min = max = x; } public Range(float min, float max) { this.max = max; this.min = min; } public boolean empty() { return min > max; } public float length() { return max(0f, max - min); } } static public class FreeOfLocalBlockedKeyword implements IF1 { public RegExp regExp; public FreeOfLocalBlockedKeyword() { List words = tlft(loadJavaXSecretTextFile("hidden-keywords.txt")); regExp = empty(words) ? null : cicAnyToRegexp(words); } public Boolean get(String s) { return regExp == null || !regExp.containedIn(s); } } final static public class ContentsIndexedList extends RandomAccessAbstractList implements IContentsIndexedList, IContentsIndexedList2 { public Map>> index = new HashMap(); final public ArrayList> list = new ArrayList(); final static public class Elem extends HasIndex { public A s; public String toString() { return "Elem " + quote(s) + "@" + idx; } } public ContentsIndexedList() { } public ContentsIndexedList(Map>> index) { this.index = index; } public ContentsIndexedList(Collection l) { addAll(l); } public A get(int i) { return list.get(i).s; } public int size() { return list.size(); } public A set(int i, A s) { Elem t = list.get(i); A old = t.s; if (eq(old, s)) return old; removeFromIdx(t); t.s = s; addToIdx(t); return old; } public boolean add(A s) { ++modCount; Elem t = new Elem(); t.s = s; t.idx = size(); list.add(t); addToIdx(t); return true; } public void add(int i, A s) { ++modCount; Elem t = new Elem(); t.s = s; t.idx = i; list.add(i, t); reorder(i + 1); addToIdx(t); } public boolean addAll(int i, Collection l) { int n = l.size(); if (n == 0) return false; ++modCount; List> l2 = emptyList(n); int j = i; for (A s : l) { Elem t = new Elem(); t.s = s; t.idx = j++; l2.add(t); } list.addAll(i, l2); reorder(i + n); for (Elem t : l2) addToIdx(t); return true; } public A remove(int i) { ++modCount; Elem t = list.get(i); removeFromIdx(t); list.remove(i); reorder(i); return t.s; } public void reorder(int fromIdx) { int n = size(); for (int i = fromIdx; i < n; i++) list.get(i).idx = i; } public void removeFromIdx(Elem t) { TreeSet> idx = index.get(t.s); idx.remove(t); if (idx.isEmpty()) index.remove(t.s); } public void addToIdx(Elem t) { TreeSet> idx = index.get(t.s); if (idx == null) index.put(t.s, idx = new TreeSet()); idx.add(t); } @Override public int indexOf(Object s) { TreeSet> l = index.get(s); return l == null ? -1 : first(l).idx; } @Override public int lastIndexOf(Object s) { TreeSet> l = index.get(s); return l == null ? -1 : last(l).idx; } @Override public boolean contains(Object s) { return index.containsKey(s); } public void clear() { ++modCount; index.clear(); list.clear(); } public void removeRange(int fromIndex, int toIndex) { if (fromIndex == toIndex) return; ++modCount; for (int i = fromIndex; i < toIndex; i++) removeFromIdx(list.get(i)); list.subList(fromIndex, toIndex).clear(); reorder(fromIndex); } public int[] indicesOf(A o) { TreeSet> idx = index.get(o); if (idx == null) return emptyIntArray(); int[] a = new int[idx.size()]; int i = 0; for (Elem t : idx) a[i++] = t.idx; return a; } public TreeSet indicesOf_treeSetOfHasIndex(A o) { return (TreeSet) index.get(o); } } static public class FileTransferable implements Transferable { public List files = new ArrayList(); public FileTransferable(File f) { files.add(f); } public FileTransferable(List files) { this.files = files; } public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DataFlavor.javaFileListFlavor }; } public boolean isDataFlavorSupported(DataFlavor flavor) { return eq(flavor, DataFlavor.javaFileListFlavor); } public Object getTransferData(DataFlavor flavor) { return files; } } abstract static public class AbstractSteppable implements Steppable { public void run() { try { stepAll(this); } catch (Exception __e) { throw rethrow(__e); } } } static public class ClassMaker { final public String getClassName() { return className(); } public String className() { return className; } public String className; final public ClassGen getCg() { return cg(); } public ClassGen cg() { return cg; } public ClassGen cg; public JavaClass baked; public InMemoryClassLoader classLoader; public Class loadedClass; final public ClassMaker setPrintDisassembly(boolean printDisassembly) { return printDisassembly(printDisassembly); } public ClassMaker printDisassembly(boolean printDisassembly) { this.printDisassembly = printDisassembly; return this; } final public boolean getPrintDisassembly() { return printDisassembly(); } public boolean printDisassembly() { return printDisassembly; } public boolean printDisassembly = false; final public ClassMaker setSuperClassName(String superClassName) { return superClassName(superClassName); } public ClassMaker superClassName(String superClassName) { this.superClassName = superClassName; return this; } final public String getSuperClassName() { return superClassName(); } public String superClassName() { return superClassName; } public String superClassName = "java.lang.Object"; final public ClassMaker setFileName(String fileName) { return fileName(fileName); } public ClassMaker fileName(String fileName) { this.fileName = fileName; return this; } final public String getFileName() { return fileName(); } public String fileName() { return fileName; } public String fileName; public ClassMaker(String className) { this(className, null); } public ClassMaker(String className, String superClassName, String[] interfaces) { this.superClassName = superClassName; this.className = className; setClassGen(new ClassGen(className, superClassName, fileName, Const.ACC_PUBLIC, interfaces)); } public ClassMaker(String className, String[] interfaces) { this.className = className; setClassGen(new ClassGen(className, superClassName, fileName, Const.ACC_PUBLIC, interfaces)); } public ClassMaker(Class interfaceToImplement) { className = randomClassName(); setClassGen(new ClassGen(className, "java.lang.Object", null, Const.ACC_PUBLIC, new String[] { utils.className(interfaceToImplement) })); addDefaultConstructor(); } public void addDefaultConstructor() { cg.addEmptyConstructor(Const.ACC_PUBLIC); } public void setClassGen(ClassGen cg) { this.cg = cg; cg.setMajor(50); cg.setMinor(0); } public JavaClass bake() { if (baked == null) { baked = cg.getJavaClass(); if (printDisassembly) printClassWithMethods(); } return baked; } public void printClassWithMethods() { print_tabToSingleSpace(bake()); for (var method : baked.getMethods()) { print_tabToSingleSpace("\n" + method); print_tabToSingleSpace(method.getCode()); } } public byte[] getBytes_cache; final public byte[] getBytes() { if (getBytes_cache == null) getBytes_cache = getBytes_load(); return getBytes_cache; } final public byte[] getBytes_load() { return toBytes(); } public byte[] toBytes() { return bake().getBytes(); } public Class load() { if (loadedClass == null) { var bytes = toBytes(); classLoader = new InMemoryClassLoader(myClassLoader()); loadedClass = (Class) classLoader.defineAClass(className, bytes); } return loadedClass; } public A newInstance() { return utils.newInstance(load()); } public void addField(FieldGen fg) { cg.addField(fg.getField()); } public ConstantPoolGen getConstantPool() { return cg.getConstantPool(); } } static public interface IContentsIndexedList2 extends List { public TreeSet indicesOf_treeSetOfHasIndex(A o); } static public List _stickyLibs_1400546 = ll("#1400546", "#1400547", "#1400548"); static public class Value implements IF0, IFieldsToList { public A value; public Value() { } public Value(A value) { this.value = value; } public boolean equals(Object o) { if (!(o instanceof Value)) return false; Value __1 = (Value) o; return eq(value, __1.value); } public int hashCode() { int h = 82420049; h = boostHashCombine(h, _hashCode(value)); return h; } public Object[] _fieldsToList() { return new Object[] { value }; } public A get() { return value; } public String toString() { return str(get()); } } static public class OKOrError implements IF0 { public A value; final public Throwable getError() { return error(); } public Throwable error() { return error; } public Throwable error; public OKOrError() { } public OKOrError(A value) { this.value = value; } public OKOrError(boolean dummy, Throwable error) { this.error = error; assertNotNull(error); } final public boolean isOK() { return ok(); } public boolean ok() { return error == null; } public boolean isError() { return error != null; } public String toString() { return ok() ? str(value) : "Error: " + str(error); } public A get() { return !ok() ? null : value; } public A getMandatory() { if (!ok()) throw rethrow(error); return value; } static public OKOrError ok(A a) { return new OKOrError(a); } static public OKOrError error(Throwable error) { return new OKOrError(false, error); } public void setValue(A value) { this.value = value; error = null; } public void setError(Throwable error) { this.value = null; this.error = error; } public void copyFrom(OKOrError x) { value = x.value; error = x.error; } } static public class ImageChooser extends SingleComponentPanel { public ImageSurface is = new ImageSurface(); public JTextField tfPath = new JTextField(); public ImageChooser(BufferedImage img) { this(); setImage(img); } public ImageChooser(RGBImage img) { this(img.getBufferedImage()); } public ImageChooser(PNGFile png) { this(png == null ? null : png.getImage()); } public ImageChooser() { bindToComponent(this, new Runnable() { public void run() { try { is.zoomToWindow(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "is.zoomToWindow()"; } }); is.loadFromClipboard(); setComponent(jMinSize(100, 100, jscroll(is))); componentPopupMenu(is, new VF1() { public void get(JPopupMenu menu) { try { addMenuItem(menu, "Screenshot in 3", new Runnable() { public void run() { try { startThread("Screenshot in 3", new Runnable() { public void run() { try { sleep(3000); final BufferedImage img = shootScreen2(); swingLater(new Runnable() { public void run() { try { is.setImage(img); infoMessage("Screenshot taken (" + img.getWidth() + "*" + img.getHeight() + " px)", 2); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "is.setImage(img);\r\n infoMessage(\"Screenshot taken (\" + img.getWidt..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "sleep(3000);\r\n final BufferedImage img = shootScreen2();\r\n ..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "thread \"Screenshot in 3\" {\r\n sleep(3000);\r\n final BufferedI..."; } }); addMenuItem(menu, "Load snippet or file...", new Runnable() { public void run() { try { final JTextField tf = new JTextField(); showFormTitled("Load image from snippet or file", "Path or snippet ID", tf, new Runnable() { public void run() { try { is.setImage(loadImage2(tf.getText().trim())); is.zoomToDisplaySize(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "is.setImage(loadImage2(tf.getText().trim()));\r\n is.zoomToDisplaySi..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new JTextField tf;\r\n showFormTitled(\"Load image from snippet or ..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, \"Screenshot in 3\", r {\r\n thread \"Screenshot in 3\" {\r..."; } }); } public boolean hasImage() { return is.getImage() != null && is.getImage().getWidth() * is.getImage().getHeight() > 1; } public BWImage getBWImage() { return is.getImage() == null ? null : new BWImage(is.getImage()); } public BufferedImage getImage() { return hasImage() ? is.getImage() : null; } public void setImage(BufferedImage img) { is.setImage(img); is.zoomToWindow(); } public PNGFile createPNGFile() { return hasImage() ? new PNGFile(getImage()) : null; } public void setTitleForUpload(String title) { is.titleForUpload = title; } } static public class Symbol implements CharSequence { public String text; public Symbol() { } public Symbol(String text, boolean dummy) { this.text = text; } public int hashCode() { return _hashCode(text); } public String toString() { return text; } public boolean equals(Object o) { return this == o; } public int length() { return text.length(); } public char charAt(int index) { return text.charAt(index); } public CharSequence subSequence(int start, int end) { return text.substring(start, end); } } static public interface IMeta { public void _setMeta(Object meta); public Object _getMeta(); default public IAutoCloseableF0 _tempMetaMutex() { return new IAutoCloseableF0() { public Object get() { return IMeta.this; } public void close() { } }; } default public Object getMeta(Object obj, Object key) { return metaGet(obj, key); } default public Object metaGet(Object obj, Object key) { return metaMapGet(obj, key); } default public Object metaGet(String key, Object obj) { return metaMapGet(obj, key); } default public Object getMeta(Object key) { return metaGet(key); } default public Object metaGet(Object key) { if (key == null) return null; Object meta = _getMeta(); if (meta instanceof Map) return ((Map) meta).get(key); return null; } default public void metaSet(IMeta obj, Object key, Object value) { metaPut(obj, key, value); } default public void metaPut(IMeta obj, Object key, Object value) { metaMapPut(obj, key, value); } default public void metaSet(Object key, Object value) { metaPut(key, value); } default public void metaPut(Object key, Object value) { if (key == null) return; Map map = convertObjectMetaToMap(this); syncMapPutOrRemove(map, key, value); } } static public class ListToMatrix extends AbstractMatrix { public ListToMatrix() { } public List data; public ListToMatrix(int w, int h, List data) { super(w, h); this.data = data; } public int xyToIndex(int x, int y) { return y * w + x; } public A get(int x, int y) { return data.get(xyToIndex(x, y)); } public void set(int x, int y, A a) { data.set(xyToIndex(x, y), a); } } static public class BetterThread extends Thread { public Runnable target; public BetterThread(Runnable target) { this.target = target; _created(); } public BetterThread(Runnable target, String name) { super(name); this.target = target; _created(); } public void _created() { vmBus_send("threadCreated", this); } public void run() { try { try { vmBus_send("threadStarted", this); if (target != null) target.run(); } finally { vmBus_send("threadEnded", this); } } catch (Exception __e) { throw rethrow(__e); } } public Runnable getTarget() { return target; } } static public class JFileDropTarget extends MetaWithChangeListeners implements Swingable { final public JFileDropTarget setMsg(String msg) { return msg(msg); } public JFileDropTarget msg(String msg) { this.msg = msg; return this; } final public String getMsg() { return msg(); } public String msg() { return msg; } public String msg = "Drop file here or click the button"; public transient FieldVar varFile_cache; public FieldVar varFile() { if (varFile_cache == null) varFile_cache = varFile_load(); return varFile_cache; } public FieldVar varFile_load() { return new FieldVar(this, "file", () -> file(), file -> file(file)); } final public JFileDropTarget setFile(File file) { return file(file); } public JFileDropTarget file(File file) { if (!eq(this.file, file)) { this.file = file; change(); } return this; } final public File getFile() { return file(); } public File file() { return file; } public File file; final public JFileDropTarget setDefaultDirectory(File defaultDirectory) { return defaultDirectory(defaultDirectory); } public JFileDropTarget defaultDirectory(File defaultDirectory) { this.defaultDirectory = defaultDirectory; return this; } final public File getDefaultDirectory() { return defaultDirectory(); } public File defaultDirectory() { return defaultDirectory; } public File defaultDirectory; transient public Set> onFileSelected; public JFileDropTarget onFileSelected(IVF1 f) { onFileSelected = createOrAddToSyncLinkedHashSet(onFileSelected, f); return this; } public JFileDropTarget removeFileSelectedListener(IVF1 f) { utils.remove(onFileSelected, f); return this; } public void fileSelected(File file) { if (onFileSelected != null) for (var listener : onFileSelected) pcallF_typed(listener, file); } public SingleComponentPanel scp = scp(); public JFileDropTarget() { varFile().onChange(file -> { updateComponent(); fileSelected(file); }); } public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { if (!scp.hasComponent()) scp.setComponent(makeComponent()); return jHandleFileDrop((IVF1) (__1 -> setFile(__1)), scp); } public void updateComponent() { scp.setComponent(makeComponent()); } public JComponent makeComponent() { var file = file(); return file == null ? noFileComponent() : componentForFile(file); } public JComponent noFileComponent() { return withBorder(BorderFactory.createDashedBorder(Color.gray, 2, 5, 5, true), jfullcenter(vstackWithSpacing(jcenteredlabel(msg), jThreadedButton("Open file...", () -> openDialog())))); } transient public IF1 componentForFile; public JComponent componentForFile(File file) { return componentForFile != null ? componentForFile.get(file) : componentForFile_base(file); } final public JComponent componentForFile_fallback(IF1 _f, File file) { return _f != null ? _f.get(file) : componentForFile_base(file); } public JComponent componentForFile_base(File file) { return jfullcenter(jFilePathLabel(file).visualize()); } public void setComponent(JComponent component) { scp.setComponent(component); } public void openDialog() { JFileChooser fc = new JFileChooser(); fc.setDialogTitle("Open file"); fc.setCurrentDirectory(or(defaultDirectory(), userDir())); if (fc.showOpenDialog(scp) == JFileChooser.APPROVE_OPTION) setFile(fc.getSelectedFile()); } } static public class BetterThreadLocal { public Map map = newWeakHashMap(); public BetterThreadLocal() { } public BetterThreadLocal(A value) { set(value); } public boolean isSet() { return map.containsKey(currentThread()); } public A get() { if (map.containsKey(currentThread())) return map.get(currentThread()); A value = initialValue(); set(value); return value; } public A get(Thread thread) { return thread == null ? null : map.get(thread); } public void set(A a) { map.put(currentThread(), a); } public A initialValue() { return null; } } static public class JTargetAndActualSlider extends MetaWithChangeListeners implements Swingable { public TargetAndActual data = new TargetAndActual(); public transient FieldVar varShowSlider_cache; public FieldVar varShowSlider() { if (varShowSlider_cache == null) varShowSlider_cache = varShowSlider_load(); return varShowSlider_cache; } public FieldVar varShowSlider_load() { return new FieldVar(this, "showSlider", () -> showSlider(), showSlider -> showSlider(showSlider)); } final public JTargetAndActualSlider setShowSlider(boolean showSlider) { return showSlider(showSlider); } public JTargetAndActualSlider showSlider(boolean showSlider) { if (!eq(this.showSlider, showSlider)) { this.showSlider = showSlider; change(); } return this; } final public boolean getShowSlider() { return showSlider(); } public boolean showSlider() { return showSlider; } public boolean showSlider = true; public transient FieldVar varSliderEnabled_cache; public FieldVar varSliderEnabled() { if (varSliderEnabled_cache == null) varSliderEnabled_cache = varSliderEnabled_load(); return varSliderEnabled_cache; } public FieldVar varSliderEnabled_load() { return new FieldVar(this, "sliderEnabled", () -> sliderEnabled(), sliderEnabled -> sliderEnabled(sliderEnabled)); } final public JTargetAndActualSlider setSliderEnabled(boolean sliderEnabled) { return sliderEnabled(sliderEnabled); } public JTargetAndActualSlider sliderEnabled(boolean sliderEnabled) { if (!eq(this.sliderEnabled, sliderEnabled)) { this.sliderEnabled = sliderEnabled; change(); } return this; } final public boolean getSliderEnabled() { return sliderEnabled(); } public boolean sliderEnabled() { return sliderEnabled; } public boolean sliderEnabled = true; public transient FieldVar varMin_cache; public FieldVar varMin() { if (varMin_cache == null) varMin_cache = varMin_load(); return varMin_cache; } public FieldVar varMin_load() { return new FieldVar(this, "min", () -> min(), min -> min(min)); } final public JTargetAndActualSlider setMin(double min) { return min(min); } public JTargetAndActualSlider min(double min) { if (!eq(this.min, min)) { this.min = min; change(); } return this; } final public double getMin() { return min(); } public double min() { return min; } public double min; public transient FieldVar varMax_cache; public FieldVar varMax() { if (varMax_cache == null) varMax_cache = varMax_load(); return varMax_cache; } public FieldVar varMax_load() { return new FieldVar(this, "max", () -> max(), max -> max(max)); } final public JTargetAndActualSlider setMax(double max) { return max(max); } public JTargetAndActualSlider max(double max) { if (!eq(this.max, max)) { this.max = max; change(); } return this; } final public double getMax() { return max(); } public double max() { return max; } public double max = 100; public transient FieldVar varDecimalsToShow_cache; public FieldVar varDecimalsToShow() { if (varDecimalsToShow_cache == null) varDecimalsToShow_cache = varDecimalsToShow_load(); return varDecimalsToShow_cache; } public FieldVar varDecimalsToShow_load() { return new FieldVar(this, "decimalsToShow", () -> decimalsToShow(), decimalsToShow -> decimalsToShow(decimalsToShow)); } final public JTargetAndActualSlider setDecimalsToShow(int decimalsToShow) { return decimalsToShow(decimalsToShow); } public JTargetAndActualSlider decimalsToShow(int decimalsToShow) { if (!eq(this.decimalsToShow, decimalsToShow)) { this.decimalsToShow = decimalsToShow; change(); } return this; } final public int getDecimalsToShow() { return decimalsToShow(); } public int decimalsToShow() { return decimalsToShow; } public int decimalsToShow = 1; public transient FieldVar varWidthOfNumbers_cache; public FieldVar varWidthOfNumbers() { if (varWidthOfNumbers_cache == null) varWidthOfNumbers_cache = varWidthOfNumbers_load(); return varWidthOfNumbers_cache; } public FieldVar varWidthOfNumbers_load() { return new FieldVar(this, "widthOfNumbers", () -> widthOfNumbers(), widthOfNumbers -> widthOfNumbers(widthOfNumbers)); } final public JTargetAndActualSlider setWidthOfNumbers(int widthOfNumbers) { return widthOfNumbers(widthOfNumbers); } public JTargetAndActualSlider widthOfNumbers(int widthOfNumbers) { if (!eq(this.widthOfNumbers, widthOfNumbers)) { this.widthOfNumbers = widthOfNumbers; change(); } return this; } final public int getWidthOfNumbers() { return widthOfNumbers(); } public int widthOfNumbers() { return widthOfNumbers; } public int widthOfNumbers = 50; public transient FieldVar varUnit_cache; public FieldVar varUnit() { if (varUnit_cache == null) varUnit_cache = varUnit_load(); return varUnit_cache; } public FieldVar varUnit_load() { return new FieldVar(this, "unit", () -> unit(), unit -> unit(unit)); } final public JTargetAndActualSlider setUnit(String unit) { return unit(unit); } public JTargetAndActualSlider unit(String unit) { if (!eq(this.unit, unit)) { this.unit = unit; change(); } return this; } final public String getUnit() { return unit(); } public String unit() { return unit; } public String unit; public transient FieldVar varDescription_cache; public FieldVar varDescription() { if (varDescription_cache == null) varDescription_cache = varDescription_load(); return varDescription_cache; } public FieldVar varDescription_load() { return new FieldVar(this, "description", () -> description(), description -> description(description)); } final public JTargetAndActualSlider setDescription(String description) { return description(description); } public JTargetAndActualSlider description(String description) { if (!eq(this.description, description)) { this.description = description; change(); } return this; } final public String getDescription() { return description(); } public String description() { return description; } public String description; public transient FieldVar varPreferredBarWidth_cache; public FieldVar varPreferredBarWidth() { if (varPreferredBarWidth_cache == null) varPreferredBarWidth_cache = varPreferredBarWidth_load(); return varPreferredBarWidth_cache; } public FieldVar varPreferredBarWidth_load() { return new FieldVar(this, "preferredBarWidth", () -> preferredBarWidth(), preferredBarWidth -> preferredBarWidth(preferredBarWidth)); } final public JTargetAndActualSlider setPreferredBarWidth(int preferredBarWidth) { return preferredBarWidth(preferredBarWidth); } public JTargetAndActualSlider preferredBarWidth(int preferredBarWidth) { if (!eq(this.preferredBarWidth, preferredBarWidth)) { this.preferredBarWidth = preferredBarWidth; change(); } return this; } final public int getPreferredBarWidth() { return preferredBarWidth(); } public int preferredBarWidth() { return preferredBarWidth; } public int preferredBarWidth = 50; final public JTargetAndActualSlider setScaling(boolean scaling) { return scaling(scaling); } public JTargetAndActualSlider scaling(boolean scaling) { this.scaling = scaling; return this; } final public boolean getScaling() { return scaling(); } public boolean scaling() { return scaling; } public boolean scaling = true; transient public JColorBar bar; transient public JSlider slider; transient public JLabel lblActual, lblTarget; public JTargetAndActualSlider() { } public JTargetAndActualSlider(TargetAndActual data) { this.data = data; } public double value() { return unnull(data.value()); } public double target() { return unnull(data.target()); } public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { bar = swing(() -> new JColorBar().max(max)); jPreferWidth(bar, preferredBarWidth); if (showSlider) { slider = scaling ? jLiveValueSlider_double_bothWays(min, max, data.varTarget()) : jLiveValueSlider_double_noScaling(iround(min), iround(max), data.varTarget()); jPreferWidth(slider, preferredBarWidth); } lblActual = jlabel(); lblTarget = jlabel(); data.varActual().onChangeAndNow(() -> { bar.setValue(value()); setText(lblActual, renderValue(value())); }); data.varTarget().onChangeAndNow(() -> { setText(lblTarget, renderValue(target())); }); varSliderEnabled().onChangeAndNow(() -> setEnabled(slider, sliderEnabled)); return vstack(slider == null ? null : westCenterAndEastWithMargin(jlabel(spaceCombine("Target", description)), slider, jMinWidth(widthOfNumbers, lblTarget)), westCenterAndEastWithMargin(jlabel(spaceCombine("Actual", description)), bar, jMinWidth(widthOfNumbers, lblActual))); } transient public IF1 renderValue; public String renderValue(double value) { return renderValue != null ? renderValue.get(value) : renderValue_base(value); } final public String renderValue_fallback(IF1 _f, double value) { return _f != null ? _f.get(value) : renderValue_base(value); } public String renderValue_base(double value) { return spaceCombine(!scaling ? n2(iround(value)) : formatDoubleX(value, decimalsToShow), unit); } public JSlider slider() { visualize(); return slider; } public JTargetAndActualSlider target(double target) { data.target(target); return this; } public JTargetAndActualSlider value(double value) { data.value(value); return this; } } static public class Lowest implements IBest { public A best; public double score; transient public Object onChange; synchronized public boolean isNewBest(double score) { return best == null || score < this.score; } synchronized public double bestScore() { return best == null ? Double.NaN : score; } public double score() { return bestScore(); } synchronized public float floatScore() { return best == null ? Float.NaN : (float) score; } synchronized public float floatScoreOr(float defaultValue) { return best == null ? defaultValue : (float) score; } public boolean put(A a, double score) { boolean change = false; synchronized (this) { if (a != null && isNewBest(score)) { best = a; this.score = score; change = true; } } if (change) pcallF(onChange); return change; } synchronized public void clear() { best = null; score = 0; } synchronized public A get() { return best; } synchronized public boolean has() { return best != null; } synchronized public Pair pair() { return best == null ? null : new Pair(best, bestScore()); } public String toString() { return "Score " + formatDouble_significant2(score, 4) + ": " + best; } } static public class CollapsibleNorthPanel extends MetaWithChangeListeners implements Swingable { public CollapsibleNorthPanel() { } public transient FieldVar varExpanded_cache; public FieldVar varExpanded() { if (varExpanded_cache == null) varExpanded_cache = varExpanded_load(); return varExpanded_cache; } public FieldVar varExpanded_load() { return new FieldVar(this, "expanded", () -> expanded(), expanded -> expanded(expanded)); } final public CollapsibleNorthPanel setExpanded(boolean expanded) { return expanded(expanded); } public CollapsibleNorthPanel expanded(boolean expanded) { if (!eq(this.expanded, expanded)) { this.expanded = expanded; change(); } return this; } final public boolean getExpanded() { return expanded(); } public boolean expanded() { return expanded; } volatile public boolean expanded = false; final public CollapsibleNorthPanel setDefaultSplitPoint(double defaultSplitPoint) { return defaultSplitPoint(defaultSplitPoint); } public CollapsibleNorthPanel defaultSplitPoint(double defaultSplitPoint) { this.defaultSplitPoint = defaultSplitPoint; return this; } final public double getDefaultSplitPoint() { return defaultSplitPoint(); } public double defaultSplitPoint() { return defaultSplitPoint; } public double defaultSplitPoint = 0.5; public transient FieldVar varSidePanelName_cache; public FieldVar varSidePanelName() { if (varSidePanelName_cache == null) varSidePanelName_cache = varSidePanelName_load(); return varSidePanelName_cache; } public FieldVar varSidePanelName_load() { return new FieldVar(this, "sidePanelName", () -> sidePanelName(), sidePanelName -> sidePanelName(sidePanelName)); } final public CollapsibleNorthPanel setSidePanelName(String sidePanelName) { return sidePanelName(sidePanelName); } public CollapsibleNorthPanel sidePanelName(String sidePanelName) { if (!eq(this.sidePanelName, sidePanelName)) { this.sidePanelName = sidePanelName; change(); } return this; } final public String getSidePanelName() { return sidePanelName(); } public String sidePanelName() { return sidePanelName; } volatile transient public String sidePanelName; final public JComponent getSideComponent() { return sideComponent(); } public JComponent sideComponent() { return sideComponent; } transient public JComponent sideComponent; final public JComponent getMainComponent() { return mainComponent(); } public JComponent mainComponent() { return mainComponent; } transient public JComponent mainComponent; transient public JSplitPane splitPane; transient public SingleComponentPanel scp = singleComponentPanel(); public CollapsibleNorthPanel(boolean expanded) { this.expanded = expanded; } public CollapsibleNorthPanel(boolean expanded, String sidePanelName, JComponent sideComponent, JComponent mainComponent) { this.mainComponent = mainComponent; this.sideComponent = sideComponent; this.sidePanelName = sidePanelName; this.expanded = expanded; } public void init(String sidePanelName, JComponent sideComponent, JComponent mainComponent) { this.sideComponent = sideComponent; this.mainComponent = mainComponent; sidePanelName(sidePanelName); } public void expand() { setExpanded(true); } public void collapse() { setExpanded(false); } public void toggle() { setExpanded(!expanded); } public void updateScp() { swing(() -> { if (metaGet("scaffolding") != null) scaffoldCalled(this, "updateScp"); if (expanded) { splitPane().setTopComponent(wrappedSideComponent()); splitPane().setBottomComponent(mainComponent); scp.set(splitPane()); } else { scp.set(northAndCenterWithMargin(collapsedSidePanel(), mainComponent)); } }); } public JComponent expandButton() { print("Making expandButton"); return jClickableImage_instantToolTip("#1103076", "Expand " + sidePanelName, new Runnable() { public void run() { try { expand(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "expand();"; } }); } public JComponent collapseButton() { print("Making collapseButton"); return jClickableImage_instantToolTip("#1103104", "Collapse " + sidePanelName, new Runnable() { public void run() { try { collapse(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "collapse();"; } }); } transient public IF0 wrappedSideComponent; public JComponent wrappedSideComponent() { return wrappedSideComponent != null ? wrappedSideComponent.get() : wrappedSideComponent_base(); } final public JComponent wrappedSideComponent_fallback(IF0 _f) { return _f != null ? _f.get() : wrappedSideComponent_base(); } public JComponent wrappedSideComponent_base() { var c = northAndCenterWithMargin(sidePanelHeading(), sideComponent); return sidePanelMargins(c); } transient public IF0 collapsedSidePanel; public JComponent collapsedSidePanel() { return collapsedSidePanel != null ? collapsedSidePanel.get() : collapsedSidePanel_base(); } final public JComponent collapsedSidePanel_fallback(IF0 _f) { return _f != null ? _f.get() : collapsedSidePanel_base(); } public JComponent collapsedSidePanel_base() { return sidePanelMargins(sidePanelHeading()); } public JComponent expandOrCollapseButton() { return expanded ? collapseButton() : expandButton(); } public JComponent sidePanelHeading() { return rightAlignedLineWithSpacing(5, onLeftClick(new Runnable() { public void run() { try { toggle(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "toggle();"; } }, liveValueLabel(varSidePanelName())), expandOrCollapseButton()); } public JSplitPane splitPane() { if (splitPane == null) { splitPane = jvsplit_minZero(defaultSplitPoint(), wrappedSideComponent(), null); varExpanded().onChangeAndNow(new Runnable() { public void run() { try { updateScp(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "updateScp();"; } }); } return splitPane; } transient public IF1 sidePanelMargins; public JComponent sidePanelMargins(JComponent c) { return sidePanelMargins != null ? sidePanelMargins.get(c) : sidePanelMargins_base(c); } final public JComponent sidePanelMargins_fallback(IF1 _f, JComponent c) { return _f != null ? _f.get(c) : sidePanelMargins_base(c); } public JComponent sidePanelMargins_base(JComponent c) { return c; } public JComponent visualize() { splitPane(); return scp; } } static public class RegionBorder_innerPoints extends AbstractSteppable implements IFieldsToList { public FastRegions_BWImage regions; public int iRegion; public RegionBorder_innerPoints() { } public RegionBorder_innerPoints(FastRegions_BWImage regions, int iRegion) { this.iRegion = iRegion; this.regions = regions; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + regions + ", " + iRegion + ")"; } public Object[] _fieldsToList() { return new Object[] { regions, iRegion }; } transient public Set> onNewTrace; public RegionBorder_innerPoints onNewTrace(IVF1 f) { onNewTrace = createOrAddToSyncLinkedHashSet(onNewTrace, f); return this; } public RegionBorder_innerPoints removeNewTraceListener(IVF1 f) { utils.remove(onNewTrace, f); return this; } public void newTrace(boolean isHole) { if (onNewTrace != null) for (var listener : onNewTrace) pcallF_typed(listener, isHole); } transient public Set> onFoundPoint; public RegionBorder_innerPoints onFoundPoint(IVF1 f) { onFoundPoint = createOrAddToSyncLinkedHashSet(onFoundPoint, f); return this; } public RegionBorder_innerPoints removeFoundPointListener(IVF1 f) { utils.remove(onFoundPoint, f); return this; } public void foundPoint(Pt p) { if (onFoundPoint != null) for (var listener : onFoundPoint) pcallF_typed(listener, p); } transient public Set onTraceDone; public RegionBorder_innerPoints onTraceDone(Runnable r) { onTraceDone = createOrAddToSyncLinkedHashSet(onTraceDone, r); return this; } public RegionBorder_innerPoints removeTraceDoneListener(Runnable r) { utils.remove(onTraceDone, r); return this; } public void traceDone() { if (onTraceDone != null) for (var listener : onTraceDone) pcallF_typed(listener); } public int w, x, y, dir; public FastRegions_BWImage.RegionIterator it; public byte[] reachedInDirections; public boolean tracing = false; final public boolean getTracingHole() { return tracingHole(); } public boolean tracingHole() { return tracingHole; } public boolean tracingHole = false; static public Pt[] directions = { pt(1, 0), pt(0, 1), pt(-1, 0), pt(0, -1) }; public void init() { w = regions.w; reachedInDirections = new byte[w * regions.h]; it = regions.regionIterator(iRegion); } public boolean step() { if (reachedInDirections == null) init(); if (tracing) { int pos = y * w + x; if ((reachedInDirections[pos] & (1 << dir)) != 0) { traceDone(); tracing = false; return true; } reachedInDirections[pos] |= (byte) 1 << dir; foundPoint(x, y); for (int turn = 3; turn <= 6; turn++) { int newDir = (dir + turn) & 3; Pt d = directions[newDir]; int x2 = x + d.x, y2 = y + d.y; boolean b = regions.inRegion(iRegion, x2, y2); if (b) { x = x2; y = y2; dir = newDir; return true; } } return true; } else { if (!it.next()) return false; x = it.x(); y = it.y(); if (reachedInDirections[y * w + x] != 0) return true; if (!regions.inRegion(iRegion, x, y - 1)) { startTrace(0); return true; } if (!regions.inRegion(iRegion, x - 1, y)) { startTrace(3); return true; } if (!regions.inRegion(iRegion, x + 1, y)) { startTrace(1); return true; } if (!regions.inRegion(iRegion, x, y + 1)) { startTrace(2); return true; } return true; } } public void startTrace(int dir) { this.dir = dir; reachedInDirections[y * w + x] = (byte) (15 & ~(1 << dir)); tracing = true; newTrace(tracingHole); tracingHole = true; } public void foundPoint(int x, int y) { foundPoint(pt(x, y)); } public List allPoints_cache; public List allPoints() { if (allPoints_cache == null) allPoints_cache = allPoints_load(); return allPoints_cache; } public List allPoints_load() { PtBuffer l = new PtBuffer(); onFoundPoint(p -> l.add(p)); run(); return l; } public OnePath onePath_cache; public OnePath onePath() { if (onePath_cache == null) onePath_cache = onePath_load(); return onePath_cache; } public OnePath onePath_load() { return new OnePath(allPoints(), true); } public void runAndPrint() { onNewTrace(hole -> print(!hole ? "new outline" : "new hole")); onTraceDone(() -> print("traceDone")); onFoundPoint(p -> print("foundPoint " + p)); stepMaxWithStats(this, 10000); } } static public class ChangeTrigger implements Runnable, IFieldsToList { public ChangeTriggerable target; public ChangeTrigger() { } public ChangeTrigger(ChangeTriggerable target) { this.target = target; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + target + ")"; } public boolean equals(Object o) { if (!(o instanceof ChangeTrigger)) return false; ChangeTrigger __1 = (ChangeTrigger) o; return eq(target, __1.target); } public int hashCode() { int h = -1239972920; h = boostHashCombine(h, _hashCode(target)); return h; } public Object[] _fieldsToList() { return new Object[] { target }; } public void run() { try { { if (target != null) target.change(); } } catch (Exception __e) { throw rethrow(__e); } } } static public class AnimatedImageSurface extends ImageSurface { public double fps = 20; public FlexibleRateTimer animationTimer = new FlexibleRateTimer(0, () -> renderFrame()).pileUp(false); public void renderFrame() { var img = makeImage(); if (img != null) setImage(img); } final public AnimatedImageSurface setFPS(double fps) { return fps(fps); } public AnimatedImageSurface fps(double fps) { this.fps = fps; { swing(() -> { updateTimer(isShowing()); }); } return this; } transient public IF0 makeImage; public BufferedImage makeImage() { return makeImage != null ? makeImage.get() : makeImage_base(); } final public BufferedImage makeImage_fallback(IF0 _f) { return _f != null ? _f.get() : makeImage_base(); } public BufferedImage makeImage_base() { return whiteImage(10, 10); } public AnimatedImageSurface() { init(); } public AnimatedImageSurface(IF0 makeImage) { this.makeImage = makeImage; init(); } public AnimatedImageSurface(double fps, IF0 makeImage) { this.makeImage = makeImage; setFPS(fps); init(); } public AnimatedImageSurface(Frequency freq, IF0 makeImage) { this.makeImage = makeImage; setFPS(freq.get()); init(); } public void updateTimer(boolean showing) { animationTimer.setFrequencyImmediately(showing ? fps : 0.0); } public void init() { setDoubleBuffered(true); bindToComponent(this, () -> { animationTimer.start(); updateTimer(true); }, () -> updateTimer(false)); } } static public class ScoredSearcher_stable { public int maxResults = 1000; public boolean returnAll = false; public List preparedTerms; public MultiMap byScore = descTreeMultiMap(); public ScoredSearcher_stable() { } public ScoredSearcher_stable(String query, Object... __) { maxResults = optPar("maxResults", __, maxResults); setQuery(query); } public void setQuery(String query) { preparedTerms = scoredSearch_prepare(query); } public void put(A object, String s) { putScored(object, score(s)); } public void putScored(A object, double score) { if (score != 0) byScore.add(score, object); } public void put(A object, Collection fields) { add(object, scoreFields(fields)); } public void putWithWeights(A object, Collection> fields) { scoredSearch_scoreWeighted2(fields, preparedTerms); } public int scoreFields(Collection fields) { return scoredSearch_score(fields, preparedTerms); } public int score(String text) { return returnAll ? 1 : scoredSearch_score(text, preparedTerms); } public void add(A object) { put(object, str(object)); } public void add(A object, Collection fields) { put(object, fields); } public void put(A object, double score) { add(object, score); } public void add(A object, double score) { putScored(object, score); } public List get() { return pairsB(takeFirst(maxResults, multiMapPairIterator(byScore))); } public List get_transformListWithinScore(IF1, List> f) { return pairsB(takeFirst(maxResults, multiMapPairIterator_transformValueList(byScore, f))); } public List> withScores() { return map(takeFirst(maxResults, multiMapPairIterator(byScore)), p -> new Scored(p.b, p.a)); } public A best() { return firstValue(byScore); } } static public class JMiniJavaIDE implements Swingable { final public JMiniJavaIDE setLvScript(SimpleLiveValue lvScript) { return lvScript(lvScript); } public JMiniJavaIDE lvScript(SimpleLiveValue lvScript) { this.lvScript = lvScript; return this; } final public SimpleLiveValue getLvScript() { return lvScript(); } public SimpleLiveValue lvScript() { return lvScript; } public SimpleLiveValue lvScript = stringLiveValue(); public String sectionTitle = "Mini Java IDE"; static public String helpText = "Javaaa"; transient public CompileResult compileResult; transient public RSyntaxTextAreaWithSearch taScript; transient public Q compileQ = new Q(); transient public JLabel lblCompileResult; transient public JButton btnRun; transient public JavaCompletionProvider completionProvider; transient public AutoCompletion autoComplete; final public JMiniJavaIDE setStringifier(IStringifier stringifier) { return stringifier(stringifier); } public JMiniJavaIDE stringifier(IStringifier stringifier) { this.stringifier = stringifier; return this; } final public IStringifier getStringifier() { return stringifier(); } public IStringifier stringifier() { return stringifier; } transient public IStringifier stringifier; public class JavaCompletionProvider extends DefaultCompletionProvider { @Override public List getCompletionByInputText(String inputText) { print("getCompletionByInputText: " + quote(inputText)); return ll(); } @Override public List getCompletionsImpl(JTextComponent comp) { return getCompletionByInputText(getAlreadyEnteredText(comp)); } } public JComponent visualize() { taScript = liveValueRSyntaxTextArea_bothWays(lvScript); awtCalcEvery(taScript.textArea(), 5.0, () -> compileQ.add(new Runnable() { public void run() { try { compile(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "compile();"; } })); { swing(() -> { completionProvider = new JavaCompletionProvider(); completionProvider.setAutoActivationRules(true, " "); autoComplete = new AutoCompletion(completionProvider); autoComplete.setAutoActivationEnabled(true); autoComplete.install(taScript.textArea); }); } return jCenteredSection(sectionTitle, centerAndSouthWithMargin(taScript.visualize(), centerAndEastWithMargin(jBorderlessHigherScrollPane(lblCompileResult = jlabel()), vstack(jline(btnRun = jbutton("Run", runnableThread(new Runnable() { public void run() { try { runButtonAction(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "runButtonAction();"; } })), jPopDownButton_noText("Show Scripting Help", runnableThread(new Runnable() { public void run() { try { showTextWordWrapped("Gazelle 'Left arrow script' Help", helpText); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showTextWordWrapped(\"Gazelle 'Left arrow script' Help\", helpText)"; } }))))))); } public boolean visible() { return isShowing(lblCompileResult); } public void compile() { var script = lvScript.get(); var result = compileResult; if (result == null || !eq(result.script, script)) { setStatus("Compiling..."); try { result = new CompileResult(); result.script = script; result.className = "UserCode_" + now(); result.adaptedScript = adaptScript(result); result.java = result.adaptedScript; result.compiledObject = veryQuickJava_finish_specialMainClass(result.className, result.java); print("compiledObject", result.compiledObject); } catch (Throwable e) { printStackTrace(e); result.compileError = e; } compileResult = result; setText(lblCompileResult, compileResult); updateRunButtonState(); } } public void updateRunButtonState() { setEnabled(btnRun, runButtonShouldBeEnabled()); } transient public IF0 runButtonShouldBeEnabled; public boolean runButtonShouldBeEnabled() { return runButtonShouldBeEnabled != null ? runButtonShouldBeEnabled.get() : runButtonShouldBeEnabled_base(); } final public boolean runButtonShouldBeEnabled_fallback(IF0 _f) { return _f != null ? _f.get() : runButtonShouldBeEnabled_base(); } public boolean runButtonShouldBeEnabled_base() { return compileResult != null && compileResult.runnable(); } public CompileResult freshCompileResult() { runInQAndWait(compileQ, new Runnable() { public void run() { try { compile(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "compile();"; } }); return compileResult; } public Object compiledObject() { return freshCompileResult().compiledObject; } transient public Runnable runButtonAction; public void runButtonAction() { if (runButtonAction != null) runButtonAction.run(); else runButtonAction_base(); } final public void runButtonAction_fallback(Runnable _f) { if (_f != null) _f.run(); else runButtonAction_base(); } public void runButtonAction_base() { runScript(); } public void runScript() { var result = freshCompileResult(); if (result.compiledObject != null) { setStatus("Running"); result.result = okOrError(() -> callCompiledObject(result.compiledObject)); setStatus(result.result.isOK() ? shorten(stringify(stringifier, result.result.get())) : exceptionToStringShorter(result.result.error())); } } public class CompileResult { public String script, adaptedScript, java; public String className; public Class compiledObject; public Throwable compileError; public OKOrError result; public String toString() { if (compileError == null) return "Compiled OK"; String msg = compileError.getMessage(); msg = dropPrefixFromLines("> ", msg); var errors = parseECJOutputForErrors(msg); if (nempty(errors)) { var error = first(errors); print("codeLine", quote(error.codeLine)); pnlQuoted(asList(lines_iterator(script))); int lineNr = indexOfLine(script, tabsToSpaces(error.codeLine)); error.lineNr = lineNr + 1; return str(error); } return msg; } public boolean runnable() { return compiledObject != null; } } public void setStatus(String status) { setText(lblCompileResult, status); } transient public IF1 extraClassMembers; public String extraClassMembers(String script) { return extraClassMembers != null ? extraClassMembers.get(script) : extraClassMembers_base(script); } final public String extraClassMembers_fallback(IF1 _f, String script) { return _f != null ? _f.get(script) : extraClassMembers_base(script); } public String extraClassMembers_base(String script) { return ""; } transient public IF1 adaptScript; public String adaptScript(CompileResult result) { return adaptScript != null ? adaptScript.get(result) : adaptScript_base(result); } final public String adaptScript_fallback(IF1 _f, CompileResult result) { return _f != null ? _f.get(result) : adaptScript_base(result); } public String adaptScript_base(CompileResult result) { return tok_moveImportsUp("class " + result.className + "{" + extraClassMembers(result.script) + "\n" + evalJava_prep(result.script) + "}"); } transient public IF1 callCompiledObject; public Object callCompiledObject(Object object) { return callCompiledObject != null ? callCompiledObject.get(object) : callCompiledObject_base(object); } final public Object callCompiledObject_fallback(IF1 _f, Object object) { return _f != null ? _f.get(object) : callCompiledObject_base(object); } public Object callCompiledObject_base(Object object) { return callCalc(object); } } static public class AutoVMExit extends TimerTask { static public boolean installed = false; static public boolean disabled = false; public int lastObjectCount = -1; static public java.util.Timer timer; static public int firstDelay = 30000; static public int delay = 5000; public static void install() { if (!installed) { installed = true; if (!disabled) { timer = new java.util.Timer("AutoVMExit"); timer.scheduleAtFixedRate(new AutoVMExit(), firstDelay, delay); } } } public void run() { if (isHiddenVM()) return; int objectCount = autoVMExit_visibleObjects(); if (objectCount == 0 && lastObjectCount == 0) { System.out.println("AutoVMExit: No windows open or tray icons installed - exiting"); cleanKillVM(); } lastObjectCount = objectCount; } public static void disable() { disabled = true; if (timer != null) timer.cancel(); } public static int getFirstDelay() { return firstDelay; } public static void setFirstDelay(int firstDelay) { AutoVMExit.firstDelay = firstDelay; } public static int getDelay() { return delay; } public static void setDelay(int delay) { AutoVMExit.delay = delay; } } static public class BoundsFinder { public int x1 = Integer.MAX_VALUE, y1 = Integer.MAX_VALUE, x2 = 0, y2 = 0; public BoundsFinder() { } public BoundsFinder(int w, int h) { x1 = w; y1 = h; } final public void add(Pt p) { addPt(p); } public void addPt(Pt p) { if (p != null) addPt(p.x, p.y); } final public void add(int x, int y) { addPt(x, y); } public void addPt(int x, int y) { if (x < x1) x1 = x; if (x > x2) x2 = x; if (y < y1) y1 = y; if (y > y2) y2 = y; } public Rect get() { return rectFromPointsOrNull(x1, y1, x2 + 1, y2 + 1); } } static public class MinimalChain implements Iterable { public A element; public MinimalChain next; public MinimalChain() { } public MinimalChain(A element) { this.element = element; } public MinimalChain(A element, MinimalChain next) { this.next = next; this.element = element; } public String toString() { return str(toList()); } public ArrayList toList() { ArrayList l = new ArrayList(); MinimalChain c = this; while (c != null) { l.add(c.element); c = c.next; } return l; } public void setElement(A a) { element = a; } public void setNext(MinimalChain next) { this.next = next; } public Iterator iterator() { return toList().iterator(); } public A get() { return element; } } static public class NamedConcept extends Concept { public String name; public String toString() { String s = super.toString(); if (nempty(name)) s += " " + quote(name); return s; } } static public class Image2B implements IBinaryImage { public Image2B() { } public int w, h; public byte[] pixels; public Image2B(int w, int h, byte[] pixels) { this.pixels = pixels; this.h = h; this.w = w; cleanPixelArray(); } public Image2B(Image2B img) { w = img.getWidth(); h = img.getHeight(); pixels = cloneByteArray(img.pixels); } public Image2B(RGBImage img) { w = img.getWidth(); h = img.getHeight(); pixels = new byte[(w * h + 7) / 8]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) if (img.getPixel(x, y).getBrightness() >= 0.5f) { int i = y * w + x; pixels[i / 8] |= 1 << (i & 7); } } public Image2B(BWImage img) { this(img, 128); } public Image2B(BWImage img, int threshold) { w = img.w(); h = img.h(); int n = w * h; int nOut = (n + 7) / 8; byte[] pixels = this.pixels = new byte[nOut]; byte[] bwPixels = img.pixels; int iIn = 0; for (int iOut = 0; iOut < nOut - 1; iOut++) { int value = 0; for (int bit = 0; bit < 8; bit++) { value >>= 1; if (ubyteToInt(bwPixels[iIn++]) >= threshold) value |= 0x80; } pixels[iOut] = (byte) value; } for (; iIn < n; iIn++) if (ubyteToInt(bwPixels[iIn]) >= threshold) pixels[nOut - 1] |= 1 << (iIn & 7); } public Image2B(BufferedImage img) { this(img, 128); } public Image2B(BufferedImage img, int threshold) { this(new BWImage(img), threshold); } public Image2B(int w, int h) { this.h = h; this.w = w; pixels = new byte[(w * h + 7) / 8]; } public RGBImage toRGB() { RGBImage img = new RGBImage(w, h, Color.black); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { int i = y * w + x; if ((pixels[i / 8] & (1 << (i & 7))) != 0) img.setPixel(x, y, Color.white); } return img; } public BWImage toBW() { BWImage img = new BWImage(w, h, 0f); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { int i = y * w + x; if ((pixels[i / 8] & (1 << (i & 7))) != 0) img.setPixel(x, y, 1f); } return img; } public BufferedImage getBufferedImage() { return toBW().getBufferedImage(); } final public boolean getBoolPixel(int x, int y) { return getPixel(x, y); } public boolean getPixel(int x, int y) { int i = y * w + x; return (pixels[i / 8] & (1 << (i & 7))) != 0; } final public boolean getBoolPixel(int x, int y, boolean defaultColor) { return getPixel(x, y, defaultColor); } public boolean getPixel(int x, int y, boolean defaultColor) { if (x < 0 || y < 0 || x >= w || y >= h) return defaultColor; return getPixel(x, y); } public void setPixel(int x, int y, boolean b) { int i = y * w + x; byte val = pixels[i / 8], shifted = (byte) (1 << (i & 7)); val = (byte) (b ? val | shifted : val & ~shifted); pixels[i / 8] = val; } public void setPixel(int x, int y) { int i = y * w + x; pixels[i / 8] |= 1 << (i & 7); } public int getWidth() { return w; } public int getHeight() { return h; } public String toString() { return "Image2B " + str_px(w, h); } public void cleanPixelArray() { int n = w * h; if ((n & 7) != 0) pixels[n / 8] &= (1 << (n & 7)) - 1; } public double averageBrightness() { return doubleRatio(bitCount(pixels), w * h); } } abstract static public class AbstractFastRegions implements Runnable, IImageRegions, IFieldsToList { public Img image; public AbstractFastRegions() { } public AbstractFastRegions(Img image) { this.image = image; } public Object[] _fieldsToList() { return new Object[] { image }; } public int w, h; public int runner; final public int getSize() { return size(); } public int size() { return size; } public int size; public IntBuffer stack = new IntBuffer(); final public int[] getRegionMatrix() { return regionMatrix(); } public int[] regionMatrix() { return regionMatrix; } public int[] regionMatrix; public IntBuffer regionPixels = new IntBuffer(); final public AbstractFastRegions setWithDiagonals(boolean withDiagonals) { return withDiagonals(withDiagonals); } public AbstractFastRegions withDiagonals(boolean withDiagonals) { this.withDiagonals = withDiagonals; return this; } final public boolean getWithDiagonals() { return withDiagonals(); } public boolean withDiagonals() { return withDiagonals; } public boolean withDiagonals = false; public IntBuffer regionFirstPixel = new IntBuffer(); public IntBuffer regionSize = new IntBuffer(); public IntBuffer regionBounds = new IntBuffer(); public List regionsBySize = new ArrayList(); public int regionCounter; public boolean verbose = false; public int currentColor; public double regionStep = .1; public int x(int pos) { return pos % w; } public int y(int pos) { return pos / w; } public int pos(int x, int y) { return y * w + x; } public Pt pt(int pos) { return new Pt(x(pos), y(pos)); } public boolean validPos(int x, int y) { return x >= 0 && y >= 0 && x < w && y < h; } abstract public int getColor(int pos); public boolean initialized() { return regionMatrix != null; } public void init() { if (initialized()) return; w = image.getWidth(); h = image.getHeight(); size = w * h; regionMatrix = new int[size]; { if (regionFirstPixel != null) regionFirstPixel.add(0); } { if (regionSize != null) regionSize.add(0); } { if (regionPixels != null) regionPixels.setSize(size); } } public void run() { try { if (initialized()) return; init(); while (runner < size) { if (regionMatrix[runner] == 0) makeRegion(); ++runner; } } catch (Exception __e) { throw rethrow(__e); } } public int makeRegion() { int region = ++regionCounter; { if (regionFirstPixel != null) regionFirstPixel.add(regionPixels != null ? l(regionPixels) : runner); } currentColor = getColor(runner); stack.add(runner); int rsize = 0, x1 = w, y1 = h, x2 = 0, y2 = 0; while (nempty(stack)) { int pos = stack.popLast(); if (regionMatrix[pos] != 0) continue; int x = x(pos), y = y(pos); int lineStart = pos - x; int xLeft = x; while (xLeft > 0 && addable(lineStart + xLeft - 1)) --xLeft; int xRight = x + 1; while (xRight < w && addable(lineStart + xRight)) ++xRight; for (x = xLeft; x < xRight; x++) { regionMatrix[lineStart + x] = region; { if (regionPixels != null) regionPixels.add(lineStart + x); } } rsize += xRight - xLeft; if (xLeft < x1) x1 = xLeft; if (xRight - 1 > x2) x2 = xRight - 1; if (y < y1) y1 = y; if (y > y2) y2 = y; int xLeft2 = withDiagonals ? max(0, xLeft - 1) : xLeft; int xRight2 = withDiagonals ? min(w, xRight + 1) : xRight; if (y > 0) addStreaks(lineStart - w, xLeft2, xRight2); if (y < h - 1) addStreaks(lineStart + w, xLeft2, xRight2); } { if (regionSize != null) regionSize.add(rsize); } { if (regionBounds != null) regionBounds.addAll(x1, y1, x2 + 1, y2 + 1); } if (regionsBySize != null) { int iBucket = dualLog(rsize); var buffer = listGetOrCreate(regionsBySize, iBucket, () -> new IntBuffer()); buffer.add(region); } return region; } public boolean addable(int pos) { if (regionMatrix[pos] != 0) return false; if (getColor(pos) != currentColor) return false; return true; } public boolean addToStack(int pos) { if (!addable(pos)) return false; stack.add(pos); return true; } public void addStreaks(int lineStart, int xLeft, int xRight) { int x = xLeft; while (x < xRight) { if (addToStack(lineStart + x)) while (x + 1 < xRight && addable(lineStart + x + 1)) ++x; ++x; } } public IBWImage regionsImage() { return iBWImageFromFunction((x, y) -> { var region = regionMatrix[pos(x, y)]; return ((region - 1) * regionStep) % (1.0 + regionStep - 0.0001); }, w, h); } final public int nRegions() { return regionCount(); } public int regionCount() { return regionCounter; } abstract public class RegionIterator { public int pos; abstract public boolean next(); public int pos() { return pos; } public int x() { return AbstractFastRegions.this.x(pos); } public int y() { return AbstractFastRegions.this.y(pos); } public int[] pixelsAsIntArray() { throw todo(); } } public class FloodRegionIterator extends RegionIterator { public int region; public IntBuffer stack = new IntBuffer(); public BitSet seen = new BitSet(size); public FloodRegionIterator(int region) { this.region = region; int pos = regionFirstPixel.get(region); printVars("region", region, "pos", pos); seen.set(pos); stack.add(pos); } public boolean next() { if (empty(stack)) return false; pos = stack.popLast(); int x = x(), y = y(); if (x > 0) tryPosition(pos - 1); if (x < w - 1) tryPosition(pos + 1); if (y > 0) tryPosition(pos - w); if (y < h - 1) tryPosition(pos + w); return true; } private void tryPosition(int p) { if (!seen.get(p) && regionMatrix[p] == region) { seen.set(p); stack.add(p); } } } public class CachedRegionIterator extends RegionIterator { public int i, to; public CachedRegionIterator(int region) { i = regionFirstPixel.get(region); to = region + 1 < l(regionFirstPixel) ? regionFirstPixel.get(region + 1) : l(regionPixels); } public boolean next() { if (i >= to) return false; pos = regionPixels.get(i++); return true; } public int[] pixelsAsIntArray() { return regionPixels.subArray(i, to); } } public int regionSize(int iRegion) { return regionSize.get(iRegion); } final public Pt firstPixel(int iRegion) { return samplePixel(iRegion); } public Pt samplePixel(int iRegion) { return pt(firstPixelPos(iRegion)); } public int firstPixelPos(int iRegion) { int i = regionFirstPixel.get(iRegion); return regionPixels != null ? regionPixels.get(i) : i; } public boolean inRegion(int iRegion, int x, int y) { return validPos(x, y) && regionMatrix[pos(x, y)] == iRegion; } public Rect regionBounds(int iRegion) { return rectFromPoints(regionBounds.get((iRegion - 1) * 4), regionBounds.get((iRegion - 1) * 4 + 1), regionBounds.get((iRegion - 1) * 4 + 2), regionBounds.get((iRegion - 1) * 4 + 3)); } public int regionAt(Pt p) { return regionAt(p.x, p.y); } public int regionAt(int x, int y) { return !validPos(x, y) ? 0 : regionMatrix[pos(x, y)]; } public int regionAt(int pos) { return regionMatrix[pos]; } public RegionIterator regionIterator(int iRegion) { return regionPixels != null ? new CachedRegionIterator(iRegion) : new FloodRegionIterator(iRegion); } public List regionPixels(int iRegion) { var it = regionIterator(iRegion); List l = new ArrayList(); while (it.next()) l.add(new Pt(it.x(), it.y())); return l; } public void collectFirstPixels() { } public void collectBounds() { } public Matrix regionBitMatrix(int iRegion) { return new AbstractMatrix(w, h) { public Boolean get(int x, int y) { return inRegion(iRegion, x, y); } }; } public void markRegionInPixelArray(int[] pixels, int iRegion, int rgba) { if (iRegion <= 0) return; for (int i = 0; i < l(pixels); i++) if (regionAt(i) == iRegion) pixels[i] = rgba; } public List regionIndices() { return virtualCountList(1, nRegions() + 1); } public IterableIterator regionsRoughlyByDecreasingSize() { return nestedIterator(countIterator_inclusive_backwards(regionsBySize.size() - 1, 0), iBucket -> iterator(regionsBySize.get(iBucket))); } final public IImageRegion get(int iRegion) { return getRegion(iRegion); } public IImageRegion getRegion(int iRegion) { return new ImageRegion(iRegion); } final public List> get() { return regions(); } public List> regions() { run(); return listFromFunction(i -> getRegion(i + 1), nRegions()); } public class ImageRegion implements IImageRegion, IFieldsToList { public int iRegion; public ImageRegion() { } public ImageRegion(int iRegion) { this.iRegion = iRegion; } public Object[] _fieldsToList() { return new Object[] { iRegion }; } public int hashCode() { return iRegion; } public boolean equals(Object o) { if (!(o instanceof AbstractFastRegions.ImageRegion)) return false; return ((AbstractFastRegions.ImageRegion) o).creator() == creator() && ((AbstractFastRegions.ImageRegion) o).iRegion == iRegion; } public Img image() { return image; } public Object creator() { return AbstractFastRegions.this; } public int indexInCreator() { return iRegion; } public Boolean createdWithDiagonals() { return withDiagonals; } public Rect bounds() { return regionBounds(iRegion); } public int numberOfPixels() { return regionSize(iRegion); } public Pt firstPixel() { return pt(firstPixelPos()); } public int firstPixelPos() { return AbstractFastRegions.this.firstPixelPos(iRegion); } public IterableIterator pixelIterator() { var it = regionIterator(iRegion); return iteratorFromFunction(() -> it.next() ? pt(it.pos()) : null); } public int[] pixelsAsIntArray() { return regionIterator(iRegion).pixelsAsIntArray(); } public boolean contains(int x, int y) { return inRegion(iRegion, x, y); } public Color color() { return toColor(rgbForRegion(this)); } final public int firstPixelLogicalColor() { return brightness(); } public int brightness() { return getColor(firstPixelPos()); } public String toString() { return renderRecordVars("Region", "brightness", brightness(), "color", color(), "pixels", numberOfPixels(), "bounds", bounds()); } } abstract public RGB rgbForRegion(ImageRegion r); public Img image() { return image; } public void markDone() { runner = size; } } static public class SynchronizedSortedSet extends SynchronizedSet implements SortedSet { public SynchronizedSortedSet() { } @java.io.Serial static final public long serialVersionUID = 8695801310862127406L; @SuppressWarnings("serial") public SortedSet ss; public SynchronizedSortedSet(SortedSet s) { super(s); ss = s; } public SynchronizedSortedSet(SortedSet s, Object mutex) { super(s, mutex); ss = s; } public Comparator comparator() { synchronized (mutex) { return ss.comparator(); } } public SortedSet subSet(E fromElement, E toElement) { synchronized (mutex) { return new SynchronizedSortedSet<>(ss.subSet(fromElement, toElement), mutex); } } public SortedSet headSet(E toElement) { synchronized (mutex) { return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex); } } public SortedSet tailSet(E fromElement) { synchronized (mutex) { return new SynchronizedSortedSet<>(ss.tailSet(fromElement), mutex); } } public E first() { synchronized (mutex) { return ss.first(); } } public E last() { synchronized (mutex) { return ss.last(); } } } static public class SSI extends AbstractSSI implements ByteIO, StringIO { public SSI() { } final public SSI setY1(short y1) { return y1(y1); } public SSI y1(short y1) { this.y1 = y1; return this; } final public short getY1() { return y1(); } public short y1() { return y1; } public short y1; final public SSI setData(short[] data) { return data(data); } public SSI data(short[] data) { this.data = data; return this; } final public short[] getData() { return data(); } public short[] data() { return data; } public short[] data; public SSI(int y1, int y2) { init(y1, y2); } public void init(int y1, int y2) { this.y1 = toShort_enforce(y1); data = newShortArrayOrNull((y2 - y1) * 2); } public void set(int y, int xLeft, int xRight) { data[(y - y1) * 2] = toShort_enforce(xLeft); data[(y - y1) * 2 + 1] = toShort_enforce(xRight); } public int getLeft(int y) { return data[(y - y1) * 2]; } public int getRight(int y) { return data[(y - y1) * 2 + 1]; } public Rect bounds_cache; public Rect bounds() { if (bounds_cache == null) bounds_cache = bounds_load(); return bounds_cache; } public Rect bounds_load() { int x1 = Integer.MAX_VALUE, x2 = 0; for (int i = 0; i < l(data); i += 2) { x1 = min(x1, data[i]); x2 = max(x2, data[i + 1]); } return rectFromPoints(x1, y1, x2, y2()); } public int numberOfPixels_cache = -1; public int numberOfPixels() { if (numberOfPixels_cache < 0) { int n = 0; for (int i = 0; i < l(data); i += 2) n += max(0, data[i + 1] - data[i]); numberOfPixels_cache = n; } return numberOfPixels_cache; } public int getHeight() { return l(data) / 2; } public int y2() { return y1 + height(); } public boolean contains(Pt p) { return contains(p.x, p.y); } public boolean contains(int x, int y) { if (y < y1) return false; int i = (y - y1) * 2; if (i >= l(data)) return false; return x >= data[i] && x < data[i + 1]; } public SSI color(Color color) { super.color(color); return this; } public SSI hi15color(short hi15color) { super.hi15color(hi15color); return this; } public void drawOn(Graphics2D g) { g.setColor(color()); int h = height(); for (int y = 0; y < h; y++) { int x1 = data[y * 2], x2 = data[y * 2 + 1]; if (x1 < x2) g.drawLine(x1, y1 + y, x2 - 1, y1 + y); } } public void drawOutline(Graphics2D g) { int h = height(); IntRange last = intRange(0, 0); for (int y = 0; y < h; y++) { IntRange r = intRange(data[y * 2], data[y * 2 + 1]); if (nempty(r)) { if (empty(last)) g.drawLine(r.start, y1 + y, r.end - 1, y1 + y); else { int xleft = max(r.start, last.start - 1); int xright = min(r.end - 1, last.end); g.drawLine(r.start, y1 + y, xleft, y1 + y); g.drawLine(xright, y1 + y, r.end - 1, y1 + y); } } last = r; } } public SSI topPart(int nLines) { if (nLines <= 0) return null; SSI ssi = new SSI(y1, toShort_enforce(y1 + nLines)).hi15color(hi15color); arrayCopy(data, ssi.data, 0, l(ssi.data)); return ssi; } public boolean coherent() { return coherent(false); } public boolean coherent(boolean withDiagonals) { int h = height(); for (int y = 0; y < h; y++) { int i = y * 2; int x1 = data[i], x2 = data[i + 1]; if (x1 >= x2) return false; if (y > 0) { int lastx1 = data[i - 2], lastx2 = data[i - 1]; if (withDiagonals) { lastx1--; lastx2++; } if (!intRangesOverlap(x1, x2, lastx1, lastx2)) return false; } } return true; } public void readWrite(ByteHead head) { head.exchangeShort(() -> hi15color, color -> hi15color = color); head.exchangeShort(() -> y1, y1 -> this.y1 = y1); head.exchangeShort(() -> toShort_enforce(y2()), y2 -> init(y1, y2)); for (int i = 0; i < l(data); i++) { var _i_2 = i; head.exchangeShort(() -> data[_i_2], x -> data[_i_2] = x); } } public SSI toSSI() { return this; } public long sizeInInts() { return 4 + height() * 2; } public SSI reduceToInts(int ints) { return topPart((ints - 4) / 2); } public void readWrite(StringHead head) { head.exchangeLine(() -> toLine(), __1 -> fromLine(__1)); } public String toLine() { return spaceCombine("s", colorToString(), y1, height(), toList(data)); } public void fromLine(String line) { Iterator it = splitAtSpaceIterator(line); assertEquals("s", nextFromIterator(it)); int y1 = parseInt(nextFromIterator(it)); int h = parseInt(nextFromIterator(it)); init(y1, y1 + h); for (int i = 0; i < l(data); i++) data[i] = toShort_enforce(parseInt(nextFromIterator(it))); } } static public class JE_CompressEachElementIndividually extends AbstractCompressor_AnyType> { final public JE_CompressEachElementIndividually setElementCompressionStrategy(IF0, El>> elementCompressionStrategy) { return elementCompressionStrategy(elementCompressionStrategy); } public JE_CompressEachElementIndividually elementCompressionStrategy(IF0, El>> elementCompressionStrategy) { this.elementCompressionStrategy = elementCompressionStrategy; return this; } final public IF0, El>> getElementCompressionStrategy() { return elementCompressionStrategy(); } public IF0, El>> elementCompressionStrategy() { return elementCompressionStrategy; } public IF0, El>> elementCompressionStrategy; public List, El>> searches = new ArrayList(); final public JE_CompressEachElementIndividually setMakeLiteral(IF1 makeLiteral) { return makeLiteral(makeLiteral); } public JE_CompressEachElementIndividually makeLiteral(IF1 makeLiteral) { this.makeLiteral = makeLiteral; return this; } final public IF1 getMakeLiteral() { return makeLiteral(); } public IF1 makeLiteral() { return makeLiteral; } public IF1 makeLiteral; public BitSet compressedElementsBitSet = new BitSet(); public JE_CompressEachElementIndividually onCompressionFail(IF1 f) { makeLiteral = f; return this; } final public JE_CompressEachElementIndividually setDebug(boolean debug) { return debug(debug); } public JE_CompressEachElementIndividually debug(boolean debug) { this.debug = debug; return this; } final public boolean getDebug() { return debug(); } public boolean debug() { return debug; } public boolean debug = false; public List renderedElements = new ArrayList(); public ICachedJavaXExpr renderedCode; public BitSet dirtyElements = new BitSet(); public int size() { return l(inputData()); } public int nNotLiteral() { return countPred(searches, search -> search.has()); } public ICachedJavaXExpr getRenderedElement(int i) { if (metaGet("scaffolding") != null) scaffoldCalled(this, "getRenderedElement", i); if (contains(dirtyElements, i) || _get(renderedElements, i) == null) { remove(dirtyElements, i); var e = renderElement(i); listSet(renderedElements, i, e); } return renderedElements.get(i); } public ICachedJavaXExpr renderElement(int i) { var search = _get(searches, i); ICachedJavaXExpr comp = search == null ? null : search.get(); if (comp != null) { synchronized (compressedElementsBitSet) { compressedElementsBitSet.set(i); } return comp; } ICachedJavaXExpr java = makeLiteral.get(_get(inputData(), i)); metaSet(java, "gaveUp", this); return java; } public boolean dirty() { return nempty(dirtyElements) || l(renderedElements) < size(); } public void flush() { if (!dirty()) return; submit(code()); } public List codeForElements() { return countIteratorToList(__144 -> getRenderedElement(__144), size()); } public ICachedJavaXExpr code() { if (dirty() || renderedCode == null) { List els = codeForElements(); int iNull = indexOf(els, null); if (iNull >= 0) throw fail("Null element: " + iNull + "/" + l(els)); renderedCode = javaExpr(functionCall_list("ll", els), () -> mapQuickEval_javaExpr(els)); } return renderedCode; } public void step0() { if (elementCompressionStrategy == null) return; probabilisticForEach(scheduler(), 1.0, 0.5, indexAsSideValue(inputData()), ivf1WithToString("Compress element", data -> { int i = data.sideValue(); var subSearch = new CompressionSearch_AnyType, El>(assertNotNull("childRegime", childRegime()), data.get(), 1); subSearch.onNewBest(() -> set(dirtyElements, i)); listSet(searches, i, subSearch); subSearch.addStrategy(elementCompressionStrategy.get()); })); } public String stats() { return renderVars("nNotLiteral", nNotLiteral() + " of " + size()); } transient public IF0>> childRegime; public CompressionRegime_AnyType> childRegime() { return childRegime != null ? childRegime.get() : childRegime_base(); } final public CompressionRegime_AnyType> childRegime_fallback(IF0>> _f) { return _f != null ? _f.get() : childRegime_base(); } public CompressionRegime_AnyType> childRegime_base() { return (CompressionRegime_AnyType) regime(); } public boolean isElementCompressed(int i) { synchronized (compressedElementsBitSet) { return compressedElementsBitSet.get(i); } } } final static public class DoubleRange implements Comparable { final public double getStart() { return start(); } public double start() { return start; } public double start; final public double getEnd() { return end(); } public double end() { return end; } public double end; public DoubleRange() { } public DoubleRange(double start, double end) { this.end = end; this.start = start; } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } public double length() { return end - start; } public boolean isEmpty() { return start >= end; } public double center() { return (start + end) / 2; } static public String _fieldOrder = "start end"; public String toString() { return "[" + start + ";" + end + "]"; } @Override public int compareTo(DoubleRange r) { int c = cmp(start, r.start); if (c != 0) return c; return cmp(end, r.end); } public boolean contains(double d) { return d >= start && d <= end; } public DoubleRange sort() { return start > end ? doubleRange(end, start) : this; } } static public class DoubleFPSCounter { public FPSCounter counter = new FPSCounter(); volatile public double value; synchronized public void inc() { if (counter.secondsSinceStart() >= 1) { value = counter.get(); counter = new FPSCounter(); } counter.inc(); } synchronized public double get() { return value; } synchronized public String toString() { return counter.isEmpty() ? "" : formatDoubleX(get(), 1) + " FPS"; } } static public class FailedRule extends RuleWithParams { public List satisfiedConditions; public Exp remainingCondition; public FailedRule() { } public FailedRule(IfThen rule, VarMatches matches, Exp remainingCondition) { this.remainingCondition = remainingCondition; this.matches = matches; this.rule = rule; } public FailedRule(IfThen rule, VarMatches matches, List satisfiedConditions, Exp remainingCondition) { this.remainingCondition = remainingCondition; this.satisfiedConditions = satisfiedConditions; this.matches = matches; this.rule = rule; } } static public class RuleWithParams implements IFieldsToList { static final public String _fieldOrder = "rule matches"; public IfThen rule; public VarMatches matches; public RuleWithParams() { } public RuleWithParams(IfThen rule, VarMatches matches) { this.matches = matches; this.rule = rule; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + rule + ", " + matches + ")"; } public boolean equals(Object o) { if (!(o instanceof RuleWithParams)) return false; RuleWithParams __7 = (RuleWithParams) o; return eq(rule, __7.rule) && eq(matches, __7.matches); } public int hashCode() { int h = 1254104616; h = boostHashCombine(h, _hashCode(rule)); h = boostHashCombine(h, _hashCode(matches)); return h; } public Object[] _fieldsToList() { return new Object[] { rule, matches }; } public String ruleID() { return rule.globalID; } } static public class IfThen implements IFieldsToList { static final public String _fieldOrder = "in out globalID options originalText"; public Exp in; public Exp out; public IfThen() { } public IfThen(Exp in, Exp out) { this.out = out; this.in = in; } public boolean equals(Object o) { if (!(o instanceof IfThen)) return false; IfThen __8 = (IfThen) o; return eq(in, __8.in) && eq(out, __8.out); } public int hashCode() { int h = -2108234502; h = boostHashCombine(h, _hashCode(in)); h = boostHashCombine(h, _hashCode(out)); return h; } public Object[] _fieldsToList() { return new Object[] { in, out }; } public String globalID; public Set options; public String originalText; public String text() { Collection opt = options; if (nempty(globalID)) opt = concatLists(ll("id: " + globalID), opt); return (nempty(opt) ? "[" + joinWithComma(opt) + "] " : "") + (in == null ? "" : in.text() + "\n => ") + nlLogic_text(out); } public String toString() { return text(); } } abstract static public class Exp { abstract public String text(); public String toString() { return text(); } } static public class Func extends Exp implements IFieldsToList { public String name; public Exp arg; public Func() { } public Func(String name, Exp arg) { this.arg = arg; this.name = name; } public boolean equals(Object o) { if (!(o instanceof Func)) return false; Func __0 = (Func) o; return eq(name, __0.name) && eq(arg, __0.arg); } public int hashCode() { int h = 2201316; h = boostHashCombine(h, _hashCode(name)); h = boostHashCombine(h, _hashCode(arg)); return h; } public Object[] _fieldsToList() { return new Object[] { name, arg }; } public List options; public Func(String name, List options, Exp arg) { this.arg = arg; this.options = options; this.name = name; } public String text() { return name + (empty(options) ? "" : "[" + joinWithComma(options) + "]") + "(" + arg.text() + ")"; } public String argText() { return nlLogic_text(arg); } } static public class And extends Exp implements IFieldsToList { public Exp a; public Exp b; public And() { } public And(Exp a, Exp b) { this.b = b; this.a = a; } public boolean equals(Object o) { if (!(o instanceof And)) return false; And __1 = (And) o; return eq(a, __1.a) && eq(b, __1.b); } public int hashCode() { int h = 65975; h = boostHashCombine(h, _hashCode(a)); h = boostHashCombine(h, _hashCode(b)); return h; } public Object[] _fieldsToList() { return new Object[] { a, b }; } public String text() { return a.text() + "\n && " + b.text(); } } static public class ExpNot extends Exp implements IFieldsToList { public Exp a; public ExpNot() { } public ExpNot(Exp a) { this.a = a; } public boolean equals(Object o) { if (!(o instanceof ExpNot)) return false; ExpNot __2 = (ExpNot) o; return eq(a, __2.a); } public int hashCode() { int h = 2089649046; h = boostHashCombine(h, _hashCode(a)); return h; } public Object[] _fieldsToList() { return new Object[] { a }; } public String text() { return "!" + a.text(); } } abstract static public class Literal extends Exp { } static public class Sentence extends Literal implements IFieldsToList { public List tok; public Sentence() { } public Sentence(List tok) { this.tok = tok; } public boolean equals(Object o) { if (!(o instanceof Sentence)) return false; Sentence __3 = (Sentence) o; return eq(tok, __3.tok); } public int hashCode() { int h = 1327381123; h = boostHashCombine(h, _hashCode(tok)); return h; } public Object[] _fieldsToList() { return new Object[] { tok }; } public String text() { return join(tok); } } static public class Sentence2 extends Literal implements IFieldsToList { public String text; public Sentence2() { } public Sentence2(String text) { this.text = text; } public boolean equals(Object o) { if (!(o instanceof Sentence2)) return false; Sentence2 __4 = (Sentence2) o; return eq(text, __4.text); } public int hashCode() { int h = -1800858097; h = boostHashCombine(h, _hashCode(text)); return h; } public Object[] _fieldsToList() { return new Object[] { text }; } public String text() { return text; } } static public class Eq extends Exp implements IFieldsToList { public Exp left; public Exp right; public Eq() { } public Eq(Exp left, Exp right) { this.right = right; this.left = left; } public boolean equals(Object o) { if (!(o instanceof Eq)) return false; Eq __5 = (Eq) o; return eq(left, __5.left) && eq(right, __5.right); } public int hashCode() { int h = 2252; h = boostHashCombine(h, _hashCode(left)); h = boostHashCombine(h, _hashCode(right)); return h; } public Object[] _fieldsToList() { return new Object[] { left, right }; } public String text() { return left.text() + " = " + right.text(); } } static public class RenderText implements MakesBufferedImage { final public RenderText setForegroundColor(Color foregroundColor) { return foregroundColor(foregroundColor); } public RenderText foregroundColor(Color foregroundColor) { this.foregroundColor = foregroundColor; return this; } final public Color getForegroundColor() { return foregroundColor(); } public Color foregroundColor() { return foregroundColor; } public Color foregroundColor = Color.black; final public RenderText setBackgroundColor(Color backgroundColor) { return backgroundColor(backgroundColor); } public RenderText backgroundColor(Color backgroundColor) { this.backgroundColor = backgroundColor; return this; } final public Color getBackgroundColor() { return backgroundColor(); } public Color backgroundColor() { return backgroundColor; } public Color backgroundColor = Color.white; final public RenderText setWithLeading(boolean withLeading) { return withLeading(withLeading); } public RenderText withLeading(boolean withLeading) { this.withLeading = withLeading; return this; } final public boolean getWithLeading() { return withLeading(); } public boolean withLeading() { return withLeading; } public boolean withLeading = true; final public RenderText setFont(Font font) { return font(font); } public RenderText font(Font font) { this.font = font; return this; } final public Font getFont() { return font(); } public Font font() { return font; } public Font font = sansSerifFont(20); final public RenderText setFontSize(Float fontSize) { return fontSize(fontSize); } public RenderText fontSize(Float fontSize) { this.fontSize = fontSize; return this; } final public Float getFontSize() { return fontSize(); } public Float fontSize() { return fontSize; } public Float fontSize; final public RenderText setSpacing(double spacing) { return spacing(spacing); } public RenderText spacing(double spacing) { this.spacing = spacing; return this; } final public double getSpacing() { return spacing(); } public double spacing() { return spacing; } public double spacing; final public RenderText setText(String text) { return text(text); } public RenderText text(String text) { this.text = text; return this; } final public String getText() { return text(); } public String text() { return text; } public String text = "DEMO"; final public RenderText setAlignment(String alignment) { return alignment(alignment); } public RenderText alignment(String alignment) { this.alignment = alignment; return this; } final public String getAlignment() { return alignment(); } public String alignment() { return alignment; } public String alignment = "left"; public Font scaledFont; public FontMetrics fm; public List lines; public RenderText() { } public RenderText(Font font) { this.font = font; } public RenderText setFont(String fontSnippetID) { return setFont(fontForName(fontSnippetID)); } public Font scaledFont() { Font font = this.font; if (spacing != 0) font = fontWithSpacing(spacing, font); return scaledFont = fontSize == null ? font : font.deriveFont(fontSize); } public BufferedImage get(String text) { text(text); return this.get(); } final public BufferedImage image() { return get(); } final public BufferedImage getBufferedImage() { return get(); } public BufferedImage get() { fm = fontMetrics(scaledFont()); lines = lines(text); var lineWidths = map(lines, line -> fm.stringWidth(line)); int width = intMax(lineWidths); if (width <= 0) return null; int lineHeight = fm.getHeight(); int height = lineHeight * l(lines); int y = withLeading ? fm.getLeading() + fm.getMaxAscent() : fm.getAscent(); BufferedImage img = bufferedImageWithoutAlpha(width, height, backgroundColor); Graphics g = imageGraphics(img); g.setColor(foregroundColor); g.setFont(scaledFont); for (int i = 0; i < l(lines); i++) { int x = 0; if (eq(alignment, "center")) x = (width - lineWidths.get(i)) / 2; g.drawString(lines.get(i), x, lineHeight * i + y); } g.dispose(); return img; } public boolean canDisplay() { return canFontDisplay(font, text); } public RenderText fontSize(float f) { return fontSize((Float) f); } public String toString() { return "RenderText " + quote(shorten(text)); } } static public class EGDiff { public EGDiff(Object[] a, Object[] b) { Hashtable h = new Hashtable(a.length + b.length); filevec[0] = new file_data(a, h); filevec[1] = new file_data(b, h); } public int equiv_max = 1; public boolean heuristic = false; public boolean no_discards = false; public int[] xvec, yvec; public int[] fdiag; public int[] bdiag; public int fdiagoff, bdiagoff; final public file_data[] filevec = new file_data[2]; public int cost; private int diag(int xoff, int xlim, int yoff, int ylim) { final int[] fd = fdiag; final int[] bd = bdiag; final int[] xv = xvec; final int[] yv = yvec; final int dmin = xoff - ylim; final int dmax = xlim - yoff; final int fmid = xoff - yoff; final int bmid = xlim - ylim; int fmin = fmid, fmax = fmid; int bmin = bmid, bmax = bmid; final boolean odd = (fmid - bmid & 1) != 0; fd[fdiagoff + fmid] = xoff; bd[bdiagoff + bmid] = xlim; for (int c = 1; ; ++c) { int d; boolean big_snake = false; if (fmin > dmin) fd[fdiagoff + --fmin - 1] = -1; else ++fmin; if (fmax < dmax) fd[fdiagoff + ++fmax + 1] = -1; else --fmax; for (d = fmax; d >= fmin; d -= 2) { int x, y, oldx, tlo = fd[fdiagoff + d - 1], thi = fd[fdiagoff + d + 1]; if (tlo >= thi) x = tlo + 1; else x = thi; oldx = x; y = x - d; while (x < xlim && y < ylim && xv[x] == yv[y]) { ++x; ++y; } if (x - oldx > 20) big_snake = true; fd[fdiagoff + d] = x; if (odd && bmin <= d && d <= bmax && bd[bdiagoff + d] <= fd[fdiagoff + d]) { cost = 2 * c - 1; return d; } } if (bmin > dmin) bd[bdiagoff + --bmin - 1] = Integer.MAX_VALUE; else ++bmin; if (bmax < dmax) bd[bdiagoff + ++bmax + 1] = Integer.MAX_VALUE; else --bmax; for (d = bmax; d >= bmin; d -= 2) { int x, y, oldx, tlo = bd[bdiagoff + d - 1], thi = bd[bdiagoff + d + 1]; if (tlo < thi) x = tlo; else x = thi - 1; oldx = x; y = x - d; while (x > xoff && y > yoff && xv[x - 1] == yv[y - 1]) { --x; --y; } if (oldx - x > 20) big_snake = true; bd[bdiagoff + d] = x; if (!odd && fmin <= d && d <= fmax && bd[bdiagoff + d] <= fd[fdiagoff + d]) { cost = 2 * c; return d; } } if (c > 200 && big_snake && heuristic) { int best = 0; int bestpos = -1; for (d = fmax; d >= fmin; d -= 2) { int dd = d - fmid; if ((fd[fdiagoff + d] - xoff) * 2 - dd > 12 * (c + (dd > 0 ? dd : -dd))) { if (fd[fdiagoff + d] * 2 - dd > best && fd[fdiagoff + d] - xoff > 20 && fd[fdiagoff + d] - d - yoff > 20) { int k; int x = fd[fdiagoff + d]; for (k = 1; k <= 20; k++) if (xvec[x - k] != yvec[x - d - k]) break; if (k == 21) { best = fd[fdiagoff + d] * 2 - dd; bestpos = d; } } } } if (best > 0) { cost = 2 * c - 1; return bestpos; } best = 0; for (d = bmax; d >= bmin; d -= 2) { int dd = d - bmid; if ((xlim - bd[bdiagoff + d]) * 2 + dd > 12 * (c + (dd > 0 ? dd : -dd))) { if ((xlim - bd[bdiagoff + d]) * 2 + dd > best && xlim - bd[bdiagoff + d] > 20 && ylim - (bd[bdiagoff + d] - d) > 20) { int k; int x = bd[bdiagoff + d]; for (k = 0; k < 20; k++) if (xvec[x + k] != yvec[x - d + k]) break; if (k == 20) { best = (xlim - bd[bdiagoff + d]) * 2 + dd; bestpos = d; } } } } if (best > 0) { cost = 2 * c - 1; return bestpos; } } } } private void compareseq(int xoff, int xlim, int yoff, int ylim) { while (xoff < xlim && yoff < ylim && xvec[xoff] == yvec[yoff]) { ++xoff; ++yoff; } while (xlim > xoff && ylim > yoff && xvec[xlim - 1] == yvec[ylim - 1]) { --xlim; --ylim; } if (xoff == xlim) while (yoff < ylim) filevec[1].changed_flag[1 + filevec[1].realindexes[yoff++]] = true; else if (yoff == ylim) while (xoff < xlim) filevec[0].changed_flag[1 + filevec[0].realindexes[xoff++]] = true; else { int d = diag(xoff, xlim, yoff, ylim); int c = cost; int b = bdiag[bdiagoff + d]; if (c == 1) { throw new IllegalArgumentException("Empty subsequence"); } else { compareseq(xoff, b, yoff, b - d); compareseq(b, xlim, b - d, ylim); } } } private void discard_confusing_lines() { filevec[0].discard_confusing_lines(filevec[1]); filevec[1].discard_confusing_lines(filevec[0]); } public boolean inhibit = false; private void shift_boundaries() { if (inhibit) return; filevec[0].shift_boundaries(filevec[1]); filevec[1].shift_boundaries(filevec[0]); } public interface ScriptBuilder { public change build_script(boolean[] changed0, int len0, boolean[] changed1, int len1); } static public class ReverseScript implements ScriptBuilder { public change build_script(final boolean[] changed0, int len0, final boolean[] changed1, int len1) { change script = null; int i0 = 0, i1 = 0; while (i0 < len0 || i1 < len1) { if (changed0[1 + i0] || changed1[1 + i1]) { int line0 = i0, line1 = i1; while (changed0[1 + i0]) ++i0; while (changed1[1 + i1]) ++i1; script = new change(line0, line1, i0 - line0, i1 - line1, script); } i0++; i1++; } return script; } } static public class ForwardScript implements ScriptBuilder { public change build_script(final boolean[] changed0, int len0, final boolean[] changed1, int len1) { change script = null; int i0 = len0, i1 = len1; while (i0 >= 0 || i1 >= 0) { if (changed0[i0] || changed1[i1]) { int line0 = i0, line1 = i1; while (changed0[i0]) --i0; while (changed1[i1]) --i1; script = new change(i0, i1, line0 - i0, line1 - i1, script); } i0--; i1--; } return script; } } public final static ScriptBuilder forwardScript = new ForwardScript(), reverseScript = new ReverseScript(); public final change diff_2(final boolean reverse) { return diff(reverse ? reverseScript : forwardScript); } public change diff(final ScriptBuilder bld) { discard_confusing_lines(); xvec = filevec[0].undiscarded; yvec = filevec[1].undiscarded; int diags = filevec[0].nondiscarded_lines + filevec[1].nondiscarded_lines + 3; fdiag = new int[diags]; fdiagoff = filevec[1].nondiscarded_lines + 1; bdiag = new int[diags]; bdiagoff = filevec[1].nondiscarded_lines + 1; compareseq(0, filevec[0].nondiscarded_lines, 0, filevec[1].nondiscarded_lines); fdiag = null; bdiag = null; shift_boundaries(); return bld.build_script(filevec[0].changed_flag, filevec[0].buffered_lines, filevec[1].changed_flag, filevec[1].buffered_lines); } public static class change { public change link; public final int inserted; public final int deleted; public final int line0; public final int line1; public change(int line0, int line1, int deleted, int inserted, change old) { this.line0 = line0; this.line1 = line1; this.inserted = inserted; this.deleted = deleted; this.link = old; } } public class file_data { public void clear() { changed_flag = new boolean[buffered_lines + 2]; } public int[] equivCount() { int[] equiv_count = new int[equiv_max]; for (int i = 0; i < buffered_lines; ++i) ++equiv_count[equivs[i]]; return equiv_count; } public void discard_confusing_lines(file_data f) { clear(); final byte[] discarded = discardable(f.equivCount()); filterDiscards(discarded); discard(discarded); } private byte[] discardable(final int[] counts) { final int end = buffered_lines; final byte[] discards = new byte[end]; final int[] equivs = this.equivs; int many = 5; int tem = end / 64; while ((tem = tem >> 2) > 0) many *= 2; for (int i = 0; i < end; i++) { int nmatch; if (equivs[i] == 0) continue; nmatch = counts[equivs[i]]; if (nmatch == 0) discards[i] = 1; else if (nmatch > many) discards[i] = 2; } return discards; } private void filterDiscards(final byte[] discards) { final int end = buffered_lines; for (int i = 0; i < end; i++) { if (discards[i] == 2) discards[i] = 0; else if (discards[i] != 0) { int j; int length; int provisional = 0; for (j = i; j < end; j++) { if (discards[j] == 0) break; if (discards[j] == 2) ++provisional; } while (j > i && discards[j - 1] == 2) { discards[--j] = 0; --provisional; } length = j - i; if (provisional * 4 > length) { while (j > i) if (discards[--j] == 2) discards[j] = 0; } else { int consec; int minimum = 1; int tem = length / 4; while ((tem = tem >> 2) > 0) minimum *= 2; minimum++; for (j = 0, consec = 0; j < length; j++) if (discards[i + j] != 2) consec = 0; else if (minimum == ++consec) j -= consec; else if (minimum < consec) discards[i + j] = 0; for (j = 0, consec = 0; j < length; j++) { if (j >= 8 && discards[i + j] == 1) break; if (discards[i + j] == 2) { consec = 0; discards[i + j] = 0; } else if (discards[i + j] == 0) consec = 0; else consec++; if (consec == 3) break; } i += length - 1; for (j = 0, consec = 0; j < length; j++) { if (j >= 8 && discards[i - j] == 1) break; if (discards[i - j] == 2) { consec = 0; discards[i - j] = 0; } else if (discards[i - j] == 0) consec = 0; else consec++; if (consec == 3) break; } } } } } private void discard(final byte[] discards) { final int end = buffered_lines; int j = 0; for (int i = 0; i < end; ++i) if (no_discards || discards[i] == 0) { undiscarded[j] = equivs[i]; realindexes[j++] = i; } else changed_flag[1 + i] = true; nondiscarded_lines = j; } public file_data(Object[] data, Hashtable h) { buffered_lines = data.length; equivs = new int[buffered_lines]; undiscarded = new int[buffered_lines]; realindexes = new int[buffered_lines]; for (int i = 0; i < data.length; ++i) { Integer ir = (Integer) h.get(data[i]); if (ir == null) h.put(data[i], new Integer(equivs[i] = equiv_max++)); else equivs[i] = ir.intValue(); } } public void shift_boundaries(file_data f) { final boolean[] changed = changed_flag; final boolean[] other_changed = f.changed_flag; int i = 0; int j = 0; int i_end = buffered_lines; int preceding = -1; int other_preceding = -1; for (; ; ) { int start, end, other_start; while (i < i_end && !changed[1 + i]) { while (other_changed[1 + j++]) other_preceding = j; i++; } if (i == i_end) break; start = i; other_start = j; for (; ; ) { while (i < i_end && changed[1 + i]) i++; end = i; if (end != i_end && equivs[start] == equivs[end] && !other_changed[1 + j] && end != i_end && !((preceding >= 0 && start == preceding) || (other_preceding >= 0 && other_start == other_preceding))) { changed[1 + end] = true; changed[1 + start++] = false; ++i; ++j; } else break; } preceding = i; other_preceding = j; } } final public int buffered_lines; final public int[] equivs; final public int[] undiscarded; final public int[] realindexes; public int nondiscarded_lines; public boolean[] changed_flag; } } static public class Meta implements IMeta { volatile public Object meta; public void _setMeta(Object meta) { this.meta = meta; } public Object _getMeta() { return meta; } final public boolean scaffolding() { return scaffoldingEnabled(); } final public boolean scaffolded() { return scaffoldingEnabled(); } public boolean scaffoldingEnabled() { return utils.scaffoldingEnabled(this); } public boolean scaffoldingEnabled(Object o) { return utils.scaffoldingEnabled(o); } public String toString_base() { return super.toString(); } public String toString() { Object o = metaGet("toString", this); if (o instanceof String) return ((String) o); if (o instanceof IF1) return str(((IF1) o).get(this)); return toString_base(); } } static public class BStack extends VStack implements IBStack { static public int idCounter; public int stackID = ++idCounter; public BStack alternative; public List undos; public BStack() { } public BStack(Computable computation) { push(computation); } public BStack(Iterable l) { pushAll(l); } static public class NoOptionsException extends RuntimeException { } public BStack cloneStack() { BStack s = new BStack(); s.alternative = alternative; s.undos = undos; undos = null; s.stack = shallowCloneElements(stack); return s; } public void addUndo(AutoCloseable undo) { if (undo == null) return; if (undos == null) undos = new ArrayList(); undos.add(undo); } public void options(B function, IVF1... options) { options(function, asList(options)); } public void options(B function, Iterable> options) { List> optionsList = nonNulls(options); if (empty(optionsList)) throw new NoOptionsException(); for (int i = l(optionsList) - 1; i > 0; i--) setAlternative(optionsList.get(i)); first(optionsList).get(function); } static public class ExecuteOption implements VStack.Computable, IFieldsToList { public IVF1 option; public ExecuteOption() { } public ExecuteOption(IVF1 option) { this.option = option; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + option + ")"; } public Object[] _fieldsToList() { return new Object[] { option }; } public void step(VStack stack, Object subComputationResult) { Object target = stack.caller(); stack._return(); option.get(target); } } public void setAlternative(IVF1 option) { alternative = cloneStack(); alternative.push(new ExecuteOption(option)); } public BStack backtrack() { try { for (int i = l(undos) - 1; i >= 0; i--) undos.get(i).close(); return alternative; } catch (Exception __e) { throw rethrow(__e); } } public A nextResult() { stepAll(this); return (A) latestResult; } public A nextResultWithPrintStruct(long maxSteps) { stepMaxWithPrintIndentedStruct(this, maxSteps); return (A) latestResult; } } public enum JVMStackCellType { none, objValue, intValue, longValue, floatValue, doubleValue } static public class FastRegions_BWImage extends AbstractFastRegions { public int getColor(int pos) { return image.getInt(x(pos), y(pos)); } public RGB rgbForRegion(ImageRegion r) { return rgbFromGrayscale(r.brightness()); } public FastRegions_BWImage(BWImage img) { super(img); } public FastRegions_BWImage(BufferedImage img) { this(toBWImage(img)); } } static public class SingleThread { public boolean running = false; public Thread thread; public void run(Object r) { go(r); } synchronized public boolean go(final Object runnable) { if (running) return false; running = true; thread = startThread("Single Thread", new Runnable() { public void run() { try { try { callF(runnable); } finally { _done(); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n callF(runnable);\r\n } finally {\r\n _done();\r\n }"; } }); return true; } synchronized public void _done() { running = false; thread = null; } synchronized public boolean running() { return running; } synchronized public Thread getThread() { return thread; } } static public class InMemoryClassLoader extends ClassLoader { final public InMemoryClassLoader setRememberClassBytes(boolean rememberClassBytes) { return rememberClassBytes(rememberClassBytes); } public InMemoryClassLoader rememberClassBytes(boolean rememberClassBytes) { this.rememberClassBytes = rememberClassBytes; return this; } final public boolean getRememberClassBytes() { return rememberClassBytes(); } public boolean rememberClassBytes() { return rememberClassBytes; } transient public boolean rememberClassBytes = false; transient public Map classBytes = syncMap(); public InMemoryClassLoader(ClassLoader parent) { super(parent); } public Class defineAClass(String name, byte[] bytes) { Class c = defineClass(name, bytes, 0, bytes.length); if (rememberClassBytes) classBytes.put(c, bytes); return c; } public byte[] getClassBytes(Class c) { return classBytes.get(c); } } static public class DefunctClassLoader { } static public class CutListToBudget { final public CutListToBudget setMaxPrice(double maxPrice) { return maxPrice(maxPrice); } public CutListToBudget maxPrice(double maxPrice) { this.maxPrice = maxPrice; return this; } final public double getMaxPrice() { return maxPrice(); } public double maxPrice() { return maxPrice; } public double maxPrice; final public CutListToBudget setInputList(Iterable inputList) { return inputList(inputList); } public CutListToBudget inputList(Iterable inputList) { this.inputList = inputList; return this; } final public Iterable getInputList() { return inputList(); } public Iterable inputList() { return inputList; } public Iterable inputList; final public List getOutputList() { return outputList(); } public List outputList() { return outputList; } public List outputList; final public double getFinalPrice() { return finalPrice(); } public double finalPrice() { return finalPrice; } public double finalPrice; final public CutListToBudget setAllowPartial(boolean allowPartial) { return allowPartial(allowPartial); } public CutListToBudget allowPartial(boolean allowPartial) { this.allowPartial = allowPartial; return this; } final public boolean getAllowPartial() { return allowPartial(); } public boolean allowPartial() { return allowPartial; } public boolean allowPartial = false; final public A getFullLastElement() { return fullLastElement(); } public A fullLastElement() { return fullLastElement; } public A fullLastElement; transient public IF1 getPrice; public double getPrice(A element) { return getPrice != null ? getPrice.get(element) : getPrice_base(element); } final public double getPrice_fallback(IF1 _f, A element) { return _f != null ? _f.get(element) : getPrice_base(element); } public double getPrice_base(A element) { throw unimplemented(); } transient public IF2 reduceElement; public A reduceElement(A element, double budget) { return reduceElement != null ? reduceElement.get(element, budget) : reduceElement_base(element, budget); } final public A reduceElement_fallback(IF2 _f, A element, double budget) { return _f != null ? _f.get(element, budget) : reduceElement_base(element, budget); } public A reduceElement_base(A element, double budget) { return null; } public CutListToBudget(IF1 getPrice) { this.getPrice = getPrice; } public CutListToBudget(IF1 getPrice, double maxPrice, Iterable inputList) { this.inputList = inputList; this.maxPrice = maxPrice; this.getPrice = getPrice; } public void run() { try { outputList = new ArrayList(); finalPrice = 0; for (var element : unnullForIteration(inputList)) { double price = getPrice(element); if (finalPrice + price > maxPrice) { if (allowPartial) { A partial = reduceElement(element, maxPrice - finalPrice); if (partial != null) { fullLastElement = element; finalPrice += getPrice(partial); outputList.add(partial); if (finalPrice > maxPrice) throw fail("reduceElement failure (over budget)"); } } break; } finalPrice += price; outputList.add(element); } } catch (Exception __e) { throw rethrow(__e); } } public List get() { if (outputList == null) run(); return outputList; } public CutListToBudget allowPartial(IF2 reduceElement) { this.reduceElement = reduceElement; return allowPartial(true); } public A lastElement() { return last(get()); } public Percent lastElementKeptPercentage() { return fullLastElement == null ? null : new Percent(getPrice(lastElement()) / getPrice(fullLastElement) * 100); } } static public class IntVar { public int a; public synchronized void set(int v) { if (v != a) { a = v; notifyAll(); } } public synchronized int get() { return a; } synchronized public int waitForValue(int x) { try { while (a != x) wait(); return a; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return str(this.get()); } } static public class PingSource { final public PingSource setAction(IF0 action) { return action(action); } public PingSource action(IF0 action) { this.action = action; return this; } final public IF0 getAction() { return action(); } public IF0 action() { return action; } volatile public IF0 action; public String text; public ThreadPool threadPool; public PingSource() { } public PingSource(ThreadPool threadPool) { this.threadPool = threadPool; } public PingSource(ThreadPool threadPool, String text) { this.text = text; this.threadPool = threadPool; } public PingSource(IF0 action) { this.action = action; } final public boolean get() { var a = action; return a != null && a.get(); } final public void ping() { var a = action; if (a != null) a.get(); } public void cancel() { action = new Cancelled(); } public class Cancelled implements IF0 { public Boolean get() { throw new PingSourceCancelledException(PingSource.this); } } public class Encapsulated implements Runnable, IFieldsToList { public Runnable r; public Encapsulated() { } public Encapsulated(Runnable r) { this.r = r; } public Object[] _fieldsToList() { return new Object[] { r }; } public void run() { try { try { pingSource_tl().set(PingSource.this); ping(); r.run(); } finally { pingSource_tl().set(null); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return PingSource.this + ": " + r; } } public void dO(Runnable r) { if (r == null) return; threadPool.acquireThreadOrQueue(new Encapsulated(r)); } public String toString() { String t = text; return nempty(t) ? t : super.toString(); } public ISleeper_v2 sleeper() { return threadPool.sleeper(); } } static public interface Renderable extends MakesBufferedImage, G2Drawable { public void renderOn(Graphics2D g, int w, int h); default public Pt preferredSize() { return pt(640, 480); } default public int getWidth() { return preferredSize().x; } default public int getHeight() { return preferredSize().y; } default public BufferedImage render() { return getBufferedImage(); } default public BufferedImage getBufferedImage() { return renderableToImage(this); } default public void drawOn(Graphics2D g) { renderOn(g, -1, -1); } } static public class jCenteredLiveValueSection_class extends SingleComponentPanel { public IF0WithChangeListeners liveValue; final public jCenteredLiveValueSection_class setBorderType(int borderType) { return borderType(borderType); } public jCenteredLiveValueSection_class borderType(int borderType) { this.borderType = borderType; return this; } final public int getBorderType() { return borderType(); } public int borderType() { return borderType; } public int borderType = BevelBorder.LOWERED; final public jCenteredLiveValueSection_class setBold(boolean bold) { return bold(bold); } public jCenteredLiveValueSection_class bold(boolean bold) { this.bold = bold; return this; } final public boolean getBold() { return bold(); } public boolean bold() { return bold; } public boolean bold = false; public String getTitle() { return liveValue.get(); } public jCenteredLiveValueSection_class(IF0WithChangeListeners liveValue, Component c) { super(c); this.liveValue = liveValue; } public jCenteredLiveValueSection_class init() { bindLiveValueListenerToComponent(this, liveValue, new Runnable() { public void run() { try { swingLater(new Runnable() { public void run() { try { var titledBorder = BorderFactory.createTitledBorder(makeBaseBorder(), liveValue.get()); if (bold) titledBorder.setTitleFont(deriveBoldFont(getFont())); setBorder(titledBorder); centerSection(jCenteredLiveValueSection_class.this); revalidate(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var titledBorder = BorderFactory.createTitledBorder(\r\n makeBaseBorder(..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "swingLater(r {\r\n var titledBorder = BorderFactory.createTitledBorder(\r\n ..."; } }); return this; } transient public IF0 makeBaseBorder; public Border makeBaseBorder() { return makeBaseBorder != null ? makeBaseBorder.get() : makeBaseBorder_base(); } final public Border makeBaseBorder_fallback(IF0 _f) { return _f != null ? _f.get() : makeBaseBorder_base(); } public Border makeBaseBorder_base() { return BorderFactory.createBevelBorder(borderType); } } static public JPanel jCenteredLiveValueSection(IF0WithChangeListeners lv, Component c) { return swing(() -> { return new jCenteredLiveValueSection_class(lv, c).init(); }); } final static public class ConceptFieldIndexDesc extends ConceptFieldIndexBase { public ConceptFieldIndexDesc(Class cc, String field) { super(cc, field); } public ConceptFieldIndexDesc(Concepts concepts, Class cc, String field) { super(concepts, cc, field); } public void init() { valueToObject = treeMultiSetMap(reverseOrder()); } public void register() { concepts.addFieldIndex(cc, field, this); } public void close() { concepts.removeFieldIndex(cc, field, this); super.close(); } synchronized public List objectsWithValueGreaterThan(Object value) { SortedMap> subMap = ((SortedMap>) valueToObject.data).headMap(value); return concatLists(values(subMap)); } } static public class HasTokenRangeWithSrc implements IHasTokenRangeWithSrc { final public HasTokenRangeWithSrc setTokenRangeWithSrc(TokenRangeWithSrc tokenRangeWithSrc) { return tokenRangeWithSrc(tokenRangeWithSrc); } public HasTokenRangeWithSrc tokenRangeWithSrc(TokenRangeWithSrc tokenRangeWithSrc) { this.tokenRangeWithSrc = tokenRangeWithSrc; return this; } final public TokenRangeWithSrc getTokenRangeWithSrc() { return tokenRangeWithSrc(); } public TokenRangeWithSrc tokenRangeWithSrc() { return tokenRangeWithSrc; } public TokenRangeWithSrc tokenRangeWithSrc; } static public class VarMatches extends WrappedMap { public VarMatches() { super(new LinkedHashMap()); } public VarMatches(Map map) { this(); utils.putAll(this, map); } } static public class Best implements IBest { public A best; public double score; public boolean verboseNewBest, replaceIfSameScore; final public Best setLowerIsBetter(boolean lowerIsBetter) { return lowerIsBetter(lowerIsBetter); } public Best lowerIsBetter(boolean lowerIsBetter) { this.lowerIsBetter = lowerIsBetter; return this; } final public boolean getLowerIsBetter() { return lowerIsBetter(); } public boolean lowerIsBetter() { return lowerIsBetter; } public boolean lowerIsBetter = false; transient public Object onChange; transient public Object stringifier; synchronized public boolean isNewBest(double score) { return best == null || !isNaN(score) && (replaceIfSameScore ? compareScores(score, this.score) >= 0 : compareScores(score, this.score) > 0); } public double worstScore() { return lowerIsBetter ? infinity() : minusInfinity(); } public int compareScores(double a, double b) { return lowerIsBetter ? -cmp(a, b) : cmp(a, b); } synchronized public double bestScore() { return best == null ? worstScore() : score; } public double score() { return bestScore(); } public double getScore() { return bestScore(); } synchronized public float floatScoreOr(float defaultValue) { return best == null ? defaultValue : (float) score; } public boolean put(Scored s) { return s != null && put(s.get(), s.score()); } public boolean put(Pair p) { return p != null && put(p.a, p.b); } public boolean put(Best b) { return b != null && put(b.get(), b.score); } public boolean put(A a, double score) { ping(); boolean change = false; if (a != null) synchronized (this) { if (isNewBest(score)) { best = a; this.score = score; change = true; } } if (change) { if (verboseNewBest) print("New best! " + this); pcallF(onChange); } return change; } synchronized public A get() { return best; } synchronized public boolean has() { return best != null; } synchronized public Pair pair() { return utils.pair(best, bestScore()); } synchronized public Scored scored() { return best == null ? null : new Scored(best, bestScore()); } synchronized public A getIfScoreAbove(double x) { return compareScores(score(), x) >= 0 ? best : null; } public String toString() { return "Score " + formatDouble_significant2(score, 4) + ": " + callStringifier(stringifier, best); } public boolean putAndPrintIfNewBest(A a, double score) { if (!put(a, score)) return false; { print(this); return true; } } synchronized public void clear() { best = null; score = 0; } } static public class ConceptL extends Concept implements Iterable { public RefL l = new RefL(); public ConceptL() { } public ConceptL(List l) { utils.addAll(this.l, l); } public void addAll(List l) { this.l.addAll(l); } public Iterator iterator() { return l.iterator(); } public List getList() { return l; } } static public class BackgroundProcessesUI implements IBackgroundProcesses { public Set processes = setWithNotify(syncLinkedHashSet(), () -> updateCount()); public SimpleLiveValue lvCount = new SimpleLiveValue(Integer.class, 0); public class Entry implements IBackgroundProcess, IFieldsToList { public String name; public Entry() { } public Entry(String name) { this.name = name; } public boolean equals(Object o) { if (!(o instanceof Entry)) return false; Entry __0 = (Entry) o; return eq(name, __0.name); } public int hashCode() { int h = 67115090; h = boostHashCombine(h, _hashCode(name)); return h; } public Object[] _fieldsToList() { return new Object[] { name }; } final public Entry setMenuItem(JMenuItem menuItem) { return menuItem(menuItem); } public Entry menuItem(JMenuItem menuItem) { this.menuItem = menuItem; return this; } final public JMenuItem getMenuItem() { return menuItem(); } public JMenuItem menuItem() { return menuItem; } public JMenuItem menuItem; final public Entry setInterruptAction(Runnable interruptAction) { return interruptAction(interruptAction); } public Entry interruptAction(Runnable interruptAction) { this.interruptAction = interruptAction; return this; } final public Runnable getInterruptAction() { return interruptAction(); } public Runnable interruptAction() { return interruptAction; } public Runnable interruptAction; public String toString() { return name; } public void close() { try { processes.remove(this); } catch (Exception __e) { throw rethrow(__e); } } } public JLabel shortLabel() { var lbl = bindToolTipToTransformedLiveValue(n -> makeToolTip(), lvCount, simpleTransformedLiveValueLabel(n -> n2(n), lvCount)); onMouseDown_anyButton(lbl, e -> { var l = cloneList(processes); JPopupMenu menu = new JPopupMenu(); int n = componentCount(menu); for (Entry a : l) addMenuItem(menu, processToMenuItem(a)); if (componentCount(menu) != n) { var border = jRaisedSectionBorder("Background Processes"); setBorder(menu, border); showPopupMenu(menu, e); var size = menu.getSize(); var borderSize = dimensionPlus(10, 0, border.getMinimumSize(menu)); printVars("size", size, "borderSize", borderSize); menu.setPopupSize(maxDimension(size, borderSize)); } }); return lbl; } public void add(Entry process) { processes.add(process); } public void remove(Entry process) { processes.remove(process); } public void addOrRemove(boolean add, Entry process) { if (add) add(process); else remove(process); } public Entry tempAdd(String name) { return tempAdd(new Entry(or2(name, "Unnamed process"))); } public Entry tempAdd(Entry process) { if (process == null) return null; processes.add(process); return process; } public void updateCount() { lvCount.set(l(processes)); } public String makeToolTip() { var l = listProcesses(); return empty(l) ? "No background processes" : n2(l, "background process", "background processes") + ": " + joinWithComma(processes); } transient public IF1 processToMenuItem; public JMenuItem processToMenuItem(Entry process) { return processToMenuItem != null ? processToMenuItem.get(process) : processToMenuItem_base(process); } final public JMenuItem processToMenuItem_fallback(IF1 _f, Entry process) { return _f != null ? _f.get(process) : processToMenuItem_base(process); } public JMenuItem processToMenuItem_base(Entry process) { { var __2 = process.getMenuItem(); if (__2 != null) return __2; } if (process.interruptAction() != null) return jMenuItem("Interrupt " + process, rThread(process.interruptAction())); return jMenuItem(process + " [no action available]"); } public List listProcesses() { return cloneList(processes); } public Collection processesNamedIC(String name) { return filter(listProcesses(), entry -> eqic(entry.name, name)); } } static public class Rect implements WidthAndHeight, IFieldsToList { static final public String _fieldOrder = "x y w h"; public int x; public int y; public int w; public int h; public Rect() { } public Rect(int x, int y, int w, int h) { this.h = h; this.w = w; this.y = y; this.x = x; } public boolean equals(Object o) { if (!(o instanceof Rect)) return false; Rect __1 = (Rect) o; return x == __1.x && y == __1.y && w == __1.w && h == __1.h; } public int hashCode() { int h = 2543108; h = boostHashCombine(h, _hashCode(x)); h = boostHashCombine(h, _hashCode(y)); h = boostHashCombine(h, _hashCode(w)); h = boostHashCombine(h, _hashCode(h)); return h; } public Object[] _fieldsToList() { return new Object[] { x, y, w, h }; } public Rect(Rectangle r) { x = r.x; y = r.y; w = r.width; h = r.height; } public Rect(Pt p, int w, int h) { this.h = h; this.w = w; x = p.x; y = p.y; } public Rect(Rect r) { x = r.x; y = r.y; w = r.w; h = r.h; } final public Rectangle getRectangle() { return new Rectangle(x, y, w, h); } public String toString() { return x + "," + y + " / " + w + "," + h; } final public int x1() { return x; } final public int y1() { return y; } final public int x2() { return x + w; } final public int y2() { return y + h; } final public boolean contains(Pt p) { return contains(p.x, p.y); } final public boolean contains(int _x, int _y) { return _x >= x && _y >= y && _x < x + w && _y < y + h; } final public boolean contains(Rectangle r) { return rectContains(this, r); } final public boolean empty() { return w <= 0 || h <= 0; } final public int getWidth() { return w; } final public int getHeight() { return h; } final public int area() { return w * h; } final public int x() { return x; } final public int y() { return y; } public WidthAndHeight widthAndHeight() { return utils.widthAndHeight(w, h); } } static public class Pt implements Comparable, IDoublePt { public int x, y; public Pt() { } public Pt(Point p) { x = p.x; y = p.y; } public Pt(int x, int y) { this.y = y; this.x = x; } public Point getPoint() { return new Point(x, y); } public boolean equals(Object o) { return o instanceof Pt && x == ((Pt) o).x && y == ((Pt) o).y; } public int hashCode() { return boostHashCombine(x, y); } public int compareTo(Pt p) { if (y != p.y) return cmp(y, p.y); return cmp(x, p.x); } public String toString() { return x + ", " + y; } public double length() { return sqrt(x * x + y * y); } public Pt minus(Pt p) { return ptMinus(this, p); } public double x_double() { return x; } public double y_double() { return y; } } static public class TimeoutException_Inner extends RuntimeExceptionWithCustomStackTrace { public Thread thread; public double timeoutSeconds; public Object function; public TimeoutException_Inner(double timeoutSeconds, Object function, Thread thread) { super("Timeout after " + iceil(timeoutSeconds) + "s by " + shorten_str(function), new Throwable("Caller"), thread.getStackTrace()); this.thread = thread; this.function = function; this.timeoutSeconds = timeoutSeconds; } } static public class BufferedImageWithMeta extends BufferedImage implements IMeta { public BufferedImageWithMeta(ColorModel cm, WritableRaster raster, boolean isRasterPremultiplied, Hashtable properties) { super(cm, raster, isRasterPremultiplied, properties); } volatile public Object meta; public void _setMeta(Object meta) { this.meta = meta; } public Object _getMeta() { return meta; } final public boolean scaffolding() { return scaffoldingEnabled(); } final public boolean scaffolded() { return scaffoldingEnabled(); } public boolean scaffoldingEnabled() { return utils.scaffoldingEnabled(this); } public boolean scaffoldingEnabled(Object o) { return utils.scaffoldingEnabled(o); } public String toString_base() { return super.toString(); } public String toString() { Object o = metaGet("toString", this); if (o instanceof String) return ((String) o); if (o instanceof IF1) return str(((IF1) o).get(this)); return toString_base(); } } static public class LeftAlignedLine extends JPanel { public LeftAlignedLine(int spacing, Component... components) { this(components); setSpacing(spacing); } public LeftAlignedLine(Component... components) { setLayout(LetterLayout.leftAlignedRow()); addAll(this, components); } public void setSpacing(int spacing) { ((LetterLayout) getLayout()).setSpacing(spacing, spacing); } public void add(String text) { add(new JLabel(text)); } } static public class AverageAndMinMax extends Average { final public double getMin() { return min(); } public double min() { return min; } public double min = infinity(); final public double getMax() { return max(); } public double max() { return max; } public double max = negativeInfinity(); public void add(double d) { super.add(d); if (d < min) min = d; if (d > max) max = d; } public String toString() { return "avg=" + super.toString() + (isEmpty() ? "" : ", min/max=" + min + "/" + max); } } static public class SynchronizedNavigableMap extends SynchronizedSortedMap implements NavigableMap { public SynchronizedNavigableMap() { } public NavigableMap innerMap() { return (NavigableMap) m; } public SynchronizedNavigableMap(NavigableMap m) { super(m); } public SynchronizedNavigableMap(NavigableMap m, Object mutex) { super(m, mutex); } public Entry lowerEntry(K key) { synchronized (mutex) { return innerMap().lowerEntry(key); } } public K lowerKey(K key) { synchronized (mutex) { return innerMap().lowerKey(key); } } public Entry floorEntry(K key) { synchronized (mutex) { return innerMap().floorEntry(key); } } public K floorKey(K key) { synchronized (mutex) { return innerMap().floorKey(key); } } public Entry ceilingEntry(K key) { synchronized (mutex) { return innerMap().ceilingEntry(key); } } public K ceilingKey(K key) { synchronized (mutex) { return innerMap().ceilingKey(key); } } public Entry higherEntry(K key) { synchronized (mutex) { return innerMap().higherEntry(key); } } public K higherKey(K key) { synchronized (mutex) { return innerMap().higherKey(key); } } public Entry firstEntry() { synchronized (mutex) { return innerMap().firstEntry(); } } public Entry lastEntry() { synchronized (mutex) { return innerMap().lastEntry(); } } public Entry pollFirstEntry() { synchronized (mutex) { return innerMap().pollFirstEntry(); } } public Entry pollLastEntry() { synchronized (mutex) { return innerMap().pollLastEntry(); } } public NavigableMap descendingMap() { synchronized (mutex) { return new SynchronizedNavigableMap<>(innerMap().descendingMap(), mutex); } } public NavigableSet keySet() { return navigableKeySet(); } public NavigableSet navigableKeySet() { synchronized (mutex) { return new SynchronizedNavigableSet<>(innerMap().navigableKeySet(), mutex); } } public NavigableSet descendingKeySet() { synchronized (mutex) { return new SynchronizedNavigableSet<>(innerMap().descendingKeySet(), mutex); } } public SortedMap subMap(K fromKey, K toKey) { synchronized (mutex) { return new SynchronizedNavigableMap<>(innerMap().subMap(fromKey, true, toKey, false), mutex); } } public SortedMap headMap(K toKey) { synchronized (mutex) { return new SynchronizedNavigableMap<>(innerMap().headMap(toKey, false), mutex); } } public SortedMap tailMap(K fromKey) { synchronized (mutex) { return new SynchronizedNavigableMap<>(innerMap().tailMap(fromKey, true), mutex); } } public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { synchronized (mutex) { return new SynchronizedNavigableMap<>(innerMap().subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } public NavigableMap headMap(K toKey, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableMap<>(innerMap().headMap(toKey, inclusive), mutex); } } public NavigableMap tailMap(K fromKey, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableMap<>(innerMap().tailMap(fromKey, inclusive), mutex); } } } public interface PCallPolicy { public void handlePcallFail(Throwable e); } static public interface IBWIntegralImage extends MakesBufferedImage, IBWImage, IMeta { public int getWidth(); public int getHeight(); public default int getIIValue(int x, int y) { return iround(getIIValue((double) x, (double) y)); } public default double getIIValue(double x, double y) { return getIIValue(ifloor(x), ifloor(y)); } default public double getPixelAverage(int x1, int y1, int x2, int y2) { int area = (x2 - x1) * (y2 - y1); return doubleRatio(getPixelSum(x1, y1, x2, y2), area); } default public double getPixelAverage(double x1, double y1, double x2, double y2) { double area = (x2 - x1) * (y2 - y1); return doubleRatio(getPixelSum(x1, y1, x2, y2), area); } default public double getPixelAverage(Rect r) { return getPixelAverage(r.x, r.y, r.x2(), r.y2()); } default public int getPixelSum(int x1, int y1, int x2, int y2) { return bwIntegralImage_sumRect(this, x1, y1, x2, y2); } default public double getPixelSum(double x1, double y1, double x2, double y2) { return bwIntegralImage_sumRect(this, x1, y1, x2, y2); } default public int getInt(int x, int y) { return getPixelBrightness(x, y); } default public int getPixelBrightness(int x, int y) { return getPixelSum(x, y, x + 1, y + 1); } default public int getPixelBrightness(Pt p) { return getPixelBrightness(p.x, p.y); } public default BufferedImage getBufferedImage() { return grayImageFromIBWIntegralImage(this); } public default float getFloatPixel(int x, int y) { return getPixelBrightness(x, y) / 255f; } } static public interface Hasher { public int hashCode(A a); public boolean equals(A a, A b); } static public interface IFieldsToList { public Object[] _fieldsToList(); } static public class JTextFileEditor implements Swingable, IFieldsToList { public File file; public JTextFileEditor() { } public JTextFileEditor(File file) { this.file = file; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + file + ")"; } public Object[] _fieldsToList() { return new Object[] { file }; } final public JTextFileEditor setAutoSave(boolean autoSave) { return autoSave(autoSave); } public JTextFileEditor autoSave(boolean autoSave) { this.autoSave = autoSave; return this; } final public boolean getAutoSave() { return autoSave(); } public boolean autoSave() { return autoSave; } public boolean autoSave = false; final public JTextFileEditor setWordWrap(boolean wordWrap) { return wordWrap(wordWrap); } public JTextFileEditor wordWrap(boolean wordWrap) { this.wordWrap = wordWrap; return this; } final public boolean getWordWrap() { return wordWrap(); } public boolean wordWrap() { return wordWrap; } public boolean wordWrap = true; final public boolean getUneditable() { return uneditable(); } public boolean uneditable() { return uneditable; } public boolean uneditable = false; final public JTextArea getTextArea() { return textArea(); } public JTextArea textArea() { return textArea; } public JTextArea textArea; public JButton btnReload, btnSave; public JLabel lblChanged; volatile public String fileContents, savedText; public FileWatchService fileWatcher; public Q q = startQ(); public RSTOverQ rstLoad = rstWithPreDelay(0.5, q, new Runnable() { public void run() { try { _load(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_load();"; } }); public RSTOverQ rstSave; public JPanel buttons; public SingleComponentPanel scpButtons = singleComponentPanel(); public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { assertNotNull(file); rstSave = rstWithPreDelay(autoSave ? 0.5 : 0.0, q, new Runnable() { public void run() { try { _save(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_save();"; } }); savedText = fileContents = loadTextFile(file); textArea = makeTextArea(); if (uneditable) makeUneditable(textArea); if (wordWrap) enableWordWrapForTextArea(textArea); setText(savedText); onChange(textArea, () -> { updateButtons(); if (autoSave) rstSave.get(); }); addKeyListener(textArea(), ctrlLetterKeyListener('s', rstSave)); bindToComponent(textArea, () -> { fileWatcher = new FileWatchService(); fileWatcher.addNonRecursiveListener(dirOfFile(file), f -> { if (sameFile(f, file)) rstLoad.get(); }); rstLoad.get(); }, () -> { { cleanUp(fileWatcher); fileWatcher = null; } }); scpButtons.set(buttons = makeButtons()); return northAndCenter(withSideMargin(10, 20, centerAndEastWithMargin(new JFilePathLabel(file).iconOnTheLeft(true).minWidth(true).visualize(), scpButtons)), withMargin(textAreaLayoutComponent())); } public JPanel makeButtons() { btnSave = btnReload = null; return jline(uneditable ? null : autoSave ? (lblChanged = jlabel()) : (btnSave = disableButton(jbutton("Save", rstSave))), uneditable ? null : (btnReload = jbutton("Reload", new Runnable() { public void run() { try { reload(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "reload();"; } }))); } transient public IF0 textAreaLayoutComponent; public JComponent textAreaLayoutComponent() { return textAreaLayoutComponent != null ? textAreaLayoutComponent.get() : textAreaLayoutComponent_base(); } final public JComponent textAreaLayoutComponent_fallback(IF0 _f) { return _f != null ? _f.get() : textAreaLayoutComponent_base(); } public JComponent textAreaLayoutComponent_base() { return jscroll(textArea()); } public void updateButtons() { boolean changed = !eq(savedText, getText(textArea)); setEnabled(btnSave, changed); setEnabled(btnReload, !eq(fileContents, savedText)); utils.setText(lblChanged, changed ? "*" : ""); } public void _save() { if (!uneditable) saveTextFileVerbose(file, savedText = getText(textArea)); } public void reload() { savedText = fileContents; setText(savedText); updateButtons(); } public void _load() { print("Loading " + file); fileContents = loadTextFile(file); updateButtons(); if (uneditable) reload(); } transient public IF0 makeTextArea; public JTextArea makeTextArea() { return makeTextArea != null ? makeTextArea.get() : makeTextArea_base(); } final public JTextArea makeTextArea_fallback(IF0 _f) { return _f != null ? _f.get() : makeTextArea_base(); } public JTextArea makeTextArea_base() { return jTypeWriterTextArea(); } public void setText(String text) { utils.setText(textArea(), text); } public JPanel buttons() { visualize(); return buttons; } public JTextFileEditor uneditable(boolean b) { if (uneditable == b) return this; uneditable = b; if (buttons != null) { scpButtons.set(buttons = makeButtons()); setEditable(textArea(), true); } return this; } } static public class WeakValueMap implements AutoCloseable, IntSize { transient public Set> onValueForKeyReleased; public WeakValueMap onValueForKeyReleased(IVF1 f) { onValueForKeyReleased = createOrAddToSyncLinkedHashSet(onValueForKeyReleased, f); return this; } public WeakValueMap removeValueForKeyReleasedListener(IVF1 f) { utils.remove(onValueForKeyReleased, f); return this; } public void valueForKeyReleased(A key) { if (onValueForKeyReleased != null) for (var listener : onValueForKeyReleased) pcallF_typed(listener, key); } public Map> map = syncMap(); public RunnablesReferenceQueue queue; public boolean myQueue = true; public WeakValueMap() { } public WeakValueMap(RunnablesReferenceQueue queue) { this.queue = queue; myQueue = false; } public class MyRef extends WeakReference implements Runnable { public A key; public MyRef(A key, B value) { super(value, queue().get()); this.key = key; } public void run() { try { boolean current = syncMapRemoveKeyAndValuePair(map, key, this); valueForKeyReleased(key); } catch (Exception __e) { throw rethrow(__e); } } } public B get(A key) { return getWeakRef(map.get(key)); } public B put(A key, B value) { synchronized (mutex()) { if (value == null) { B old = getWeakRef(map.get(key)); map.remove(key); return old; } else return getWeakRef(map.put(key, new MyRef(key, value))); } } public Object mutex() { return collectionMutex(map); } public RunnablesReferenceQueue queue() { synchronized (mutex()) { if (queue == null) queue = new RunnablesReferenceQueue(); return queue; } } public void close() { try { if (myQueue) synchronized (mutex()) { { cleanUp(queue); queue = null; } } } catch (Exception __e) { throw rethrow(__e); } } public int size() { return map.size(); } public Map snapshot() { synchronized (mutex()) { Map snapshot = new HashMap(); for (var __0 : _entrySet(map)) { var key = __0.getKey(); var ref = __0.getValue(); mapPut(snapshot, key, getWeakRef(ref)); } return snapshot; } } final public void queue(RunnablesReferenceQueue queue) { setQueue(queue); } public void setQueue(RunnablesReferenceQueue queue) { synchronized (mutex()) { if (queue == null || this.queue == queue) return; if (this.queue != null) throw fail("Can't change queue once we're started"); this.queue = queue; myQueue = false; } } } static public class VarWithNotify extends Var implements IVarWithNotify { transient public Set onChange; public VarWithNotify onChange(Runnable r) { onChange = createOrAddToSyncLinkedHashSet(onChange, r); return this; } public VarWithNotify removeChangeListener(Runnable r) { utils.remove(onChange, r); return this; } public void fireChange() { if (onChange != null) for (var listener : onChange) pcallF_typed(listener); } public VarWithNotify() { } public VarWithNotify(A a) { super(a); } public void set(A a) { A v = get(); if (eq(v, a)) { return; } synchronized (this) { this.v = a; notifyAll(); } fireChange(); } } static public class Zip4j_MergeZipFilesWithFilter implements AutoCloseable, IFieldsToList { public File zipOut; public Zip4j_MergeZipFilesWithFilter() { } public Zip4j_MergeZipFilesWithFilter(File zipOut) { this.zipOut = zipOut; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + zipOut + ")"; } public Object[] _fieldsToList() { return new Object[] { zipOut }; } public ZipModel zipModel; public ZipModel zipModelOut = new ZipModel(); public SplitOutputStream outputStream; public HeaderWriter headerWriter = new HeaderWriter(); public net.lingala.zip4j.progress.ProgressMonitor progressMonitor = new net.lingala.zip4j.progress.ProgressMonitor(); public int bufferSize = InternalZipConstants.BUFF_SIZE; public Charset charset; public List filteredFileHeaders = new ArrayList(); public void close() { try { { cleanUp(outputStream); outputStream = null; } } catch (Exception __e) { throw rethrow(__e); } } public void init() throws IOException { if (outputStream == null) outputStream = new SplitOutputStream(zipOut); } public void addZipFile(File zipIn, IF1 fileFilter) throws IOException { init(); try (var randomAccessFile = new RandomAccessFile(zipIn, RandomAccessFileMode.READ.getValue())) { zipModel = new HeaderReader().readAllHeaders(randomAccessFile, buildConfig()); zipModel.setZipFile(zipIn); } var inputStream = new RandomAccessFile(zipModel.getZipFile(), RandomAccessFileMode.READ.getValue()); try { long currentFileCopyPointer = 0; long runningOffset = outputStream.getFilePointer(); List sortedFileHeaders = sortedByComparator(zipModel.getCentralDirectory().getFileHeaders(), (o1, o2) -> { if (eq(o1.getFileName(), o2.getFileName())) return 0; return cmp(o1.getOffsetLocalHeader(), o2.getOffsetLocalHeader()); }); for (int iFileHeader = 0; iFileHeader < l(sortedFileHeaders); iFileHeader++) { var fileHeader = sortedFileHeaders.get(iFileHeader); var fileHeaderOffset = fileHeader.getOffsetLocalHeader(); var nextOffset = getOffsetOfNextEntry(sortedFileHeaders, iFileHeader, zipModel); long fp = outputStream.getFilePointer(); long lengthOfCurrentEntry = nextOffset + runningOffset - fp; if (!fileFilter.get(fileHeader.getFileName())) { runningOffset -= lengthOfCurrentEntry; currentFileCopyPointer += lengthOfCurrentEntry; } else { addOffsetToFileHeader(fileHeader, runningOffset); filteredFileHeaders.add(fileHeader); currentFileCopyPointer += copyFile(inputStream, outputStream, currentFileCopyPointer, lengthOfCurrentEntry, progressMonitor, buildConfig().getBufferSize()); } } var endOfCDR = zipModel.getEndOfCentralDirectoryRecord(); endOfCDR.setTotalNumberOfEntriesInCentralDirectory(l(filteredFileHeaders)); endOfCDR.setTotalNumberOfEntriesInCentralDirectoryOnThisDisk(l(filteredFileHeaders)); } finally { _close(inputStream); } } public void finish() throws IOException { zipModelOut.getCentralDirectory().setFileHeaders(filteredFileHeaders); headerWriter.finalizeZipFile(zipModelOut, outputStream, buildConfig().getCharset()); close(); } public long getOffsetOfNextEntry(List sortedFileHeaders, int indexOfFileHeader, ZipModel zipModel) throws ZipException { if (indexOfFileHeader == sortedFileHeaders.size() - 1) return HeaderUtil.getOffsetStartOfCentralDirectory(zipModel); else return sortedFileHeaders.get(indexOfFileHeader + 1).getOffsetLocalHeader(); } public long copyFile(RandomAccessFile randomAccessFile, OutputStream outputStream, long start, long length, net.lingala.zip4j.progress.ProgressMonitor progressMonitor, int bufferSize) throws IOException { net.lingala.zip4j.util.FileUtils.copyFile(randomAccessFile, outputStream, start, start + length, progressMonitor, bufferSize); return length; } public Zip4jConfig buildConfig() { return new Zip4jConfig(charset, bufferSize); } public void addOffsetToFileHeader(FileHeader fileHeader, long offsetToAdd) { fileHeader.setOffsetLocalHeader(fileHeader.getOffsetLocalHeader() + offsetToAdd); if (zipModel.isZip64Format() && fileHeader.getZip64ExtendedInfo() != null && fileHeader.getZip64ExtendedInfo().getOffsetLocalHeader() != -1) fileHeader.getZip64ExtendedInfo().setOffsetLocalHeader(fileHeader.getZip64ExtendedInfo().getOffsetLocalHeader() + offsetToAdd); } } static public class JColorBar extends JComponentWithChangeListeners { public transient FieldVar varValue_cache; public FieldVar varValue() { if (varValue_cache == null) varValue_cache = varValue_load(); return varValue_cache; } public FieldVar varValue_load() { return new FieldVar(this, "value", () -> value(), value -> value(value)); } final public JColorBar setValue(double value) { return value(value); } public JColorBar value(double value) { if (!eq(this.value, value)) { this.value = value; change(); } return this; } final public double getValue() { return value(); } public double value() { return value; } public double value; public transient FieldVar varMax_cache; public FieldVar varMax() { if (varMax_cache == null) varMax_cache = varMax_load(); return varMax_cache; } public FieldVar varMax_load() { return new FieldVar(this, "max", () -> max(), max -> max(max)); } final public JColorBar setMax(double max) { return max(max); } public JColorBar max(double max) { if (!eq(this.max, max)) { this.max = max; change(); } return this; } final public double getMax() { return max(); } public double max() { return max; } public double max = 100; public JColorBar() { setForeground(Color.red); for (var var : ll(varValue(), varMax())) var.onChange(() -> repaint()); jMinSize(50, 10, this); } public void paintComponent(Graphics g) { super.paintComponent(g); int w = getWidth(), h = getHeight(); fillRect(g, 0, 0, iround(w * clampZeroToOne(doubleRatio(value, max))), h, getForeground()); } } static public interface IVar extends IF0 { public void set(A a); public A get(); default public Class getType() { return null; } default public IF0 getter() { return () -> get(); } default public IVF1 setter() { return __1 -> set(__1); } default public boolean has() { return get() != null; } default public void clear() { set(null); } } abstract static public class DynPrintLogAndEnabled extends DynPrintLog { public JComponent visualize() { return dm_visualizeWithEnabled(super.visualize()); } volatile public boolean enabled = true; transient public JPanel buttons; transient public SingleComponentPanel scpStretcherControl; public JComponent visualizeWithoutEnabled() { return super.visualize(); } public JComponent dm_visualizeWithEnabled(JComponent main) { return centerAndSouthWithMargins(main, wrapControlArea()); } public JComponent wrapControlArea() { return makeControlArea(); } public JPanel makeControlArea() { if (scpStretcherControl == null) scpStretcherControl = singleComponentPanel(); var cb = makeEnabledCheckBox(); buttons = jrightalignedline(cb); return centerAndEastWithMargin(scpStretcherControl, buttons); } static public JCheckBox makeEnabledCheckBox() { return dm_fieldCheckBox("enabled"); } public void setEnabled(boolean b) { setField("enabled", b); } final public void addControls(Component... components) { addToControlArea(components); } public void addToControlArea(Component... components) { addComponentsFirst(buttons, components); } final public void addControl(Component component) { addButton(component); } public void addButton(Component component) { addComponentsFirst(buttons, component); } public void addControl(Swingable component) { addComponentsFirst(buttons, wrap(component)); } public void setMainControl(JComponent control) { scpSet(scpStretcherControl, control); } } static public class Gazelle22_GradientImage { public BWImage posterized; public double gradientThreshold = .25; public BWImage out; public PosterizeBWImage op; public BWImage unposterized; public int w, h, brightnessLevels, singleStep; public Gazelle22_GradientImage(BWImage posterized) { this.posterized = posterized; } public boolean init() { op = (PosterizeBWImage) getMetaSrc(posterized); if (op == null) return false; unposterized = op.img; brightnessLevels = op.brightnessLevels; assertSameSize(unposterized, posterized); w = posterized.getWidth(); h = posterized.getHeight(); singleStep = iceil(doubleRatio(255, brightnessLevels - 1)); return true; } public BWImage get() { init(); out = new BWImage(w * 2 + 1, h * 2 + 1); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { if (x < w - 1) checkPair(x, y, x + 1, y); if (y < h - 1) checkPair(x, y, x, y + 1); } return out; } public boolean isGradientPoint(int x, int y) { if (op == null) return false; IntMinMax posterizedMinMax = new IntMinMax(); IntMinMax unposterizedMinMax = new IntMinMax(); for (int y2 = max(0, y - 1); y2 <= min(h - 1, y + 1); y2++) for (int x2 = max(0, x - 1); x2 <= min(w - 1, x + 1); x2++) { posterizedMinMax.add(posterized.getInt(x2, y2)); unposterizedMinMax.add(unposterized.getInt(x2, y2)); } int posterizedContrast = posterizedMinMax.rangeLength(); if (posterizedContrast > singleStep) return false; if (posterizedContrast == 0) return true; int unposterizedContrast = unposterizedMinMax.rangeLength(); return unposterizedContrast <= posterizedContrast * gradientThreshold; } public void checkPair(int x, int y, int x2, int y2) { int posterizedContrast = absDiff(posterized.getInt(x, y), posterized.getInt(x2, y2)); if (posterizedContrast == 0) return; if (posterizedContrast > singleStep) return; int realContrast = absDiff(unposterized.getInt(x, y), unposterized.getInt(x2, y2)); double ratio = doubleRatio(realContrast, singleStep); float result = (float) ((.5 - ratio) * 2); { out.setPixel(x * 2 + 1 - (y2 - y), y * 2 + 1, result); out.setPixel(x * 2 + 1, y * 2 + 1 - (x2 - x), result); } } } static public class TokenRangeWithSrc extends TokenRange { public List tok; final public TokenRangeWithSrc setSourceInfo(Object sourceInfo) { return sourceInfo(sourceInfo); } public TokenRangeWithSrc sourceInfo(Object sourceInfo) { this.sourceInfo = sourceInfo; return this; } final public Object getSourceInfo() { return sourceInfo(); } public Object sourceInfo() { return sourceInfo; } public Object sourceInfo; public TokenRangeWithSrc() { } public TokenRangeWithSrc(List tok, int start) { this.start = start; end = start; } public TokenRangeWithSrc(List tok, int start, int end) { this.end = end; this.start = start; } public TokenRangeWithSrc(ListAndIndex startPtr, ListAndIndex endPtr) { assertNotNull("startPtr", startPtr); assertNotNull("endPtr", endPtr); assertSame(tok = startPtr.list(), endPtr.list()); start = startPtr.idx(); end = endPtr.idx(); } public ListAndIndex startPtr() { return new ListAndIndex(tok, start); } public ListAndIndex endPtr() { return new ListAndIndex(tok, end); } public LineAndColumn startLineAndCol() { return tokenToLineAndColumn(startPtr()); } public LineAndColumn endLineAndCol() { return tokenToLineAndColumn(endPtr()); } public String text() { return joinSubList(tok, start, end); } public String renderRange() { return renderLineAndColumnRange(startLineAndCol(), endLineAndCol()); } public String toString() { return spaceCombine(sourceInfo(), renderRange()); } public String fullSourceText() { return join(tok); } } static public class ConceptWithGlobalID extends Concept implements IHasGlobalID { public GlobalID globalID = aGlobalIDObjUnlessLoading(); public GlobalID globalID() { return globalID; } public String globalIDStr() { return strOrNull(globalID); } public String prependGlobalID(String s) { return globalID == null ? s : "[" + globalID + "] " + s; } } static public class LiteralJavaXExpr extends Meta implements ICachedJavaXExpr, IFieldsToList { public Object expr; public LiteralJavaXExpr() { } public LiteralJavaXExpr(Object expr) { this.expr = expr; } public boolean equals(Object o) { if (!(o instanceof LiteralJavaXExpr)) return false; LiteralJavaXExpr __1 = (LiteralJavaXExpr) o; return eq(expr, __1.expr); } public int hashCode() { int h = 1878341052; h = boostHashCombine(h, _hashCode(expr)); return h; } public Object[] _fieldsToList() { return new Object[] { expr }; } public String toString() { return str(expr); } public transient IF0 quickEval; public A quickEval() { return quickEval != null ? quickEval.get() : quickEval_base(); } final public A quickEval_fallback(IF0 _f) { return _f != null ? _f.get() : quickEval_base(); } public A quickEval_base() { return ICachedJavaXExpr.super.quickEval(); } } static public class SimpleOutlineWalker implements Steppable { public IIntIntPred pixelIsInside; public int x, y; final public SimpleOutlineWalker setProcessBacktracks(boolean processBacktracks) { return processBacktracks(processBacktracks); } public SimpleOutlineWalker processBacktracks(boolean processBacktracks) { this.processBacktracks = processBacktracks; return this; } final public boolean getProcessBacktracks() { return processBacktracks(); } public boolean processBacktracks() { return processBacktracks; } public boolean processBacktracks = false; public int startX, startY; public NESWDirection direction = NESWDirection.east; final public int getNPixels() { return nPixels(); } public int nPixels() { return nPixels; } public int nPixels; public PtBuffer pixels = new PtBuffer(); public List backtrackStack = new ArrayList(); public CompactLongSet seen = new CompactLongSet(); transient public Set> onFoundPoint; public SimpleOutlineWalker onFoundPoint(IVF2 f) { onFoundPoint = createOrAddToSyncLinkedHashSet(onFoundPoint, f); return this; } public SimpleOutlineWalker removeFoundPointListener(IVF2 f) { utils.remove(onFoundPoint, f); return this; } public void foundPoint(int x, int y) { if (onFoundPoint != null) for (var listener : onFoundPoint) pcallF_typed(listener, x, y); } static public class BacktrackPoint implements IFieldsToList { static final public String _fieldOrder = "x y dir turn"; public int x; public int y; public NESWDirection dir; public int turn; public BacktrackPoint() { } public BacktrackPoint(int x, int y, NESWDirection dir, int turn) { this.turn = turn; this.dir = dir; this.y = y; this.x = x; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + x + ", " + y + ", " + dir + ", " + turn + ")"; } public boolean equals(Object o) { if (!(o instanceof BacktrackPoint)) return false; BacktrackPoint __1 = (BacktrackPoint) o; return x == __1.x && y == __1.y && eq(dir, __1.dir) && turn == __1.turn; } public int hashCode() { int h = 342533964; h = boostHashCombine(h, _hashCode(x)); h = boostHashCombine(h, _hashCode(y)); h = boostHashCombine(h, _hashCode(dir)); h = boostHashCombine(h, _hashCode(turn)); return h; } public Object[] _fieldsToList() { return new Object[] { x, y, dir, turn }; } } public SimpleOutlineWalker(IIntIntPred pixelIsInside, Pt p) { this(pixelIsInside, p.x, p.y); } public SimpleOutlineWalker(IIntIntPred pixelIsInside, int x, int y) { this.y = y; this.x = x; this.pixelIsInside = pixelIsInside; if (!pixelIsInside.get(x, y)) throw fail("pixel is not inside shape: " + x + "/" + y); while (pixelIsInside.get(x, y - 1)) --y; startX = x; startY = y; this.y = y; } public boolean step() { ++nPixels; { if (pixels != null) pixels.add(x, y); } foundPoint(x, y); if (walkOneStep()) return true; if (!processBacktracks) return false; while (nempty(backtrackStack)) if (processBacktrack()) return true; return false; } public boolean walkOneStep() { return walkOneStep(3); } public boolean walkOneStep(int turn) { for (; turn <= 6; turn++) { NESWDirection newDirection = direction.plus(turn); int x2 = x + newDirection.x, y2 = y + newDirection.y; boolean inside = pixelIsInside.get(x2, y2); if (inside) { if (turn < 6) backtrackStack.add(new BacktrackPoint(x, y, direction, turn + 1)); x = x2; y = y2; direction = newDirection; break; } } return seen.add(intPairToLong(x, y)); } public boolean processBacktrack() { if (empty(backtrackStack)) return false; var bt = popLast(backtrackStack); x = bt.x; y = bt.y; direction = bt.dir; return walkOneStep(bt.turn); } public Pt currentPt() { return pt(x, y); } } static final public class ParameterizedTypeImpl implements ParameterizedType { public ParameterizedTypeImpl() { } public Type ownerType; public Type rawType; public Type[] typeArguments; public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) { this.typeArguments = typeArguments; this.rawType = rawType; this.ownerType = ownerType; } public Type[] getActualTypeArguments() { return typeArguments; } public Type getRawType() { return rawType; } public Type getOwnerType() { return ownerType; } @Override public boolean equals(Object other) { if (other instanceof ParameterizedType) return eq(ownerType, ((ParameterizedType) other).getOwnerType()) && eq(rawType, ((ParameterizedType) other).getRawType()) && eq(asList(typeArguments), asList(((ParameterizedType) other).getActualTypeArguments())); return false; } @Override public int hashCode() { return Arrays.hashCode(typeArguments) ^ rawType.hashCode() ^ _hashCode(ownerType); } @Override public String toString() { int length = typeArguments.length; if (length == 0) return typeToString(rawType); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(typeToString(rawType)).append("<").append(typeToString(typeArguments[0])); for (int i = 1; i < length; i++) { stringBuilder.append(", ").append(typeToString(typeArguments[i])); } return stringBuilder.append(">").toString(); } static public String typeToString(Type type) { return type instanceof Class ? ((Class) type).getName() : type.toString(); } } static public class Timestamp implements Comparable, IFieldsToList { public long date; public Timestamp(long date) { this.date = date; } public boolean equals(Object o) { if (!(o instanceof Timestamp)) return false; Timestamp __1 = (Timestamp) o; return date == __1.date; } public int hashCode() { int h = 2059094262; h = boostHashCombine(h, _hashCode(date)); return h; } public Object[] _fieldsToList() { return new Object[] { date }; } public Timestamp() { date = now(); } public Timestamp(Date date) { if (date != null) this.date = date.getTime(); } final public long toLong() { return unixDate(); } public long unixDate() { return date; } public long unixSeconds() { return unixDate() / 1000; } public String toString() { return formatLocalDateWithSeconds(date); } public int compareTo(Timestamp t) { return t == null ? 1 : cmp(date, t.date); } public Timestamp plus(Seconds seconds) { return plus(seconds == null ? null : seconds.getDouble()); } final public Timestamp plusSeconds(double seconds) { return plus(seconds); } public Timestamp plus(double seconds) { return new Timestamp(date + toMS(seconds)); } public long minus(Timestamp ts) { return unixDate() - ts.unixDate(); } public Timestamp minus(long milliseconds) { return new Timestamp(date - milliseconds); } public long sysTime() { return clockTimeToSystemTime(date); } public Duration minusAsDuration(Timestamp ts) { return Duration.ofMillis(minus(ts)); } } static public class ImageInfiller { final public ImageInfiller setInputImage(BufferedImage inputImage) { return inputImage(inputImage); } public ImageInfiller inputImage(BufferedImage inputImage) { this.inputImage = inputImage; return this; } final public BufferedImage getInputImage() { return inputImage(); } public BufferedImage inputImage() { return inputImage; } public BufferedImage inputImage; final public ImageInfiller setMaxDepth(int maxDepth) { return maxDepth(maxDepth); } public ImageInfiller maxDepth(int maxDepth) { this.maxDepth = maxDepth; return this; } final public int getMaxDepth() { return maxDepth(); } public int maxDepth() { return maxDepth; } public int maxDepth = 2; final public ImageInfiller setInfillOpacity(int infillOpacity) { return infillOpacity(infillOpacity); } public ImageInfiller infillOpacity(int infillOpacity) { this.infillOpacity = infillOpacity; return this; } final public int getInfillOpacity() { return infillOpacity(); } public int infillOpacity() { return infillOpacity; } public int infillOpacity = 255; final public ImageInfiller setVerbose(boolean verbose) { return verbose(verbose); } public ImageInfiller verbose(boolean verbose) { this.verbose = verbose; return this; } final public boolean getVerbose() { return verbose(); } public boolean verbose() { return verbose; } public boolean verbose = false; public int w, h; public int[] pixels; public IntBuffer queue; public IntBuffer nextQueue; public BufferedImage outputImage; final public int getRounds() { return rounds(); } public int rounds() { return rounds; } public int rounds; final public int getFilledPixels() { return filledPixels(); } public int filledPixels() { return filledPixels; } public int filledPixels; public ImageInfiller() { } public ImageInfiller(BufferedImage inputImage) { this.inputImage = inputImage; } public ImageInfiller(BufferedImage inputImage, int maxDepth) { this.maxDepth = maxDepth; this.inputImage = inputImage; } public void run() { try { prepare(); while (!done()) oneRound(); } catch (Exception __e) { throw rethrow(__e); } } public boolean prepared() { return pixels != null; } public boolean done() { return nextQueue != null && nextQueue.isEmpty() || rounds >= maxDepth; } public BufferedImage get() { run(); return pixelsToBufferedImage(pixels, w); } public void prepare() { if (pixels != null) return; pixels = pixelsFromBufferedImage(inputImage); w = inputImage.getWidth(); h = inputImage.getHeight(); } public void oneRound() { ++rounds; queue = nextQueue; nextQueue = new IntBuffer(); BitSet queued = new BitSet(); assertBetween("infillOpacity", 1, 255, infillOpacity); IntBuffer toFill = new IntBuffer(); for (var pos : queue == null ? countIterator(w * h) : queue) { int rgba = pixels[pos]; if (!isFullyTransparent(rgba)) continue; int x = pos % w, y = pos / w; MultiSet surroundingColors = new MultiSet(); for (int y2 = max(0, y - 1); y2 < min(h, y + 2); y2++) for (int x2 = max(0, x - 1); x2 < min(w, x + 2); x2++) { rgba = pixels[y2 * w + x2]; if (!isFullyTransparent(rgba)) surroundingColors.add(withOpacity(infillOpacity, rgba)); } if (!surroundingColors.isEmpty()) { toFill.add(y * w + x); toFill.add(surroundingColors.mostPopular()); filledPixels++; for (int y2 = max(0, y - 1); y2 < min(h, y + 2); y2++) for (int x2 = max(0, x - 1); x2 < min(w, x + 2); x2++) { int pos2 = y2 * w + x2; if (!queued.get(pos2) && isFullyTransparent(pixels[pos2])) { queued.set(pos2); nextQueue.add(pos2); } } } } queue = null; int n = l(toFill); for (int i = 0; i < n; i += 2) pixels[toFill.get(i)] = toFill.get(i + 1); if (verbose) print("Round " + rounds + " pixels filled: " + n2(filledPixels) + ", nextQueue: " + l(nextQueue)); } public ImageInfiller unlimited() { maxDepth(Integer.MAX_VALUE); return this; } public void eraseOriginalPixels() { run(); if (infillOpacity >= 255) throw fail("Need semi-transparency to erase original pixels"); int[] pixels = this.pixels; for (int i = 0; i < l(pixels); i++) if (!isTransparent(pixels[i])) pixels[i] = 0; } public int nRemainingTransparentPixels() { return nextQueue.size(); } } abstract static public class ConceptFieldIndexBase implements IConceptIndex, IFieldIndex, IConceptCounter, AutoCloseable { public Concepts concepts; public Class cc; public String field; public Map objectToValue = syncHashMap(); public MultiSetMap valueToObject; public ConceptFieldIndexBase() { init(); } public ConceptFieldIndexBase(Class cc, String field) { this(db_mainConcepts(), cc, field); } public ConceptFieldIndexBase(Concepts concepts, Class cc, String field) { this(); this.field = field; this.cc = cc; this.concepts = concepts; concepts.addConceptIndex(this); updateAll(); register(); updateAll(); } public void updateAll() { for (A c : setToIndex()) updateImpl(c); } public Collection setToIndex() { return list(concepts, cc); } abstract public void init(); abstract public void register(); public void update(Concept c) { if (!isInstance(cc, c)) return; updateImpl((A) c); } synchronized public void updateImpl(A c) { Val newValue = (Val) (cget(c, field)); Val oldValue = objectToValue.get(c); if (newValue == oldValue && (oldValue != null || objectToValue.containsKey(c))) return; valueToObject.remove(oldValue, c); valueToObject.put(newValue, c); put(objectToValue, c, newValue); } public synchronized void remove(Concept c) { if (!isInstance(cc, c)) return; if (!objectToValue.containsKey(c)) return; Val value = objectToValue.get(c); objectToValue.remove(c); valueToObject.remove(value, (A) c); } synchronized public A get(Val value) { return valueToObject.getFirst(value); } public synchronized Collection getAll(Val value) { return valueToObject.get(value); } public synchronized List allValues() { return cloneKeys_noSync(valueToObject.data); } public IterableIterator objectIterator() { return navigableMultiSetMapValuesIterator_concurrent(valueToObject, this); } public synchronized MultiSet allValues_multiSet() { return multiSetMapToMultiSet(valueToObject); } public Class conceptClass() { return cc; } public int countConcepts() { return l(objectToValue); } public Collection allConcepts() { return (Collection) keys(objectToValue); } public Object mutex() { return this; } public void close() { try { concepts.removeConceptIndex(this); } catch (Exception __e) { throw rethrow(__e); } } } static public class ManyCirclePainter implements MakesBufferedImage { final public ManyCirclePainter setW(int w) { return w(w); } public ManyCirclePainter w(int w) { this.w = w; return this; } final public int getW() { return w(); } public int w() { return w; } public int w; final public ManyCirclePainter setH(int h) { return h(h); } public ManyCirclePainter h(int h) { this.h = h; return this; } final public int getH() { return h(); } public int h() { return h; } public int h; final public ManyCirclePainter setCircles(List circles) { return circles(circles); } public ManyCirclePainter circles(List circles) { this.circles = circles; return this; } final public List getCircles() { return circles(); } public List circles() { return circles; } public List circles = new ArrayList(); public int[] pixels; public List[] startCircle, stopCircle; public boolean ran = false; static public class Circle implements IFieldsToList { public Pt center; public int radius; public Circle() { } public Circle(Pt center, int radius) { this.radius = radius; this.center = center; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + center + ", " + radius + ")"; } public boolean equals(Object o) { if (!(o instanceof Circle)) return false; Circle __1 = (Circle) o; return eq(center, __1.center) && radius == __1.radius; } public int hashCode() { int h = 2018617584; h = boostHashCombine(h, _hashCode(center)); h = boostHashCombine(h, _hashCode(radius)); return h; } public Object[] _fieldsToList() { return new Object[] { center, radius }; } } public int getWidth() { return w; } public int getHeight() { return h; } public ManyCirclePainter addCircle(int x, int y, int radius) { circles.add(new Circle(pt(x, y), radius)); return this; } public void run() { try { if (ran) return; ran = true; pixels = new int[w * h]; if (pixels.length == 0) return; int nCircles = l(circles); startCircle = new List[h]; stopCircle = new List[h]; for (var circle : circles) { int y1 = max(0, circle.center.y - circle.radius); int y2 = circle.center.y + circle.radius + 1; if (y1 >= y2) continue; startCircle[y1] = addOrCreate(startCircle[y1], circle); if (y2 < h) stopCircle[y2] = addOrCreate(stopCircle[y2], circle); } int[] startStop = new int[w]; Set liveCircles = new HashSet(); int iPixel = 0; for (int y = 0; y < h; y++) { fillArray(startStop, 0); addAll(liveCircles, startCircle[y]); removeAll(liveCircles, stopCircle[y]); for (var c : liveCircles) { int width = iround(sqrt(sqr(c.radius) - sqr(y - c.center.y))); int x1 = c.center.x - width, x2 = c.center.x + width + 1; if (x1 > w || x2 <= 0) continue; startStop[max(x1, 0)]++; if (x2 < w) startStop[x2]--; } int count = 0; for (int x = 0; x < w; x++) { count += startStop[x]; pixels[iPixel++] = countToColor(count, nCircles); } } } catch (Exception __e) { throw rethrow(__e); } } public int countToColor(int count, int nCircles) { return rgbIntFromBrightness(doubleRatio(count, min(nCircles, 8))); } final public BufferedImage get() { return getBufferedImage(); } public BufferedImage getBufferedImage() { run(); return bufferedImageWithoutAlpha(w, h, pixels); } } final static public class LongRange { public long start, end; public LongRange() { } public LongRange(long start, long end) { this.end = end; this.start = start; } public boolean equals(Object o) { if (o instanceof LongRange) return start == ((LongRange) o).start && end == ((LongRange) o).end; return false; } public int hashCode() { return boostHashCombine(hashOfLong(start), hashOfLong(end)); } public long length() { return end - start; } static public String _fieldOrder = "start end"; public String toString() { return "[" + start + ";" + end + "]"; } } static public class SSIList extends NotifyingList implements ByteIO { public SSIList() { init(); } public SSIList(Collection l) { initAndAddAll(l); } public void readWrite(ByteHead head) { head.exchangeInt(() -> size(), size -> addAll(repF(size, () -> new SSI()))); head.exchangeAll(this); } public BufferedImage render(WidthAndHeight size) { return renderAll(this, size); } public BufferedImage render(BufferedImage canvas) { return renderAll(this, canvas); } public BufferedImage renderOutlines(WidthAndHeight size) { return utils.render(size, g -> { g.setColor(Color.black); for (var ssi : this) ssi.drawOutline(g); }); } } static public class RawBufferedImageDistance_sameSize implements IFieldsToList { public BufferedImage img1; public BufferedImage img2; public RawBufferedImageDistance_sameSize() { } public RawBufferedImageDistance_sameSize(BufferedImage img1, BufferedImage img2) { this.img2 = img2; this.img1 = img1; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + img1 + ", " + img2 + ")"; } public Object[] _fieldsToList() { return new Object[] { img1, img2 }; } final public RawBufferedImageDistance_sameSize setStoppingValue(long stoppingValue) { return stoppingValue(stoppingValue); } public RawBufferedImageDistance_sameSize stoppingValue(long stoppingValue) { this.stoppingValue = stoppingValue; return this; } final public long getStoppingValue() { return stoppingValue(); } public long stoppingValue() { return stoppingValue; } public long stoppingValue = Integer.MAX_VALUE; public int w, h; public int x, y; public long sum; public boolean completed() { return w != 0 && x == w && y == h; } public long get() { int w = this.w = img1.getWidth(), h = this.h = img1.getHeight(); assertSameSize(img1, img2); var gp1 = grabbableIntPixels_fastOrSlow(img1); var gp2 = grabbableIntPixels_fastOrSlow(img2); int iPixels1 = gp1.offset, iPixels2 = gp2.offset; int[] pixels1 = gp1.data, pixels2 = gp2.data; long sum = 0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { sum += rawRGBDiff(pixels1[iPixels1 + x], pixels2[iPixels2 + x]); if (sum > stoppingValue) { this.x = x; this.y = y; this.sum = sum; return sum; } } iPixels1 += gp1.scanlineStride; iPixels2 += gp2.scanlineStride; } this.x = w; this.y = h; return this.sum = sum; } } static public class JECompressionSearch extends CompressionSearch_AnyType { public JECompressionSearch() { } public JECompressionSearch(Data data, long inputSize) { super(jeCompressionRegime(), data, inputSize); } } static public class JComponentWithChangeListeners extends JComponent implements IMeta, IHasChangeListeners, ChangeTriggerable { transient public Set onChange; public JComponentWithChangeListeners onChange(Runnable r) { onChange = createOrAddToSyncLinkedHashSet(onChange, r); return this; } public JComponentWithChangeListeners removeChangeListener(Runnable r) { utils.remove(onChange, r); return this; } public void change() { if (onChange != null) for (var listener : onChange) pcallF_typed(listener); } volatile public Object meta; public void _setMeta(Object meta) { this.meta = meta; } public Object _getMeta() { return meta; } final public boolean scaffolding() { return scaffoldingEnabled(); } final public boolean scaffolded() { return scaffoldingEnabled(); } public boolean scaffoldingEnabled() { return utils.scaffoldingEnabled(this); } public boolean scaffoldingEnabled(Object o) { return utils.scaffoldingEnabled(o); } public String toString_base() { return super.toString(); } public String toString() { Object o = metaGet("toString", this); if (o instanceof String) return ((String) o); if (o instanceof IF1) return str(((IF1) o).get(this)); return toString_base(); } public A print(A a) { return print("", a); } public A print(String msg, A a) { return _print(msg, a); } } static public class MultiSet implements IMultiSet { public Map map = new HashMap(); public int size; public MultiSet(boolean useTreeMap) { if (useTreeMap) map = new TreeMap(); } public MultiSet(TreeMap map) { this.map = map; } public MultiSet() { } public MultiSet(Iterable c) { addAll(c); } public MultiSet(MultiSet ms) { synchronized (ms) { for (A a : ms.keySet()) add(a, ms.get(a)); } } public synchronized int add(A key) { return add(key, 1); } synchronized public void addAll(Iterable c) { if (c != null) for (A a : c) add(a); } synchronized public void addAll(MultiSet ms) { for (A a : ms.keySet()) add(a, ms.get(a)); } synchronized public int add(A key, int count) { if (count <= 0) return 0; size += count; Integer i = map.get(key); map.put(key, i != null ? (count += i) : count); return count; } synchronized public void put(A key, int count) { int oldCount = get(key); if (count == oldCount) return; size += count - oldCount; if (count != 0) map.put(key, count); else map.remove(key); } public synchronized int get(A key) { Integer i = map.get(key); return i != null ? i : 0; } synchronized public boolean contains(A key) { return map.containsKey(key); } synchronized public void remove(A key) { Integer i = map.get(key); if (i != null) { --size; if (i > 1) map.put(key, i - 1); else map.remove(key); } } synchronized public List topTen() { return getTopTen(); } synchronized public List getTopTen() { return getTopTen(10); } synchronized public List getTopTen(int maxSize) { List list = getSortedListDescending(); return list.size() > maxSize ? list.subList(0, maxSize) : list; } synchronized public List highestFirst() { return getSortedListDescending(); } synchronized public List lowestFirst() { return reversedList(getSortedListDescending()); } synchronized public List getSortedListDescending() { List list = new ArrayList(map.keySet()); Collections.sort(list, new Comparator() { public int compare(A a, A b) { return map.get(b).compareTo(map.get(a)); } }); return list; } synchronized public int getNumberOfUniqueElements() { return map.size(); } synchronized public int uniqueSize() { return map.size(); } synchronized public Set asSet() { return map.keySet(); } synchronized public NavigableSet navigableSet() { return navigableKeys((NavigableMap) map); } public synchronized Set keySet() { return map.keySet(); } final public A mostPopular() { return getMostPopularEntry(); } synchronized public A getMostPopularEntry() { int max = 0; A a = null; for (Map.Entry entry : map.entrySet()) { if (entry.getValue() > max) { max = entry.getValue(); a = entry.getKey(); } } return a; } synchronized public void removeAll(A key) { size -= get(key); map.remove(key); } public synchronized int size() { return size; } synchronized public MultiSet mergeWith(MultiSet set) { MultiSet result = new MultiSet(); for (A a : set.asSet()) { result.add(a, set.get(a)); } return result; } public synchronized boolean isEmpty() { return map.isEmpty(); } synchronized public String toString() { return str(map); } synchronized public void clear() { map.clear(); size = 0; } final public Map toMap() { return asMap(); } synchronized public Map asMap() { return cloneMap(map); } } static public class T3 { public A a; public B b; public C c; public T3() { } public T3(A a, B b, C c) { this.c = c; this.b = b; this.a = a; } public T3(T3 t) { a = t.a; b = t.b; c = t.c; } public int hashCode() { return _hashCode(a) + 2 * _hashCode(b) - 4 * _hashCode(c); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof T3)) return false; T3 t = (T3) o; return eq(a, t.a) && eq(b, t.b) && eq(c, t.c); } public String toString() { return "(" + quoteBorderless(a) + ", " + quoteBorderless(b) + ", " + quoteBorderless(c) + ")"; } } static public interface IResourceHolder { public A add(A a); public Collection takeAll(); } static public class CloseablesHolder extends Meta implements AutoCloseable, IResourceHolder { public LinkedHashSet closeables = new LinkedHashSet(); public WeakReference createdInThread = weakRef(currentThread()); public synchronized void addAll(Iterable l) { for (var a : unnullForIteration(l)) add(a); } public synchronized A add(A a) { if (a != null) closeables.add(a); return a; } final public A takeOut(A a) { return remove(a); } synchronized public A remove(A a) { closeables.remove(a); return a; } synchronized public A close(A a) { if (a == null) return a; closeables.remove(a); utils.close(a); return a; } public void close() { try { for (AutoCloseable c : reversed(takeAll())) utils.close(c); } catch (Exception __e) { throw rethrow(__e); } } final public void clear() { forget(); } public synchronized void forget() { closeables.clear(); } public synchronized Collection takeAll() { return cloneAndClear(closeables); } } static public class EvalJavaPrep { public List global = new ArrayList(); public List outer = new ArrayList(); } public interface SizeInInts { public long sizeInInts(); } static abstract public class DynamicStack extends JPanel { final public DynamicStack setSpacing(int spacing) { return spacing(spacing); } public DynamicStack spacing(int spacing) { this.spacing = spacing; return this; } final public int getSpacing() { return spacing(); } public int spacing() { return spacing; } public int spacing = 10; public boolean useFiller = false; public DynamicStack() { this(true); } public DynamicStack(boolean useFiller) { super(new GridBagLayout()); this.useFiller = useFiller; _addFiller(); } abstract public GridBagConstraints _componentConstraints(); abstract public GridBagConstraints _fillerConstraints(); public void _addFiller() { if (useFiller) add(jrigid(), _fillerConstraints()); } public void addComponent(final Component c) { addComponents(ll(c)); } public void addComponents(Collection l) { swing(() -> { for (Component c : unnullForIteration(l)) if (c.getParent() != this) add(c, _componentConstraints(), getComponentCount() - (useFiller ? 1 : 0)); revalidate(); }); } public void setComponents(Collection l) { removeAll(); _addFiller(); addComponents(l); } public void clearComponents() { setComponents(null); } public void removeComponent(Component c) { swing(() -> { if (c != null) { remove(c); revalidate(); } }); } public int numComponents() { return countComponents() - 1; } public List components() { return dropLast(utils.getComponents(this)); } public boolean isEmpty() { return numComponents() == 0; } } static public class OHLCEntry { final public OHLCEntry setDateRange(TimestampRange dateRange) { return dateRange(dateRange); } public OHLCEntry dateRange(TimestampRange dateRange) { this.dateRange = dateRange; return this; } final public TimestampRange getDateRange() { return dateRange(); } public TimestampRange dateRange() { return dateRange; } public TimestampRange dateRange; final public OHLCEntry setOpen(double open) { return open(open); } public OHLCEntry open(double open) { this.open = open; return this; } final public double getOpen() { return open(); } public double open() { return open; } public double open; final public OHLCEntry setHigh(double high) { return high(high); } public OHLCEntry high(double high) { this.high = high; return this; } final public double getHigh() { return high(); } public double high() { return high; } public double high; final public OHLCEntry setLow(double low) { return low(low); } public OHLCEntry low(double low) { this.low = low; return this; } final public double getLow() { return low(); } public double low() { return low; } public double low; final public OHLCEntry setClose(double close) { return close(close); } public OHLCEntry close(double close) { this.close = close; return this; } final public double getClose() { return close(); } public double close() { return close; } public double close; final public OHLCEntry setVwap(double vwap) { return vwap(vwap); } public OHLCEntry vwap(double vwap) { this.vwap = vwap; return this; } final public double getVwap() { return vwap(); } public double vwap() { return vwap; } public double vwap; final public OHLCEntry setVolume(double volume) { return volume(volume); } public OHLCEntry volume(double volume) { this.volume = volume; return this; } final public double getVolume() { return volume(); } public double volume() { return volume; } public double volume; final public OHLCEntry setCount(int count) { return count(count); } public OHLCEntry count(int count) { this.count = count; return this; } final public int getCount() { return count(); } public int count() { return count; } public int count; public String toString() { return stdToString(this); } } static public class RegionHoleBounds implements IFieldsToList { public IImageRegion region; public RegionHoleBounds() { } public RegionHoleBounds(IImageRegion region) { this.region = region; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + region + ")"; } public Object[] _fieldsToList() { return new Object[] { region }; } public List holeBounds = new ArrayList(); public BoundsFinder bf; public List get() { if (region == null) return holeBounds; var borderWalker = new RegionBorder_innerPoints_v2(region); borderWalker.onNewTrace(isHole -> { if (isHole) { if (bf != null) holeBounds.add(bf.get()); bf = new BoundsFinder(); } else bf = null; }); borderWalker.onFoundPoint(p -> { { if (bf != null) bf.addPt(p); } }); borderWalker.run(); if (bf != null) holeBounds.add(bf.get()); return holeBounds; } } public interface IPersistenceInfo { public Map _persistenceInfo(); } static public class BoxBlurFilter extends AbstractBufferedImageOp implements IF1 { public int hRadius; public int vRadius; public int iterations = 1; public BoxBlurFilter() { } public BoxBlurFilter(int radius) { hRadius = vRadius = radius; } public BoxBlurFilter(int hRadius, int vRadius) { this.vRadius = vRadius; this.hRadius = hRadius; } public BufferedImage get(BufferedImage src) { return filter(src, null); } public BufferedImage filter(BufferedImage src, BufferedImage dst) { int width = src.getWidth(); int height = src.getHeight(); if (dst == null) dst = createCompatibleDestImage(src, null); int[] inPixels = new int[width * height]; int[] outPixels = new int[width * height]; getRGB(src, 0, 0, width, height, inPixels); for (int i = 0; i < iterations; i++) { blur(inPixels, outPixels, width, height, hRadius); blur(outPixels, inPixels, height, width, vRadius); } setRGB(dst, 0, 0, width, height, inPixels); return dst; } static public void blur(int[] in, int[] out, int width, int height, int radius) { int widthMinus1 = width - 1; int tableSize = 2 * radius + 1; int[] divide = new int[256 * tableSize]; for (int i = 0; i < 256 * tableSize; i++) divide[i] = i / tableSize; int inIndex = 0; for (int y = 0; y < height; y++) { int outIndex = y; int ta = 0, tr = 0, tg = 0, tb = 0; for (int i = -radius; i <= radius; i++) { int rgb = in[inIndex + clamp(i, 0, width - 1)]; ta += (rgb >> 24) & 0xff; tr += (rgb >> 16) & 0xff; tg += (rgb >> 8) & 0xff; tb += rgb & 0xff; } for (int x = 0; x < width; x++) { out[outIndex] = (divide[ta] << 24) | (divide[tr] << 16) | (divide[tg] << 8) | divide[tb]; int i1 = x + radius + 1; if (i1 > widthMinus1) i1 = widthMinus1; int i2 = x - radius; if (i2 < 0) i2 = 0; int rgb1 = in[inIndex + i1]; int rgb2 = in[inIndex + i2]; ta += ((rgb1 >> 24) & 0xff) - ((rgb2 >> 24) & 0xff); tr += ((rgb1 & 0xff0000) - (rgb2 & 0xff0000)) >> 16; tg += ((rgb1 & 0xff00) - (rgb2 & 0xff00)) >> 8; tb += (rgb1 & 0xff) - (rgb2 & 0xff); outIndex += height; } inIndex += width; } } } static public class IntRange { public int start, end; public IntRange() { } public IntRange(int start, int end) { this.end = end; this.start = start; } public IntRange(IntRange r) { start = r.start; end = r.end; } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } final public int length() { return end - start; } final public boolean empty() { return start >= end; } final public boolean isEmpty() { return start >= end; } static public String _fieldOrder = "start end"; public String toString() { return "[" + start + ";" + end + "]"; } public boolean contains(int i) { return i >= start && i <= end; } } static public class ExtendedCSVParser implements Steppable { public String csv; public int numFields; public long numRecords; public long maxRecordsToLoad = -1; public int i, startOfValue; public boolean inQuotedValue = false; public ExtendedCSVParser() { } public ExtendedCSVParser(String csv) { this.csv = csv; } public void run() { try { stepAll(this); } catch (Exception __e) { throw rethrow(__e); } } public boolean step() { if (i >= l(csv)) { foundValue(substring(csv, startOfValue)); endOfRecord(); return false; } char c = csv.charAt(i); if (c == ',') { if (!inQuotedValue) { foundValue(substring(csv, startOfValue, i)); startOfValue = i + 1; } } else if (c == '\r' || c == '\n') { if (!inQuotedValue) { foundValue(substring(csv, startOfValue, i)); startOfValue = i + 1; if (endOfRecord()) return false; } } else if (c == '"') { if (inQuotedValue) { if (charAt(csv, i + 1) == '"') i++; else inQuotedValue = false; } else inQuotedValue = true; } i++; return true; } public String unquoteValue(String value) { return dropPrefix("\"", dropSuffix("\"", replace(trim(value), "\"\"", "\""))); } public void foundValue(String value) { if (nempty(value)) { ++numFields; onValueFound(unquoteValue(value)); } } public boolean endOfRecord() { if (numFields == 0) return false; onEndOfRecord(); numFields = 0; return ++numRecords >= maxRecordsToLoad && maxRecordsToLoad >= 0; } transient public IVF1 onValueFound; public void onValueFound(String value) { if (onValueFound != null) onValueFound.get(value); else onValueFound_base(value); } final public void onValueFound_fallback(IVF1 _f, String value) { if (_f != null) _f.get(value); else onValueFound_base(value); } public void onValueFound_base(String value) { } transient public Runnable onEndOfRecord; public void onEndOfRecord() { if (onEndOfRecord != null) onEndOfRecord.run(); else onEndOfRecord_base(); } final public void onEndOfRecord_fallback(Runnable _f) { if (_f != null) _f.run(); else onEndOfRecord_base(); } public void onEndOfRecord_base() { } } static public class HuffmanTree implements BitIO { final public HuffmanTree setRoot(Node root) { return root(root); } public HuffmanTree root(Node root) { this.root = root; return this; } final public Node getRoot() { return root(); } public Node root() { return root; } public Node root; public Leaf[] characterMap = new Leaf[256]; final public HuffmanTree setDebug(boolean debug) { return debug(debug); } public HuffmanTree debug(boolean debug) { this.debug = debug; return this; } final public boolean getDebug() { return debug(); } public boolean debug() { return debug; } public boolean debug = false; abstract public class Node implements BitIO { final public Node setParent(Branch parent) { return parent(parent); } public Node parent(Branch parent) { this.parent = parent; return this; } final public Branch getParent() { return parent(); } public Branch parent() { return parent; } public Branch parent; public void buildSymbol(BitBuffer head, Node child) { { if (parent != null) parent.buildSymbol(head, this); } } abstract public Leaf readSymbol(BitHead head); } public class Branch extends Node { final public Node getZero() { return zero(); } public Node zero() { return zero; } public Node zero; final public Node getOne() { return one(); } public Node one() { return one; } public Node one; public Branch zero(Node zero) { this.zero = zero; zero.parent = this; return this; } public Branch one(Node one) { this.one = one; one.parent = this; return this; } public void readWrite(BitHead head) { head.exchangeBit(1); head.exchange(zero, () -> zero(readNode(head))); head.exchange(one, () -> one(readNode(head))); } public void buildSymbol(BitBuffer head, Node child) { head.add(child == one); super.buildSymbol(head, child); } public Leaf readSymbol(BitHead head) { boolean bit = head.readBit(); if (debug) print("Read bit " + bit); return (bit ? one : zero).readSymbol(head); } } public class Leaf extends Node { final public byte getLiteral() { return literal(); } public byte literal() { return literal; } public byte literal; public Leaf() { } public Leaf(int literal) { literal((byte) literal); } public byte get() { return literal; } public Leaf literal(byte b) { literal = b; fillCharacterMap(); return this; } public void readWrite(BitHead head) { head.exchangeBit(0); head.exchangeByte(literal, __3 -> literal(__3)); if (debug) print(this); } public void fillCharacterMap() { characterMap[ubyteToInt(literal)] = this; } public Leaf readSymbol(BitHead head) { if (debug) print("Reached symbol " + this); return this; } public String toString() { return "Literal " + byteToHex(literal); } } public void makeRootIfEmpty() { if (root == null) root = new Leaf(0); } public Node readNode(BitHead head) { boolean type = head.peekBit(); Node node = type ? new Branch() : new Leaf(); if (debug) print(type ? "Branch" : "Leaf"); node.readWrite(head); return node; } public void readWrite(BitHead head) { if (head.writeMode()) { makeRootIfEmpty(); root.readWrite(head); } if (head.readMode()) root = readNode(head); } public String toString() { makeRootIfEmpty(); List out = new ArrayList(); StringBuilder symbol = new StringBuilder(); final class _C_1 { public void toString_collect(Node node) { if (node instanceof Leaf) { out.add(symbol + ": " + quote(codePoint(ubyteToInt(((Leaf) node).get())))); } else { symbol.append("0"); toString_collect(((Branch) node).zero()); removeLast(symbol); symbol.append("1"); toString_collect(((Branch) node).one()); removeLast(symbol); } } } final _C_1 __2 = new _C_1(); __2.toString_collect(root); return lines(out); } final public void writeSymbol(int sym, BitHead head) { writeCharacter(sym, head); } public void writeCharacter(int sym, BitHead head) { sym &= 0xFF; Leaf node = characterMap[sym]; if (node == null) throw fail("Symbol cannot be encoded: " + sym); BitBuffer buffer = new BitBuffer(); node.buildSymbol(buffer, null); if (buffer.isEmpty()) buffer.add(0); for (int i = l(buffer) - 1; i >= 0; i--) head.writeBit(buffer.get(i)); } public int readSymbol(BitHead head) { if (head.isEOF()) return -1; if (root instanceof Leaf) head.advanceBit(); return ubyteToInt(root.readSymbol(head).get()); } } static public class PleaseIncludeFunctionsStatement { public List tok; public int iStart, iFirstIdentifier, iDot, iEnd; public boolean containsFunction(String name) { return contains(subList(tok, iFirstIdentifier, iDot), name); } } static public class UnsynchronizedCompactHashSet extends java.util.AbstractSet { final static public int INITIAL_SIZE = 3; public final static double LOAD_FACTOR = 0.75; final static public Object nullObject = new Object(); final static public Object deletedObject = new Object(); public int elements; public int freecells; public A[] objects; public int modCount; public UnsynchronizedCompactHashSet() { this(INITIAL_SIZE); } public UnsynchronizedCompactHashSet(int size) { objects = (A[]) new Object[(size == 0 ? 1 : size)]; elements = 0; freecells = objects.length; modCount = 0; } public UnsynchronizedCompactHashSet(Collection c) { this(c.size()); addAll(c); } @Override public Iterator iterator() { return new CompactHashIterator(); } @Override public int size() { return elements; } @Override public boolean isEmpty() { return elements == 0; } @Override public boolean contains(Object o) { return find(o) != null; } public A find(Object o) { if (o == null) o = nullObject; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) { index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset * 2 + 1; if (offset == -1) offset = 2; } return objects[index]; } public boolean removeIfSame(Object o) { A value = find(o); if (value == o) { remove(value); return true; } return false; } @Override public boolean add(Object o) { if (o == null) o = nullObject; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; int deletedix = -1; while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) { if (objects[index] == deletedObject) deletedix = index; index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset * 2 + 1; if (offset == -1) offset = 2; } if (objects[index] == null) { if (deletedix != -1) index = deletedix; else freecells--; modCount++; elements++; objects[index] = (A) o; if (1 - (freecells / (double) objects.length) > LOAD_FACTOR) rehash(); return true; } else return false; } @Override public boolean remove(Object o) { if (o == null) o = nullObject; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) { index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset * 2 + 1; if (offset == -1) offset = 2; } if (objects[index] != null) { objects[index] = (A) deletedObject; modCount++; elements--; return true; } else return false; } @Override public void clear() { elements = 0; for (int ix = 0; ix < objects.length; ix++) objects[ix] = null; freecells = objects.length; modCount++; } @Override public Object[] toArray() { Object[] result = new Object[elements]; Object[] objects = this.objects; int pos = 0; for (int i = 0; i < objects.length; i++) if (objects[i] != null && objects[i] != deletedObject) { if (objects[i] == nullObject) result[pos++] = null; else result[pos++] = objects[i]; } return result; } @Override public T[] toArray(T[] a) { int size = elements; if (a.length < size) a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); A[] objects = this.objects; int pos = 0; for (int i = 0; i < objects.length; i++) if (objects[i] != null && objects[i] != deletedObject) { if (objects[i] == nullObject) a[pos++] = null; else a[pos++] = (T) objects[i]; } return a; } public void rehash() { int garbagecells = objects.length - (elements + freecells); if (garbagecells / (double) objects.length > 0.05) rehash(objects.length); else rehash(objects.length * 2 + 1); } public void rehash(int newCapacity) { int oldCapacity = objects.length; @SuppressWarnings("unchecked") A[] newObjects = (A[]) new Object[newCapacity]; for (int ix = 0; ix < oldCapacity; ix++) { Object o = objects[ix]; if (o == null || o == deletedObject) continue; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % newCapacity; int offset = 1; while (newObjects[index] != null) { index = ((index + offset) & 0x7FFFFFFF) % newCapacity; offset = offset * 2 + 1; if (offset == -1) offset = 2; } newObjects[index] = (A) o; } objects = newObjects; freecells = objects.length - elements; } public class CompactHashIterator implements Iterator { public int index; public int lastReturned = -1; public int expectedModCount; @SuppressWarnings("empty-statement") public CompactHashIterator() { for (index = 0; index < objects.length && (objects[index] == null || objects[index] == deletedObject); index++) ; expectedModCount = modCount; } @Override public boolean hasNext() { return index < objects.length; } @SuppressWarnings("empty-statement") @Override public T next() { int length = objects.length; if (index >= length) { lastReturned = -2; throw new NoSuchElementException(); } lastReturned = index; for (index += 1; index < length && (objects[index] == null || objects[index] == deletedObject); index++) ; if (objects[lastReturned] == nullObject) return null; else return (T) objects[lastReturned]; } @Override public void remove() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (lastReturned == -1 || lastReturned == -2) throw new IllegalStateException(); if (objects[lastReturned] != null && objects[lastReturned] != deletedObject) { objects[lastReturned] = (A) deletedObject; elements--; modCount++; expectedModCount = modCount; } } } public int capacity() { return objects.length; } public boolean shrinkToFactor(double factor) { if (factor > LOAD_FACTOR) throw fail("Shrink factor must be equal to or smaller than load factor: " + factor + " / " + LOAD_FACTOR); int newCapacity = max(INITIAL_SIZE, iround(size() / factor)); if (newCapacity >= capacity()) return false; rehash(newCapacity); return true; } } static public class TimestampRange implements Comparable, IFieldsToList { static final public String _fieldOrder = "start end"; public Timestamp start; public Timestamp end; public TimestampRange() { } public TimestampRange(Timestamp start, Timestamp end) { this.end = end; this.start = start; } public boolean equals(Object o) { if (!(o instanceof TimestampRange)) return false; TimestampRange __1 = (TimestampRange) o; return eq(start, __1.start) && eq(end, __1.end); } public int hashCode() { int h = -2020922905; h = boostHashCombine(h, _hashCode(start)); h = boostHashCombine(h, _hashCode(end)); return h; } public Object[] _fieldsToList() { return new Object[] { start, end }; } public TimestampRange(long start, long end) { this(new Timestamp(start), new Timestamp(end)); } final public Timestamp startTime() { return start(); } public Timestamp start() { return start; } final public Timestamp endTime() { return end(); } public Timestamp end() { return end; } final public TimestampRange startTime(Timestamp start) { return start(start); } public TimestampRange start(Timestamp start) { this.start = start; return this; } final public TimestampRange endTime(Timestamp end) { return end(end); } public TimestampRange end(Timestamp end) { this.end = end; return this; } public boolean complete() { return start != null && end != null; } public Duration duration() { return !complete() ? null : end.minusAsDuration(start); } public long length() { return !complete() ? 0 : end.unixDate() - start.unixDate(); } public String toString() { return start + " to " + end; } public int compareTo(TimestampRange r) { return cmp(start, r.start); } public List toList() { return ll(start, end); } } static public class JPaintTool extends MetaWithChangeListeners implements Swingable, AutoCloseable { public transient FieldVar varAutoPersistFile_cache; public FieldVar varAutoPersistFile() { if (varAutoPersistFile_cache == null) varAutoPersistFile_cache = varAutoPersistFile_load(); return varAutoPersistFile_cache; } public FieldVar varAutoPersistFile_load() { return new FieldVar(this, "autoPersistFile", () -> autoPersistFile(), autoPersistFile -> autoPersistFile(autoPersistFile)); } final public JPaintTool setAutoPersistFile(File autoPersistFile) { return autoPersistFile(autoPersistFile); } public JPaintTool autoPersistFile(File autoPersistFile) { if (!eq(this.autoPersistFile, autoPersistFile)) { this.autoPersistFile = autoPersistFile; change(); } return this; } final public File getAutoPersistFile() { return autoPersistFile(); } public File autoPersistFile() { return autoPersistFile; } public File autoPersistFile; public transient FieldVar varAutoPersistInterval_cache; public FieldVar varAutoPersistInterval() { if (varAutoPersistInterval_cache == null) varAutoPersistInterval_cache = varAutoPersistInterval_load(); return varAutoPersistInterval_cache; } public FieldVar varAutoPersistInterval_load() { return new FieldVar(this, "autoPersistInterval", () -> autoPersistInterval(), autoPersistInterval -> autoPersistInterval(autoPersistInterval)); } final public JPaintTool setAutoPersistInterval(double autoPersistInterval) { return autoPersistInterval(autoPersistInterval); } public JPaintTool autoPersistInterval(double autoPersistInterval) { if (!eq(this.autoPersistInterval, autoPersistInterval)) { this.autoPersistInterval = autoPersistInterval; change(); } return this; } final public double getAutoPersistInterval() { return autoPersistInterval(); } public double autoPersistInterval() { return autoPersistInterval; } public double autoPersistInterval = 10.0; public transient FieldVar varBrushColor_cache; public FieldVar varBrushColor() { if (varBrushColor_cache == null) varBrushColor_cache = varBrushColor_load(); return varBrushColor_cache; } public FieldVar varBrushColor_load() { return new FieldVar(this, "brushColor", () -> brushColor(), brushColor -> brushColor(brushColor)); } final public JPaintTool setBrushColor(Color brushColor) { return brushColor(brushColor); } public JPaintTool brushColor(Color brushColor) { if (!eq(this.brushColor, brushColor)) { this.brushColor = brushColor; change(); } return this; } final public Color getBrushColor() { return brushColor(); } public Color brushColor() { return brushColor; } public Color brushColor = Color.black; public transient FieldVar varDrawingAllowed_cache; public FieldVar varDrawingAllowed() { if (varDrawingAllowed_cache == null) varDrawingAllowed_cache = varDrawingAllowed_load(); return varDrawingAllowed_cache; } public FieldVar varDrawingAllowed_load() { return new FieldVar(this, "drawingAllowed", () -> drawingAllowed(), drawingAllowed -> drawingAllowed(drawingAllowed)); } final public JPaintTool setDrawingAllowed(boolean drawingAllowed) { return drawingAllowed(drawingAllowed); } public JPaintTool drawingAllowed(boolean drawingAllowed) { if (!eq(this.drawingAllowed, drawingAllowed)) { this.drawingAllowed = drawingAllowed; change(); } return this; } final public boolean getDrawingAllowed() { return drawingAllowed(); } public boolean drawingAllowed() { return drawingAllowed; } public boolean drawingAllowed = true; final public JPaintTool setBgColor(Color bgColor) { return bgColor(bgColor); } public JPaintTool bgColor(Color bgColor) { this.bgColor = bgColor; return this; } final public Color getBgColor() { return bgColor(); } public Color bgColor() { return bgColor; } public Color bgColor = Color.lightGray; transient public Set> onImageChanged; public JPaintTool onImageChanged(IVF1 f) { onImageChanged = createOrAddToSyncLinkedHashSet(onImageChanged, f); return this; } public JPaintTool removeImageChangedListener(IVF1 f) { utils.remove(onImageChanged, f); return this; } public void imageChanged(BufferedImage image) { if (onImageChanged != null) for (var listener : onImageChanged) pcallF_typed(listener, image); } final public JPaintTool setDirty(boolean dirty) { return dirty(dirty); } public JPaintTool dirty(boolean dirty) { if (!eq(this.dirty, dirty)) { this.dirty = dirty; change(); } return this; } final public boolean getDirty() { return dirty(); } public boolean dirty() { return dirty; } transient volatile public boolean dirty = false; final public BufferedImage getImage() { return image(); } public BufferedImage image() { return image; } transient public BufferedImage image; final public ImageSurface getImageSurface() { return imageSurface(); } public ImageSurface imageSurface() { return imageSurface; } transient public ImageSurface imageSurface; transient public boolean autoPersistInstalled = false; transient public ReliableSingleThread rstPersist = new ReliableSingleThread(new Runnable() { public void run() { try { _persist(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_persist();"; } }); transient public JPanel buttons; transient public ImageSurfaceScribbleTool scribbler = new ImageSurfaceScribbleTool(); transient public ImageSurfaceDragger dragger = new ImageSurfaceDragger(); transient public ImageSurfaceSelector selector = new ImageSurfaceSelector(); transient public JComboBox cbImageSize; transient public ButtonGroup colorButtonGroup = new ButtonGroup(); transient public ButtonGroup toolSelectButtonGroup = new ButtonGroup(); transient public boolean ran_init = false; public void init() { if (ran_init) return; ran_init = true; init_impl(); } public void init_impl() { imageSurface = makeImageSurface(); imageSurface.onUserModifiedImage(image -> { print("userModifiedImage"); setImage(image); fireImageChanged(); }); cbImageSize = jTypedComboBox(imageSizes()); utils.onChange(cbImageSize, __1 -> setImageSize(__1)); printVars("JPaintTool.init", "image", image, "autoPersistFile", autoPersistFile); if (image == null) { setImage(makeNewImage()); if (autoPersistFile != null) { try { var img = loadImage2(autoPersistFile); if (img != null) { setImage(img); print("Image loaded"); } } catch (Throwable __e) { pcallFail(__e); } if (!autoPersistInstalled) { autoPersistInstalled = true; awtEvery(imageSurface, autoPersistInterval, rstPersist); bindToComponent(imageSurface, null, rstPersist); } } } varDrawingAllowed().onChangeAndNow(b -> scribbler.enabled(print("scribblerEnabled", b))); } public BufferedImage makeNewImage() { return utils.newImage(defaultImageSize()); } public WidthAndHeight defaultImageSize() { return getSelected(cbImageSize); } public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { init(); var filePathLabel = new JFilePathLabel(autoPersistFile).nameOnly(); varAutoPersistFile().onChange(file -> filePathLabel.setFile(file)); var filePathLabelVis = filePathLabel.visualize(); componentPopupMenuItem(filePathLabel.button.visualize(), "Save image now", new Runnable() { public void run() { try { dirty = true; rstPersist.get(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "dirty = true; rstPersist!;"; } }); return withTopMargin(northCenterAndSouthWithMargin(buttons = jcenteredline(flattenToList(jbutton("New image", runnableThread(new Runnable() { public void run() { try { newImage(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "newImage();"; } })), withLabel("Size:", cbImageSize), map(__145 -> colorSelectButton(__145), colors()), swing(() -> new JImageSwitch("#1103077", "#1103078", varDrawingAllowed()).setToolTips("Drawing allowed (click to change)", "Drawing not allowed (click to change)")))), centerAndEastWithMargin(jscroll_borderless(setBackground(bgColor, jFullCenter(imageSurface))), vstackWithSpacing(makeToolSelectors())), centerAndEast(withLeftMargin(bottomLeftControls()), autoPersistFile == null ? jpanel() : withSideMargin(withLabel("Image:", filePathLabelVis))))); } public void setImage(BufferedImage image) { this.image = image; imageSurface.setImage(image); imageChanged(image); } transient public IF0 makeImageSurface; public ImageSurface makeImageSurface() { return makeImageSurface != null ? makeImageSurface.get() : makeImageSurface_base(); } final public ImageSurface makeImageSurface_fallback(IF0 _f) { return _f != null ? _f.get() : makeImageSurface_base(); } public ImageSurface makeImageSurface_base() { var is = pixelatedImageSurface(); is.specialPurposed = true; is.allowPaste(true); is.zoomable(false); is.removeAllTools(); scribbler.onPainted(() -> fireImageChanged()); varBrushColor().onChangeAndNow(color -> scribbler.setColor(color)); is.setTool(scribbler); return is; } public void fireImageChanged() { dirty = true; imageChanged(getImage()); } public void _persist() { if (autoPersistFile != null && dirty) { dirty = false; savePNGVerbose(autoPersistFile, image); } } public void loadImageProtected(File file) { loadImage(file); drawingAllowed(false); } public void loadImage(File file) { close(); var img = loadImage2(file); autoPersistFile(file); setImage(img); } public void newImage() { try { close(); var file = createAutoPersistFile(); print("Created auto persist file: " + f2s(file)); autoPersistFile(file); setImage(makeNewImage()); drawingAllowed(true); dirty = false; } catch (Exception __e) { throw rethrow(__e); } } transient public IF0 createAutoPersistFile; public File createAutoPersistFile() { return createAutoPersistFile != null ? createAutoPersistFile.get() : createAutoPersistFile_base(); } final public File createAutoPersistFile_fallback(IF0 _f) { return _f != null ? _f.get() : createAutoPersistFile_base(); } public File createAutoPersistFile_base() { return autoPersistFile(); } public JToggleButton colorSelectButton(Color color) { var btn = jImageToggleButton(utils.newImage(16, color), "Select color to draw with", () -> setBrushColor(color), eq(brushColor(), color)); return addToButtonGroup(colorButtonGroup, btn); } public List colors() { return colorPaletteByBits(1); } public List imageSizes() { return mapLL(__146 -> sixteenToNine_p(__146), 240, 360, 480, 720); } public void setImageSize(WidthAndHeight size) { if (!sameSize(getImage(), size)) newImage(); } public void close() { try { rstPersist.triggerAndWait(); } catch (Exception __e) { throw rethrow(__e); } } transient public IF0 bottomLeftControls; public JComponent bottomLeftControls() { return bottomLeftControls != null ? bottomLeftControls.get() : bottomLeftControls_base(); } final public JComponent bottomLeftControls_fallback(IF0 _f) { return _f != null ? _f.get() : bottomLeftControls_base(); } public JComponent bottomLeftControls_base() { return jpanel(); } public void selectTool(ImageSurfaceMouseHandler tool) { imageSurface.setTool(tool); } public JToggleButton toolSelectButton(ImageSurfaceMouseHandler tool, String imageID, String toolTip) { return addToButtonGroup(toolSelectButtonGroup, jImageToggleButton(imageID, toolTip, () -> selectTool(tool), imageSurface.hasTool(tool))); } public List makeToolSelectors() { return ll(instaToolTip(() -> "Draw on image with left mouse button" + stringIf(!drawingAllowed, " (click lock icon to start)"), toolSelectButton(scribbler, "#1103080", null)), toolSelectButton(dragger, "#1103079", "Scroll image with left mouse button"), toolSelectButton(selector, "#1103081", "Select rectangular area with left mouse button")); } } static public class Stringifier_ToString implements IStringifier { public String toString(Object o) { return str(o); } } static public class JavaXClassLoaderWithParent2 extends JavaXClassLoader { public ClassLoader virtualParent; public List classesToSkip; public JavaXClassLoaderWithParent2(String progID, List files, ClassLoader virtualParent, List classesToSkip) { super(progID, files); this.virtualParent = virtualParent; this.classesToSkip = classesToSkip; } public Class findClass(String name) throws ClassNotFoundException { if (shouldDelegate(name)) { Class c = virtualParent.loadClass(name); if (c != null) return c; } return super.findClass(name); } public boolean shouldDelegate(String name) { for (String s : classesToSkip) if (eq(name, s) || startsWith(name, s + "$")) return true; return false; } } static public class AWTOnConceptChangesByClass implements AutoCloseable { final public AWTOnConceptChangesByClass setComponent(JComponent component) { return component(component); } public AWTOnConceptChangesByClass component(JComponent component) { this.component = component; return this; } final public JComponent getComponent() { return component(); } public JComponent component() { return component; } public JComponent component; final public AWTOnConceptChangesByClass setAction(Runnable action) { return action(action); } public AWTOnConceptChangesByClass action(Runnable action) { this.action = action; return this; } final public Runnable getAction() { return action(); } public Runnable action() { return action; } public Runnable action; final public AWTOnConceptChangesByClass setConcepts(Concepts concepts) { return concepts(concepts); } public AWTOnConceptChangesByClass concepts(Concepts concepts) { this.concepts = concepts; return this; } final public Concepts getConcepts() { return concepts(); } public Concepts concepts() { return concepts; } public Concepts concepts; final public AWTOnConceptChangesByClass setConceptClass(Class conceptClass) { return conceptClass(conceptClass); } public AWTOnConceptChangesByClass conceptClass(Class conceptClass) { this.conceptClass = conceptClass; return this; } final public Class getConceptClass() { return conceptClass(); } public Class conceptClass() { return conceptClass; } public Class conceptClass; final public AWTOnConceptChangesByClass setFirstDelay(int firstDelay) { return firstDelay(firstDelay); } public AWTOnConceptChangesByClass firstDelay(int firstDelay) { this.firstDelay = firstDelay; return this; } final public int getFirstDelay() { return firstDelay(); } public int firstDelay() { return firstDelay; } public int firstDelay; final public AWTOnConceptChangesByClass setDelay(int delay) { return delay(delay); } public AWTOnConceptChangesByClass delay(int delay) { this.delay = delay; return this; } final public int getDelay() { return delay(); } public int delay() { return delay; } public int delay = 500; volatile public long changes = -1, changeCounter; public javax.swing.Timer timer; public AutoCloseable closer; public AWTOnConceptChangesByClass(Concepts concepts, Class conceptClass, JComponent component, Runnable action) { this.action = action; this.component = component; this.conceptClass = conceptClass; this.concepts = concepts; } public void install() { assertNotNull(concepts); assertNotNull(conceptClass); assertNotNull(component); bindToComponent(component, () -> closer = onConceptChangeByClass_notOnAllChanged(concepts, conceptClass, () -> ++changeCounter), () -> { { cleanUp(closer); closer = null; } }); timer = installTimer(component, delay, firstDelay, new Runnable() { public void run() { try { _trigger(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_trigger();"; } }); } public void _trigger() { long c = changeCounter; if (changes != c) { changes = c; { if (action != null) action.run(); } } } public void close() { try { { cleanUp(timer); timer = null; } { cleanUp(closer); closer = null; } } catch (Exception __e) { throw rethrow(__e); } } } static public class PtBuffer extends RandomAccessAbstractList { public LongBuffer buf = new LongBuffer(); public PtBuffer() { } public PtBuffer(int size) { buf.allocate(size); } public PtBuffer(Iterable l) { if (l != null) for (Pt p : l) add(p); } public int size() { return buf.size(); } public Pt get(int i) { return longToPt(buf.get(i)); } public long getLong(int i) { return buf.get(i); } public Pt set(int i, Pt val) { Pt old = get(i); buf.set(i, ptToLong(val)); return old; } public boolean add(Pt p) { buf.add(ptToLong(p)); return true; } public void add(int x, int y) { buf.add(ptToLong(x, y)); } public Pt remove(int i) { Pt p = get(i); buf.remove(i); return p; } public void clear() { buf.clear(); } } static public class SynchronizedDoubleBuffer implements IDoubleBuffer { public double[] data; public int size; public SynchronizedDoubleBuffer() { } public SynchronizedDoubleBuffer(int size) { if (size != 0) data = new double[size]; } public SynchronizedDoubleBuffer(Iterable l) { addAll(l); } public SynchronizedDoubleBuffer(Collection l) { this(l(l)); addAll(l); } public SynchronizedDoubleBuffer(double... data) { this.data = data; size = l(data); } public synchronized void add(double i) { if (size >= lDoubleArray(data)) { data = resizeDoubleArray(data, Math.max(1, toInt(Math.min(maximumSafeArraySize(), lDoubleArray(data) * 2L)))); if (size >= data.length) throw fail("DoubleBuffer too large: " + size); } data[size++] = i; } public synchronized void addAll(Iterable l) { if (l != null) for (double i : l) add(i); } public synchronized double[] toArray() { return size == 0 ? null : resizeDoubleArray(data, size); } public double[] toArrayNonNull() { return unnull(toArray()); } synchronized public List toList() { return doubleArrayToList(data, 0, size); } synchronized public List asVirtualList() { return new RandomAccessAbstractList() { public int size() { return SynchronizedDoubleBuffer.this.size(); } public Double get(int i) { return SynchronizedDoubleBuffer.this.get(i); } public Double set(int i, Double val) { synchronized (SynchronizedDoubleBuffer.this) { Double a = get(i); data[i] = val; return a; } } }; } synchronized public void reset() { size = 0; } public void clear() { reset(); } public synchronized int size() { return size; } public synchronized boolean isEmpty() { return size == 0; } public synchronized double get(int idx) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); return data[idx]; } synchronized public void set(int idx, double value) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); data[idx] = value; } public synchronized double popLast() { if (size == 0) throw fail("empty buffer"); return data[--size]; } public synchronized double first() { return data[0]; } public synchronized double last() { return data[size - 1]; } synchronized public double nextToLast() { return data[size - 2]; } public String toString() { return squareBracket(joinWithSpace(toList())); } public Iterator iterator() { return new IterableIterator() { public int i = 0; public boolean hasNext() { return i < size(); } public Double next() { synchronized (SynchronizedDoubleBuffer.this) { return data[i++]; } } }; } public synchronized void trimToSize() { data = resizeDoubleArray(data, size); } public synchronized int indexOf(double b) { for (int i = 0; i < size; i++) if (data[i] == b) return i; return -1; } synchronized public double[] subArray(int start, int end) { return subDoubleArray(data, start, min(end, size)); } public synchronized void insertAt(int idx, double[] l) { int n = l(l); if (n == 0) return; double[] newData = new double[size + n]; arraycopy(data, 0, newData, 0, idx); arraycopy(l, 0, newData, idx, n); arraycopy(data, idx, newData, idx + n, size - idx); data = newData; size = newData.length; } public void integrityCheck() { assertTrue("Size positive", size >= 0); assertTrue("Data length", l(data) >= size); } } static public class Frequency implements Comparable, IFieldsToList { public double frequency; public Frequency() { } public boolean equals(Object o) { if (!(o instanceof Frequency)) return false; Frequency __1 = (Frequency) o; return frequency == __1.frequency; } public int hashCode() { int h = 1933944124; h = boostHashCombine(h, _hashCode(frequency)); return h; } public Object[] _fieldsToList() { return new Object[] { frequency }; } final public double getInterval() { return interval(); } public double interval() { return interval; } public double interval; final public double get() { return frequency(); } public double frequency() { return frequency; } public Frequency(double frequency) { this.frequency = frequency; interval = doubleRatio(1, frequency); } public String toString() { return format3(); } public String format3() { return format(3); } public String format1() { return format(1); } public String format(int digits) { return str(new Rendering(digits)); } public class Rendering implements IFieldsToList { public int digits; public Rendering() { } public Rendering(int digits) { this.digits = digits; } public Object[] _fieldsToList() { return new Object[] { digits }; } public double value = frequency; public String unit = "Hz"; transient public IF0 formatValue; public String formatValue() { return formatValue != null ? formatValue.get() : formatValue_base(); } final public String formatValue_fallback(IF0 _f) { return _f != null ? _f.get() : formatValue_base(); } public String formatValue_base() { return formatDouble(value, digits); } public void run() { try { while (abs(value) >= 1000) { value /= 1000; unit = "k" + unit; } unit = replacePrefixes(unit, "kkkk", "T", "kkk", "G", "kk", "M"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { run(); return spaceCombine(formatValue(), unit); } } public int compareTo(Frequency f) { return cmp(frequency, f.frequency); } } public interface CompressionRegime_AnyType { public byte[] decompressorToBytes(A decompressor); public A decompressorFromBytes(byte[] compressed); public Object runDecompressor(A a); public CompressionRegime_AnyType fullRegime(); } static public class RGBImage implements MakesBufferedImage, IRGBImage { transient public BufferedImage bufferedImage; public int width, height; public int[] pixels; public RGBImage() { } public RGBImage(BufferedImage image) { bufferedImage = image; width = image.getWidth(); height = image.getHeight(); pixels = new int[width * height]; var gp = grabbableIntPixels_fastOrSlow(image); if (gp.scanlineStride == width && gp.offset == 0) pixels = gp.data; else { pixels = new int[width * height]; int iIn = 0, iOut = 0; for (int y = 0; y < height; y++) { arrayCopy(gp.data, iIn, pixels, iOut, width); iIn += gp.scanlineStride; iOut += width; } } cleanPixels(); } public RGBImage(Dimension size, Color color) { this(size.width, size.height, color); } public RGBImage(Dimension size, RGB color) { this(size.width, size.height, color); } private void cleanPixels() { var pixels = this.pixels; for (int i = 0; i < pixels.length; i++) pixels[i] &= 0xFFFFFF; } public RGBImage(int width, int height, int[] pixels) { this.width = width; this.height = height; this.pixels = pixels; } public RGBImage(int w, int h, RGB[] pixels) { this.width = w; this.height = h; this.pixels = asInts(pixels); } public static int[] asInts(RGB[] pixels) { int[] ints = new int[pixels.length]; for (int i = 0; i < pixels.length; i++) ints[i] = pixels[i] == null ? 0 : pixels[i].getColor().getRGB(); return ints; } public RGBImage(int w, int h) { this(w, h, Color.black); } public RGBImage(int w, int h, RGB rgb) { this.width = w; this.height = h; this.pixels = new int[w * h]; int col = rgb.asInt(); if (col != 0) for (int i = 0; i < pixels.length; i++) pixels[i] = col; } public RGBImage(RGBImage image) { this(image.width, image.height, copyPixels(image.pixels)); } public RGBImage(int width, int height, Color color) { this(width, height, new RGB(color)); } public RGBImage(MakesBufferedImage img) { this(toBufferedImage(img)); } private static int[] copyPixels(int[] pixels) { int[] copy = new int[pixels.length]; System.arraycopy(pixels, 0, copy, 0, pixels.length); return copy; } public int getIntPixel(int x, int y) { if (inRange(x, y)) return pixels[y * width + x]; else return 0xFFFFFF; } public int getIntPixel_noRangeCheck(int idx) { return pixels[idx]; } public static RGB asRGB(int packed) { int r = (packed >> 16) & 0xFF; int g = (packed >> 8) & 0xFF; int b = packed & 0xFF; return new RGB(r / 255f, g / 255f, b / 255f); } public RGB getRGB(int x, int y) { if (inRange(x, y)) return asRGB(pixels[y * width + x]); else return new RGB(0xFFFFFF); } public RGB getPixel(int x, int y) { return getRGB(x, y); } public RGB getPixel(Pt p) { return getPixel(p.x, p.y); } public int getWidth() { return width; } public int getHeight() { return height; } public int w() { return width; } public int h() { return height; } public BufferedImage getBufferedImage() { if (bufferedImage == null) { bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) bufferedImage.setRGB(x, y, pixels[y * width + x]); } return bufferedImage; } public RGBImage clip(Rect r) { return r == null ? null : clip(r.getRectangle()); } public RGBImage clip(Rectangle r) { r = fixClipRect(r); if (r.x == 0 && r.y == 0 && r.width == width && r.height == height) return this; int[] newPixels; try { newPixels = new int[r.width * r.height]; } catch (RuntimeException e) { System.out.println(r); throw e; } for (int y = 0; y < r.height; y++) { System.arraycopy(pixels, (y + r.y) * width + r.x, newPixels, y * r.width, r.width); } return new RGBImage(r.width, r.height, newPixels); } private Rectangle fixClipRect(Rectangle r) { r = r.intersection(new Rectangle(0, 0, width, height)); if (r.isEmpty()) r = new Rectangle(r.x, r.y, 0, 0); return r; } public int getInt(int x, int y) { return pixels[y * width + x]; } public void save(File file) { saveImage(file, getBufferedImage()); } public static RGBImage dummyImage() { return new RGBImage(1, 1, new int[] { 0xFFFFFF }); } public int[] getPixels() { return pixels; } public void setPixel(int x, int y, int r, int g, int b) { if (x >= 0 && y >= 0 && x < width && y < height) pixels[y * width + x] = (limitToUByte(r) << 16) | (limitToUByte(g) << 8) | limitToUByte(b); } public void setPixel(int x, int y, RGB rgb) { if (x >= 0 && y >= 0 && x < width && y < height) pixels[y * width + x] = rgb.asInt(); } final public void set(int x, int y, Color color) { setPixel(x, y, color); } public void setPixel(int x, int y, Color color) { setPixel(x, y, new RGB(color)); } public void setInt(int x, int y, int rgb) { setPixel(x, y, rgb); } public void setPixel(int x, int y, int rgb) { if (x >= 0 && y >= 0 && x < width && y < height) pixels[y * width + x] = rgb; } public void setPixel(Pt p, RGB rgb) { setPixel(p.x, p.y, rgb); } public void setPixel(Pt p, Color color) { setPixel(p.x, p.y, color); } public RGBImage copy() { return new RGBImage(this); } public boolean inRange(int x, int y) { return x >= 0 && y >= 0 && x < width && y < height; } public Dimension getSize() { return new Dimension(width, height); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RGBImage rgbImage = (RGBImage) o; if (height != rgbImage.height) return false; if (width != rgbImage.width) return false; if (!Arrays.equals(pixels, rgbImage.pixels)) return false; return true; } @Override public int hashCode() { int result = width; result = 31 * result + height; result = 31 * result + Arrays.hashCode(pixels); return result; } public String getHex(int x, int y) { return getPixel(x, y).getHexString(); } public RGBImage clip(int x, int y, int width, int height) { return clip(new Rectangle(x, y, width, height)); } public RGBImage clipLine(int y) { return clip(0, y, width, 1); } public int numPixels() { return width * height; } public RGBImage uncacheBufferedImage() { bufferedImage = null; return this; } } static public class FileWatchService implements AutoCloseable { final public FileWatchService setInterval(int interval) { return interval(interval); } public FileWatchService interval(int interval) { this.interval = interval; return this; } final public int getInterval() { return interval(); } public int interval() { return interval; } public int interval = 50; public int sleepSeconds = 60; public WatchService watchService; public MultiMap> listeners = new MultiMap(); public Thread pollThread; volatile public boolean closed = false; public FileWatchService() { try { watchService = FileSystems.getDefault().newWatchService(); } catch (Exception __e) { throw rethrow(__e); } } public void close() { closed = true; { cleanUp(watchService); watchService = null; } } public WatchKey addListenerImpl(File path, IVF1 listener, WatchEvent.Kind... eventKinds) { try { if (path == null) return null; startPollThread(); WatchKey key = path.toPath().register(watchService, eventKinds); listeners.put(key, listener); return key; } catch (Exception __e) { throw rethrow(__e); } } public void addNonRecursiveListener(File path, IVF1 listener) { addListenerImpl(path, listener, jdk_watchService_allEventKinds()); } public void addRecursiveListener(File path, IVF1 listener) { Set listeningTo = synchroSet(); IVF1 listener2 = new IVF1() { public void get(File f) { boolean isDir = f.isDirectory(); if (isDir && listeningTo.add(f)) try { addListenerImpl(f, this, jdk_watchService_allEventKinds()); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } callF(listener, f); } }; addListenerImpl(path, listener2, jdk_watchService_allEventKinds()); for (File subDir : findAllDirs(path)) addListenerImpl(subDir, listener2, jdk_watchService_allEventKinds()); } synchronized public void startPollThread() { if (pollThread != null) return; pollThread = startThread("File Watch Service", new Runnable() { public void run() { try { try { while (licensed() && !closed) { WatchKey key = watchService.poll(sleepSeconds, TimeUnit.SECONDS); if (key != null) { Path dir = (Path) (key.watchable()); sleep(interval); List> events = key.pollEvents(); LinkedHashSet changedFiles = new LinkedHashSet(); for (WatchEvent event : reversedIterator(events)) { try { final Path changed = (Path) event.context(); if (changed == null) continue; File full = newFile(dir.toFile(), changed.toFile().getPath()); changedFiles.add(full); } catch (Throwable __e) { pcallFail(__e); } } for (File f : changedFiles) pcallFAll(listeners.get(key), f); key.reset(); } } } catch (ClosedWatchServiceException e) { } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n while (licensed() && !closed) { \r\n WatchKey key = wat..."; } }); } } static public class ComponentResizeDragger extends MouseAdapter { public Component component; public int cornerSize = 10; final public ComponentResizeDragger setDebug(boolean debug) { return debug(debug); } public ComponentResizeDragger debug(boolean debug) { this.debug = debug; return this; } final public boolean getDebug() { return debug(); } public boolean debug() { return debug; } public boolean debug = false; public MouseEvent mouseDownEvent; public JComponent src; public Rect originalPosition, srcBounds; public int dragX, dragY; public Cursor originalCursor, ourCursor; public ComponentResizeDragger(Component component, JComponent src) { this.src = src; this.component = component; addMouseAndMotionListener(src, this); } public boolean engaged() { return mouseDownEvent != null; } public void start(MouseEvent e) { this.mouseDownEvent = e; originalPosition = toRect(getBounds(component)); cursorCalc(e, true); } public void cursorCalc(MouseEvent e, boolean inside) { srcBounds = toRect(boundsOnScreen(src)); Pt mouse = pt(e.getXOnScreen(), e.getYOnScreen()); if (distance(mouse.y, srcBounds.y2()) <= cornerSize) dragY = 1; else if (distance(mouse.y, srcBounds.y1()) <= cornerSize) dragY = -1; else dragY = 0; if (distance(mouse.x, srcBounds.x2()) <= cornerSize) dragX = 1; else if (distance(mouse.x, srcBounds.x1()) <= cornerSize) dragX = -1; else dragX = 0; originalCursor = src.getCursor(); int iCursor = dragY * 3 + dragX + 4; int cursor = new int[] { Cursor.NW_RESIZE_CURSOR, Cursor.N_RESIZE_CURSOR, Cursor.NE_RESIZE_CURSOR, Cursor.W_RESIZE_CURSOR, -1, Cursor.E_RESIZE_CURSOR, Cursor.SW_RESIZE_CURSOR, Cursor.S_RESIZE_CURSOR, Cursor.SE_RESIZE_CURSOR }[iCursor]; Cursor newCursor = cursor >= 0 && inside ? Cursor.getPredefinedCursor(cursor) : null; if (newCursor != ourCursor) { ourCursor = newCursor; src.setCursor(newCursor); } } @Override public void mouseEntered(MouseEvent e) { if (debug) print("mouseEntered"); if (!engaged()) cursorCalc(e, true); } @Override public void mouseExited(MouseEvent e) { if (debug) print("mouseExited"); if (!engaged()) cursorCalc(e, false); } public void mousePressed(MouseEvent e) { if (e.getButton() != MouseEvent.BUTTON1) return; if (engaged()) return; if (!mouseEventIsInBorder(e)) return; start(e); } public void mouseDragged(MouseEvent e) { if (!engaged()) return; updatePosition(e); } public void mouseMoved(MouseEvent e) { cursorCalc(e, true); } public void mouseReleased(MouseEvent e) { if (mouseDownEvent == null) return; if (e.getButton() != mouseDownEvent.getButton()) return; updatePosition(e); if (debug) print("drag done"); if (src.getCursor() == ourCursor) src.setCursor(originalCursor); mouseDownEvent = null; dragDone(); } public void updatePosition(MouseEvent e) { Rect w = toRect(component.getBounds()); Pt a = topLeftCorner(w), b = bottomRightCorner(w); Pt mouse = pt(e.getXOnScreen(), e.getYOnScreen()); Pt minSize = toPt(component.getMinimumSize()); if (dragX < 0) a.x = max(0, min(b.x - minSize.x, mouse.x + originalPosition.x - mouseDownEvent.getXOnScreen())); else if (dragX > 0) b.x = max(a.x + minSize.x, mouse.x + originalPosition.x2() - mouseDownEvent.getXOnScreen()); if (dragY < 0) a.y = max(0, min(b.y - minSize.y, mouse.y + originalPosition.y - mouseDownEvent.getYOnScreen())); else if (dragY > 0) b.y = max(a.y + minSize.y, mouse.y + originalPosition.y2() - mouseDownEvent.getYOnScreen()); Rect r = rectFromPoints(a, b); if (debug) printVars("ComponentResizeDragger.updatePosition", "w", w, "mouse", mouse, "a", a, "b", b, "dragX", dragX, "dragY", dragY); component.setBounds(toRectangle(r)); } public void dragDone() { } } static public class RegionBorder_innerPoints_v2 extends AbstractBorderTracer implements IFieldsToList { public IImageRegion region; public RegionBorder_innerPoints_v2() { } public RegionBorder_innerPoints_v2(IImageRegion region) { this.region = region; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + region + ")"; } public Object[] _fieldsToList() { return new Object[] { region }; } public Rect bounds; public int x, y, dir; public Iterator it; public byte[] reachedInDirections; public boolean tracing = false; public int nTrace; static public Pt[] directions = { pt(1, 0), pt(0, 1), pt(-1, 0), pt(0, -1) }; public void init() { bounds = region.bounds(); reachedInDirections = new byte[area(bounds)]; it = region.pixelIterator(); } public boolean step() { if (reachedInDirections == null) init(); if (tracing) return walkOnePixel(); else return findFirstPixel(); } public boolean walkOnePixel() { int posInBounds = (y - bounds.y) * bounds.w + x - bounds.x; if ((reachedInDirections[posInBounds] & (1 << dir)) != 0) { traceDone(); tracing = false; return includeHoles; } reachedInDirections[posInBounds] |= (byte) 1 << dir; foundPoint(x, y); for (int turn = 3; turn <= 6; turn++) { int newDir = (dir + turn) & 3; Pt d = directions[newDir]; int x2 = x + d.x, y2 = y + d.y; boolean b = region.contains(x2, y2); if (b) { x = x2; y = y2; dir = newDir; return true; } } return true; } public boolean findFirstPixel() { if (!it.hasNext()) return false; Pt p = it.next(); x = p.x; y = p.y; int posInBounds = (y - bounds.y) * bounds.w + x - bounds.x; if (reachedInDirections[posInBounds] != 0) return true; if (!region.contains(x, y - 1)) { startTrace(0); return true; } if (!region.contains(x - 1, y)) { startTrace(3); return true; } if (!region.contains(x + 1, y)) { startTrace(1); return true; } if (!region.contains(x, y + 1)) { startTrace(2); return true; } return true; } public void startTrace(int dir) { this.dir = dir; int posInBounds = (y - bounds.y) * bounds.w + x - bounds.x; reachedInDirections[posInBounds] = (byte) (15 & ~(1 << dir)); tracing = true; newTrace(++nTrace > 1); } public void foundPoint(int x, int y) { foundPoint(pt(x, y)); } public List allPoints_cache; public List allPoints() { if (allPoints_cache == null) allPoints_cache = allPoints_load(); return allPoints_cache; } public List allPoints_load() { PtBuffer l = new PtBuffer(); onFoundPoint(p -> l.add(p)); run(); return l; } public OnePath onePath_cache; public OnePath onePath() { if (onePath_cache == null) onePath_cache = onePath_load(); return onePath_cache; } public OnePath onePath_load() { includeHoles(false); return new OnePath(allPoints(), true); } public OnePathWithOrigin onePathWithOrigin_cache; public OnePathWithOrigin onePathWithOrigin() { if (onePathWithOrigin_cache == null) onePathWithOrigin_cache = onePathWithOrigin_load(); return onePathWithOrigin_cache; } public OnePathWithOrigin onePathWithOrigin_load() { includeHoles(false); return new OnePathWithOrigin(allPoints(), true); } public void runAndPrint() { onNewTrace(hole -> print(!hole ? "new outline" : "new hole")); onTraceDone(() -> print("traceDone")); onFoundPoint(p -> print("foundPoint " + p)); stepMaxWithStats(this, 10000); } public boolean tracingHole() { return nTrace > 1; } } static public class ImageSurfaceScribbleTool extends ImageSurfaceMouseHandler { final public ImageSurfaceScribbleTool setStroke(BasicStroke stroke) { return stroke(stroke); } public ImageSurfaceScribbleTool stroke(BasicStroke stroke) { this.stroke = stroke; return this; } final public BasicStroke getStroke() { return stroke(); } public BasicStroke stroke() { return stroke; } public BasicStroke stroke = new BasicStroke(5); final public ImageSurfaceScribbleTool setColor(Color color) { return color(color); } public ImageSurfaceScribbleTool color(Color color) { this.color = color; return this; } final public Color getColor() { return color(); } public Color color() { return color; } public Color color = Color.black; final public ImageSurfaceScribbleTool setEnabled(boolean enabled) { return enabled(enabled); } public ImageSurfaceScribbleTool enabled(boolean enabled) { this.enabled = enabled; return this; } final public boolean getEnabled() { return enabled(); } public boolean enabled() { return enabled; } public boolean enabled = false; public Pt lastPt; transient public Set onPainted; public ImageSurfaceScribbleTool onPainted(Runnable r) { onPainted = createOrAddToSyncLinkedHashSet(onPainted, r); return this; } public ImageSurfaceScribbleTool removePaintedListener(Runnable r) { utils.remove(onPainted, r); return this; } public void painted() { if (onPainted != null) for (var listener : onPainted) pcallF_typed(listener); } transient public Set> onScribbleDone; public ImageSurfaceScribbleTool onScribbleDone(IVF1 f) { onScribbleDone = createOrAddToSyncLinkedHashSet(onScribbleDone, f); return this; } public ImageSurfaceScribbleTool removeScribbleDoneListener(IVF1 f) { utils.remove(onScribbleDone, f); return this; } public void scribbleDone(Scribble scribble) { if (onScribbleDone != null) for (var listener : onScribbleDone) pcallF_typed(listener, scribble); } public Scribble scribble; public ImageSurfaceScribbleTool() { } public ImageSurfaceScribbleTool(ImageSurface is) { this.register(is); } public void mousePressed(MouseEvent evt) { if (evt.getButton() != MouseEvent.BUTTON1) return; if (!enabled) return; lastPt = getPt(evt); scribble = new Scribble(color, stroke.getLineWidth(), new ArrayList()); drawPoint(lastPt); } public void mouseReleased(MouseEvent e) { mouseDragged(e); lastPt = null; scribbleDone(scribble); scribble = null; } public void mouseDragged(MouseEvent e) { if (lastPt == null) return; Pt p = getPt(e); if (!eq(p, lastPt)) drawLine(lastPt, p); lastPt = p; is.repaint(); } public void drawPoint(Pt p) { drawLine(p, p); } public void drawLine(Pt a, Pt b) { { if (scribble != null) scribble.addPoint(b); } Graphics2D g = getImageSurface().getImage().createGraphics(); g.setStroke(stroke); g.setColor(color); g.drawLine(a.x, a.y, b.x, b.y); g.dispose(); painted(); } } static public class SimpleCRUD_v2 extends JConceptsTable { public JPanel buttons, panel; public Set unshownFields; public Set excludeFieldsFromEditing; public String modifiedField; public TableSearcher tableSearcher; public Set multiLineFields; public Set dontDuplicateFields; public int formFixer = 12; public boolean showBackRefs = false; public int maxRefsToShow = 3; public boolean showClassNameSelectors = false; public boolean allowNewFields = false; public int newFieldsToShow = 3; public boolean emptyStringsToNull = false; public int formLabelsWidth = 100; final public SimpleCRUD_v2 setShowSearchBar(boolean showSearchBar) { return showSearchBar(showSearchBar); } public SimpleCRUD_v2 showSearchBar(boolean showSearchBar) { this.showSearchBar = showSearchBar; return this; } final public boolean getShowSearchBar() { return showSearchBar(); } public boolean showSearchBar() { return showSearchBar; } public boolean showSearchBar = true; final public SimpleCRUD_v2 setShowAddButton(boolean showAddButton) { return showAddButton(showAddButton); } public SimpleCRUD_v2 showAddButton(boolean showAddButton) { this.showAddButton = showAddButton; return this; } final public boolean getShowAddButton() { return showAddButton(); } public boolean showAddButton() { return showAddButton; } public boolean showAddButton = true; final public SimpleCRUD_v2 setShowEditButton(boolean showEditButton) { return showEditButton(showEditButton); } public SimpleCRUD_v2 showEditButton(boolean showEditButton) { this.showEditButton = showEditButton; return this; } final public boolean getShowEditButton() { return showEditButton(); } public boolean showEditButton() { return showEditButton; } public boolean showEditButton = true; final public SimpleCRUD_v2 setShowDeleteButton(boolean showDeleteButton) { return showDeleteButton(showDeleteButton); } public SimpleCRUD_v2 showDeleteButton(boolean showDeleteButton) { this.showDeleteButton = showDeleteButton; return this; } final public boolean getShowDeleteButton() { return showDeleteButton(); } public boolean showDeleteButton() { return showDeleteButton; } public boolean showDeleteButton = true; final public SimpleCRUD_v2 setShowDuplicateButton(boolean showDuplicateButton) { return showDuplicateButton(showDuplicateButton); } public SimpleCRUD_v2 showDuplicateButton(boolean showDuplicateButton) { this.showDuplicateButton = showDuplicateButton; return this; } final public boolean getShowDuplicateButton() { return showDuplicateButton(); } public boolean showDuplicateButton() { return showDuplicateButton; } public boolean showDuplicateButton = true; final public SimpleCRUD_v2 setIconButtons(boolean iconButtons) { return iconButtons(iconButtons); } public SimpleCRUD_v2 iconButtons(boolean iconButtons) { this.iconButtons = iconButtons; return this; } final public boolean getIconButtons() { return iconButtons(); } public boolean iconButtons() { return iconButtons; } public boolean iconButtons = false; final public SimpleCRUD_v2 setEditWindowScrollable(boolean editWindowScrollable) { return editWindowScrollable(editWindowScrollable); } public SimpleCRUD_v2 editWindowScrollable(boolean editWindowScrollable) { this.editWindowScrollable = editWindowScrollable; return this; } final public boolean getEditWindowScrollable() { return editWindowScrollable(); } public boolean editWindowScrollable() { return editWindowScrollable; } public boolean editWindowScrollable = false; final public SimpleCRUD_v2 setScrollableButtons(boolean scrollableButtons) { return scrollableButtons(scrollableButtons); } public SimpleCRUD_v2 scrollableButtons(boolean scrollableButtons) { this.scrollableButtons = scrollableButtons; return this; } final public boolean getScrollableButtons() { return scrollableButtons(); } public boolean scrollableButtons() { return scrollableButtons; } public boolean scrollableButtons = false; public SingleComponentPanel scpButtonFiller; public JComponent wrappedButtonBar; transient public Set> onConceptSaved; public SimpleCRUD_v2 onConceptSaved(IVF1 f) { onConceptSaved = createOrAddToSyncLinkedHashSet(onConceptSaved, f); return this; } public SimpleCRUD_v2 removeConceptSavedListener(IVF1 f) { utils.remove(onConceptSaved, f); return this; } public void conceptSaved(A concept) { if (onConceptSaved != null) for (var listener : onConceptSaved) pcallF_typed(listener, concept); } public SimpleCRUD_v2(Class conceptClass) { super(conceptClass); } public SimpleCRUD_v2(Concepts concepts, Class conceptClass) { super(concepts, conceptClass); } public SimpleCRUD_v2 show(String frameTitle) { make(); showFrame(frameTitle, panel); return this; } public SimpleCRUD_v2 show() { return show(entityNamePlural()); } public SimpleCRUD_v2 showMaximized() { show(); maximizeFrame(panel); return this; } public JPanel makePanel() { return make(); } public JPanel make() { db(); framesBot(); return make_dontStartBots(); } transient public IF1> itemToMap_inner; public Map itemToMap_inner(A a) { return itemToMap_inner != null ? itemToMap_inner.get(a) : itemToMap_inner_base(a); } final public Map itemToMap_inner_fallback(IF1> _f, A a) { return _f != null ? _f.get(a) : itemToMap_inner_base(a); } public Map itemToMap_inner_base(A a) { return super.itemToMap_base(a); } public Map itemToMap_base(A a) { Map map = itemToMap_inner(a); if (map == null) return null; return putAll(map, moreSpecialFieldsForItem(a)); } transient public IF1> moreSpecialFieldsForItem; public Map moreSpecialFieldsForItem(A a) { return moreSpecialFieldsForItem != null ? moreSpecialFieldsForItem.get(a) : moreSpecialFieldsForItem_base(a); } final public Map moreSpecialFieldsForItem_fallback(IF1> _f, A a) { return _f != null ? _f.get(a) : moreSpecialFieldsForItem_base(a); } public Map moreSpecialFieldsForItem_base(A a) { Map map = litorderedmap(); if (showBackRefs) { Collection refs = allBackRefs(a); if (nempty(refs)) { refs = sortedByConceptID(refs); int more = l(refs) - maxRefsToShow; map.put("Referenced by", joinWithComma(takeFirst(maxRefsToShow, refs)) + (more > 0 ? ", " + more + " more" : "")); } } return map; } public JPanel make_dontStartBots() { return (JPanel) visualize(); } public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { dropFields = asList(unshownFields); makeTable(); { swing(() -> { JButton deleteButton = !showDeleteButton ? null : tableDependButton(table, makeDeleteButton(new Runnable() { public void run() { try { List l = selectedConcepts(); withDBLock(concepts, new Runnable() { public void run() { try { for (A c : l) c.delete(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "for (A c : l) c.delete()"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "List l = selectedConcepts();\r\n withDBLock(concepts, r { for (A c ..."; } })); buttons = jRightAlignedLine(flattenToList(!showAddButton ? null : makeAddButton(new Runnable() { public void run() { try { newConcept(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "newConcept();"; } }), !showEditButton || !showDuplicateButton ? null : tableDependButton(table, makeDuplicateButton(new Runnable() { public void run() { try { duplicateConcept(selectedConcept()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "duplicateConcept(selectedConcept())"; } })), !showEditButton ? null : tableDependButton(table, makeEditButton(new Runnable() { public void run() { try { editConcept(selectedConcept()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "editConcept(selectedConcept())"; } })), deleteButton)); wrappedButtonBar = wrapButtonBar(centerAndEastWithMargin(scpButtonFiller = singleComponentPanel(), buttons)); if (showSearchBar) { tableSearcher = tableWithSearcher2(table, "withMargin", true); panel = centerAndSouthWithMargin(tableSearcher.panel, wrappedButtonBar); } else panel = centerAndSouthWithMargin(table, wrappedButtonBar); var fEdit = new VF1() { public void get(Integer row) { try { editConcept(getItem(row)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "editConcept(getItem(row))"; } }; tablePopupMenuItem(table, "Edit", fEdit); onDoubleClick(table, fEdit); tablePopupMenuFirst(table, (menu, row) -> { Concept c = getItem(row); if (c != null) addMenuItem(menu, "Delete " + quote(shorten(str(c))), runnableThread(new Runnable() { public void run() { try { deleteConcept(c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "deleteConcept(c);"; } })); }); }); } return panel; } transient public IF1 wrapButtonBar; public JComponent wrapButtonBar(JComponent buttonBar) { return wrapButtonBar != null ? wrapButtonBar.get(buttonBar) : wrapButtonBar_base(buttonBar); } final public JComponent wrapButtonBar_fallback(IF1 _f, JComponent buttonBar) { return _f != null ? _f.get(buttonBar) : wrapButtonBar_base(buttonBar); } public JComponent wrapButtonBar_base(JComponent buttonBar) { if (scrollableButtons) return jBorderlessHigherHorizontalScrollPane(vstack(buttonBar)); return buttonBar; } transient public Runnable newConcept; public void newConcept() { if (newConcept != null) newConcept.run(); else newConcept_base(); } final public void newConcept_fallback(Runnable _f) { if (_f != null) _f.run(); else newConcept_base(); } public void newConcept_base() { duplicateConcept(null); } transient public IF1 createDuplicate; public A createDuplicate(A c) { return createDuplicate != null ? createDuplicate.get(c) : createDuplicate_base(c); } final public A createDuplicate_fallback(IF1 _f, A c) { return _f != null ? _f.get(c) : createDuplicate_base(c); } public A createDuplicate_base(A c) { A clone = (A) unlisted(_getClass(c)); ccopyFieldsExcept(c, clone, dontDuplicateFields); return clone; } public void duplicateConcept(A oldConcept) { EditWindow ew = new EditWindow(); if (oldConcept == null) ew.item = unlisted(conceptClass); else ew.item = createDuplicate(oldConcept); csetAll(ew.item, filters); makeComponents(ew); F0 r = new F0() { public Boolean get() { try { try { selectAfterUpdate(ew.item); concepts.register(ew.item); saveData(ew); } catch (Throwable e) { printStackTrace(e); infoBox(e); return false; } return true; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n selectAfterUpdate(ew.item);\r\n concepts.register(ew.item..."; } }; AutoCloseable __2 = tempSetMCOpt("formLayouter1_fixer2", formFixer); try { String title = "New " + entityName(); title += appendBracketed(javaClassDescForItem(ew.item)); renameSubmitButton("Create", showAForm(title, toObjectArray(listPlus(ew.matrix, r)))); } finally { _close(__2); } } public void editConcept(A c) { if (c == null) return; EditWindow ew = new EditWindow(); ew.item = c; makeComponents(ew); F0 r = new F0() { public Boolean get() { try { try { if (ew.item != c) { print("Replacing object: " + c + " => " + ew.item); replaceConceptAndUpdateRefs(c, ew.item); } saveData(ew); } catch (Throwable e) { printStackTrace(e); infoBox(e); return false; } return true; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n // concept class was changed, replace object\r\n if (ew.i..."; } }; AutoCloseable __3 = tempSetMCOpt("formLayouter1_fixer2", formFixer); try { renameSubmitButton("Save", showAForm("Edit " + entityName() + " #" + c.id, toObjectArray(listPlus(ew.matrix, r)))); } finally { _close(__3); } } public JComponent fieldComponent(A c, String field) { Class type = getFieldType(c.getClass(), field); Type genericType = genericFieldType(conceptClass, field); if (type == Concept.Ref.class) type = getTypeArgumentAsClass(genericType); Object value = cget(c, field); if (type == null) type = _getClass(value); if (type == boolean.class) return jCenteredCheckBox(isTrue(value)); else if (contains(multiLineFields, field) || containsNewLines(optCast(String.class, value))) return makeTextArea((String) value); else if (isSubtype(type, Concept.class)) return jcomboboxFromConcepts_str(concepts, type, (Concept) value); else if (type == SecretValue.class) return jpassword(strOrEmpty(getVar(((SecretValue) value)))); else if (isUneditableFieldType(type)) return jlabel(structureOrText_crud(value)); else try { return autoComboBox(structureOrText_crud(value), new TreeSet(map(__147 -> structureOrText_crud(__147), collect(list(concepts, conceptClass), field)))); } catch (Throwable e) { printException(e); return jTextField(structureOrText_crud(value)); } } public void saveComponent(A c, String field, JComponent comp) { comp = unwrap(comp); Class type = fieldType(c, field); Type genericType = genericFieldType(conceptClass, field); if (type == Concept.Ref.class) type = getTypeArgumentAsClass(genericType); if (type == SecretValue.class) { String text = getTextTrim((JPasswordField) comp); cset(c, field, empty(text) ? null : new SecretValue(text)); } else if (comp instanceof JTextComponent) { String text = trimIf(!(comp instanceof JTextArea), getText((JTextComponent) comp)); Object value = postProcessValue(text); Object converted = convertToField(value, c.getClass(), field); cset(c, field, converted); } else if (comp instanceof JComboBox) { String text = getTextTrim((JComboBox) comp); if (isSubtype(type, Concept.class)) cset(c, field, getConcept(concepts, parseFirstLong(text))); else { Object value = postProcessValue(text); cset(c, field, convertToField(value, c.getClass(), field)); } } else if (comp instanceof JCheckBox) cset(c, field, isChecked((JCheckBox) comp)); else if (comp instanceof ImageChooser) cUpdatePNGFile(c, field, ((ImageChooser) comp).getImage(), false); } transient public IF1> editableFieldsForItem; public Collection editableFieldsForItem(A c) { return editableFieldsForItem != null ? editableFieldsForItem.get(c) : editableFieldsForItem_base(c); } final public Collection editableFieldsForItem_fallback(IF1> _f, A c) { return _f != null ? _f.get(c) : editableFieldsForItem_base(c); } public Collection editableFieldsForItem_base(A c) { if (excludeFieldsFromEditing != null && modifiedField != null) excludeFieldsFromEditing.add(modifiedField); return listWithoutSet(conceptFieldsInOrder(c), joinSets(excludeFieldsFromEditing, unshownFields, keys(filters))); } public void excludeFieldsFromEditing(String... fields) { excludeFieldsFromEditing = setPlus(excludeFieldsFromEditing, fields); } public Collection> possibleClasses() { return (Collection) moveItemFirst(conceptClass, dropTypeParameter(sortClassesByNameIC(myNonAbstractClassesImplementing(conceptClass)))); } public JComboBox> classSelectorComponent(A c) { return setComboBoxRenderer(jTypedComboBox(possibleClasses(), _getClass(c)), customToStringListCellRenderer(__209 -> shortClassName(__209))); } public class NewField { public JTextField tfName = jtextfield(); public JTextField tfValue = jtextfield(); public JComboBox cbRef = jcomboboxFromConcepts_str(concepts, conceptClass); public JComboBox cbType = jcombobox("String", "Reference"); public SingleComponentPanel scpValue = singleComponentPanel(); public JPanel panel() { onChangeAndNow(cbType, new Runnable() { public void run() { try { updateSCP(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "updateSCP();"; } }); return jhgridWithSpacing(withToolTip("Name for new field", withLabel("Name", tfName)), withLabel("Value", westAndCenterWithMargin(cbType, scpValue))); } public String typeStr() { return getText(cbType); } public void updateSCP() { scpValue.setComponent(eqic(typeStr(), "Reference") ? cbRef : withToolTip("Contents of new field", tfValue)); } public String field() { return gtt(tfName); } public Object value() { return eqic(typeStr(), "Reference") ? getConcept(concepts, parseFirstLong(getText(cbRef))) : gtt(tfValue); } } public class EditWindow { public A item; public Map componentsByField = litorderedmap(); public List matrix = new ArrayList(); public JComboBox> classSelector; public List newFields = new ArrayList(); } public void makeComponents(EditWindow ew) { if (showClassNameSelectors) { addAll(ew.matrix, makeLabel("Java Class"), ew.classSelector = classSelectorComponent(ew.item)); onChange(ew.classSelector, new Runnable() { public void run() { try { Class oldClass = _getClass(ew.item); Class newClass = getSelectedItem_typed(ew.classSelector); if (oldClass == newClass) return; A oldItem = ew.item; ew.item = unlisted(newClass); ccopyFields(oldItem, ew.item); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Class oldClass = _getClass(ew.item);\r\n Class..."; } }); } for (String field : editableFieldsForItem(ew.item)) { JComponent c = fieldComponent(ew.item, field); ew.componentsByField.put(field, c); addAll(ew.matrix, makeLabel(field), c); } if (allowNewFields && newFieldsToShow > 0) { addAll(ew.matrix, " ", jlabel()); for (int i = 0; i < newFieldsToShow; i++) { NewField nf = new NewField(); ew.newFields.add(nf); addAll(ew.matrix, makeLabel(""), nf.panel()); } } } public void saveData(EditWindow ew) { for (Map.Entry __0 : _entrySet(ew.componentsByField)) { String field = __0.getKey(); JComponent component = __0.getValue(); if (isIdentifier(field)) saveComponent(ew.item, field, component); } for (NewField nf : ew.newFields) { String field = nf.field(); Object value = nf.value(); if (nempty(field) && notNullOrEmptyString(value)) cset(ew.item, field, value); } if (modifiedField != null) cset(ew.item, modifiedField, now()); conceptSaved(ew.item); } public Object postProcessValue(Object o) { if (emptyStringsToNull && eq(o, "")) return null; return o; } public JComponent makeLabel(String label) { return jMinWidthAtLeast(formLabelsWidth, jlabel(label)); } transient public IF2 showAForm; public JComponent showAForm(String title, Object... parts) { return showAForm != null ? showAForm.get(title, parts) : showAForm_base(title, parts); } final public JComponent showAForm_fallback(IF2 _f, String title, Object... parts) { return _f != null ? _f.get(title, parts) : showAForm_base(title, parts); } public JComponent showAForm_base(String title, Object... parts) { JForm form = new JForm(parts).disposeFrameOnSubmit(); var panel = form.visualize(); showFrame(title, editWindowScrollable ? jscroll_vertical(panel) : panel); return panel; } public boolean isUneditableFieldType(Class type) { return isSubclassOfAny(type, Map.class, Collection.class, Pair.class); } public void hideField(String field) { hideFields(field); } public void hideFields(String... fields) { unshownFields = createOrAddToSet(unshownFields, fields); } public SimpleCRUD_v2 entityName(String name) { entityName = if0_const(name); return this; } transient public IF0 entityName; public String entityName() { return entityName != null ? entityName.get() : entityName_base(); } final public String entityName_fallback(IF0 _f) { return _f != null ? _f.get() : entityName_base(); } public String entityName_base() { return shortClassName(conceptClass); } transient public IF0 entityNamePlural; public String entityNamePlural() { return entityNamePlural != null ? entityNamePlural.get() : entityNamePlural_base(); } final public String entityNamePlural_fallback(IF0 _f) { return _f != null ? _f.get() : entityNamePlural_base(); } public String entityNamePlural_base() { return plural(entityName()); } transient public IF0 entityNameLower; public String entityNameLower() { return entityNameLower != null ? entityNameLower.get() : entityNameLower_base(); } final public String entityNameLower_fallback(IF0 _f) { return _f != null ? _f.get() : entityNameLower_base(); } public String entityNameLower_base() { return firstToLower(entityName()); } transient public IF0 entityNamePluralLower; public String entityNamePluralLower() { return entityNamePluralLower != null ? entityNamePluralLower.get() : entityNamePluralLower_base(); } final public String entityNamePluralLower_fallback(IF0 _f) { return _f != null ? _f.get() : entityNamePluralLower_base(); } public String entityNamePluralLower_base() { return firstToLower(entityNamePlural()); } public JPanel buttons() { visualize(); return buttons; } public void addButtonInFront(String text, Runnable r) { addButtonInFront(jbutton(text, r)); } public void addButton(String text, Runnable r) { addButton(jbutton(text, r)); } public void addButton(JComponent c) { buttons().add(c); } public void addButtonInFront(JComponent c) { addComponentInFront(buttons(), c); } public JButton makeAddButton(Runnable r) { return makeButton("Add...", "Create a new " + entityNameLower(), "#1103069", r); } public JButton makeDeleteButton(Runnable r) { return makeButton("Delete", "Delete selected " + entityNamePluralLower(), "#1103067", r); } public JButton makeEditButton(Runnable r) { return makeButton("Edit...", "Edit selected " + entityNameLower(), "#1103068", r); } public JButton makeDuplicateButton(Runnable r) { return makeButton("Duplicate...", "Duplicate selected " + entityNameLower(), "#1103070", r); } public JButton makeButton(String text, String iconID, Runnable r) { return makeButton(text, null, iconID, r); } public JButton makeButton(String text, String toolTip, String iconID, Runnable r) { if (iconButtons) return toolTip(or2(toolTip, text), jimageButtonScaledToWidth(16, iconID, text, r)); else return toolTip(toolTip, jbutton(text, r)); } public void multiLineField(String field) { multiLineFields = addOrCreate(multiLineFields, field); } transient public IF1 makeTextArea; public JComponent makeTextArea(String text) { return makeTextArea != null ? makeTextArea.get(text) : makeTextArea_base(text); } final public JComponent makeTextArea_fallback(IF1 _f, String text) { return _f != null ? _f.get(text) : makeTextArea_base(text); } public JComponent makeTextArea_base(String text) { return typeWriterTextArea(text); } public void setButtonFiller(JComponent c) { scpButtonFiller.set(c); } public TableSearcher tableSearcher() { visualize(); return tableSearcher; } } static public class SinglePixelPosterizer implements IPosterizer { public int brightnessLevels; public double factor1, factor2; final public SinglePixelPosterizer setDrift(double drift) { return drift(drift); } public SinglePixelPosterizer drift(double drift) { this.drift = drift; return this; } final public double getDrift() { return drift(); } public double drift() { return drift; } public double drift; final public SinglePixelPosterizer setAntiDrift(double antiDrift) { return antiDrift(antiDrift); } public SinglePixelPosterizer antiDrift(double antiDrift) { this.antiDrift = antiDrift; return this; } final public double getAntiDrift() { return antiDrift(); } public double antiDrift() { return antiDrift; } public double antiDrift; public SinglePixelPosterizer(int brightnessLevels) { this.brightnessLevels = brightnessLevels; factor1 = doubleRatio(brightnessLevels, 256); factor2 = doubleRatio(255, brightnessLevels - 1); } public int get(int brightness) { var inner = brightness * factor1 + drift; var posterized = ifloor(inner) + antiDrift; return clampUByteInt(iround(posterized * factor2)); } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } } static public class ScanlineBitMatrix extends AbstractMatrix implements Matrix { public ScanlineBitMatrix() { } public int bx1 = Integer.MAX_VALUE, by1, bx2, by2; public int pixels; public int[] scanlineData; public int[] scanlineStarts; public ScanlineBitMatrix(Matrix m) { super(m.getWidth(), m.getHeight()); while (by1 < h && bitMatrixRowEmpty(m, by1)) by1++; by2 = h; while (by2 > by1 && bitMatrixRowEmpty(m, by2 - 1)) by2--; int ptr = 0, pixels = 0; scanlineStarts = new int[by2 - by1]; IntBuffer scanlineData = new IntBuffer(); lineLoop: for (int y = by1; y < by2; y++) { scanlineStarts[y - by1] = l(scanlineData); for (int x = 0; x < w; ) { while (!m.get(x, y)) if (++x >= w) continue lineLoop; int x2 = x + 1; while (x2 < w && m.get(x2, y)) ++x2; scanlineData.add(x); scanlineData.add(x2); pixels += x2 - x; if (x < bx1) bx1 = x; if (x2 > bx2) bx2 = x2; x = x2; } } this.scanlineData = scanlineData.toArray(); this.pixels = pixels; } public Boolean get(int x, int y) { if (x < bx1 || y < by1 || x >= bx2 || y >= by2) return false; int ptr = scanlineStarts[y - by1]; int end = y == by2 - 1 ? scanlineData.length : scanlineStarts[y - by1 + 1]; while (ptr < end) { int x1 = scanlineData[ptr++]; if (x < x1) return false; int x2 = scanlineData[ptr++]; if (x < x2) return true; } return false; } public void set(int x, int y, Boolean a) { throw unimplemented(); } public Rect boundingBoxOfTrueBits() { return bx1 >= bx2 ? null : rect(bx1, by1, bx2, by2); } public int nRuns() { return scanlineData.length / 2; } public IterableIterator runs() { return new IterableIterator() { public int y = 0, ptr = 0; public boolean hasNext() { return ptr < l(scanlineData); } public Rect next() { while (y < scanlineStarts.length - 1 && ptr >= scanlineStarts[y + 1]) ++y; int x1 = scanlineData[ptr++]; int x2 = scanlineData[ptr++]; return rect(x1, by1 + y, x2 - x1, 1); } }; } public int pixelCount() { return pixels; } } static public class GoodThingsToTrack implements IFieldsToList { public BWImage image; public GoodThingsToTrack() { } public GoodThingsToTrack(BWImage image) { this.image = image; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + image + ")"; } public Object[] _fieldsToList() { return new Object[] { image }; } final public GoodThingsToTrack setWindowSize(int windowSize) { return windowSize(windowSize); } public GoodThingsToTrack windowSize(int windowSize) { this.windowSize = windowSize; return this; } final public int getWindowSize() { return windowSize(); } public int windowSize() { return windowSize; } public int windowSize = 3; final public GoodThingsToTrack setScoreFactor(double scoreFactor) { return scoreFactor(scoreFactor); } public GoodThingsToTrack scoreFactor(double scoreFactor) { this.scoreFactor = scoreFactor; return this; } final public double getScoreFactor() { return scoreFactor(); } public double scoreFactor() { return scoreFactor; } public double scoreFactor = 1 / 256.0; final public BWImage getOutputImage() { return outputImage(); } public BWImage outputImage() { return outputImage; } public BWImage outputImage; final public double getMaxScore() { return maxScore(); } public double maxScore() { return maxScore; } public double maxScore; public void run() { try { int w = image.getWidth(), h = image.getHeight(); int wn = windowSize * windowSize; int ofs = (windowSize + 1) / 2; outputImage = new BWImage(w, h); for (int y = 1; y < h - windowSize - 1; y++) { for (int x = 1; x < w - windowSize - 1; x++) { double[] ix = new double[wn]; double[] iy = new double[wn]; int iw = 0; for (int yy = 0; yy < windowSize; yy++) for (int xx = 0; xx < windowSize; xx++) { double left = image.getInt(x + xx - 1, y + yy); double right = image.getInt(x + xx + 1, y + yy); double above = image.getInt(x + xx, y + yy - 1); double below = image.getInt(x + xx, y + yy + 1); ix[iw] = right - left; iy[iw] = below - above; iw++; } double sideSum = 0; for (int i = 0; i < wn; i++) sideSum += ix[i] * iy[i]; double xSum = 0; for (int i = 0; i < wn; i++) xSum += sqr(ix[i]); double ySum = 0; for (int i = 0; i < wn; i++) ySum += sqr(iy[i]); double[][] matrix = new double[][] { { xSum, sideSum }, { sideSum, ySum } }; Complex[] lambdas = eigenvaluesOfSymmetricMatrix(matrix); if (l(lambdas) == 2) { double score = min(abs(lambdas[0]), abs(lambdas[1])); if (score > maxScore) maxScore = score; outputImage.setInt(x + ofs, y + ofs, iround(score * scoreFactor)); } } } } catch (Exception __e) { throw rethrow(__e); } } } static public class WindowDragger extends MouseAdapter { public MouseEvent mouseDownEvent; public JComponent src; public Pt rel; public Window window; public WindowDragger(MouseEvent mouseDownEvent) { this.mouseDownEvent = mouseDownEvent; if (mouseDownEvent == null) return; src = optCast(JComponent.class, mouseDownEvent.getComponent()); if (src == null) return; window = getWindow(src); if (window == null) return; rel = pt(mouseDownEvent.getXOnScreen() - window.getX(), mouseDownEvent.getYOnScreen() - window.getY()); addMouseAndMotionListener(src, this); } public void mouseDragged(MouseEvent e) { updatePosition(e); } public void mouseReleased(MouseEvent e) { if (e.getButton() != mouseDownEvent.getButton()) return; updatePosition(e); removeMouseAdapter(src, this); dragDone(); } public void updatePosition(MouseEvent e) { window.setLocation(e.getXOnScreen() - rel.x, e.getYOnScreen() - rel.y); } public void dragDone() { } } static public interface IF2_IntInt_Double { public double get(int a, int b); } public interface IMultiMap { public Set keySet(); public Collection get(A a); public int size(); public int keyCount(); } static public class RegionBorder_innerPoints_withDiagonals extends AbstractBorderTracer implements IFieldsToList { public IImageRegion region; public RegionBorder_innerPoints_withDiagonals() { } public RegionBorder_innerPoints_withDiagonals(IImageRegion region) { this.region = region; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + region + ")"; } public Object[] _fieldsToList() { return new Object[] { region }; } public Rect bounds; public int x, y; public int dir; public Iterator it; public byte[] reachedInDirections; public boolean tracing = false; public int nTrace; public void init() { bounds = region.bounds(); reachedInDirections = new byte[area(bounds)]; it = region.pixelIterator(); } public boolean step() { if (reachedInDirections == null) init(); if (tracing) return walkOnePixel(); else return findFirstPixel(); } public boolean walkOnePixel() { int posInBounds = (y - bounds.y) * bounds.w + x - bounds.x; if ((reachedInDirections[posInBounds] & (1 << (dir - 1))) != 0) { traceDone(); tracing = false; return includeHoles; } reachedInDirections[posInBounds] |= (byte) 1 << (dir - 1); foundPoint(x, y); for (int turn = -2; turn <= 4; turn++) { int newDir = modRange_incl(dir + turn, 1, 8); Pt d = onePathDirection(newDir); int x2 = x + d.x, y2 = y + d.y; boolean b = region.contains(x2, y2); if (b) { x = x2; y = y2; dir = newDir; return true; } } return true; } public boolean findFirstPixel() { if (!it.hasNext()) return false; Pt p = it.next(); x = p.x; y = p.y; int posInBounds = (y - bounds.y) * bounds.w + x - bounds.x; if (reachedInDirections[posInBounds] != 0) return true; if (!region.contains(x, y - 1)) { startTrace(4); return true; } if (!region.contains(x - 1, y)) { startTrace(2); return true; } if (!region.contains(x + 1, y)) { startTrace(6); return true; } if (!region.contains(x, y + 1)) { startTrace(8); return true; } return true; } public void startTrace(int dir) { this.dir = dir; int posInBounds = (y - bounds.y) * bounds.w + x - bounds.x; reachedInDirections[posInBounds] = (byte) ~(1 << (dir - 1)); tracing = true; newTrace(++nTrace > 1); } public void foundPoint(int x, int y) { foundPoint(pt(x, y)); } public List allPoints_cache; public List allPoints() { if (allPoints_cache == null) allPoints_cache = allPoints_load(); return allPoints_cache; } public List allPoints_load() { PtBuffer l = new PtBuffer(); onFoundPoint(p -> l.add(p)); run(); return l; } public OnePath onePath_cache; public OnePath onePath() { if (onePath_cache == null) onePath_cache = onePath_load(); return onePath_cache; } public OnePath onePath_load() { includeHoles(false); return new OnePath(allPoints(), true); } public OnePathWithOrigin onePathWithOrigin_cache; public OnePathWithOrigin onePathWithOrigin() { if (onePathWithOrigin_cache == null) onePathWithOrigin_cache = onePathWithOrigin_load(); return onePathWithOrigin_cache; } public OnePathWithOrigin onePathWithOrigin_load() { includeHoles(false); return new OnePathWithOrigin(allPoints(), true); } public void runAndPrint() { onNewTrace(hole -> print(!hole ? "new outline" : "new hole")); onTraceDone(() -> print("traceDone")); onFoundPoint(p -> print("foundPoint " + p)); stepMaxWithStats(this, 10000); } public boolean tracingHole() { return nTrace > 1; } } static public interface IF1_IntToInt { public int get(int i); } static public class BoolVarWithNotify extends BoolVar { transient public Set onChange; public BoolVarWithNotify onChange(Runnable r) { onChange = createOrAddToSyncLinkedHashSet(onChange, r); return this; } public BoolVarWithNotify removeChangeListener(Runnable r) { utils.remove(onChange, r); return this; } public void fireChange() { if (onChange != null) for (var listener : onChange) pcallF_typed(listener); } public BoolVarWithNotify() { } public BoolVarWithNotify(boolean value) { super(value); } @Override public synchronized void set(boolean a) { if (get() != a) { super.set(a); fireChange(); } } public BoolVarWithNotify onChangeAndNow(Runnable r) { onChange(r); r.run(); return this; } } static public interface IBWImage extends MakesBufferedImage, IRGBImage { public float getFloatPixel(int x, int y); default public int getInt(int x, int y) { return iround(getFloatPixel(x, y) * 255f); } default public int getIntPixel(int x, int y) { return rgbIntFromGrayscale(getInt(x, y)); } default public float getFloatPixel(Pt p) { return getFloatPixel(p.x, p.y); } default public float getFloatPixel(int index) { int w = w(); return getFloatPixel(index % w, index / w); } default public float[] toFloatArray() { float[] data = new float[w() * h()]; for (int i = 0; i < l(data); i++) data[i] = getFloatPixel(i); return data; } public default BufferedImage getBufferedImage() { return grayImageFromIBWImage(this); } default public BWImage toBWImage() { return this instanceof BWImage ? (BWImage) this : iBWImageToBWImage(this); } } static public class PtInComponent implements IFieldsToList { public A component; public Pt p; public PtInComponent() { } public PtInComponent(A component, Pt p) { this.p = p; this.component = component; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + component + ", " + p + ")"; } public boolean equals(Object o) { if (!(o instanceof PtInComponent)) return false; PtInComponent __1 = (PtInComponent) o; return eq(component, __1.component) && eq(p, __1.p); } public int hashCode() { int h = -1774729068; h = boostHashCombine(h, _hashCode(component)); h = boostHashCombine(h, _hashCode(p)); return h; } public Object[] _fieldsToList() { return new Object[] { component, p }; } public PtInComponent(Pt p, A component) { this.component = component; this.p = p; } } static public class JConceptsTable implements Swingable { public Class conceptClass; public Concepts concepts; public JTable table; public Map filters; public String hID = "ID"; final public JConceptsTable setDropFields(List dropFields) { return dropFields(dropFields); } public JConceptsTable dropFields(List dropFields) { this.dropFields = dropFields; return this; } final public List getDropFields() { return dropFields(); } public List dropFields() { return dropFields; } public List dropFields; final public JConceptsTable setNoSubclasses(boolean noSubclasses) { return noSubclasses(noSubclasses); } public JConceptsTable noSubclasses(boolean noSubclasses) { this.noSubclasses = noSubclasses; return this; } final public boolean getNoSubclasses() { return noSubclasses(); } public boolean noSubclasses() { return noSubclasses; } public boolean noSubclasses = false; public IF1 postProcess; public Runnable afterUpdate; public boolean latestFirst = false; public IF1, Collection> sorter = __1 -> defaultSort(__1); public int idWidth = 50; final public JConceptsTable setUpdateInterval(int updateInterval) { return updateInterval(updateInterval); } public JConceptsTable updateInterval(int updateInterval) { this.updateInterval = updateInterval; return this; } final public int getUpdateInterval() { return updateInterval(); } public int updateInterval() { return updateInterval; } public int updateInterval = 100; public int firstUpdateInterval = 100; public boolean humanizeFieldNames = true; public Float tableFontSize; public Integer tableRowHeight; final public JConceptsTable setAddCountToEnclosingTab(boolean addCountToEnclosingTab) { return addCountToEnclosingTab(addCountToEnclosingTab); } public JConceptsTable addCountToEnclosingTab(boolean addCountToEnclosingTab) { this.addCountToEnclosingTab = addCountToEnclosingTab; return this; } final public boolean getAddCountToEnclosingTab() { return addCountToEnclosingTab(); } public boolean addCountToEnclosingTab() { return addCountToEnclosingTab; } public boolean addCountToEnclosingTab = false; final public JConceptsTable setUseNewChangeHandler(boolean useNewChangeHandler) { return useNewChangeHandler(useNewChangeHandler); } public JConceptsTable useNewChangeHandler(boolean useNewChangeHandler) { this.useNewChangeHandler = useNewChangeHandler; return this; } final public boolean getUseNewChangeHandler() { return useNewChangeHandler(); } public boolean useNewChangeHandler() { return useNewChangeHandler; } public boolean useNewChangeHandler = false; final public JConceptsTable setDefaultAction(IVF1 defaultAction) { return defaultAction(defaultAction); } public JConceptsTable defaultAction(IVF1 defaultAction) { this.defaultAction = defaultAction; return this; } final public IVF1 getDefaultAction() { return defaultAction(); } public IVF1 defaultAction() { return defaultAction; } public IVF1 defaultAction; public boolean pauseUpdates = false; public int count; transient public Set onSelectionChanged; public JConceptsTable onSelectionChanged(Runnable r) { onSelectionChanged = createOrAddToSyncLinkedHashSet(onSelectionChanged, r); return this; } public JConceptsTable removeSelectionChangedListener(Runnable r) { utils.remove(onSelectionChanged, r); return this; } public void selectionChanged() { if (onSelectionChanged != null) for (var listener : onSelectionChanged) pcallF_typed(listener); } transient public Set onSingleSelectionChanged; public JConceptsTable onSingleSelectionChanged(Runnable r) { onSingleSelectionChanged = createOrAddToSyncLinkedHashSet(onSingleSelectionChanged, r); return this; } public JConceptsTable removeSingleSelectionChangedListener(Runnable r) { utils.remove(onSingleSelectionChanged, r); return this; } public void singleSelectionChanged() { if (onSingleSelectionChanged != null) for (var listener : onSingleSelectionChanged) pcallF_typed(listener); } public AWTOnConceptChanges changeHandler; public AWTOnConceptChangesByClass newChangeHandler; public boolean updatingList = false; final public JConceptsTable setSelectAfterUpdate(A selectAfterUpdate) { return selectAfterUpdate(selectAfterUpdate); } public JConceptsTable selectAfterUpdate(A selectAfterUpdate) { this.selectAfterUpdate = selectAfterUpdate; return this; } final public A getSelectAfterUpdate() { return selectAfterUpdate(); } public A selectAfterUpdate() { return selectAfterUpdate; } public A selectAfterUpdate; public A lastSelected; public JConceptsTable() { } public JConceptsTable(Class conceptClass) { this.conceptClass = conceptClass; } public JConceptsTable(Concepts concepts, Class conceptClass) { this.conceptClass = conceptClass; this.concepts = concepts; } transient public IF1> itemToMap; public Map itemToMap(A a) { return itemToMap != null ? itemToMap.get(a) : itemToMap_base(a); } final public Map itemToMap_fallback(IF1> _f, A a) { return _f != null ? _f.get(a) : itemToMap_base(a); } public Map itemToMap_base(A a) { Map map = specialFieldsForItem(a); try { putAll(map, mapValues(__148 -> renderValue(__148), itemToMap_inner2(a))); } catch (Throwable e) { printStackTrace(e); map.put("Error", str(e)); } return map; } transient public IF1 renderValue; public Object renderValue(Object o) { return renderValue != null ? renderValue.get(o) : renderValue_base(o); } final public Object renderValue_fallback(IF1 _f, Object o) { return _f != null ? _f.get(o) : renderValue_base(o); } public Object renderValue_base(Object o) { return renderForTable_noStruct(o); } transient public IF1> itemToMap_inner2; public Map itemToMap_inner2(A a) { return itemToMap_inner2 != null ? itemToMap_inner2.get(a) : itemToMap_inner2_base(a); } final public Map itemToMap_inner2_fallback(IF1> _f, A a) { return _f != null ? _f.get(a) : itemToMap_inner2_base(a); } public Map itemToMap_inner2_base(A a) { return allConceptFieldsAsMapExcept(a, dropFields); } transient public IF1> specialFieldsForItem; public Map specialFieldsForItem(A a) { return specialFieldsForItem != null ? specialFieldsForItem.get(a) : specialFieldsForItem_base(a); } final public Map specialFieldsForItem_fallback(IF1> _f, A a) { return _f != null ? _f.get(a) : specialFieldsForItem_base(a); } public Map specialFieldsForItem_base(A a) { Map map = litorderedmap(hID, str(a.id)); mapPut(map, "Java Class", javaClassDescForItem(a)); return map; } public String javaClassDescForItem(A a) { String className = dynShortClassName(a); if (neq(className, shortClassName(conceptClass))) { String text = className; String realClass = shortClassName(a); if (neq(className, realClass)) text += " as " + realClass; return text; } return null; } public String defaultTitle() { return plural(shortClassName(conceptClass)); } public void showAsFrame() { showAsFrame(defaultTitle()); } public void showAsFrame(String title) { makeTable(); showFrame(title, table); } public void makeTable() { if (table != null) return; if (concepts == null) concepts = db_mainConcepts(); table = sexyTable(); if (tableFontSize != null) { setTableFontSizes(tableFontSize, table); if (tableRowHeight == null) tableRowHeight = iround(tableFontSize * 1.5); } if (tableRowHeight != null) setRowHeight(table, tableRowHeight); if (useNewChangeHandler) { newChangeHandler = new AWTOnConceptChangesByClass(concepts, conceptClass, table, () -> _update()).delay(updateInterval).firstDelay(firstUpdateInterval); newChangeHandler.install(); } else { changeHandler = new AWTOnConceptChanges(concepts, table, () -> _update()).delay(updateInterval).firstDelay(firstUpdateInterval); changeHandler.install(); } onTableSelectionChanged(table, () -> { if (updatingList) return; selectionChanged(); }); onSelectionChanged(() -> { var a = selected(); if (a != lastSelected) { lastSelected = a; singleSelectionChanged(); } }); onDoubleClickOrEnter(table, () -> { A a = selected(); if (a != null && defaultAction != null) pcallF(defaultAction, a); }); } public void update() { { swing(() -> { _update(); }); } } public void _update() { if (table == null || pauseUpdates) return; updatingList = true; boolean allRestored = false; A selectAfterUpdate = selectAfterUpdate(); try { List data = new ArrayList(); Set selection; if (selectAfterUpdate != null) { selection = litset(selectAfterUpdate._conceptID()); selectAfterUpdate(null); } else selection = toSet(selectedConceptIDs()); Collection l = conceptsWhere(concepts, conceptClass, mapToParams(filters)); if (noSubclasses) l = filter(l, x -> x.getClass() == conceptClass); l = postProcess(sorter, l); for (A c : l) addIfNotNull(data, itemToMap(c)); if (latestFirst) reverseInPlace(data); data = (List) postProcess(postProcess, data); count = l(data); dataToTable_uneditable(data, table); if (humanizeFieldNames) humanizeTableColumns(); tableColumnMaxWidth(table, 0, idWidth); allRestored = restoreSelection(selection); if (addCountToEnclosingTab) updateEnclosingTabTitle(); } finally { updatingList = false; } pcallF(afterUpdate); if (!allRestored || selectAfterUpdate != null) selectionChanged(); } public void updateEnclosingTabTitle() { updateEnclosingTabTitleWithCount(table, count); } public void humanizeTableColumns() { int n = tableColumnCount(table); for (int i = 0; i < n; i++) setColumnName(table, i, humanizeFormLabel(getColumnName(table, i))); } public JComponent visualize() { return table(); } public JTable table() { makeTable(); return table; } public A selectedConcept() { return (A) concepts.getConcept(toLong(selectedTableCell(table, 0))); } public A selected() { return selectedConcept(); } public long getItemID(int row) { return toLong(getTableCell(table, row, 0)); } public List getList() { return swing(() -> { return countIteratorAsList(size(), row -> getItem(row)); }); } public A getItem(int row) { return (A) concepts.getConcept(getItemID(row)); } public int size() { return tableRowCount(table); } public int indexOfConcept(final A c) { if (c == null) return -1; return swing(new F0() { public Integer get() { try { int n = size(); for (int row = 0; row < n; row++) if (toLong(getTableCell(table, row, 0)) == c.id) return row; return -1; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "int n = size();\r\n for row to n:\r\n if (toLong(getTableCell(table, ..."; } }); } public List selectedConcepts() { return swing(() -> { int[] rows = table.getSelectedRows(); List l = new ArrayList(); for (int row : rows) l.add(getItem(row)); return l; }); } public List selectedConceptIDs() { return swing(() -> { int[] rows = table.getSelectedRows(); List l = emptyList(l(rows)); for (int row : rows) l.add(getItemID(row)); return l; }); } public boolean restoreSelection(Set selection) { return swing(() -> { int n = size(); IntBuffer toSelect = new IntBuffer(); for (int row = 0; row < n; row++) if (selection.contains(getItemID(row))) toSelect.add(row); selectTableRows(table, toSelect.toIntArray()); return toSelect.size() == selection.size(); }); } public void setSelected(A a) { selectRow(table(), indexOfConcept(a)); } public Collection defaultSort(Collection l) { return sortByConceptID(l); } public JConceptsTable addFilter(String field, Object value) { filters = orderedMapPutOrCreate(filters, field, value); return this; } public void onSelectionChangedAndWhenShowing(Runnable r) { bindToComponent(table(), r); onSelectionChanged(r); } public void onSelectionChangedAndNow(Runnable r) { if (r == null) return; onSelectionChanged(r); r.run(); } public JConceptsTable updateInterval(double seconds) { return updateInterval(toMS_int(seconds)); } public JConceptsTable pauseUpdates(boolean b) { { swing(() -> { if (pauseUpdates != b) { if (!(pauseUpdates = b)) _update(); } }); } return this; } } static public class ConceptFieldIndex extends ConceptFieldIndexBase { public ConceptFieldIndex(Class cc, String field) { super(cc, field); } public ConceptFieldIndex(Concepts concepts, Class cc, String field) { super(concepts, cc, field); } public void init() { valueToObject = new MultiSetMap(); } public void register() { concepts.addFieldIndex(cc, field, this); } } static public class GrabbableGrayPixels implements IFieldsToList { static final public String _fieldOrder = "data w h offset scanlineStride"; public byte[] data; public int w; public int h; public int offset; public int scanlineStride; public GrabbableGrayPixels() { } public GrabbableGrayPixels(byte[] data, int w, int h, int offset, int scanlineStride) { this.scanlineStride = scanlineStride; this.offset = offset; this.h = h; this.w = w; this.data = data; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + data + ", " + w + ", " + h + ", " + offset + ", " + scanlineStride + ")"; } public boolean equals(Object o) { if (!(o instanceof GrabbableGrayPixels)) return false; GrabbableGrayPixels __1 = (GrabbableGrayPixels) o; return eq(data, __1.data) && w == __1.w && h == __1.h && offset == __1.offset && scanlineStride == __1.scanlineStride; } public int hashCode() { int h = 1984426208; h = boostHashCombine(h, _hashCode(data)); h = boostHashCombine(h, _hashCode(w)); h = boostHashCombine(h, _hashCode(h)); h = boostHashCombine(h, _hashCode(offset)); h = boostHashCombine(h, _hashCode(scanlineStride)); return h; } public Object[] _fieldsToList() { return new Object[] { data, w, h, offset, scanlineStride }; } } static public interface IHasBackRefs { public void _registerBackRef(IRef ref); public void _unregisterBackRef(IRef ref); } static public class StepperWithStats extends MetaWithChangeListeners implements Steppable, IFieldsToList { public Steppable steppable; public StepperWithStats() { } public StepperWithStats(Steppable steppable) { this.steppable = steppable; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + steppable + ")"; } public Object[] _fieldsToList() { return new Object[] { steppable }; } public transient FieldVar varTimeRange_cache; public FieldVar varTimeRange() { if (varTimeRange_cache == null) varTimeRange_cache = varTimeRange_load(); return varTimeRange_cache; } public FieldVar varTimeRange_load() { return new FieldVar(this, "timeRange", () -> timeRange(), timeRange -> timeRange(timeRange)); } final public StepperWithStats setTimeRange(TimestampRange timeRange) { return timeRange(timeRange); } public StepperWithStats timeRange(TimestampRange timeRange) { if (!eq(this.timeRange, timeRange)) { this.timeRange = timeRange; change(); } return this; } final public TimestampRange getTimeRange() { return timeRange(); } public TimestampRange timeRange() { return timeRange; } public TimestampRange timeRange = new TimestampRange(); public transient FieldVar varStepCount_cache; public FieldVar varStepCount() { if (varStepCount_cache == null) varStepCount_cache = varStepCount_load(); return varStepCount_cache; } public FieldVar varStepCount_load() { return new FieldVar(this, "stepCount", () -> stepCount(), stepCount -> stepCount(stepCount)); } final public StepperWithStats setStepCount(long stepCount) { return stepCount(stepCount); } public StepperWithStats stepCount(long stepCount) { if (!eq(this.stepCount, stepCount)) { this.stepCount = stepCount; change(); } return this; } final public long getStepCount() { return stepCount(); } public long stepCount() { return stepCount; } public long stepCount; public transient FieldVar varDone_cache; public FieldVar varDone() { if (varDone_cache == null) varDone_cache = varDone_load(); return varDone_cache; } public FieldVar varDone_load() { return new FieldVar(this, "done", () -> done(), done -> done(done)); } final public StepperWithStats setDone(boolean done) { return done(done); } public StepperWithStats done(boolean done) { if (!eq(this.done, done)) { this.done = done; change(); } return this; } final public boolean getDone() { return done(); } public boolean done() { return done; } public boolean done = false; public boolean step() { if (done) return false; if (steppable == null) return false; ping(); if (timeRange.start() == null) timeRange.startTime(tsNow()); stepCount(stepCount + 1); if (steppable.step()) return true; timeRange.endTime(tsNow()); done(true); return false; } public String renderStats() { String s = nSteps(stepCount); if (done) { s += " (done"; if (timeRange.complete()) s += " in " + formatSeconds(timeRange.duration(), 1) + "s"; s += ")"; } return s; } } static public class MapI extends IterableIterator { public IF1 f; public Iterator it; public MapI(IF1 f, Iterator it) { this.it = it; this.f = f; } public boolean hasNext() { return it.hasNext(); } public B next() { return f.get(it.next()); } } static public class VectorOptimizedSSIList extends AbstractSSIList { public VectorOptimizedSSIList() { init(); } public VectorOptimizedSSIList(Collection l) { super(l); } static public VectorOptimizedSSIList alreadyOptimized(List l) { VectorOptimizedSSIList list = new VectorOptimizedSSIList(); list.addAll(l); return list; } @Override public AbstractSSI importSSI(AbstractSSI ssi) { return vectorizeSSIIfBeneficial(ssi.toSSI()); } } static public class JDraggableBoxDemo implements Swingable { public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { var parent = jpanelWithoutLayoutManager(); var box = jMinSize(400, 300, jcenteredlabel("Drag or resize me!")); setBorder(box, BorderFactory.createLineBorder(Color.green, 10)); onMouseDown(box, event -> { if (!mouseEventIsInBorder(event)) { printVars("ComponentDragger start"); new ComponentDragger(box, event).debug(true).start(); } }); new ComponentResizeDragger(box, box).debug(true); setBounds(box, 50, 50, 400, 300); addToContainer(parent, box); return parent; } } public static interface IF0 { public A get(); } static public interface IF2 { public C get(A a, B b); } static public interface IF1 { public B get(A a); } public interface IPosterizer extends IF1_IntToInt { } static public interface IVF3 { public void get(A a, B b, C c); } static public interface IVF1 { public void get(A a); } static public interface IVF2 { public void get(A a, B b); } public interface IWithSideValue extends IF0 { public A sideValue(); } static public class MultiPointGradient implements MakesBufferedImage { public List> gradientPoints; public int w, h; public int[] pixels; public double[] gradientPointArray; public Color[] colors; public boolean hasRun = false; public MultiPointGradient(List> gradientPoints, int w, int h) { this.h = h; this.w = w; this.gradientPoints = gradientPoints; } public MultiPointGradient(WidthAndHeight size, List> gradientPoints) { this.gradientPoints = gradientPoints; w = size.getWidth(); h = size.getHeight(); } public MultiPointGradient(int w, int h, List> gradientPoints) { this.gradientPoints = gradientPoints; this.h = h; this.w = w; } public int getWidth() { return w; } public int getHeight() { return h; } public BufferedImage getBufferedImage() { run(); return intArrayToBufferedImageWithoutAlpha(pixels, w, h); } public void init() { if (pixels == null) pixels = new int[w * h]; if (gradientPointArray == null) gradientPointArray = iDoublePtsToDoubleArray(pairsA(gradientPoints)); if (colors == null) colors = toArray(Color.class, pairsB(gradientPoints)); } public void run() { try { if (hasRun) return; hasRun = true; init(); int n = l(colors); double[] colorRatios = new double[n]; int iPixel = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { fillArray(colorRatios, 1); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (i != j) { var d = getProjectionDistance2(gradientPointArray[i * 2], gradientPointArray[i * 2 + 1], gradientPointArray[j * 2], gradientPointArray[j * 2 + 1], x, y); colorRatios[i] *= clampZeroToOne(d); } pixels[iPixel++] = blendMultipleColorsToInt(colors, colorRatios); } } catch (Exception __e) { throw rethrow(__e); } } } static public class Options extends ConceptL { public Options() { } public Options(List l) { super(l); } public Options(Concept... l) { super(asList(l)); } } static public class ScoredStringSearcher extends ScoredSearcher_stable { public Set seen; public ScoredStringSearcher() { } public ScoredStringSearcher(String query, Object... __) { super(query); } public ScoredStringSearcher uniquify(boolean b) { seen = b ? new HashSet() : null; return this; } final public void add(String s) { put(s); } public void put(String s) { if (seen == null || seen.add(s)) put(s, s); } public void addAll(Iterable l) { for (var s : unnullForIteration(l)) add(s); } public void addAll(String... l) { addAll(asList(l)); } } static public class TreeSetWithDuplicates extends AbstractSet { public NavigableSet> sets; public Comparator comparator; public int size; public TreeSetWithDuplicates() { this((Comparator) null); } public TreeSetWithDuplicates(Comparator comparator) { this.comparator = comparator; sets = new TreeSet>(comparator == null ? (setA, setB) -> cmp(utils.first(setA), utils.first(setB)) : (setA, setB) -> comparator.compare(utils.first(setA), utils.first(setB))); } public TreeSetWithDuplicates(NavigableSet> sets) { this.sets = sets; } public CompactLinkedHashSet makeInnerSet() { return new CompactLinkedHashSet(); } public boolean add(A a) { var probe = probe(a); CompactLinkedHashSet found = navigableSet_find(sets, probe); if (found != null) { if (!found.add(a)) return false; } else sets.add(probe); ++size; return true; } public boolean remove(Object a) { CompactLinkedHashSet newSet = makeInnerSet(); newSet.add((A) a); CompactLinkedHashSet found = navigableSet_find(sets, newSet); if (found == null) return false; if (l(found) == 1) sets.remove(found); else found.remove(a); --size; return true; } public A first() { return utils.first(utils.first(sets)); } public A last() { var last = sets.last(); return last == null ? null : last.last(); } public IterableIterator iterator() { return nestedIterator(sets, __1 -> __1.iterator()); } public int size() { return size; } public Set tiedForFirst() { return utils.first(sets); } public CompactLinkedHashSet probe(Object a) { return addAndReturnCollection(makeInnerSet(), (A) a); } public boolean contains(Object a) { return navigableSet_find(sets, probe(a)) != null; } } static public class ScreenOverlay implements AutoCloseable { public JWindow window; final public ScreenOverlay setBgColor(Color bgColor) { return bgColor(bgColor); } public ScreenOverlay bgColor(Color bgColor) { this.bgColor = bgColor; return this; } final public Color getBgColor() { return bgColor(); } public Color bgColor() { return bgColor; } public Color bgColor = colorWithAlpha(Color.blue, 0); final public ScreenOverlay setBounds(Rect bounds) { return bounds(bounds); } public ScreenOverlay bounds(Rect bounds) { this.bounds = bounds; return this; } final public Rect getBounds() { return bounds(); } public Rect bounds() { return bounds; } public Rect bounds; final public ScreenOverlay setHideOnMouseOver(boolean hideOnMouseOver) { return hideOnMouseOver(hideOnMouseOver); } public ScreenOverlay hideOnMouseOver(boolean hideOnMouseOver) { this.hideOnMouseOver = hideOnMouseOver; return this; } final public boolean getHideOnMouseOver() { return hideOnMouseOver(); } public boolean hideOnMouseOver() { return hideOnMouseOver; } public boolean hideOnMouseOver = false; final public ScreenOverlay setComponent(Component component) { return component(component); } public ScreenOverlay component(Component component) { this.component = component; return this; } final public Component getComponent() { return component(); } public Component component() { return component; } public Component component; public void show() { swing(() -> { if (window == null) { if (usingJTattoo()) warn("Screen overlays don't really work with JTattoo"); assertNotNull("bounds", bounds); window = new JWindow(); window.setBackground(bgColor); utils.setBounds(window, bounds); window.setAlwaysOnTop(true); if (component != null) window.add(component); disposeWindowOnClick(window); if (hideOnMouseOver) addMouseListener(getContentPane(window), new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { hide(); } }); } window.setVisible(true); }); } final public void close() { swing(() -> { hide(); }); } public void hide() { swing(() -> { if (window == null) return; window.setVisible(false); }); } public void daThing() { component(new JPanel() { public void paintComponent(Graphics g) { g.setColor(Color.RED); g.drawRect(0, 0, 511, 511); } }); } } static public class TimedCache { public long timeout; volatile public A value; public Object function; public long set; public Lock lock = lock(); public boolean keepValueWhileCalculating = false; public int stores, fails, hits; public TimedCache(double timeoutSeconds, IF0 function) { this(function, timeoutSeconds); } public TimedCache(double timeoutSeconds, Object function) { this(function, timeoutSeconds); } public TimedCache(IF0 function, double timeoutSeconds) { this((Object) function, timeoutSeconds); } public TimedCache(Object function, double timeoutSeconds) { this(timeoutSeconds); this.function = function; } public TimedCache(double timeoutSeconds) { timeout = toMS(timeoutSeconds); } public A set(A a) { Lock __0 = lock; lock(__0); try { ++stores; value = a; set = now(); return a; } finally { unlock(__0); } } public boolean has() { Lock __1 = lock; lock(__1); try { clean(); if (set != 0) { ++hits; return true; } ++fails; return false; } finally { unlock(__1); } } public A get() { Lock __2 = lock; lock(__2); try { if (function != null) return get(function); clean(); if (set != 0) ++hits; else ++fails; return value; } finally { unlock(__2); } } public A get(IF0 makerFunction) { return get((Object) makerFunction); } public A get(Object makerFunction) { Lock __3 = lock; lock(__3); try { if (keepValueWhileCalculating) { if (value == null || shouldClean()) set((A) callF(makerFunction)); return value; } else { return this.has() ? getNoClean() : set((A) callF(makerFunction)); } } finally { unlock(__3); } } public A getNoClean() { Lock __4 = lock; lock(__4); try { return value; } finally { unlock(__4); } } public void clean() { Lock __5 = lock; lock(__5); try { if (shouldClean()) clear(); } finally { unlock(__5); } } public boolean shouldClean() { return timeout > 0 && now() > set + timeout; } public void clear() { Lock __6 = lock; lock(__6); try { set = 0; value = null; } finally { unlock(__6); } } public String stats() { return "Stores: " + stores + ", hits: " + hits + ", fails: " + fails; } public A peek() { return value; } } static public interface ISetAndGet extends ISetter, IF0 { } static public class ToJava { public Object get(Object o) { { var __1 = getOpt(o); if (__1 != null) return __1; } throw fail("Can't ToJava: " + className(o)); } public Object getOpt(Object o) { if (o == null) return "null"; if (o instanceof String) return quote(o); if (o instanceof Number) return str(o); if (o instanceof IFieldsToList) return formatFunctionCall("new " + shortName((IFieldsToList) o), map(__149 -> get(__149), ((IFieldsToList) o)._fieldsToList())); if (o instanceof List) return functionCall_list("ll", map(__150 -> get(__150), (List) o)); if (o instanceof Class) return shortClassName((Class) o) + ".class"; if (o instanceof int[]) return "new int[] {" + joinWithComma(toList((int[]) o)) + "}"; return null; } } static public class JFFMPEGVideoPlayer extends JSelfSwingable { public ImageSurface imageSurface; public JPanel buttons = rightAlignedLine(); public JButton btnPlayPause = jDisabledButton("Pause", new Runnable() { public void run() { try { playPause(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "playPause();"; } }); public ImageStreamFromVideoFile stream; public long playStartTime; public BoolVar paused = new BoolVar(); public RSTVar imageToDisplay = new RSTVar<>(image -> imageSurface.setImage(image)); final public File getVideoFile() { return videoFile(); } public File videoFile() { return videoFile; } public File videoFile; transient public Set> onVideoStarted; public JFFMPEGVideoPlayer onVideoStarted(IVF1 f) { onVideoStarted = createOrAddToSyncLinkedHashSet(onVideoStarted, f); return this; } public JFFMPEGVideoPlayer removeVideoStartedListener(IVF1 f) { utils.remove(onVideoStarted, f); return this; } public void videoStarted(File videoFile) { if (onVideoStarted != null) for (var listener : onVideoStarted) pcallF_typed(listener, videoFile); } transient public Set> onUserSelectedVideo; public JFFMPEGVideoPlayer onUserSelectedVideo(IVF1 f) { onUserSelectedVideo = createOrAddToSyncLinkedHashSet(onUserSelectedVideo, f); return this; } public JFFMPEGVideoPlayer removeUserSelectedVideoListener(IVF1 f) { utils.remove(onUserSelectedVideo, f); return this; } public void userSelectedVideo(File videoFile) { if (onUserSelectedVideo != null) for (var listener : onUserSelectedVideo) pcallF_typed(listener, videoFile); } public void init() { imageSurface = doubleBufferedImageSurface(); imageSurface.setAutoZoomToDisplay(true); buttons.add(btnPlayPause); buttons.add(jbutton("Open video...", runnableThread(new Runnable() { public void run() { try { openDialog(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "openDialog();"; } }))); bindToComponent(imageSurface, null, runnableThread(new Runnable() { public void run() { try { closeStream(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "closeStream();"; } })); setComponent(centerAndSouth(jscroll_center_borderless(imageSurface), withMargin(buttons))); } public JFFMPEGVideoPlayer standardZoom() { imageSurface.standardZoom(); return this; } public JFFMPEGVideoPlayer() { init(); } public JFFMPEGVideoPlayer(File videoFile) { init(); if (videoFile != null) onFirstShow(imageSurface, () -> play(videoFile)); } public void openDialog() { swing(() -> { JFileChooser fc = new JFileChooser(); fc.setDialogTitle("Open video"); fc.setCurrentDirectory(dirToOpen()); File videoFile = execFileChooser(fc); if (videoFile == null) return; print("openDialog " + nListeners(onUserSelectedVideo)); userSelectedVideo(videoFile); play(videoFile); }); } public File dirToOpen() { if (videoFile != null) return dirOfFile(videoFile); return videosDir(); } public void play(File videoFile) { printCommaCombine("JFFMPEGVideoPlayer.play " + videoFile, nListeners(onVideoStarted)); if (!isFile(videoFile)) { print("Not a file"); return; } { startThread(new Runnable() { public void run() { try { if (videoFile == null) return; JFFMPEGVideoPlayer.this.videoFile = videoFile; try { closeStream(); stream = new ImageStreamFromVideoFile(); stream.open(videoFile); stream.onHaveImage((image, pos) -> { waitWhileTrue(paused); if (playStartTime == 0 || playStartTime + pos.toMillis() < sysNow()) playStartTime = sysNow() - pos.toMillis(); else sleepUntilSysTime(playStartTime + pos.toMillis()); possiblyDisplay(image); }); paused.set(false); enableButton(btnPlayPause); stream.startDecodeThread(); videoStarted(videoFile); } catch (Throwable __e) { infoBox(__e); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (videoFile == null) return;\r\n JFFMPEGVideoPlayer.this.videoFile = vid..."; } }); } } public void possiblyDisplay(BufferedImage image) { imageToDisplay.set(cloneBufferedImage(image)); } public void closeStream() { disableButton(btnPlayPause); possiblyDisplay(whiteImage(10)); { cleanUp(stream); stream = null; } playStartTime = 0; } public void playPause() { swing(() -> { paused.set(!paused.get()); setText(btnPlayPause, paused.get() ? "Play" : "Pause"); }); } } abstract static public class AbstractSSI extends AbstractHasHi15Color implements G2Drawable, HasBounds, SizeInInts, StringIO, INumberOfPixels { public AbstractSSI() { } final public SSI render() { return toSSI(); } abstract public SSI toSSI(); public void copyAbstractSSI(AbstractSSI dest) { dest.hi15color(hi15color); } public double compressibility() { return doubleRatio(numberOfPixels(), sizeInInts()); } public AbstractSSI reduceToInts(int ints) { return null; } } static public class RSyntaxTextAreaWithSearch implements SearchListener, Swingable { public JPanel panel; final public RSyntaxTextArea getTextArea() { return textArea(); } public RSyntaxTextArea textArea() { return textArea; } volatile public RSyntaxTextArea textArea; public CollapsibleSectionPanel csp; public FindDialog findDialog; public ReplaceDialog replaceDialog; public FindToolBar findToolBar; public ReplaceToolBar replaceToolBar; public StatusBar statusBar; public RSyntaxTextAreaWithSearch() { init(); } public RSyntaxTextAreaWithSearch(IF1 wrapStatusLabel) { this.wrapStatusLabel = wrapStatusLabel; init(); } public RSyntaxTextAreaWithSearch(String text) { init(); setText(text); } public RSyntaxTextAreaWithSearch(RSyntaxTextArea textArea) { this.textArea = textArea; init(); } public JComponent visualize() { return panel; } public void init() { swing(() -> { rsyntaxTextArea_fixNumPad(); initSearchDialogs(); panel = new JPanel(new BorderLayout()); csp = new CollapsibleSectionPanel(); panel.add(csp); if (textArea == null) textArea = javaxSyntaxTextArea(); RTextScrollPane sp = new RTextScrollPane(textArea); csp.add(sp); ErrorStrip errorStrip = new ErrorStrip(textArea); panel.add(errorStrip, BorderLayout.LINE_END); statusBar = new StatusBar(); panel.add(statusBar, BorderLayout.SOUTH); }); } transient public IF1 wrapStatusLabel; public JComponent wrapStatusLabel(JComponent label) { return wrapStatusLabel != null ? wrapStatusLabel.get(label) : wrapStatusLabel_base(label); } final public JComponent wrapStatusLabel_fallback(IF1 _f, JComponent label) { return _f != null ? _f.get(label) : wrapStatusLabel_base(label); } public JComponent wrapStatusLabel_base(JComponent label) { return label; } public void addItem(Action a, ButtonGroup bg, JMenu menu) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(a); bg.add(item); menu.add(item); } public void menuLessOperation() { swing(() -> { var mb = createMenuBar(); for (var menu : getMenus(mb)) for (var menuItem : getMenuItems(menu)) { var ks = menuItem.getAccelerator(); if (ks != null) { var action = menuItem.getAction(); textArea.getInputMap().put(ks, action); } } }); } public JMenuBar createMenuBar() { JMenuBar mb = new JMenuBar(); JMenu menu = new JMenu("Search"); menu.add(new JMenuItem(new ShowFindDialogAction())); menu.add(new JMenuItem(new ShowReplaceDialogAction())); menu.add(new JMenuItem(new GoToLineAction())); menu.addSeparator(); int ctrl = getToolkit().getMenuShortcutKeyMask(); int shift = InputEvent.SHIFT_MASK; KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_F, ctrl | shift); Action a = csp.addBottomComponent(ks, findToolBar); a.putValue(Action.NAME, "Show Find Search Bar"); menu.add(new JMenuItem(a)); ks = KeyStroke.getKeyStroke(KeyEvent.VK_H, ctrl | shift); a = csp.addBottomComponent(ks, replaceToolBar); a.putValue(Action.NAME, "Show Replace Search Bar"); menu.add(new JMenuItem(a)); mb.add(menu); return mb; } public String getSelectedText() { return textArea.getSelectedText(); } public void initSearchDialogs() { findDialog = new FindDialog((java.awt.Dialog) null, this); replaceDialog = new ReplaceDialog((java.awt.Dialog) null, this); SearchContext context = findDialog.getSearchContext(); replaceDialog.setSearchContext(context); findToolBar = new FindToolBar(this); findToolBar.setSearchContext(context); replaceToolBar = new ReplaceToolBar(this); replaceToolBar.setSearchContext(context); } @Override public void searchEvent(SearchEvent e) { SearchEvent.Type type = e.getType(); SearchContext context = e.getSearchContext(); SearchResult result = null; switch(type) { default: case MARK_ALL: result = SearchEngine.markAll(textArea, context); break; case FIND: result = SearchEngine.find(textArea, context); if (!result.wasFound()) { Caret c = textArea.getCaret(); int pos = c.getDot(); if (context.getSearchForward()) { c.setDot(0); } else { c.setDot(textArea.getDocument().getLength()); } result = SearchEngine.find(textArea, context); if (!result.wasFound()) { c.setDot(pos); UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } break; case REPLACE: result = SearchEngine.replace(textArea, context); if (!result.wasFound()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } break; case REPLACE_ALL: result = SearchEngine.replaceAll(textArea, context); JOptionPane.showMessageDialog(null, result.getCount() + " occurrences replaced."); break; } String text = null; if (result.wasFound()) { text = "Text found; occurrences marked: " + result.getMarkedCount(); } else if (type == SearchEvent.Type.MARK_ALL) { if (result.getMarkedCount() > 0) { text = "Occurrences marked: " + result.getMarkedCount(); } else { text = ""; } } else { text = "Text not found"; } setStatus(text); } public class GoToLineAction extends AbstractAction { public GoToLineAction() { super("Go To Line..."); int c = getToolkit().getMenuShortcutKeyMask(); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_L, c)); } public void actionPerformed(ActionEvent e) { findDialog.setVisible(false); replaceDialog.setVisible(false); GoToDialog dialog = new GoToDialog((java.awt.Dialog) null); dialog.setMaxLineNumberAllowed(textArea.getLineCount()); showDialogOnSameScreen(dialog, panel); int line = dialog.getLineNumber(); if (line > 0) { try { textArea.setCaretPosition(textArea.getLineStartOffset(line - 1)); } catch (BadLocationException ble) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); ble.printStackTrace(); } } } } public class ShowFindDialogAction extends AbstractAction { public ShowFindDialogAction() { super("Find..."); int c = getToolkit().getMenuShortcutKeyMask(); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, c)); } public void actionPerformed(ActionEvent e) { replaceDialog.setVisible(false); showDialogOnSameScreen(findDialog, panel); } } public class ShowReplaceDialogAction extends AbstractAction { public ShowReplaceDialogAction() { super("Replace..."); int c = getToolkit().getMenuShortcutKeyMask(); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_H, c)); } public void actionPerformed(ActionEvent e) { findDialog.setVisible(false); showDialogOnSameScreen(replaceDialog, panel); } } public class StatusBar extends JPanel { public JLabel label; public StatusBar() { label = new JLabel(" "); setLayout(new BorderLayout()); add(wrapStatusLabel(label), BorderLayout.CENTER); add(new JLabel(new SizeGripIcon()), BorderLayout.EAST); } public void setText(String label) { utils.setText(this.label, shorten(1000, label)); } } public void setStatus(String text) { statusBar.setText(text); } public void setText(String text) { utils.setText(textArea, text); } public String getText() { return utils.getText(textArea); } public void setEditorFont(final Font font) { swing(() -> { SyntaxScheme ss = textArea.getSyntaxScheme(); ss = (SyntaxScheme) ss.clone(); for (int i = 0; i < ss.getStyleCount(); i++) if (ss.getStyle(i) != null) ss.getStyle(i).font = font; textArea.setSyntaxScheme(ss); textArea.setFont(font); }); } public Font getEditorFont() { return swing(new F0() { public Font get() { try { return textArea.getFont(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return textArea.getFont();"; } }); } public int getEditorFontSize() { return getEditorFont().getSize(); } public void setEditorFontSize(int size) { setEditorFont(deriveFont(getEditorFont(), size)); } public RSyntaxDocument getDocument() { return (RSyntaxDocument) textArea.getDocument(); } public Toolkit getToolkit() { return panel.getToolkit(); } public JLabel statusLabel() { return statusBar.label; } } static public class InterpolatedDoubleArray implements IntSize { public InterpolatedDoubleArray() { } public int[] indices; public double[] values; public InterpolatedDoubleArray(int[] indices, double[] values) { this.values = values; this.indices = indices; } final public int length() { return size(); } public int size() { return empty(indices) ? 0 : last(indices) + 1; } public int nPillars() { return l(indices); } final public double[] get() { return toDoubleArray(); } public double[] toDoubleArray() { int n = length(); double[] array = new double[n]; for (int i = 0; i < indices.length; i++) { int iEnd = indices[i]; double value = values[i]; array[iEnd] = value; if (i > 0) { int iStart = indices[i - 1]; if (iStart + 1 < iEnd) { double startValue = values[i - 1]; double step = (value - startValue) / (iEnd - iStart), val = startValue; for (int j = iStart + 1; j < iEnd; j++) { val += step; array[j] = val; } } } } return array; } public int[] rounded() { return iroundDoubleArray(get()); } public double[] indicesAndValues() { int n = nPillars(); double[] array = new double[n * 2]; for (int i = 0; i < n; i++) { array[i * 2] = indices[i]; array[i * 2 + 1] = values[i]; } return array; } public double[] indicesAndValues_withoutFirstAndLastIndex() { int n = nPillars(); double[] array = new double[max(1, n * 2 - 2)]; int j = 0; for (int i = 0; i < n; i++) { if (i != 0 && i != n - 1) array[j++] = indices[i]; array[j++] = values[i]; } return array; } public int nInts_withoutFirstAndLastIndex() { return max(1, nPillars() * 2 - 2); } public int nInts() { return nPillars() * 2; } public InterpolatedDoubleArray topPart(int nPillars) { return new InterpolatedDoubleArray(takeFirst(nPillars, indices), takeFirst(nPillars, values)); } } static public class QuickException extends RuntimeException { public Throwable fillInStackTrace() { return this; } public QuickException() { } public QuickException(Throwable e) { super(e); } public QuickException(String msg) { super(msg); } public QuickException(String msg, Throwable e) { super(msg, e); } } static public class SynchronizedSet extends SynchronizedCollection implements Set { public SynchronizedSet() { } public SynchronizedSet(Set s) { super(s); } public SynchronizedSet(Set s, Object mutex) { super(s, mutex); } public boolean equals(Object o) { if (this == o) return true; synchronized (mutex) { return c.equals(o); } } public int hashCode() { synchronized (mutex) { return c.hashCode(); } } } static public class JObjectTable implements Swingable { public List data = new ArrayList(); transient public IF1 itemToMap; transient public Set hideFields; transient public boolean debug, fieldsInOrder = true, withSearcher; final public JObjectTable setDefaultAction(IVF1 defaultAction) { return defaultAction(defaultAction); } public JObjectTable defaultAction(IVF1 defaultAction) { this.defaultAction = defaultAction; return this; } final public IVF1 getDefaultAction() { return defaultAction(); } public IVF1 defaultAction() { return defaultAction; } public IVF1 defaultAction; final public JTable getTable() { return table(); } public JTable table() { return table; } transient public JTable table; transient public TableSearcher searcher; transient public boolean useStruct = false; transient public Set onListChanged; public JObjectTable onListChanged(Runnable r) { onListChanged = createOrAddToSyncLinkedHashSet(onListChanged, r); return this; } public JObjectTable removeListChangedListener(Runnable r) { utils.remove(onListChanged, r); return this; } public void listChanged() { if (onListChanged != null) for (var listener : onListChanged) pcallF_typed(listener); } public JObjectTable() { itemToMap = a -> { if (a instanceof String) return litorderedmap("", (String) a); Map map = humanizeKeys(fieldsInOrder ? objectToMap_inOrder_withoutFields(a, hideFields) : objectToMap(a)); if (!useStruct) map = mapValues(__151 -> strOrEmpty(__151), map); return map; }; } public void onListChangedAndNow(Runnable r) { if (r == null) return; onListChanged(r); r.run(); } public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { List l = map(itemToMap, data); table = dataToTable_uneditable(sexyTable(), l); onDoubleClickOrEnter(table, new VF1() { public void get(Integer row) { try { A a = _get(data, row); if (a != null) { if (defaultAction != null) defaultAction.get(a); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "A a = _get(data, row);\r\n if (a != null) defaultAction?.get(a);"; } }); if (withSearcher) return (searcher = tableWithSearcher2(table)).panel; return jscroll(table); } public void updateTable() { if (table != null) { swing(() -> { Point scrollPosition = enclosingViewPosition(table); if (debug) print("Scroll position: " + scrollPosition); dataToTable_uneditable(table, map(itemToMap, data)); setEnclosingViewPosition(table, scrollPosition); if (searcher != null) searcher.rowIndices = null; if (debug) print("dataToTable done, alerting " + n2(onListChanged, "listener")); }); } listChanged(); } public void clear() { syncClear(data); fireDataChanged(); } public void add(A a) { syncAdd(data, a); fireDataChanged(); } public A addAndReturn(A a) { add(a); return a; } public void add(int idx, A a) { syncAdd(data, idx, a); fireDataChanged(); } public void addAll(Collection l) { if (empty(l)) return; syncAddAll(data, l); fireDataChanged(); } public void addAndScrollDown(A a) { add(a); scrollDown(); } public void remove(A a) { syncRemove(data, a); fireDataChanged(); } public void removeAll(List a) { syncRemoveAll(data, a); fireDataChanged(); } public void setList(Iterable data) { setData(data); } public void removeSelected() { removeAll(allSelected()); } public void setData(Iterable data) { setData(data, false); } public void setData(Iterable data, boolean force) { { swing(() -> { int[] selection = selectedTableRows_array(table); List cloned = cloneList(data); if (force || !eq(this.data, cloned)) { this.data = cloned; updateTable(); } selectTableRows(table, selection); }); } } public int count() { return syncL(data); } public void setData_force(Iterable data) { setData(data, true); } public void fireDataChanged() { setData_force(data); } public int rowFromSearcher(int i) { return searcher == null || searcher.rowIndices == null ? i : or(get(searcher.rowIndices, i), -1); } public A selected() { return syncGet(data, rowFromSearcher(selectedTableRowInModel(table))); } public List allSelected() { return syncListGetMulti(data, selectedIndices()); } public int selectedIndex() { return selectedTableRow(table); } public List selectedIndices() { return map(i -> rowFromSearcher(i), selectedTableRowsInModel(table)); } public boolean selectItem(A a) { int i = indexOf(data, a); selectRow(table, i); return i >= 0; } public void doubleClickItem(A a) { if (selectItem(a)) { if (defaultAction != null) defaultAction.get(a); } } public void popupMenuItem(String text, IVF1 r) { tablePopupMenuItemsThreaded(table, text, _convertRunnable(r)); } public void popupMenuItem_top(String text, IVF1 r) { tablePopupMenuItemsThreaded_top(table, text, _convertRunnable(r)); } public IVF1 _convertRunnable(IVF1 r) { return r == null ? null : idx -> r.get(syncGet(data, idx)); } public void hideFields(String... fields) { if (hideFields == null) hideFields = new HashSet(); _addAll(hideFields, fields); } public A getRow(int row) { return get(data, row); } public void scrollDown() { scrollTableDownNow(table); } public void onSelect(IVF1 r) { visualize(); onTableSelectionChanged(table, () -> pcallF_typed(r, selected())); } public List getList() { return data; } } static public class ProbabilisticList extends RandomAccessAbstractList> { public Map probabilities = hashMap(); public MultiSetMap byProbability = multiSetMap_outerDescTreeMap_innerCompactLinkedHashSet(); public List> list; public double cutoffProbabilityOnAdd = 0; public Collection> listeners; public ProbabilisticList() { } public ProbabilisticList(Iterable> l) { utils.addAll(this, l); } public synchronized WithProbability get(int idx) { if (idx < 0 || idx >= size()) return null; makeListUpToIndex(idx); return list.get(idx); } public synchronized int size() { return l(probabilities); } public void makeListUpToIndex(int idx) { if (idx < l(list)) return; if (list == null) list = new ArrayList(); WithProbability lastEntry = utils.last(list); A a = lastEntry == null ? null : lastEntry.get(); double probability = lastEntry == null ? 0 : lastEntry.probability(); while (idx >= l(list)) { if (a == null) { probability = byProbability.firstKey(); a = first(byProbability.get(probability)); } else { CompactLinkedHashSet setForProbability = (CompactLinkedHashSet) (byProbability.get(probability)); a = setForProbability.nextElement(a); if (a == null) { probability = byProbability.higherKey(probability); a = first(byProbability.get(probability)); } } list.add(new WithProbability(probability, a)); } } synchronized public boolean containsElement(A a) { return probabilities.containsKey(a); } final public boolean put(A a, double probability) { return add(a, probability); } public boolean add(A a, double probability) { return add(new WithProbability(probability, a)); } public boolean add(WithProbability wp) { A a; double newP; synchronized (this) { if (wp == null || wp.probability() <= cutoffProbabilityOnAdd) return false; a = wp.get(); newP = wp.probability(); Double oldP = probabilities.get(a); if (oldP != null) { if (oldP.doubleValue() >= newP) return false; else remove(new WithProbability(oldP, a)); } clearListFrom(newP); probabilities.put(a, newP); byProbability.add(newP, a); } fireElementAdded(a, newP); return true; } @Override public boolean remove(Object wp) { if (wp == null) return false; return removeElement(((WithProbability) wp).get()); } public synchronized boolean removeElement(A a) { if (a == null) return false; Double oldP = probabilities.get(a); if (oldP == null) return false; clearListFrom(oldP); probabilities.remove(a); byProbability.remove(oldP, a); return true; } @Override public synchronized WithProbability remove(int idx) { var a = get(idx); remove(a); return a; } public void clearListFrom(double p) { int idx = generalizedBinarySearch2(list, a -> a.probability() <= p ? 1 : -1); idx = -idx - 1; truncateList(list, idx); } public void at(double p, A a) { add(new WithProbability(p, a)); } public void truncate(int size) { if (size < 0) throw fail(); while (size() > size) removeLast(); } public double getProbability(A a) { return orZero(probabilities.get(a)); } public void truncateBelow(double thresholdProbability) { A a; while ((a = last()) != null && getProbability(a) < thresholdProbability) removeElement(a); } public A last() { Double last = byProbability.lastKey(); if (last == null) return null; CompactLinkedHashSet set = (CompactLinkedHashSet) (byProbability.getOpt(last)); return set.last(); } public void removeLast() { removeElement(last()); } public int indexOfElement(A a) { double p = getProbability(a); if (p == 0) return -1; int n = size(); for (int i = 0; i < n; i++) if (eq(a, get(i).get())) return i; throw fail("Internal error"); } final public List elementsOnly() { return rawList(); } public List rawList() { return lazyMap_noSave(this, a -> a.get()); } public List probabilities() { return lazyMap_noSave(this, a -> a.probability()); } public List> listenersList() { if (listeners == null) return null; synchronized (this) { return cloneList(listeners); } } public void fireElementAdded(A a, double probability) { utils.forEach(listenersList(), l -> l.elementAdded(a, probability)); } synchronized public void addListener(ProbabilisticListListener l) { listeners = addOrCreate(listeners, l); } synchronized public void removeListener(ProbabilisticListListener l) { { if (listeners != null) listeners.remove(l); } } public void onElementAdded(IVF2 f) { if (f != null) addListener(new ProbabilisticListAdapter() { @Override public void elementAdded(A a, double probability) { f.get(a, probability); } }); } } static public interface Steppable { public boolean step(); } public interface G2Drawable { public void drawOn(Graphics2D g); default public void drawOn(BufferedImage img) { drawOn(img.createGraphics()); } } static public class UIURLSystem extends MetaWithChangeListeners implements IFieldsToList { transient public Enterable owner; transient public SimpleLiveValue uiURL; public UIURLSystem() { } public UIURLSystem(Enterable owner, SimpleLiveValue uiURL) { this.uiURL = uiURL; this.owner = owner; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + owner + ", " + uiURL + ")"; } public Object[] _fieldsToList() { return new Object[] { owner, uiURL }; } final public UIURLSystem setShowHomeButton(boolean showHomeButton) { return showHomeButton(showHomeButton); } public UIURLSystem showHomeButton(boolean showHomeButton) { this.showHomeButton = showHomeButton; return this; } final public boolean getShowHomeButton() { return showHomeButton(); } public boolean showHomeButton() { return showHomeButton; } public boolean showHomeButton = true; final public UIURLSystem setMaxHistoryEntries(int maxHistoryEntries) { return maxHistoryEntries(maxHistoryEntries); } public UIURLSystem maxHistoryEntries(int maxHistoryEntries) { this.maxHistoryEntries = maxHistoryEntries; return this; } final public int getMaxHistoryEntries() { return maxHistoryEntries(); } public int maxHistoryEntries() { return maxHistoryEntries; } public int maxHistoryEntries = 100; final public UIURLSystem setShowGoButton(boolean showGoButton) { return showGoButton(showGoButton); } public UIURLSystem showGoButton(boolean showGoButton) { this.showGoButton = showGoButton; return this; } final public boolean getShowGoButton() { return showGoButton(); } public boolean showGoButton() { return showGoButton; } public boolean showGoButton = false; transient public Map uiMap = syncCIMap(); public List preferredURLs = syncList(); public List history = syncLinkedList(); public List forwardHistory = syncLinkedList(); static public class Entry { public String url; public String toolTip; public IF0 makeComponent; public Entry(String url, IF0 makeComponent) { this.makeComponent = makeComponent; this.url = url; } public Entry(String url, String toolTip, IF0 makeComponent) { this.makeComponent = makeComponent; this.toolTip = toolTip; this.url = url; } } final public UIURLSystem setScp(SingleComponentPanel scp) { return scp(scp); } public UIURLSystem scp(SingleComponentPanel scp) { this.scp = scp; return this; } final public SingleComponentPanel getScp() { return scp(); } public SingleComponentPanel scp() { return scp; } transient public SingleComponentPanel scp; transient public JComboBox comboBox; transient public JButton btnHome, btnBack, btnForward; transient public JComponent urlBar_cache; public JComponent urlBar() { if (urlBar_cache == null) urlBar_cache = urlBar_load(); return urlBar_cache; } public JComponent urlBar_load() { comboBox = jcombobox(urlsForComboBox()); comboBox.setRenderer(new CenteredComboBoxRenderer(new ListCellRendererWithToolTip(url -> toolTipForURL(url), (ListCellRenderer) comboBox.getRenderer()))); onSelectedItem(bindComboBoxToLiveValue(comboBox, uiURL), url -> showUIURL(url)); Runnable cbAction = comboBoxAction(comboBox, url -> showUIURL(url)); JPanel rightButtons = jlineWithSpacing(5); JPanel leftButtons = jlineWithSpacing(5); if (showGoButton) rightButtons.add(jbutton("Go", cbAction)); JComponent panel = withLabel("Show", centerAndEastWithMargin(comboBox, rightButtons)); btnBack = jimageButtonScaledToWidth(16, "#1103102", () -> goBack()); add(rightButtons, btnBack); btnForward = jimageButtonScaledToWidth(16, "#1103103", () -> goForward()); add(rightButtons, btnForward); if (showHomeButton) { String homeURL = homeURL(); btnHome = jimageButtonScaledToWidth(16, "#1103101", homeURL != null ? "Go to " + homeURL : "Go to home URL", () -> goHome()); add(rightButtons, btnHome); } uiURL.onChangeAndNow(() -> updateButtons()); if (!emptyContainer(leftButtons)) panel = westAndCenterWithMargin(leftButtons, panel); return panel; } public void updateButtons() { { swing(() -> { String homeURL = homeURL(); setEnabled(btnHome, homeURL != null && !eq(homeURL, url())); String backURL = last(history); setEnabled(btnBack, backURL != null); setToolTip(btnBack, backURL == null ? "Go back" : "Go back to " + backURL); String forwardURL = first(forwardHistory); printVars("updateButtons", "forwardURL", forwardURL); setEnabled(btnForward, forwardURL != null); setToolTip(btnForward, forwardURL == null ? "Go forward" : "Go forward to " + forwardURL); }); } change(); } final public JComponent renderUIURL(String url) { return renderUIUrl(url); } final public JComponent uiGet(String url) { return renderUIUrl(url); } public JComponent renderUIUrl(String url) { try { AutoCloseable __1 = tempEnter(owner); try { var entry = uiMap.get(url); if (entry == null) return jCenteredLabel("URL not found: " + url); var component = entry.makeComponent.get(); return component; } finally { _close(__1); } } catch (Throwable e) { printStackTrace(e); return jErrorView(e); } } public boolean hasURL(String url) { return uiMap.containsKey(url); } public void showUIURL(String url) { swing(() -> { if (!eqic(url(), url)) { addToHistory(url()); showUIURL_dontAddToHistory(url); } }); } public void addToHistory(String url) { printVars("addToHistory", "url", url); if (empty(url) || eqic(last(history), url)) return; removeAllIC_useIterator(history, url); history.add(url); if (l(history) > maxHistoryEntries) removeFirst(history); forwardHistory.clear(); updateButtons(); } public void showUIURL_dontAddToHistory(String url) { AutoCloseable __2 = tempEnter(owner); try { setURL(trim(url)); go(); } finally { _close(__2); } } public void go() { setComponent(scp, renderUIUrl(url())); } public String url() { return uiURL.get(); } public void setURL(String url) { assertURLValid(url); uiURL.set(url); } transient public IVF1 assertURLValid; public void assertURLValid(String url) { if (assertURLValid != null) assertURLValid.get(url); else assertURLValid_base(url); } final public void assertURLValid_fallback(IVF1 _f, String url) { if (_f != null) _f.get(url); else assertURLValid_base(url); } public void assertURLValid_base(String url) { if (!uiMap.containsKey(url)) throw fail("UIURL not found: " + url); } public UIURLSystem put(WithToolTip url, IF0 maker) { return put(url.get(), url.toolTip(), maker); } public UIURLSystem put(String url, IF0 maker) { return put(url, null, maker); } public UIURLSystem put(String url, String toolTip, IF0 maker) { uiMap.put(url, new Entry(url, toolTip, maker)); setComboBoxItems(comboBox, urlsForComboBox()); return this; } public String toolTipForURL(String url) { var e = uiMap.get(url); return e == null ? null : e.toolTip; } public List urlsForComboBox() { var sorted = cloneKeys(uiMap); return concatLists(listSetIntersection(preferredURLs, sorted), sorted); } public void addPreferredUIURL(String uiURL) { addIfNotContained(preferredURLs, uiURL); } public String homeURL() { return first(preferredURLs); } public void goHome() { showUIURL(homeURL()); } public void goBack() { swing(() -> { String url = popLast(history); if (url != null) { String currentURL = url(); if (nempty(currentURL)) forwardHistory.add(0, currentURL); printVars("goBack", "url", url, "currentURL", currentURL, "forwardHistory", forwardHistory); updateButtons(); showUIURL_dontAddToHistory(url); } }); } public void goForward() { swing(() -> { String url = popFirst(forwardHistory); if (url != null) { String currentURL = url(); if (nempty(currentURL)) history.add(currentURL); printVars("goForward", "url", url, "currentURL", currentURL, "history", history); updateButtons(); showUIURL_dontAddToHistory(url); } }); } } abstract static public class ImageSurfaceMouseHandler extends MouseAdapter implements AutoCloseable { public ImageSurface is; public void register(ImageSurface is) { this.is = is; is.tools.add(this); is.addMouseListener(this); is.addMouseMotionListener(this); } public void close() { try { if (is == null) return; is.tools.remove(this); is.removeMouseListener(this); is.removeMouseMotionListener(this); is = null; } catch (Exception __e) { throw rethrow(__e); } } public Pt getPt(MouseEvent e) { return toPt(getPoint(e)); } public Point getPoint(MouseEvent e) { return new Point((int) (e.getX() / is.getZoomX()), (int) (e.getY() / is.getZoomY())); } public ImageSurface getImageSurface() { return is; } } static public class Pair implements Comparable> { final public Pair setA(A a) { return a(a); } public Pair a(A a) { this.a = a; return this; } final public A getA() { return a(); } public A a() { return a; } public A a; final public Pair setB(B b) { return b(b); } public Pair b(B b) { this.b = b; return this; } final public B getB() { return b(); } public B b() { return b; } public B b; public Pair() { } public Pair(A a, B b) { this.b = b; this.a = a; } public int hashCode() { return hashCodeFor(a) + 2 * hashCodeFor(b); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Pair)) return false; Pair t = (Pair) o; return eq(a, t.a) && eq(b, t.b); } public String toString() { return "<" + a + ", " + b + ">"; } public int compareTo(Pair p) { if (p == null) return 1; int i = ((Comparable) a).compareTo(p.a); if (i != 0) return i; return ((Comparable) b).compareTo(p.b); } } static public interface Swingable { public JComponent visualize(); } static public class FastDownscale2x2 { static final public int scaleX = 2, scaleY = scaleX; public int w, h, w2, h2; public int[] finalPixels; public void scaleDown(BufferedImage img) { scaleDown(utils.grabbableIntPixels_fastOrSlow(img)); } public void scaleDown(GrabbableIntPixels gp) { w = gp.w; int h = this.h = gp.h; int w2 = this.w2 = w / scaleX, h2 = this.h2 = h / scaleY; int stride = gp.scanlineStride; int scaleArea = scaleX * scaleY; int[] newPixels = finalPixels = new int[w2 * h2]; int iRow = gp.offset, iOut = 0; int[] pixels = gp.data; for (int y = 0; y < h2; y++) { int iIn = iRow; for (int x = 0; x < w2; x++) { int r = 0, g = 0, b = 0; int iSub = iIn; for (int subY = 0; subY < scaleY; subY++) { for (int subX = 0; subX < scaleX; subX++) { int rgb = pixels[iSub + subX]; r += (rgb >> 16) & 0xFF; g += (rgb >> 8) & 0xFF; b += rgb & 0xFF; } iSub += stride; } iIn += scaleX; newPixels[iOut++] = rgbIntFullAlpha(r / scaleArea, g / scaleArea, b / scaleArea); } iRow += stride * scaleY; } } public BufferedImage get(BufferedImage img) { scaleDown(img); return get(); } public BufferedImage get() { return bufferedImage(w2, h2, finalPixels); } public GrabbableIntPixels grabbableIntPixels() { return new GrabbableIntPixels(finalPixels, w2, h2, 0, w2); } } static public class SingleThreadProfiler extends AbstractProfiler { final public SingleThreadProfiler setThreadToSample(Thread threadToSample) { return threadToSample(threadToSample); } public SingleThreadProfiler threadToSample(Thread threadToSample) { this.threadToSample = threadToSample; return this; } final public Thread getThreadToSample() { return threadToSample(); } public Thread threadToSample() { return threadToSample; } public Thread threadToSample = currentThread(); public String toString() { return threadToSample == null ? shortClassName(this) : "Profiler for " + threadToSample; } public void stepImpl() { samples++; StackTraceElement[] stackTrace = threadToSample.getStackTrace(); if (skipSleeping && !isThreadRunnable_x(stackTrace)) return; Lock __0 = lock; lock(__0); try { addSample(stackTrace); } finally { unlock(__0); } } @Override public void assertCanStart() { assertNotNull("threadToSample", threadToSample); } } static public class Percent implements IFieldsToList { public double percent; public Percent() { } public Percent(double percent) { this.percent = percent; } public boolean equals(Object o) { if (!(o instanceof Percent)) return false; Percent __1 = (Percent) o; return percent == __1.percent; } public int hashCode() { int h = 985725989; h = boostHashCombine(h, _hashCode(percent)); return h; } public Object[] _fieldsToList() { return new Object[] { percent }; } static public Percent fromRatio(double ratio) { return new Percent(ratio * 100); } static public Percent fromRatio(double x, double y) { return fromRatio(doubleRatio(x, y)); } public void set(double percent) { percent = percent; } public double get() { return percent; } public String toString() { return renderValue(percent) + " %"; } public String renderValue(double percent) { return formatDouble(percent, 1); } final public String withDecimals(int decimals) { return renderWithDecimals(decimals); } public String renderWithDecimals(int decimals) { return formatDouble(percent, decimals) + " %"; } public String withExactDecimals(int decimals) { return formatDoubleX(percent, decimals) + " %"; } public String oneDecimal() { return withDecimals(1); } public String exactlyOneDecimal() { return withExactDecimals(1); } static public Percent ratio(double x, double y) { return new Percent(doubleRatio(x, y) * 100); } } static public class RSTADummyParser extends org.fife.ui.rsyntaxtextarea.parser.AbstractParser { final public Pair> getErrors() { return errors(); } public Pair> errors() { return errors; } public Pair> errors; static public class Error { final public Error setStart(LineAndColumn start) { return start(start); } public Error start(LineAndColumn start) { this.start = start; return this; } final public LineAndColumn getStart() { return start(); } public LineAndColumn start() { return start; } public LineAndColumn start; final public Error setEnd(LineAndColumn end) { return end(end); } public Error end(LineAndColumn end) { this.end = end; return this; } final public LineAndColumn getEnd() { return end(); } public LineAndColumn end() { return end; } public LineAndColumn end; final public Error setMsg(String msg) { return msg(msg); } public Error msg(String msg) { this.msg = msg; return this; } final public String getMsg() { return msg(); } public String msg() { return msg; } public String msg; } @Override public org.fife.ui.rsyntaxtextarea.parser.ParseResult parse(RSyntaxDocument doc, String style) { var result = new org.fife.ui.rsyntaxtextarea.parser.DefaultParseResult(this); try { var p = this.errors; if (p == null) return result; String src = p.a; var errors = p.b; if (empty(errors)) return result; String text = doc.getText(0, doc.getLength()); if (!eq(text, src)) { return result; } for (Error e : errors) { LineAndColumn start = e.start; LineAndColumn end = e.end; int lineStart = lineNrToCharIndex(text, start.line); int lineLength = lengthOfLine(text, start.line - 1); result.addNotice(new org.fife.ui.rsyntaxtextarea.parser.DefaultParserNotice(this, e.msg, start.line - 1, lineStart, lineLength)); } } catch (Throwable __e) { pcallFail(__e); } return result; } public void setErrors(String text, List errors, RSyntaxTextArea textArea) { this.errors = pair(text, errors); { swing(() -> { textArea.forceReparsing(RSTADummyParser.this); }); } } public void install(RSyntaxTextArea textArea) { swing(() -> { textArea.addParser(RSTADummyParser.this); }); } } static public class LineAndColumn implements IFieldsToList { static final public String _fieldOrder = "line col getLineText"; public int line; public int col; public LineAndColumn() { } public LineAndColumn(int line, int col) { this.col = col; this.line = line; } public boolean equals(Object o) { if (!(o instanceof LineAndColumn)) return false; LineAndColumn __1 = (LineAndColumn) o; return line == __1.line && col == __1.col; } public int hashCode() { int h = -1128952231; h = boostHashCombine(h, _hashCode(line)); h = boostHashCombine(h, _hashCode(col)); return h; } public Object[] _fieldsToList() { return new Object[] { line, col }; } transient public IF1 getLineText; public String getLineText(int line) { return getLineText != null ? getLineText.get(line) : getLineText_base(line); } final public String getLineText_fallback(IF1 _f, int line) { return _f != null ? _f.get(line) : getLineText_base(line); } public String getLineText_base(int line) { return null; } public String toString() { return "Line " + n2(line) + ", col " + n2(col); } } static public class UniqueString implements CharSequence { public String s; public UniqueString() { } public UniqueString(String s, boolean dummy) { this.s = s; } public String toString() { return s; } public char charAt(int index) { return s.charAt(index); } public int length() { return s.length(); } public CharSequence subSequence(int start, int end) { return uniqueString(s.substring(start, end)); } } public interface ICharPred { public boolean get(char c); } public interface ChangeTriggerable { public void change(); } static public class GrabbableIntPixels implements IFieldsToList { static final public String _fieldOrder = "data w h offset scanlineStride"; public int[] data; public int w; public int h; public int offset; public int scanlineStride; public GrabbableIntPixels() { } public GrabbableIntPixels(int[] data, int w, int h, int offset, int scanlineStride) { this.scanlineStride = scanlineStride; this.offset = offset; this.h = h; this.w = w; this.data = data; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + data + ", " + w + ", " + h + ", " + offset + ", " + scanlineStride + ")"; } public boolean equals(Object o) { if (!(o instanceof GrabbableIntPixels)) return false; GrabbableIntPixels __1 = (GrabbableIntPixels) o; return eq(data, __1.data) && w == __1.w && h == __1.h && offset == __1.offset && scanlineStride == __1.scanlineStride; } public int hashCode() { int h = -1183022196; h = boostHashCombine(h, _hashCode(data)); h = boostHashCombine(h, _hashCode(w)); h = boostHashCombine(h, _hashCode(h)); h = boostHashCombine(h, _hashCode(offset)); h = boostHashCombine(h, _hashCode(scanlineStride)); return h; } public Object[] _fieldsToList() { return new Object[] { data, w, h, offset, scanlineStride }; } public int[] asPackedArray() { if (offset == 0 && data.length == w * h) return data; int[] pixels = new int[w * h]; for (int y = 0; y < h; y++) arrayCopy(data, offset + y * scanlineStride, pixels, y * h, w); return pixels; } } static public class IIVirtualClip extends Meta implements IIntegralImage { public RegisteredReference fullImage = new RegisteredReference<>(this); public int x1, y1, w, h; public IIVirtualClip() { } public IIVirtualClip(IIntegralImage fullImage, int x1, int y1, int w, int h) { this.fullImage.set(fullImage); this.h = h; this.w = w; this.y1 = y1; this.x1 = x1; } public int getWidth() { return w; } public int getHeight() { return h; } public double getIntegralValue(int x, int y, int channel) { return fullImage.get().getIntegralValue(x + x1, y + y1, channel); } public double getIntegralValue(int x, int y) { return fullImage.get().getIntegralValue(x + x1, y + y1); } public BufferedImage getBufferedImage() { return clipBufferedImage(fullImage.get().getBufferedImage(), x1, y1, w, h); } } static public class DynamicHStack extends DynamicStack { public DynamicHStack() { } public DynamicHStack(boolean useFiller) { super(useFiller); } public GridBagConstraints _componentConstraints() { return gridBagConstraints_hstack_1(spacing); } public GridBagConstraints _fillerConstraints() { return gridBagConstraints_hstack_rest(); } } static public class MetaWithChangeListeners extends Meta implements IHasChangeListeners, ChangeTriggerable { transient public Set onChange; public MetaWithChangeListeners onChange(Runnable r) { onChange = createOrAddToSyncLinkedHashSet(onChange, r); return this; } public MetaWithChangeListeners removeChangeListener(Runnable r) { utils.remove(onChange, r); return this; } public void change() { if (onChange != null) for (var listener : onChange) pcallF_typed(listener); } } static public class BresenhamLineDrawer extends Meta implements Iterable, IFieldsToList { public int x1; public int y1; public int x2; public int y2; public BresenhamLineDrawer() { } public BresenhamLineDrawer(int x1, int y1, int x2, int y2) { this.y2 = y2; this.x2 = x2; this.y1 = y1; this.x1 = x1; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + ")"; } public Object[] _fieldsToList() { return new Object[] { x1, y1, x2, y2 }; } public int mainStepX, mainStepY; public int sideStepX, sideStepY; public int i; public int x, y; public int fraction, increment, denominator; public BresenhamLineDrawer(Pt start, Pt end) { x1 = start.x; y1 = start.y; x2 = end.x; y2 = end.y; } public boolean ran_init = false; public void init() { if (ran_init) return; ran_init = true; init_impl(); } public void init_impl() { x = x1; y = y1; if (abs(x2 - x1) > abs(y2 - y1)) { mainStepX = sideStepX = sign(x2 - x1); sideStepY = sign(y2 - y1); denominator = abs(x2 - x1); increment = abs(y2 - y1); } else { mainStepY = sideStepY = sign(y2 - y1); sideStepX = sign(x2 - x1); denominator = abs(y2 - y1); increment = abs(x2 - x1); } fraction = denominator / 2; if (scaffolding()) printVars("BresenhamLineDrawer", "x1", x1, "y1", y1, "x2", x2, "y2", y2, "denominator", denominator); } public Pt next() { init(); if (i > denominator) return null; Pt p = pt(x, y); if (i++ < denominator) { fraction += increment; if (fraction >= denominator) { fraction -= denominator; x += sideStepX; y += sideStepY; } else { x += mainStepX; y += mainStepY; } if (scaffolding()) printVars("BresenhamLineDrawer", "i", i, "fraction", fraction, "increment", increment, "denominator", denominator, "x", x, "y", y, "p", p); } return p; } public IterableIterator iterator() { return iff_null(() -> next()); } public PtBuffer points() { return new PtBuffer(iterator()); } } static public class CheckerBoard2 implements G2Drawable { final public CheckerBoard2 setW(int w) { return w(w); } public CheckerBoard2 w(int w) { this.w = w; return this; } final public int getW() { return w(); } public int w() { return w; } public int w = 256; final public CheckerBoard2 setH(int h) { return h(h); } public CheckerBoard2 h(int h) { this.h = h; return this; } final public int getH() { return h(); } public int h() { return h; } public int h = 256; final public CheckerBoard2 setShiftX(double shiftX) { return shiftX(shiftX); } public CheckerBoard2 shiftX(double shiftX) { this.shiftX = shiftX; return this; } final public double getShiftX() { return shiftX(); } public double shiftX() { return shiftX; } public double shiftX; final public CheckerBoard2 setShiftY(double shiftY) { return shiftY(shiftY); } public CheckerBoard2 shiftY(double shiftY) { this.shiftY = shiftY; return this; } final public double getShiftY() { return shiftY(); } public double shiftY() { return shiftY; } public double shiftY; final public CheckerBoard2 setCellW(double cellW) { return cellW(cellW); } public CheckerBoard2 cellW(double cellW) { this.cellW = cellW; return this; } final public double getCellW() { return cellW(); } public double cellW() { return cellW; } public double cellW = 8; final public CheckerBoard2 setCellH(double cellH) { return cellH(cellH); } public CheckerBoard2 cellH(double cellH) { this.cellH = cellH; return this; } final public double getCellH() { return cellH(); } public double cellH() { return cellH; } public double cellH = 8; final public CheckerBoard2 setColor1(Color color1) { return color1(color1); } public CheckerBoard2 color1(Color color1) { this.color1 = color1; return this; } final public Color getColor1() { return color1(); } public Color color1() { return color1; } public Color color1 = Color.lightGray; final public CheckerBoard2 setColor2(Color color2) { return color2(color2); } public CheckerBoard2 color2(Color color2) { this.color2 = color2; return this; } final public Color getColor2() { return color2(); } public Color color2() { return color2; } public Color color2 = Color.gray; public CheckerBoard2 cellSize(double cellSize) { return cellW(cellSize).cellH(cellSize); } public int getWidth() { return w; } public int getHeight() { return h; } public void drawOn(Graphics2D g) { int xofs = idiv_floor(shiftX, cellW); int yofs = idiv_floor(shiftY, cellH); double x1 = mod(shiftX, cellW) - cellW; double y1 = mod(shiftY, cellH) - cellH; boolean bRow = odd(yofs ^ xofs); for (double y = y1; y < h; y += cellH) { bRow = !bRow; boolean b = bRow; for (double x = x1; x < w; x += cellW) { b = !b; g.setColor(b ? color1 : color2); g.fill(new Rectangle2D.Double(x, y, cellW, cellH)); } } } } static public class TokenRange extends IntRange { public TokenRange() { } public TokenRange(int start, int end) { this.end = end; this.start = start; } } static public class Seconds implements Comparable, IFieldsToList { public double seconds; public Seconds() { } public Seconds(double seconds) { this.seconds = seconds; } public boolean equals(Object o) { if (!(o instanceof Seconds)) return false; Seconds __1 = (Seconds) o; return seconds == __1.seconds; } public int hashCode() { int h = -660217249; h = boostHashCombine(h, _hashCode(seconds)); return h; } public Object[] _fieldsToList() { return new Object[] { seconds }; } final public double get() { return seconds(); } final public double getDouble() { return seconds(); } public double seconds() { return seconds; } public String toString() { return formatDouble(seconds, 3) + " s"; } public int compareTo(Seconds s) { return cmp(seconds, s.seconds); } public Seconds div(double x) { return new Seconds(get() / x); } public Seconds minus(Seconds x) { return new Seconds(get() - x.get()); } } static public class SynchronizedSortedMap extends SynchronizedMap implements SortedMap { public SynchronizedSortedMap() { } public SortedMap innerMap() { return (SortedMap) m; } public SynchronizedSortedMap(SortedMap m) { super(m); } public SynchronizedSortedMap(SortedMap m, Object mutex) { super(m, mutex); } public Comparator comparator() { synchronized (mutex) { return innerMap().comparator(); } } public SortedMap subMap(K fromKey, K toKey) { synchronized (mutex) { return new SynchronizedSortedMap<>(innerMap().subMap(fromKey, toKey), mutex); } } public SortedMap headMap(K toKey) { synchronized (mutex) { return new SynchronizedSortedMap<>(innerMap().headMap(toKey), mutex); } } public SortedMap tailMap(K fromKey) { synchronized (mutex) { return new SynchronizedSortedMap<>(innerMap().tailMap(fromKey), mutex); } } public K firstKey() { synchronized (mutex) { return innerMap().firstKey(); } } public K lastKey() { synchronized (mutex) { return innerMap().lastKey(); } } } static public class ScaledBWImageFromBWIntegralImage implements ScalingImageOpResult, IFieldsToList { public IBWIntegralImage img; public int w; public int h; public ScaledBWImageFromBWIntegralImage() { } public ScaledBWImageFromBWIntegralImage(IBWIntegralImage img, int w, int h) { this.h = h; this.w = w; this.img = img; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + img + ", " + w + ", " + h + ")"; } public Object[] _fieldsToList() { return new Object[] { img, w, h }; } public BWImage result; public void run() { try { byte[] pixels = img instanceof BWIntegralImage ? scaledGrayBytesFromBWIntegralImage(((BWIntegralImage) img), w, h) : scaledGrayBytesFromBWIntegralImage(img, w, h); result = new BWImage(w, h, pixels); } catch (Exception __e) { throw rethrow(__e); } } public IBWIntegralImage scalingSrcImage() { return img; } } static public class HInitWebSocket { public String wsVar = "ws"; public String readyMsg = "WebSocket ready!"; public boolean handleEvals = true; public boolean wsVerbose = true; public boolean autoOpen = true; public Map params = new HashMap(); public String reconnectParams = "reconnect=1"; public HInitWebSocket() { } public HInitWebSocket(IWebRequest req) { if (req != null && eq(req.get("wsVerbose"), "1")) wsVerbose = true; } final public String get() { return headStuff(); } final public String toString() { return headStuff(); } public String headStuff() { return hreconnectingWebSockets() + hscript(js()); } public List dependencies() { return ll(hjssnippet(hreconnectingWebSockets_snippetID(), "data-comment", "ReconnectingWebSocket")); } public String js() { return jsDollarVars("\r\n var wsReady = false;\r\n var wsInitialMsgs = [];\r\n var wsMsgListeners = [];\r\n var wsOpenListeners = [];\r\n var wsWillReconnectListeners = [];\r\n var wsVerbose = $wsVerbose;\r\n var wsConnectionCount = 0;\r\n var wsAugmentURL = function(url) { return url; };\r\n var wsURL = ((window.location.protocol === \"https:\") ? \"wss://\" : \"ws://\") + window.location.host\r\n + window.location.pathname + window.location.search;\r\n if ($params != \"\")\r\n wsURL += (wsURL.match(/\\?/) ? \"&\" : \"?\") + $params;\r\n \r\n var $wsVar = new ReconnectingWebSocket(wsURL, null, $options);\r\n \r\n $wsVar.onopen = function(event) {\r\n wsReady = true;\r\n console.log($readyMsg + \" \" + ws.url);\r\n \r\n if (++wsConnectionCount == 1)\r\n if ($reconnectParams != \"\") {\r\n wsURL += (wsURL.match(/\\?/) ? \"&\" : \"?\") + $reconnectParams;\r\n ws.url = wsAugmentURL(wsURL);\r\n }\r\n\r\n wsOpenListeners.forEach(function(f) { f(); });\r\n\r\n ws.onmessage = function(event) {\r\n if (wsVerbose) console.log(\"Got msg: \" + event.data.substring(0, 200));\r\n wsMsgListeners.forEach(function(listener) {\r\n listener(event);\r\n });\r\n };\r\n \r\n ws.onclose = function(event) {\r\n if (wsVerbose) console.log(\"WebSocket closed\");\r\n wsReady = false;\r\n };\r\n\r\n wsInitialMsgs.forEach(function(msg) {\r\n if (wsVerbose) console.log(\"Sending initial msg: \" + msg);\r\n ws.send(msg);\r\n });\r\n wsInitialMsgs = [];\r\n if (wsVerbose) console.log(\"Cleared initial msgs\");\r\n };\r\n \r\n // send it now if ws is open already or when ws was opened\r\n function wsSend(msg) {\r\n if (wsReady) {\r\n if (wsVerbose) console.log(\"Sending msg: \" + msg);\r\n ws.send(msg); // TODO: wsReady = false on failed send?\r\n return;\r\n } else {\r\n if (wsVerbose) console.log(\"Scheduling msg: \" + msg);\r\n wsInitialMsgs.push(msg);\r\n }\r\n }\r\n \r\n function wsOnOpen(f) {\r\n wsOpenListeners.push(f); \r\n }\r\n \r\n function wsOnMessage(f) {\r\n wsMsgListeners.push(f); \r\n }\r\n \r\n function wsSetAugmentURL(f) {\r\n wsAugmentURL = f;\r\n if (ws) ws.url = wsAugmentURL(wsURL);\r\n }\r\n \r\n ", "wsVar", new JS(wsVar), "wsVerbose", wsVerbose, "readyMsg", readyMsg, "params", makePostData(params), "reconnectParams", unnull(reconnectParams), "options", options()) + (!handleEvals ? "" : "wsOnMessage(" + js_evalOnWebSocketMessage() + ");\n"); } public Map options() { return litorderedmap("automaticOpen", autoOpen ? null : false); } } static public class PtSet extends java.util.AbstractSet { final public CompactLongSet set; public PtSet() { set = new CompactLongSet(); } public PtSet(int size) { set = new CompactLongSet(size); } public PtSet(Iterable l) { this(); if (l != null) for (Pt p : l) add(p); } public PtSet(Collection l) { this(l(l)); if (l != null) for (Pt p : l) add(p); } public int size() { return set.size(); } @Override public boolean contains(Object o) { return contains(((Pt) o)); } public boolean contains(Pt p) { return set.contains(ptToLong(p)); } public boolean contains(int x, int y) { return set.contains(ptToLong(x, y)); } public boolean add(Pt p) { return set.add(ptToLong(p)); } public boolean add(int x, int y) { return set.add(ptToLong(x, y)); } public boolean remove(Pt p) { return set.remove(ptToLong(p)); } public boolean remove(int x, int y) { return set.remove(ptToLong(x, y)); } public void clear() { set.clear(); } public Iterator iterator() { RenamedLongIterator it = set.iterator(); return new IterableIterator() { public boolean hasNext() { return it.hasNext(); } public Pt next() { return ptFromLong(it.nextLong()); } public void remove() { it.remove(); } }; } } static public class MultiSetMap implements IMultiMap { public Map> data = new HashMap>(); public int size; public MultiSetMap() { } public MultiSetMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); } public MultiSetMap(MultiSetMap map) { putAll(map); } public MultiSetMap(Map> data) { this.data = data; } public boolean put(A key, B value) { synchronized (data) { Set set = data.get(key); if (set == null) data.put(key, set = _makeEmptySet()); if (!set.add(value)) return false; { ++size; return true; } } } public boolean add(A key, B value) { return put(key, value); } public void addAll(A key, Collection values) { synchronized (data) { putAll(key, values); } } public void addAllIfNotThere(A key, Collection values) { synchronized (data) { for (B value : values) setPut(key, value); } } public void setPut(A key, B value) { synchronized (data) { if (!containsPair(key, value)) put(key, value); } } final public boolean contains(A key, B value) { return containsPair(key, value); } public boolean containsPair(A key, B value) { synchronized (data) { return get(key).contains(value); } } public void putAll(A key, Collection values) { synchronized (data) { for (B value : values) put(key, value); } } public void removeAll(A key, Collection values) { synchronized (data) { for (B value : values) remove(key, value); } } public Set get(A key) { synchronized (data) { Set set = data.get(key); return set == null ? Collections.emptySet() : set; } } public List getAndClear(A key) { synchronized (data) { List l = cloneList(data.get(key)); remove(key); return l; } } public Set getOpt(A key) { synchronized (data) { return data.get(key); } } public Set getActual(A key) { synchronized (data) { Set set = data.get(key); if (set == null) data.put(key, set = _makeEmptySet()); return set; } } public void clean(A key) { synchronized (data) { Set list = data.get(key); if (list != null && list.isEmpty()) data.remove(key); } } final public Set keys() { return keySet(); } public Set keySet() { synchronized (data) { return data.keySet(); } } public void remove(A key) { synchronized (data) { size -= l(data.get(key)); data.remove(key); } } public void remove(A key, B value) { synchronized (data) { Set set = data.get(key); if (set != null) { if (set.remove(value)) { --size; if (set.isEmpty()) data.remove(key); } } } } public void clear() { synchronized (data) { data.clear(); size = 0; } } public boolean containsKey(A key) { synchronized (data) { return data.containsKey(key); } } public B getFirst(A key) { synchronized (data) { return first(get(key)); } } public void addAll(MultiSetMap map) { putAll(map); } public void putAll(MultiSetMap map) { synchronized (data) { for (A key : map.keySet()) putAll(key, map.get(key)); } } public void putAll(Map map) { synchronized (data) { if (map != null) for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue()); } } final public int keyCount() { return keysSize(); } public int keysSize() { synchronized (data) { return l(data); } } public int size() { synchronized (data) { return size; } } public int getSize(A key) { return l(data.get(key)); } public int count(A key) { return getSize(key); } public Set reverseGet(B b) { synchronized (data) { Set l = new HashSet(); for (A key : data.keySet()) if (data.get(key).contains(b)) l.add(key); return l; } } public A keyForValue(B b) { synchronized (data) { for (A key : data.keySet()) if (data.get(key).contains(b)) return key; return null; } } public Map> asMap() { synchronized (data) { return cloneMap(data); } } public boolean isEmpty() { synchronized (data) { return data.isEmpty(); } } public Set _makeEmptySet() { return new HashSet(); } public Collection> allLists() { synchronized (data) { return new HashSet(data.values()); } } public List allValues() { return concatLists(values(data)); } public List> allEntries() { synchronized (data) { List> l = emptyList(size); for (Map.Entry> __0 : _entrySet(data)) { A a = __0.getKey(); Set set = __0.getValue(); for (B b : set) l.add(pair(a, b)); } return l; } } public Object mutex() { return data; } public String toString() { return "mm" + str(data); } public Pair firstEntry() { synchronized (data) { if (empty(data)) return null; Map.Entry> entry = data.entrySet().iterator().next(); return pair(entry.getKey(), first(entry.getValue())); } } public A firstKey() { synchronized (data) { return utils.firstKey(data); } } public A lastKey() { synchronized (data) { return (A) ((NavigableMap) data).lastKey(); } } public A higherKey(Object a) { synchronized (data) { return (A) ((NavigableMap) data).higherKey(a); } } } static public class Var implements IVar, ISetter { public Var() { } public Var(A v) { this.v = v; } public A v; public synchronized void set(A a) { if (v != a) { v = a; notifyAll(); } } public synchronized A get() { return v; } public synchronized boolean has() { return v != null; } public void clear() { set(null); } public synchronized A getAndSet(A a) { var value = v; set(a); return value; } public IF0 getter() { return () -> get(); } public IVF1 setter() { return __205 -> set(__205); } public String toString() { return str(this.get()); } } static public class ClassNameResolver { final public ClassNameResolver setByteCodePath(File byteCodePath) { return byteCodePath(byteCodePath); } public ClassNameResolver byteCodePath(File byteCodePath) { this.byteCodePath = byteCodePath; return this; } final public File getByteCodePath() { return byteCodePath(); } public File byteCodePath() { return byteCodePath; } public File byteCodePath = byteCodePathForClass(getClass()); public List importedPackages = itemPlusList("java.lang", endingWith_dropSuffix(standardImports(), ".*")); public Set allFullyQualifiedClassNames_cache; public Set allFullyQualifiedClassNames() { if (allFullyQualifiedClassNames_cache == null) allFullyQualifiedClassNames_cache = allFullyQualifiedClassNames_load(); return allFullyQualifiedClassNames_cache; } public Set allFullyQualifiedClassNames_load() { Set set = new HashSet(); assertNotNull(byteCodePath); set.addAll(classNamesInJarOrDir(byteCodePath)); printVars("ClassNameResolver", "byteCodePath", byteCodePath, "classesFound", l(set)); set.addAll(classNamesInLoadedJigsawModules()); return set; } public ClassNameResolver init() { allFullyQualifiedClassNames(); return this; } public String findClass(String name) { for (String pkg : importedPackages) { String fullName = pkg + "." + name; if (allFullyQualifiedClassNames().contains(fullName)) return fullName; } return null; } public void printMe() { printVars("ClassNameResolver", "byteCodePath", byteCodePath); print("importedPackages", importedPackages); } } static public class Best_comparable { public A best; public Comparable score; public boolean verboseNewBest, replaceIfSameScore; transient public Object onChange; transient public Object stringifier; synchronized public boolean isNewBest(Comparable score) { return this.score == null || (replaceIfSameScore ? cmp(score, this.score) >= 0 : cmp(score, this.score) > 0); } synchronized public Comparable bestScore() { return score; } public Comparable score() { return bestScore(); } public Comparable getScore() { return bestScore(); } synchronized public float floatScoreOr(float defaultValue) { return best == null ? defaultValue : (float) score; } public boolean put(Pair p) { return p != null && put(p.a, p.b); } public boolean put(Best b) { return b != null && put(b.get(), b.score); } public boolean put(A a, Comparable score) { ping(); boolean change = false; if (a != null) synchronized (this) { if (isNewBest(score)) { best = a; this.score = score; change = true; } } if (change) { if (verboseNewBest) print("New best! " + this); pcallF(onChange); } return change; } synchronized public A get() { return best; } synchronized public boolean has() { return best != null; } synchronized public Pair pair() { return utils.pair(best, bestScore()); } synchronized public A getIfScoreAbove(Comparable x) { return cmp(x, score()) >= 0 ? best : null; } public String toString() { return !has() ? "-" : "Score " + score + ": " + callStringifier(stringifier, best); } public boolean putAndPrintIfNewBest(A a, Comparable score) { if (!put(a, score)) return false; { print(this); return true; } } synchronized public void clear() { best = null; score = 0; } } static public class Scorer { public double score, total; public List successes, errors; public boolean verboseFailures, verboseAll; final public void add(double score) { addZeroToOne(score); } public void addZeroToOne(double score) { ++total; this.score += clamp(score, 0, 1); } public void addZeroToOneError(double error) { addZeroToOne(1 - error); } public void addError() { add(false); } public void addError(A info) { add(false, info); } public void error(A info) { addError(info); } public void addOK() { add(true); } public void addOK(A info) { add(true, info); } public void ok() { addOK(); } public void ok(A info) { addOK(info); } public boolean add(boolean correct) { ++total; if (correct) ++score; return correct; } public boolean add(boolean correct, A info) { utils.add(correct ? successes : errors, info); if (verboseAll || verboseFailures && !correct) _print((correct ? "[GOOD] " : "[BAD] ") + info); return add(correct); } public void eq(Object a, Object b) { if (_eq(a, b)) add(true); else add(false, (A) (a + " != " + b)); } public void print() { utils.print(toString()); } public String toString() { return formatDouble(ratioToPercent(score, total), 1) + "% correct (n=" + formatDouble(total, 1) + ")"; } public double get() { return ratioToPercent(score, total); } public double percentScore() { return get(); } public double score() { return get(); } public boolean allCorrect() { return score == total; } public void add(Scorer scorer) { if (scorer == null) return; total += scorer.total; score += scorer.score; addAll(successes, scorer.successes); addAll(errors, scorer.errors); } public void collectErrors() { errors = new ArrayList(); } public void collectSuccesses() { successes = new ArrayList(); } } static public interface ITokCondition { public boolean get(List tok, int i); } static public class PopupMenuMaker { final public PopupMenuMaker setAllowScrolling(boolean allowScrolling) { return allowScrolling(allowScrolling); } public PopupMenuMaker allowScrolling(boolean allowScrolling) { this.allowScrolling = allowScrolling; return this; } final public boolean getAllowScrolling() { return allowScrolling(); } public boolean allowScrolling() { return allowScrolling; } public boolean allowScrolling = true; final public PopupMenuMaker setEvent(MouseEvent event) { return event(event); } public PopupMenuMaker event(MouseEvent event) { this.event = event; return this; } final public MouseEvent getEvent() { return event(); } public MouseEvent event() { return event; } public MouseEvent event; final public PopupMenuMaker setPtInComponent(PtInComponent ptInComponent) { return ptInComponent(ptInComponent); } public PopupMenuMaker ptInComponent(PtInComponent ptInComponent) { this.ptInComponent = ptInComponent; return this; } final public PtInComponent getPtInComponent() { return ptInComponent(); } public PtInComponent ptInComponent() { return ptInComponent; } public PtInComponent ptInComponent; final public PopupMenuMaker setFillMenu(IVF1 fillMenu) { return fillMenu(fillMenu); } public PopupMenuMaker fillMenu(IVF1 fillMenu) { this.fillMenu = fillMenu; return this; } final public IVF1 getFillMenu() { return fillMenu(); } public IVF1 fillMenu() { return fillMenu; } public IVF1 fillMenu; final public PopupMenuMaker setExistingMenu(JPopupMenu existingMenu) { return existingMenu(existingMenu); } public PopupMenuMaker existingMenu(JPopupMenu existingMenu) { this.existingMenu = existingMenu; return this; } final public JPopupMenu getExistingMenu() { return existingMenu(); } public JPopupMenu existingMenu() { return existingMenu; } public JPopupMenu existingMenu; final public PopupMenuMaker setAddSeparator(boolean addSeparator) { return addSeparator(addSeparator); } public PopupMenuMaker addSeparator(boolean addSeparator) { this.addSeparator = addSeparator; return this; } final public boolean getAddSeparator() { return addSeparator(); } public boolean addSeparator() { return addSeparator; } public boolean addSeparator = true; public JPopupMenu menu; public PopupMenuMaker() { } public PopupMenuMaker(MouseEvent event, IVF1 fillMenu) { this.fillMenu = fillMenu; this.event = event; } public void run() { swing(() -> { if (existingMenu != null) { fix(); var menu = existingMenu; int emptyCount = menu.getComponentCount(); if (addSeparator) menu.addSeparator(); int emptyCount2 = menu.getComponentCount(); { if (fillMenu != null) fillMenu.get(menu); } if (menu.getComponentCount() == emptyCount2) truncateContainer(menu, emptyCount); packWindow(menu); } else { JPopupMenu menu = new JPopupMenu(); int emptyCount = menu.getComponentCount(); { if (fillMenu != null) fillMenu.get(menu); } if (menu.getComponentCount() == emptyCount) return; if (allowScrolling) { menu = new JPopupMenu(); JMenuScroller scroller = JMenuScroller.setScrollerFor(menu); scroller.fillMenu = toVF1(fillMenu); } if (ptInComponent == null) ptInComponent = ptInComponentFromEvent(event); if (hasParentOfType(JPopupMenu.class, ptInComponent.component)) { menu.setInvoker(ptInComponent.component); menu.setVisible(true); } else menu.show(ptInComponent.component, ptInComponent.p.x, ptInComponent.p.y); } }); } static public void fix() { JPopupMenu.setDefaultLightWeightPopupEnabled(false); } } static public class CountingOutputStream extends FilterOutputStream { public long counter; public CountingOutputStream(OutputStream out) { super(out); } @Override public void write(int b) throws IOException { ++counter; out.write(b); } @Override public void write(byte[] b) throws IOException { counter += b.length; out.write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { if (len == 0) return; counter += len; out.write(b, off, len); } public long getFilePointer() { return counter; } } public interface INumberOfPixels { public int numberOfPixels(); } public interface Matrix extends WidthAndHeight { public A get(int x, int y); public void set(int x, int y, A a); default public Pt size() { return pt(getWidth(), getHeight()); } default public int nCells() { return getWidth() * getHeight(); } default public A get(Pt p) { return get(p.x, p.y); } default public void put(Pt p, A a) { set(p, a); } default public void set(Pt p, A a) { set(p.x, p.y, a); } default public List getLine(int y) { return new RandomAccessAbstractList() { public int size() { return getWidth(); } public A get(int x) { return Matrix.this.get(x, y); } public A set(int x, A val) { A old = Matrix.this.get(x, y); Matrix.this.set(x, y, val); return old; } }; } } static public class PrecisePolygon extends Path2D.Double { final public List getPoints() { return points(); } public List points() { return points; } public List points; public PrecisePolygon(double... points) { this(toDoublePts(points)); } public PrecisePolygon(List pts) { points = iDoublePtsToDoublePts(pts); var p = first(points); moveTo(p.x, p.y); for (int i = 1; i < l(points); i++) { p = points.get(i); lineTo(p.x, p.y); } closePath(); } } static public class RunResultWithTimestamps extends OKOrError { final public RunResultWithTimestamps setStarted(Timestamp started) { return started(started); } public RunResultWithTimestamps started(Timestamp started) { this.started = started; return this; } final public Timestamp getStarted() { return started(); } public Timestamp started() { return started; } public Timestamp started; final public RunResultWithTimestamps setEnded(Timestamp ended) { return ended(ended); } public RunResultWithTimestamps ended(Timestamp ended) { this.ended = ended; return this; } final public Timestamp getEnded() { return ended(); } public Timestamp ended() { return ended; } public Timestamp ended; final public RunResultWithTimestamps setPrintOutput(CharSequence printOutput) { return printOutput(printOutput); } public RunResultWithTimestamps printOutput(CharSequence printOutput) { this.printOutput = printOutput; return this; } final public CharSequence getPrintOutput() { return printOutput(); } public CharSequence printOutput() { return printOutput; } public CharSequence printOutput; public RunResultWithTimestamps run(IF0 f) { return run(f, true); } public RunResultWithTimestamps run(IF0 f, boolean printStackTrace) { return setPrintOutput(hijackPrint_tee(new Runnable() { public void run() { try { started(tsNow()); copyFrom(okOrError(f, printStackTrace)); ended(tsNow()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "started(tsNow());\r\n copyFrom(okOrError(f, printStackTrace));\r\n ende..."; } })); } public boolean hasRun() { return ended != null; } public OKOrError result() { return this; } public Duration duration() { return ended.minusAsDuration(started); } public String renderDuration() { return formatElapsedTimeWithAppropriateUnit(nanosToSeconds(duration().toNanos())); } } abstract static public class CompactAbstractMap implements Map { public int size() { return entrySet().size(); } public boolean isEmpty() { return size() == 0; } public boolean containsValue(Object value) { Iterator> i = entrySet().iterator(); if (value == null) { while (i.hasNext()) { Entry e = i.next(); if (e.getValue() == null) return true; } } else { while (i.hasNext()) { Entry e = i.next(); if (value.equals(e.getValue())) return true; } } return false; } public boolean containsKey(Object key) { Iterator> i = entrySet().iterator(); if (key == null) { while (i.hasNext()) { Entry e = i.next(); if (e.getKey() == null) return true; } } else { while (i.hasNext()) { Entry e = i.next(); if (key.equals(e.getKey())) return true; } } return false; } public V get(Object key) { Iterator> i = entrySet().iterator(); if (key == null) { while (i.hasNext()) { Entry e = i.next(); if (e.getKey() == null) return e.getValue(); } } else { while (i.hasNext()) { Entry e = i.next(); if (key.equals(e.getKey())) return e.getValue(); } } return null; } public V put(K key, V value) { throw new UnsupportedOperationException(); } public V remove(Object key) { Iterator> i = entrySet().iterator(); Entry correctEntry = null; if (key == null) { while (correctEntry == null && i.hasNext()) { Entry e = i.next(); if (e.getKey() == null) correctEntry = e; } } else { while (correctEntry == null && i.hasNext()) { Entry e = i.next(); if (key.equals(e.getKey())) correctEntry = e; } } V oldValue = null; if (correctEntry != null) { oldValue = correctEntry.getValue(); i.remove(); } return oldValue; } public void putAll(Map m) { for (Entry e : m.entrySet()) put(e.getKey(), e.getValue()); } public void clear() { entrySet().clear(); } public Set keySet() { return new AbstractSet() { public Iterator iterator() { return new Iterator() { public Iterator> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public K next() { return i.next().getKey(); } public void remove() { i.remove(); } }; } public int size() { return CompactAbstractMap.this.size(); } public boolean isEmpty() { return CompactAbstractMap.this.isEmpty(); } public void clear() { CompactAbstractMap.this.clear(); } public boolean contains(Object k) { return CompactAbstractMap.this.containsKey(k); } }; } public Collection values() { return new AbstractCollection() { public Iterator iterator() { return new Iterator() { public Iterator> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public V next() { return i.next().getValue(); } public void remove() { i.remove(); } }; } public int size() { return CompactAbstractMap.this.size(); } public boolean isEmpty() { return CompactAbstractMap.this.isEmpty(); } public void clear() { CompactAbstractMap.this.clear(); } public boolean contains(Object v) { return CompactAbstractMap.this.containsValue(v); } }; } public abstract Set> entrySet(); public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Map)) return false; Map m = (Map) o; if (m.size() != size()) return false; try { for (Entry e : entrySet()) { K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(m.get(key) == null && m.containsKey(key))) return false; } else { if (!value.equals(m.get(key))) return false; } } } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } return true; } public int hashCode() { int h = 0; for (Entry entry : entrySet()) h += entry.hashCode(); return h; } public String toString() { Iterator> i = entrySet().iterator(); if (!i.hasNext()) return "{}"; StringBuilder sb = new StringBuilder(); sb.append('{'); for (; ; ) { Entry e = i.next(); K key = e.getKey(); V value = e.getValue(); sb.append(key == this ? "(this Map)" : key); sb.append('='); sb.append(value == this ? "(this Map)" : value); if (!i.hasNext()) return sb.append('}').toString(); sb.append(',').append(' '); } } public Object clone() throws CloneNotSupportedException { CompactAbstractMap result = (CompactAbstractMap) super.clone(); return result; } public static class SimpleEntry implements Entry, java.io.Serializable { @java.io.Serial static final public long serialVersionUID = -8499721149061103585L; @SuppressWarnings("serial") final public K key; @SuppressWarnings("serial") public V value; public SimpleEntry(K key, V value) { this.key = key; this.value = value; } public SimpleEntry(Entry entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Entry e = (Entry) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public String toString() { return key + "=" + value; } } public static class SimpleImmutableEntry implements Entry, java.io.Serializable { @java.io.Serial static final public long serialVersionUID = 7138329143949025153L; @SuppressWarnings("serial") final public K key; @SuppressWarnings("serial") final public V value; public SimpleImmutableEntry(K key, V value) { this.key = key; this.value = value; } public SimpleImmutableEntry(Entry entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { throw new UnsupportedOperationException(); } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Entry e = (Entry) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public String toString() { return key + "=" + value; } } } static public class TripletLSFR { public int n; public int value = 1; public int a, b, c; final public int getCycleLength() { return cycleLength(); } public int cycleLength() { return cycleLength; } public int cycleLength; public int step; static final public int[][] tripletsTable = { { 0, 0, 0 }, { 0, 1, 1 }, { 0, 1, 1 }, { 0, 1, 3 }, { 0, 1, 1 }, { 0, 1, 1 }, { 0, 1, 3 }, { 1, 1, 2 }, { 0, 1, 1 }, { 0, 3, 7 }, { 0, 1, 1 }, { 1, 1, 4 }, { 0, 1, 6 }, { 0, 1, 1 }, { 0, 1, 4 }, { 1, 1, 14 }, { 0, 3, 7 }, { 1, 3, 14 }, { 0, 1, 3 }, { 1, 5, 6 }, { 0, 1, 6 }, { 0, 1, 21 }, { 0, 1, 1 }, { 1, 5, 18 }, { 0, 1, 12 }, { 0, 1, 1 }, { 0, 2, 7 }, { 0, 3, 25 }, { 0, 1, 1 }, { 0, 1, 1 }, { 0, 3, 28 } }; public TripletLSFR(int n) { this.n = n; if (n < 1 || n > tripletsTable.length) throw fail("Don't have triples for " + nBits(n)); init(tripletsTable[n - 1]); } public TripletLSFR(int n, int a, int b, int c) { this.n = n; init(a, b, c); } public void init(int[] triplet) { init(triplet[0], triplet[1], triplet[2]); } public void init(int a, int b, int c) { this.a = a == 0 ? n : a; this.b = b == 0 ? n : b; this.c = c == 0 ? n : c; cycleLength = (1 << n) - 1; } public int next() { step++; int x = value; x ^= (x << a) & cycleLength; x ^= x >>> b; x ^= (x << c) & cycleLength; return value = x; } public boolean cycleComplete() { return step >= cycleLength(); } final public TripletLSFR value(int start) { return start(start); } public TripletLSFR start(int start) { value = mod(start, cycleLength) + 1; return this; } } static public class BitBuffer implements IntSize { public BitBuffer() { } public ByteBuffer byteBuffer = new ByteBuffer(); public int currentByte, currentBit; public void add(int b) { add(odd(b)); } public void add(boolean b) { if (b) currentByte |= 1 << currentBit; if (currentBit == 7) { byteBuffer.add((byte) currentByte); currentByte = 0; currentBit = 0; } else ++currentBit; } public boolean get(int iBit) { int iByte = iBit >> 3; int theByte = iByte == byteBuffer.size() ? currentByte : byteBuffer.get(iByte); return (theByte & (1 << (iBit & 7))) != 0; } public boolean hasFullByte() { return !byteBuffer.isEmpty(); } public byte popFullByte() { return byteBuffer.popFirst(); } public int size() { return byteBuffer.size() * 8 + currentBit; } } static public class Fail extends RuntimeException implements IFieldsToList { public Object[] objects; public Fail() { } public Fail(Object... objects) { this.objects = objects; } public Object[] _fieldsToList() { return new Object[] { objects }; } public Fail(Throwable cause, Object... objects) { super(cause); this.objects = objects; } public String toString() { return joinNemptiesWithColon("Fail", getMessage()); } public String getMessage() { return commaCombine(getCause(), objects); } } static public class FunctionTimings { public Map data = syncMap(); final public void timeCtex(A function, RunnableWithExceptions r) { doCtex(function, r); } public void doCtex(A function, RunnableWithExceptions r) { try { if (r == null) return; long time = nanoTime(); try { r.run(); } finally { time = nanoTime() - time; saveTiming(function, time); } } catch (Exception __e) { throw rethrow(__e); } } public B get(A function, IF0 f) { if (f == null) return null; Var var = new Var(); time(function, () -> var.set(f.get())); return var.get(); } final public void time(A function, Runnable r) { dO(function, r); } public void dO(A function, Runnable r) { if (r == null) return; long time = nanoTime(); try { r.run(); } finally { time = nanoTime() - time; saveTiming(function, time); } } public void saveTiming(A function, long time) { Average avg = syncMapGetOrCreate(data, function, () -> new Average()); avg.add(time); } public Map get() { return cloneMap(data); } final public void clear() { reset(); } public void reset() { data.clear(); } final public String toString() { return render(); } public String render() { return lines(renderedEntries()); } public List renderedEntries() { return ciSorted(map(get(), (f, avg) -> functionToString(f) + ": " + n2(iround(nsToMicroseconds(avg.get()))) + " " + microSymbol() + "s (" + n2(iround(avg.n())) + ")")); } public String toStringSingleLine() { return joinWithComma(renderedEntries()); } public String functionToString(A f) { return firstToUpper(str(f)); } } static public interface ISetter { public void set(A a); } static public class DoneFlag extends Flag { transient volatile public Object error; transient public boolean printErrors = false; public DoneFlag() { } public DoneFlag(boolean printErrors) { this.printErrors = printErrors; } public void done() { raise(); } final public void setError(Object error) { done(error); } public void done(Object error) { this.error = error; if (printErrors) printStackTrace_gen(error); raise(); } public boolean hasError() { return error != null; } public boolean isDone() { return isUp(); } } static public class RSTOverQ implements Runnable { public boolean _isTransient() { return true; } public Runnable runnable; public Q q = startQ(); public F0 enter; public boolean trigger, running; public RSTOverQ(Runnable runnable) { this.runnable = runnable; } public RSTOverQ(Runnable runnable, Q q) { this.q = q; this.runnable = runnable; assertNotNull(q); } public RSTOverQ(Q q, Runnable runnable) { this(runnable, q); } public void trigger() { go(); } synchronized public void go() { if (trigger) return; trigger = true; q.add(new Runnable() { public void run() { try { _run(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_run();"; } }); } public void run() { go(); } public void get() { go(); } synchronized public boolean running() { return running; } public void _run() { synchronized (this) { if (!trigger) return; running = true; trigger = false; } try { AutoCloseable __1 = callF(enter); try { pcallF(runnable); } finally { _close(__1); } } finally { synchronized (this) { running = false; } } } synchronized public boolean triggered() { return trigger; } public void waitUntilDone() { while (running()) sleep(1); } public String stats() { return renderVars("trigger", trigger, "running", running, "q", q, "runnable", runnable); } } abstract static public class AIStrategy implements Steppable { public F1 submit; public AIStrategy() { } public AIStrategy(F1 submit) { this.submit = submit; } public AIStrategy setJudge(IF1 judge) { submit = new F1() { public Double get(A a) { try { return judge.get(a).doubleValue(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "judge.get(a).doubleValue()"; } }; return this; } public long round; public Best best = new Best(); public boolean verbose = false; transient public Set> onNewBest; public AIStrategy onNewBest(IVF2 f) { onNewBest = createOrAddToSyncLinkedHashSet(onNewBest, f); return this; } public AIStrategy removeNewBestListener(IVF2 f) { utils.remove(onNewBest, f); return this; } public void newBest(A guess, double score) { if (onNewBest != null) for (var listener : onNewBest) pcallF_typed(listener, guess, score); } public void updateBest(A guess, double score) { if (best.put(guess, score)) newBest(guess, score); } public double submit(A guess) { if (guess == null) return best.worstScore(); double score = callF(submit, guess); updateBest(guess, score); return score; } public AIStrategy lowerIsBetter(boolean b) { best.lowerIsBetter(b); return this; } } public interface IResolvableClass extends Type { public String resolveToClassName(); public Class resolveToClass(); } static public class SubMatrix extends AbstractMatrix { public SubMatrix() { } public Matrix matrix; public int x1, y1; public SubMatrix(Matrix matrix, Rect r) { super(r.w, r.h); this.matrix = matrix; x1 = r.x; y1 = r.y; } public A get(int x, int y) { try { return matrix.get(x + x1, y + y1); } catch (Throwable e) { throw augmentException(e, this); } } public void set(int x, int y, A a) { matrix.set(x + x1, y + y1, a); } public String toString() { return renderFunctionCall("SubMatrix", x1, y1, w, h); } } static public class SimplyLinkedList { public A head; public SimplyLinkedList tail; static public SimplyLinkedList cons(B head, SimplyLinkedList tail) { SimplyLinkedList l = new SimplyLinkedList(); l.head = head; l.tail = tail; return l; } } static public class AIStrategy_RandomWithVariation extends AIStrategy { public F0 random; public F1 vary; public AIStrategy_RandomWithVariation() { } public AIStrategy_RandomWithVariation(IF1 judge, IF0 random, IF1 vary) { setJudge(judge); this.random = toF0(random); this.vary = toF1(vary); } public boolean step() { go(); return true; } public void go() { submit(guess()); } public A guess() { A a = null; if (odd(round++) && vary != null && best.has()) a = callF(vary, best.get()); if (a == null) a = callF(random); return a; } } public interface WebServable { public Object html(IWebRequest req); } static public class FPSCounter { public Timestamp started = new Timestamp(); public double counter; synchronized public void inc() { counter++; } synchronized public double get() { return doubleRatio(counter, secondsSinceStart()); } synchronized public boolean isEmpty() { return counter == 0; } public double secondsSinceStart() { return elapsedSeconds(started); } synchronized public void reset() { started = tsNow(); counter = 0; } } static public class MechMode implements IFieldsToList { public Object readMode; public Object writeMode; public MechMode() { } public MechMode(Object readMode, Object writeMode) { this.writeMode = writeMode; this.readMode = readMode; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + readMode + ", " + writeMode + ")"; } public boolean equals(Object o) { if (!(o instanceof MechMode)) return false; MechMode __1 = (MechMode) o; return eq(readMode, __1.readMode) && eq(writeMode, __1.writeMode); } public int hashCode() { int h = -866263200; h = boostHashCombine(h, _hashCode(readMode)); h = boostHashCombine(h, _hashCode(writeMode)); return h; } public Object[] _fieldsToList() { return new Object[] { readMode, writeMode }; } } static final public class NotifyingStringBuffer implements CharSequence, Appendable { public StringBuilder builder = new StringBuilder(); public long changes; public List onChange; public synchronized Appendable append(char c) { builder.append(c); return change(); } public synchronized Appendable append(CharSequence csq, int start, int end) { builder.append(csq, start, end); return change(); } public synchronized Appendable append(CharSequence csq) { builder.append(csq); return change(); } public synchronized void setLength(int i) { builder.setLength(i); change(); } public synchronized void trimToSize() { builder.trimToSize(); } public NotifyingStringBuffer change() { ++changes; pcallFAll(onChange); return this; } synchronized public String toString() { return builder.toString(); } public synchronized char charAt(int index) { return builder.charAt(index); } public synchronized int length() { return builder.length(); } public synchronized CharSequence subSequence(int start, int end) { return builder.subSequence(start, end); } synchronized public String substring(int start) { return builder.substring(start); } public int capacity() { return builder.capacity(); } public synchronized void onChange(Runnable r) { onChange = listCreateAndAdd(onChange, r); } } static public interface IF2_Int { public int get(int a, int b); } static public class VolatileImageMakerForComponent implements IFieldsToList { public Component component; public int w; public int h; public Renderable renderable; public VolatileImageMakerForComponent() { } public VolatileImageMakerForComponent(Component component, int w, int h, Renderable renderable) { this.renderable = renderable; this.h = h; this.w = w; this.component = component; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + component + ", " + w + ", " + h + ", " + renderable + ")"; } public Object[] _fieldsToList() { return new Object[] { component, w, h, renderable }; } public VolatileImage vImg; public long contentsLostCounter; transient public Set onContentsLost; public VolatileImageMakerForComponent onContentsLost(Runnable r) { onContentsLost = createOrAddToSyncLinkedHashSet(onContentsLost, r); return this; } public VolatileImageMakerForComponent removeContentsLostListener(Runnable r) { utils.remove(onContentsLost, r); return this; } public void fireContentsLost() { if (onContentsLost != null) for (var listener : onContentsLost) pcallF_typed(listener); } public void renderOffscreen() { do { if (vImg.validate(component.getGraphicsConfiguration()) == VolatileImage.IMAGE_INCOMPATIBLE) vImg = component.createVolatileImage(w, h); Graphics2D g = vImg.createGraphics(); renderable.renderOn(g, w, h); g.dispose(); } while (contentsLost()); } public void paintOnScreen(Graphics2D gScreen) { do { if (vImg == null) vImg = component.createVolatileImage(w, h); int returnCode = vImg.validate(component.getGraphicsConfiguration()); if (returnCode == VolatileImage.IMAGE_RESTORED) { renderOffscreen(); } else if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) { vImg = component.createVolatileImage(w, h); renderOffscreen(); } gScreen.drawImage(vImg, 0, 0, component); } while (contentsLost()); } public boolean contentsLost() { if (!vImg.contentsLost()) return false; ++contentsLostCounter; fireContentsLost(); return true; } public boolean sizeIs(int w, int h) { return this.w == w && this.h == h; } } static public class CompactHashMap extends CompactAbstractMap { final static public int INITIAL_SIZE = 3; final static public double LOAD_FACTOR = 0.6; final static public Object nullObject = new Object(); final static public Object deletedObject = new Object(); public int elements; public int freecells; public Object[] table; public CompactHashMap() { this(INITIAL_SIZE); } public CompactHashMap(int size) { table = new Object[(size == 0 ? 1 : size) * 2]; elements = 0; freecells = tableSize(); } public CompactHashMap(Map map) { this(0); if (map != null) putAll(map); } public synchronized int size() { return elements; } public synchronized boolean isEmpty() { return elements == 0; } public synchronized void clear() { elements = 0; for (int ix = 0; ix < tableSize(); ix++) { key(ix, null); value(ix, null); } freecells = tableSize(); } public synchronized boolean containsKey(Object k) { return key(findKeyIndex(k)) != null; } public synchronized boolean containsValue(Object v) { if (v == null) v = (V) nullObject; for (int ix = 0; ix < tableSize(); ix++) if (value(ix) != null && value(ix).equals(v)) return true; return false; } public synchronized Set> entrySet() { return new EntrySet(); } public synchronized V remove(Object k) { int index = findKeyIndex(k); if (key(index) != null) { V v = value(index); key(index, deletedObject); value(index, deletedObject); elements--; return v; } else return null; } public synchronized V put(K k, V v) { if (k == null) k = (K) nullObject; int hash = k.hashCode(); int index = (hash & 0x7FFFFFFF) % tableSize(); int offset = 1; int deletedix = -1; while (key(index) != null && !(key(index).hashCode() == hash && key(index).equals(k))) { if (key(index) == deletedObject) deletedix = index; index = ((index + offset) & 0x7FFFFFFF) % tableSize(); offset = offset * 2 + 1; if (offset == -1) offset = 2; } if (key(index) == null) { if (deletedix != -1) index = deletedix; else freecells--; elements++; key(index, k); value(index, v); if (1 - (freecells / (double) tableSize()) > LOAD_FACTOR) rehash(tableSize() * 2 + 1); return null; } else { V oldv = value(index); value(index, v); return oldv; } } public void rehash(int newCapacity) { int oldCapacity = tableSize(); Object[] newTable = new Object[newCapacity * 2]; for (int ix = 0; ix < oldCapacity; ix++) { Object k = key(ix); if (k == null || k == deletedObject) continue; int hash = k.hashCode(); int index = (hash & 0x7FFFFFFF) % newCapacity; int offset = 1; while (newTable[index * 2] != null) { index = ((index + offset) & 0x7FFFFFFF) % newCapacity; offset = offset * 2 + 1; if (offset == -1) offset = 2; } newTable[index * 2] = k; newTable[index * 2 + 1] = value(ix); } table = newTable; freecells = tableSize() - elements; } public synchronized V get(Object k) { return value(findKeyIndex(k)); } public synchronized Collection values() { return new ValueCollection(); } public synchronized Set keySet() { return new KeySet(); } final public int findKeyIndex(Object k) { if (k == null) k = nullObject; int hash = k.hashCode(); int index = (hash & 0x7FFFFFFF) % tableSize(); int offset = 1; while (key(index) != null && !(key(index).hashCode() == hash && key(index).equals(k))) { index = ((index + offset) & 0x7FFFFFFF) % tableSize(); offset = offset * 2 + 1; if (offset == -1) offset = 2; } return index; } public class KeySet extends AbstractSet { public int size() { synchronized (CompactHashMap.this) { return elements; } } public boolean contains(Object k) { synchronized (CompactHashMap.this) { return containsKey(k); } } public Iterator iterator() { synchronized (CompactHashMap.this) { return new KeyIterator(); } } } public class KeyIterator implements Iterator { public int ix; public KeyIterator() { synchronized (CompactHashMap.this) { for (; ix < tableSize(); ix++) if (value(ix) != null && key(ix) != deletedObject) break; } } public boolean hasNext() { synchronized (CompactHashMap.this) { return ix < tableSize(); } } public void remove() { throw new UnsupportedOperationException("Collection is read-only"); } public K next() { synchronized (CompactHashMap.this) { if (ix >= tableSize()) throw new NoSuchElementException(); K key = (K) key(ix++); for (; ix < tableSize(); ix++) if (key(ix) != null && key(ix) != deletedObject) break; return key; } } } public class EntrySet extends AbstractSet> { public int size() { synchronized (CompactHashMap.this) { return elements; } } public boolean contains(Object o) { synchronized (CompactHashMap.this) { if (o instanceof Map.Entry) { Object key = ((Map.Entry) o).getKey(); if (!containsKey((Map.Entry) o)) return false; return eq(((Map.Entry) o).getValue(), get(key)); } return false; } } public Iterator> iterator() { return new EntryIterator(); } } public class EntryIterator implements Iterator> { public int ix; public EntryIterator() { synchronized (CompactHashMap.this) { for (; ix < tableSize(); ix++) if (value(ix) != null && key(ix) != deletedObject) break; } } public boolean hasNext() { synchronized (CompactHashMap.this) { return ix < tableSize(); } } public void remove() { throw new UnsupportedOperationException("Collection is read-only"); } public Map.Entry next() { synchronized (CompactHashMap.this) { if (ix >= tableSize()) throw new NoSuchElementException(); K key = key(ix); V val = value(ix); ++ix; for (; ix < tableSize(); ix++) if (key(ix) != null && key(ix) != deletedObject) break; return simpleMapEntry(key, val); } } } public class ValueCollection extends AbstractCollection { public int size() { synchronized (CompactHashMap.this) { return elements; } } public Iterator iterator() { return new ValueIterator(); } public boolean contains(Object v) { return containsValue(v); } } public class ValueIterator implements Iterator { public int ix; public ValueIterator() { synchronized (CompactHashMap.this) { for (; ix < table.length / 2; ix++) if (value(ix) != null && value(ix) != deletedObject) break; } } public boolean hasNext() { synchronized (CompactHashMap.this) { return ix < tableSize(); } } public void remove() { throw new UnsupportedOperationException("Collection is read-only"); } public V next() { synchronized (CompactHashMap.this) { if (ix >= tableSize()) throw new NoSuchElementException(); V value = (V) value(ix++); for (; ix < tableSize(); ix++) if (value(ix) != null && value(ix) != deletedObject) break; return value; } } } public K key(int i) { return (K) table[i * 2]; } public void key(int i, Object key) { table[i * 2] = key; } public V value(int i) { return (V) table[i * 2 + 1]; } public void value(int i, Object value) { table[i * 2 + 1] = value; } public int tableSize() { return table.length / 2; } } static public interface IProbabilistic { public void setScheduler(IProbabilisticScheduler ps); public IProbabilisticScheduler scheduler(); default public A initAction(A a) { scheduler().initAction(a); return a; } public void step0(); } static public class JVolatileImageSurface extends Surface { public VolatileImageMakerForComponent volatileImageMaker; final public JVolatileImageSurface setVolatileMode(boolean volatileMode) { return volatileMode(volatileMode); } public JVolatileImageSurface volatileMode(boolean volatileMode) { this.volatileMode = volatileMode; return this; } final public boolean getVolatileMode() { return volatileMode(); } public boolean volatileMode() { return volatileMode; } public boolean volatileMode = true; final public JVolatileImageSurface setRenderable(Renderable renderable) { return renderable(renderable); } public JVolatileImageSurface renderable(Renderable renderable) { this.renderable = renderable; return this; } final public Renderable getRenderable() { return renderable(); } public Renderable renderable() { return renderable; } public Renderable renderable; public JVolatileImageSurface() { } public JVolatileImageSurface(Renderable renderable) { this.renderable = renderable; } { clearSurface = false; } @Override public void render(int w, int h, Graphics2D g) { if (renderable == null) { fillRect(g, 0, 0, w, h, Color.white); return; } if (!volatileMode) renderable.renderOn(g, w, h); else { if (volatileImageMaker == null || !volatileImageMaker.sizeIs(w, h)) volatileImageMaker = new VolatileImageMakerForComponent(this, w, h, renderable); volatileImageMaker.paintOnScreen(g); } } } static public class Complex implements IFieldsToList { static final public String _fieldOrder = "re im"; public double re; public double im; public Complex() { } public Complex(double re, double im) { this.im = im; this.re = re; } public boolean equals(Object o) { if (!(o instanceof Complex)) return false; Complex __1 = (Complex) o; return re == __1.re && im == __1.im; } public int hashCode() { int h = -1679819632; h = boostHashCombine(h, _hashCode(re)); h = boostHashCombine(h, _hashCode(im)); return h; } public Object[] _fieldsToList() { return new Object[] { re, im }; } public double abs() { return sqrt(re * re + im * im); } public double re() { return re; } public double im() { return im; } final public double angle() { return phase(); } public double phase() { return Math.atan2(im, re); } public double fracAngle() { return fracNonNeg(angle() / twoPi()); } public String toString() { if (im != 0) return re == 0 ? im + "i" : re + plusPrefixUnlessMinus(str(im)) + "i"; else return str(re); } } static public class RasterBars extends Animation { public List> streaks; public RasterBars() { } public RasterBars(int w, int h, List> streaks) { this.streaks = streaks; this.h = h; this.w = w; } public void paint() { for (var streak : streaks) fillRect(g, 0, streak.a.start, w, l(streak.a), grayToColor(streak.b)); } } static public class MultiMap implements IMultiMap { public Map> data = new HashMap>(); public int fullSize; public MultiMap() { } public MultiMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); } public MultiMap(MultiMap map) { putAll(map); } public MultiMap(Map> data) { this.data = data; } public void put(A key, B value) { synchronized (data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); list.add(value); ++fullSize; } } public void add(A key, B value) { put(key, value); } public void addAll(A key, Collection values) { putAll(key, values); } public void addAllIfNotThere(A key, Collection values) { synchronized (data) { for (B value : values) setPut(key, value); } } public void setPut(A key, B value) { synchronized (data) { if (!containsPair(key, value)) put(key, value); } } public boolean containsPair(A key, B value) { synchronized (data) { return get(key).contains(value); } } public void putAll(Collection keys, B value) { synchronized (data) { for (A key : unnullForIteration(keys)) put(key, value); } } public void putAll(A key, Collection values) { synchronized (data) { if (nempty(values)) getActual(key).addAll(values); } } public void putAll(Iterable> pairs) { synchronized (data) { for (Pair p : unnullForIteration(pairs)) put(p.a, p.b); } } public void removeAll(A key, Collection values) { synchronized (data) { for (B value : values) remove(key, value); } } public List get(A key) { synchronized (data) { List list = data.get(key); return list == null ? Collections.emptyList() : list; } } public List getOpt(A key) { synchronized (data) { return data.get(key); } } public List getAndClear(A key) { synchronized (data) { List l = cloneList(data.get(key)); remove(key); return l; } } public List getActual(A key) { synchronized (data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); return list; } } public void clean(A key) { synchronized (data) { List list = data.get(key); if (list != null && list.isEmpty()) { fullSize -= l(list); data.remove(key); } } } final public Set keys() { return keySet(); } public Set keySet() { synchronized (data) { return data.keySet(); } } public void remove(A key) { synchronized (data) { fullSize -= l(this.getOpt(key)); data.remove(key); } } final public void remove(Pair p) { removePair(p); } public void removePair(Pair p) { if (p != null) remove(p.a, p.b); } public void remove(A key, B value) { synchronized (data) { List list = data.get(key); if (list != null) { if (list.remove(value)) fullSize--; if (list.isEmpty()) data.remove(key); } } } public void clear() { synchronized (data) { data.clear(); } } public boolean containsKey(A key) { synchronized (data) { return data.containsKey(key); } } public B getFirst(A key) { synchronized (data) { List list = get(key); return list.isEmpty() ? null : list.get(0); } } public void addAll(MultiMap map) { putAll(map); } public void putAll(MultiMap map) { synchronized (data) { for (A key : map.keySet()) putAll(key, map.get(key)); } } public void putAll(Map map) { synchronized (data) { if (map != null) for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue()); } } final public int keyCount() { return keysSize(); } public int keysSize() { synchronized (data) { return l(data); } } final public int fullSize() { return size(); } public int size() { synchronized (data) { return fullSize; } } public List reverseGet(B b) { synchronized (data) { List l = new ArrayList(); for (A key : data.keySet()) if (data.get(key).contains(b)) l.add(key); return l; } } public Map> asMap() { synchronized (data) { return cloneMap(data); } } public boolean isEmpty() { synchronized (data) { return data.isEmpty(); } } public List _makeEmptyList() { return new ArrayList(); } public Collection> allLists() { synchronized (data) { return new ArrayList(data.values()); } } public Collection> values() { return allLists(); } public List allValues() { return concatLists(data.values()); } public Object mutex() { return data; } public String toString() { return "mm" + str(data); } public Map> innerMap() { return data; } } static public class RSTVar extends VarWithNotify { public IVF1 action; public A lastSentValue; public ReliableSingleThread rst = new ReliableSingleThread(() -> update()); volatile public boolean forceUpdate = false; public RSTVar(IVF1 action) { this.action = action; onChange(rst); } private void update() { A value = get(); if (!eq(lastSentValue, value) || forceUpdate) { forceUpdate = false; lastSentValue = value; { if (action != null) action.get(value); } } } public void forceUpdate() { forceUpdate = true; rst.trigger(); } } static public class ProbabilisticScheduler extends Meta implements IProbabilisticScheduler, Steppable { public TreeSetWithDuplicates entries = new TreeSetWithDuplicates<>(byProbability()); public long stepCount; public boolean verbose = false; public double cutoffProbabilityOnAdd = 0; public double cutoffProbabilityOnExecute = 0; public Comparator byProbability() { return (a, b) -> cmp(b.probability, a.probability); } public long dropped; public double lastExecutedProbability = 1.0; public ThreadLocal threadProbability = new ThreadLocal(); public class Entry { public Entry() { } public double probability; public Runnable action; public Entry(double probability, Runnable action) { this.action = action; this.probability = probability; } public void run() { try { initAction(action); AutoCloseable __1 = tempSetTL(threadProbability, probability); try { action.run(); } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return str(new WithProbability(probability, action)); } } final public void at(double probability, Runnable action) { add(probability, action); } public void add(double probability, Runnable action) { if (action == null) return; if (probability < cutoffProbabilityOnAdd) { ++dropped; { if (scaffoldingEnabled(this)) scaffoldCalled(this, "Not scheduling " + withProbability(probability, action) + " (below threshold of " + cutoffProbabilityOnAdd + ")"); } return; } { if (scaffoldingEnabled(this)) scaffoldCalled(this, "Scheduling " + withProbability(probability, action)); } entries.add(new Entry(probability, action)); } public boolean step() { return stepFirstUnstepped(); } public Entry nextSteppable() { Entry s = first(entries); if (s != null && s.probability <= cutoffProbabilityOnExecute) return null; return s; } public boolean stepFirstUnstepped() { Entry s = nextSteppable(); if (s == null) return false; if (verbose) print("Current scheduler probability: " + s.probability); entries.remove(s); ++stepCount; lastExecutedProbability = s.probability; s.run(); return true; } public void reset() { entries.clear(); } public void run() { try { stepAll(this); } catch (Exception __e) { throw rethrow(__e); } } public void runWithStats() { stepAllWithStats(this); } public void run(int maxSteps) { stepMax(maxSteps, this); } public void printStats() { Entry first = entries.first(), last = entries.last(); Entry next = nextSteppable(); print("ProbabilisticScheduler. " + nEntries(entries) + ", highest probability in queue: " + (first == null ? "-" : first.probability) + ", lowest probability in queue: " + (last == null ? "-" : last.probability) + ", cutoff probability: " + cutoffProbabilityOnAdd + "/" + cutoffProbabilityOnExecute + ", " + (next == null ? "done" : "next step: " + next.action)); } final public double current() { return currentProbability(); } public double currentProbability() { return or(threadProbability.get(), 1.0); } public double remainingProbability() { Entry s = nextSteppable(); return s == null ? 0.0 : s.probability; } public double lastExecutedProbability() { return lastExecutedProbability; } public long stepCount() { return stepCount; } public boolean isEmpty() { return empty(entries); } } static public interface IResourceLoader { public String loadSnippet(String snippetID); public String getTranspiled(String snippetID); public int getSnippetType(String snippetID); public String getSnippetTitle(String snippetID); public File loadLibrary(String snippetID); default public File pathToJavaXJar() { return pathToJavaxJar_noResourceLoader(); } default public File getSnippetJar(String snippetID, String transpiledSrc) { return null; } } static final public class WeakHasherMap extends AbstractMap implements Map { public Hasher hasher = null; private boolean keyEquals(Object k1, Object k2) { return (hasher == null ? k1.equals(k2) : hasher.equals(k1, k2)); } private int keyHashCode(Object k1) { return (hasher == null ? k1.hashCode() : hasher.hashCode(k1)); } private WeakKey WeakKeyCreate(K k) { if (k == null) return null; else return new WeakKey(k); } private WeakKey WeakKeyCreate(K k, ReferenceQueue q) { if (k == null) return null; else return new WeakKey(k, q); } final public class WeakKey extends WeakReference { public int hash; public WeakKey(K k) { super(k); hash = keyHashCode(k); } private WeakKey create(K k) { if (k == null) return null; else return new WeakKey(k); } public WeakKey(K k, ReferenceQueue q) { super(k, q); hash = keyHashCode(k); } private WeakKey create(K k, ReferenceQueue q) { if (k == null) return null; else return new WeakKey(k, q); } @Override public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; if (!(o.getClass().equals(WeakKey.class))) return false; Object t = this.get(); @SuppressWarnings("unchecked") Object u = ((WeakKey) o).get(); if ((t == null) || (u == null)) return false; if (t == u) return true; return keyEquals(t, u); } @Override public int hashCode() { return hash; } } public HashMap hash; public ReferenceQueue queue = new ReferenceQueue(); @SuppressWarnings("unchecked") private void processQueue() { WeakKey wk; while ((wk = (WeakKey) queue.poll()) != null) { hash.remove(wk); } } public WeakHasherMap(int initialCapacity, float loadFactor) { hash = new HashMap(initialCapacity, loadFactor); } public WeakHasherMap(int initialCapacity) { hash = new HashMap(initialCapacity); } public WeakHasherMap() { hash = new HashMap(); } public WeakHasherMap(Hasher h) { hash = new HashMap(); hasher = h; } @Override public int size() { return entrySet().size(); } @Override public boolean isEmpty() { return entrySet().isEmpty(); } @Override public boolean containsKey(Object key) { @SuppressWarnings("unchecked") K kkey = (K) key; return hash.containsKey(WeakKeyCreate(kkey)); } @Override public V get(Object key) { @SuppressWarnings("unchecked") K kkey = (K) key; return hash.get(WeakKeyCreate(kkey)); } @Override public V put(K key, V value) { processQueue(); return hash.put(WeakKeyCreate(key, queue), value); } @Override public V remove(Object key) { processQueue(); @SuppressWarnings("unchecked") K kkey = (K) key; return hash.remove(WeakKeyCreate(kkey)); } @Override public void clear() { processQueue(); hash.clear(); } @SuppressWarnings("TypeParameterShadowing") final public class Entry implements Map.Entry { public Map.Entry ent; public K key; public Entry(Map.Entry ent, K key) { this.ent = ent; this.key = key; } @Override public K getKey() { return key; } @Override public V getValue() { return ent.getValue(); } @Override public V setValue(V value) { return ent.setValue(value); } private boolean keyvalEquals(K o1, K o2) { return (o1 == null) ? (o2 == null) : keyEquals(o1, o2); } private boolean valEquals(V o1, V o2) { return (o1 == null) ? (o2 == null) : o1.equals(o2); } @SuppressWarnings("NonOverridingEquals") public boolean equals(Map.Entry e) { return (keyvalEquals(key, e.getKey()) && valEquals(getValue(), e.getValue())); } @Override public int hashCode() { V v; return (((key == null) ? 0 : keyHashCode(key)) ^ (((v = getValue()) == null) ? 0 : v.hashCode())); } } final public class EntrySet extends AbstractSet> { public Set> hashEntrySet = hash.entrySet(); @Override public Iterator> iterator() { return new Iterator>() { public Iterator> hashIterator = hashEntrySet.iterator(); public Map.Entry next = null; @Override public boolean hasNext() { while (hashIterator.hasNext()) { Map.Entry ent = hashIterator.next(); WeakKey wk = ent.getKey(); K k = null; if ((wk != null) && ((k = wk.get()) == null)) { continue; } next = new Entry(ent, k); return true; } return false; } @Override public Map.Entry next() { if ((next == null) && !hasNext()) throw new NoSuchElementException(); Map.Entry e = next; next = null; return e; } @Override public void remove() { hashIterator.remove(); } }; } @Override public boolean isEmpty() { return !(iterator().hasNext()); } @Override public int size() { int j = 0; for (Iterator> i = iterator(); i.hasNext(); i.next()) j++; return j; } @Override public boolean remove(Object o) { processQueue(); if (!(o instanceof Map.Entry)) return false; @SuppressWarnings("unchecked") Map.Entry e = (Map.Entry) o; Object ev = e.getValue(); WeakKey wk = WeakKeyCreate(e.getKey()); Object hv = hash.get(wk); if ((hv == null) ? ((ev == null) && hash.containsKey(wk)) : hv.equals(ev)) { hash.remove(wk); return true; } return false; } @Override public int hashCode() { int h = 0; for (Iterator> i = hashEntrySet.iterator(); i.hasNext(); ) { Map.Entry ent = i.next(); WeakKey wk = ent.getKey(); Object v; if (wk == null) continue; h += (wk.hashCode() ^ (((v = ent.getValue()) == null) ? 0 : v.hashCode())); } return h; } } public Set> entrySet = null; @Override public Set> entrySet() { if (entrySet == null) entrySet = new EntrySet(); return entrySet; } public K findKey(Object key) { processQueue(); K kkey = (K) key; WeakKey wkey = WeakKeyCreate(kkey); WeakKey found = hashMap_findKey(hash, wkey); return found == null ? null : found.get(); } } static public class Either { public byte which; public Object value; public Either() { } public Either(int which, Object value) { this.which = (byte) which; this.value = value; } public boolean isA() { return which == 1; } public boolean isB() { return which == 2; } public A a() { if (which != 1) _failMe(); return (A) value; } public B b() { if (which != 2) _failMe(); return (B) value; } public A aOpt() { return which != 1 ? null : (A) value; } public B bOpt() { return which != 2 ? null : (B) value; } public void _failMe() { throw fail("Either object is of wrong type: " + shortClassName(value)); } public String toString() { return "Either" + (isA() ? "A" : "B") + "(" + value + ")"; } } static public class Ratio implements IFieldsToList { static final public String _fieldOrder = "numerator denominator"; public double numerator; public double denominator; public Ratio() { } public Ratio(double numerator, double denominator) { this.denominator = denominator; this.numerator = numerator; } public boolean equals(Object o) { if (!(o instanceof Ratio)) return false; Ratio __1 = (Ratio) o; return numerator == __1.numerator && denominator == __1.denominator; } public int hashCode() { int h = 78733291; h = boostHashCombine(h, _hashCode(numerator)); h = boostHashCombine(h, _hashCode(denominator)); return h; } public Object[] _fieldsToList() { return new Object[] { numerator, denominator }; } public Ratio(double numerator) { this(numerator, 1); } public double get() { return doubleRatio(numerator, denominator); } public String toString() { return numerator + "/" + denominator + "=" + (denominator == 0 ? "oops" : str(get())); } } static public class FunctionCall implements Transformable, IFieldsToList { public Object function; public Object[] args; public FunctionCall() { } public Object[] _fieldsToList() { return new Object[] { function, args }; } static public String _fieldOrder = "function args"; public FunctionCall(Object function, Object... args) { this.args = args; this.function = function; if (empty(this.args)) this.args = null; } public FunctionCall(Object function, List args) { this(function, toObjectArray(args)); } public String toString() { return function + "(" + joinWithComma(allToString(args)) + ")"; } public String toStringWithOptionalParens() { return empty(args) ? str(function) : toString(); } public boolean equals(Object o) { return o instanceof FunctionCall && eq(function, ((FunctionCall) o).function) && objectArraysEqual(args, ((FunctionCall) o).args); } public int hashCode() { return hashAboutObjects(function, asList(args)); } public List args() { return asList(args); } public Object transformUsing(IF1 f) { return new FunctionCall(f.get(function), mapObjectArray(f, args)); } } static public class PosterizeBufferedImage implements PixelPreservingImageOpResult { public BufferedImage img; public BufferedImage result; public IPosterizer posterizer; public CachedPosterizer cachedPosterizer; public PosterizeBufferedImage(int brightnessLevels, BufferedImage img) { this.img = img; if (brightnessLevels >= 256 || img == null) posterizer = new DummyPosterizer(); posterizer = new SinglePixelPosterizer(brightnessLevels); } public PosterizeBufferedImage(IPosterizer posterizer, BufferedImage img) { this.img = img; this.posterizer = posterizer; } public void run() { try { if (img == null) return; if (posterizer instanceof DummyPosterizer) { result = img; return; } GrabbableIntPixels gp = grabbableIntPixels_fastOrSlow(img); int w = img.getWidth(), h = img.getHeight(), n = w * h; int[] pixels = gp.data; int[] pixels2 = new int[n]; cachePosterizer(); var cachedPosterizer = this.cachedPosterizer; int iOut = 0, iIn = gp.offset; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int rgb = pixels[iIn + x]; pixels2[iOut++] = rgbInt(cachedPosterizer.get(rgbRed(rgb)), cachedPosterizer.get(rgbGreen(rgb)), cachedPosterizer.get(rgbBlue(rgb))); } iIn += gp.scanlineStride; } result = bufferedImageWithoutAlpha(w, h, pixels2); } catch (Exception __e) { throw rethrow(__e); } } public BufferedImage pixelPreservingSrcImage() { return img; } public BufferedImage get() { if (result == null) run(); return result; } private void cachePosterizer() { if (cachedPosterizer == null) cachedPosterizer = utils.cachePosterizer(posterizer); } } abstract static public class NotifyingSet extends NotifyingCollection implements Set { public Set set; public NotifyingSet() { } public NotifyingSet(Set set) { super(set); this.set = set; } } static public class CompilerBot { static public boolean verbose = false; static public File compileSnippet(String snippetID) { return compileSnippet(snippetID, ""); } static public Pair compileSnippet2(String snippetID) { return compileSnippet2(snippetID, ""); } static public File compileSnippet(String snippetID, String javaTarget) { return compileSnippet2(snippetID, javaTarget).a; } static public Pair compileSnippet2(String snippetID, String javaTarget) { String transpiledSrc = getServerTranspiled2(snippetID); if (transpiledSrc == null) throw fail("Snippet not found or not public: " + snippetID); int i = transpiledSrc.indexOf('\n'); String libs = transpiledSrc.substring(0, Math.max(0, i)); if (verbose) print("Compiling snippet: " + snippetID + ". Libs: " + libs); transpiledSrc = transpiledSrc.substring(i + 1); return pair(compile(transpiledSrc, libs, javaTarget, snippetID), transpiledSrc); } static public File compile(String src) { return compile(src, ""); } static public File compile(String src, String libs) { return compile(src, libs, null); } static public File compile(String src, String dehlibs, String javaTarget) { return compile(src, dehlibs, javaTarget, null); } static public File compile(String src, String dehlibs, String javaTarget, String progID) { if (verbose) print("Compiling " + l(src) + " chars"); String md5 = md5(dehlibs + "\n" + src + "\n" + fsIOpt(progID)); File jar = getJarFile(md5); if (jar == null || jar.length() <= 22) { List tok = javaTok(src); List mainClass = findMainClass(tok); boolean canRename = mainClass != null && useDummyMainClasses() && isSnippetID(progID) && !tok_classHasModifier(mainClass, "public"); if (verbose) print("useRenaming: " + useDummyMainClasses() + ", canRename: " + canRename + ", progID: " + progID); String mainClassName = joinNemptiesWithDot(tok_packageName(tok), or(getClassDeclarationName(mainClass), "main")); AutoCloseable __1 = tempSetTL(javaCompileToJar_addMoreFiles, dir -> { if (!eq(mainClassName, "main")) saveTextFile(newFile(dir, "main-class"), mainClassName); saveTextFile(newFile(dir, manifestPathInJar()), manifestTextForMainClass(mainClassName)); }); try { javaCompileToJar_optionalRename(src, dehlibs, jar, canRename ? progID : null, progID); } finally { _close(__1); } } else { if (verbose) print("Getting classes from cache (" + jar.getAbsolutePath() + ", " + jar.length() + " bytes)"); touchFile(jar); } return jar; } static public File getJarFile(String md5) { assertTrue(isMD5(md5)); String fileName = md5 + ".jar"; File f = newFile(destDir(), fileName); return fileExists(f) ? f : userDir(appendSlash(compilerBotDestDirSubName()) + fileName); } static public File destDir() { return compilerBotDestDir(); } } static public class JMenuScroller { public VF1 fillMenu; public JPopupMenu menu; public Component[] menuItems; public MenuScrollItem upItem; public MenuScrollItem downItem; final public MenuScrollListener menuListener = new MenuScrollListener(); public int scrollCount; public int interval; public int topFixedCount; public int bottomFixedCount; public int firstIndex = 0; public int keepVisibleIndex = -1; public static JMenuScroller setScrollerFor(JMenu menu) { return new JMenuScroller(menu); } public static JMenuScroller setScrollerFor(JPopupMenu menu) { return new JMenuScroller(menu); } public static JMenuScroller setScrollerFor(JMenu menu, int scrollCount) { return new JMenuScroller(menu, scrollCount); } public static JMenuScroller setScrollerFor(JPopupMenu menu, int scrollCount) { return new JMenuScroller(menu, scrollCount); } public static JMenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval) { return new JMenuScroller(menu, scrollCount, interval); } public static JMenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval) { return new JMenuScroller(menu, scrollCount, interval); } public static JMenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { return new JMenuScroller(menu, scrollCount, interval, topFixedCount, bottomFixedCount); } public static JMenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { return new JMenuScroller(menu, scrollCount, interval, topFixedCount, bottomFixedCount); } public JMenuScroller(JMenu menu) { this(menu, 15); } public JMenuScroller(JPopupMenu menu) { this(menu, 15); } public JMenuScroller(JMenu menu, int scrollCount) { this(menu, scrollCount, 150); } public JMenuScroller(JPopupMenu menu, int scrollCount) { this(menu, scrollCount, 150); } public JMenuScroller(JMenu menu, int scrollCount, int interval) { this(menu, scrollCount, interval, 0, 0); } public JMenuScroller(JPopupMenu menu, int scrollCount, int interval) { this(menu, scrollCount, interval, 0, 0); } public JMenuScroller(JMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { this(menu.getPopupMenu(), scrollCount, interval, topFixedCount, bottomFixedCount); } public JMenuScroller(JPopupMenu menu, int scrollCount, int interval, int topFixedCount, int bottomFixedCount) { if (scrollCount <= 0 || interval <= 0) { throw new IllegalArgumentException("scrollCount and interval must be greater than 0"); } if (topFixedCount < 0 || bottomFixedCount < 0) { throw new IllegalArgumentException("topFixedCount and bottomFixedCount cannot be negative"); } upItem = new MenuScrollItem(UP, -1); downItem = new MenuScrollItem(DOWN, +1); setScrollCount(scrollCount); setInterval(interval); setTopFixedCount(topFixedCount); setBottomFixedCount(bottomFixedCount); this.menu = menu; menu.addPopupMenuListener(menuListener); } public int getInterval() { return interval; } public void setInterval(int interval) { if (interval <= 0) { throw new IllegalArgumentException("interval must be greater than 0"); } upItem.setInterval(interval); downItem.setInterval(interval); this.interval = interval; } public int getscrollCount() { return scrollCount; } public void setScrollCount(int scrollCount) { if (scrollCount <= 0) { throw new IllegalArgumentException("scrollCount must be greater than 0"); } this.scrollCount = scrollCount; } public int getTopFixedCount() { return topFixedCount; } public void setTopFixedCount(int topFixedCount) { if (firstIndex <= topFixedCount) { firstIndex = topFixedCount; } else { firstIndex += (topFixedCount - this.topFixedCount); } this.topFixedCount = topFixedCount; } public int getBottomFixedCount() { return bottomFixedCount; } public void setBottomFixedCount(int bottomFixedCount) { this.bottomFixedCount = bottomFixedCount; } public void keepVisible(JMenuItem item) { if (item == null) { keepVisibleIndex = -1; } else { int index = menu.getComponentIndex(item); keepVisibleIndex = index; } } public void keepVisible(int index) { keepVisibleIndex = index; } public void dispose() { if (menu != null) { menu.removePopupMenuListener(menuListener); menu = null; } } @Override public void finalize() throws Throwable { dispose(); } private void refreshMenu() { if (menuItems != null && menuItems.length > 0) { firstIndex = Math.max(topFixedCount, firstIndex); firstIndex = Math.min(menuItems.length - bottomFixedCount - scrollCount, firstIndex); upItem.setEnabled(firstIndex > topFixedCount); downItem.setEnabled(firstIndex + scrollCount < menuItems.length - bottomFixedCount); menu.removeAll(); for (int i = 0; i < topFixedCount; i++) { menu.add(menuItems[i]); } if (topFixedCount > 0) { menu.addSeparator(); } menu.add(upItem); for (int i = firstIndex; i < scrollCount + firstIndex; i++) { menu.add(menuItems[i]); } menu.add(downItem); if (bottomFixedCount > 0) { menu.addSeparator(); } for (int i = menuItems.length - bottomFixedCount; i < menuItems.length; i++) { menu.add(menuItems[i]); } JComponent parent = (JComponent) upItem.getParent(); parent.revalidate(); parent.repaint(); } } public class MenuScrollListener implements PopupMenuListener { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { if (fillMenu != null) { clearPopupMenu(menu); callF(fillMenu, menu); } setMenuItems(); } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { if (fillMenu != null) clearPopupMenu(menu); else restoreMenuItems(); } @Override public void popupMenuCanceled(PopupMenuEvent e) { if (fillMenu != null) clearPopupMenu(menu); else restoreMenuItems(); } private void setMenuItems() { menuItems = menu.getComponents(); if (keepVisibleIndex >= topFixedCount && keepVisibleIndex <= menuItems.length - bottomFixedCount && (keepVisibleIndex > firstIndex + scrollCount || keepVisibleIndex < firstIndex)) { firstIndex = Math.min(firstIndex, keepVisibleIndex); firstIndex = Math.max(firstIndex, keepVisibleIndex - scrollCount + 1); } if (menuItems.length > topFixedCount + scrollCount + bottomFixedCount) { refreshMenu(); } } private void restoreMenuItems() { menu.removeAll(); for (Component component : menuItems) { menu.add(component); } } } public class MenuScrollTimer extends javax.swing.Timer { public MenuScrollTimer(final int increment, int interval) { super(interval, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { firstIndex += increment; refreshMenu(); } }); } } public class MenuScrollItem extends JMenuItem implements ChangeListener { public MenuScrollTimer timer; public MenuScrollItem(MenuIcon icon, int increment) { setIcon(icon); setDisabledIcon(icon); timer = new MenuScrollTimer(increment, interval); addChangeListener(this); } public void setInterval(int interval) { timer.setDelay(interval); } @Override public void stateChanged(ChangeEvent e) { if (isArmed() && !timer.isRunning()) { timer.start(); } if (!isArmed() && timer.isRunning()) { timer.stop(); } } } static public MenuIcon UP = new MenuIcon(9, 1, 9); static public MenuIcon DOWN = new MenuIcon(1, 9, 1); static public class MenuIcon implements Icon { final public int[] xPoints = { 1, 5, 9 }; final public int[] yPoints; public MenuIcon(int... yPoints) { this.yPoints = yPoints; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { Dimension size = c.getSize(); Graphics g2 = g.create(size.width / 2 - 5, size.height / 2 - 5, 10, 10); g2.setColor(Color.GRAY); g2.drawPolygon(xPoints, yPoints, 3); if (c.isEnabled()) { g2.setColor(Color.BLACK); g2.fillPolygon(xPoints, yPoints, 3); } g2.dispose(); } @Override public int getIconWidth() { return 0; } @Override public int getIconHeight() { return 10; } } } static public class CharInToken implements IFieldsToList { static final public String _fieldOrder = "tok iTok iChar"; public List tok; public int iTok; public int iChar; public CharInToken() { } public CharInToken(List tok, int iTok, int iChar) { this.iChar = iChar; this.iTok = iTok; this.tok = tok; } public boolean equals(Object o) { if (!(o instanceof CharInToken)) return false; CharInToken __1 = (CharInToken) o; return eq(tok, __1.tok) && iTok == __1.iTok && iChar == __1.iChar; } public int hashCode() { int h = 2081721214; h = boostHashCombine(h, _hashCode(tok)); h = boostHashCombine(h, _hashCode(iTok)); h = boostHashCombine(h, _hashCode(iChar)); return h; } public Object[] _fieldsToList() { return new Object[] { tok, iTok, iChar }; } public String token() { return get(tok, iTok); } public String toString() { return renderRecordVars("CharInToken", "iTok", iTok, "iChar", iChar, "token", token()); } } static public class ImageFileFilter extends javax.swing.filechooser.FileFilter { final public ImageFileFilter setAllowDirectories(boolean allowDirectories) { return allowDirectories(allowDirectories); } public ImageFileFilter allowDirectories(boolean allowDirectories) { this.allowDirectories = allowDirectories; return this; } final public boolean getAllowDirectories() { return allowDirectories(); } public boolean allowDirectories() { return allowDirectories; } public boolean allowDirectories = false; public boolean accept(File f) { if (isDirectory(f)) return allowDirectories; return isImageFile(f); } public String getDescription() { return "Images"; } } public interface ScalingImageOpResult { public Img scalingSrcImage(); } static public class MRUCache extends LinkedHashMap { public int maxSize = 10; public MRUCache() { } public MRUCache(int maxSize) { this.maxSize = maxSize; } public boolean removeEldestEntry(Map.Entry eldest) { return size() > maxSize; } public Object _serialize() { return ll(maxSize, cloneLinkedHashMap(this)); } static public MRUCache _deserialize(List l) { MRUCache m = new MRUCache(); m.maxSize = (int) first(l); m.putAll((LinkedHashMap) second(l)); return m; } } static public class Angle { public Angle() { } public double radians; public Angle(double radians) { this.radians = radians; } public Angle(double x, double y) { radians = atan2(x, y); } static public Angle fromRadians(double radians) { return new Angle(radians); } static public Angle fromDegrees(double degrees) { return new Angle(degreesToRadians(degrees)); } public double radians() { return radians; } public double degrees() { return radiansToDegrees(radians); } public double x() { return cos(radians); } public double y() { return sin(radians); } public String toString() { return formatDouble(degrees(), 1) + "°"; } } static public class Scored extends Var { public float score; public Scored() { } public Scored(A a, float score) { super(a); this.score = score; } public Scored(A a, double score) { super(a); this.score = (float) score; } public float score() { return score; } public String toString() { return toIntPercent(score) + "%: " + str(get()); } } static public class IIBWVirtualClip extends Meta implements IBWIntegralImage { public IBWIntegralImage fullImage; public int x1, y1, w, h; public IIBWVirtualClip() { } public IIBWVirtualClip(IBWIntegralImage fullImage, Rect r) { this(fullImage, r.x, r.y, r.w, r.h); } public IIBWVirtualClip(IBWIntegralImage fullImage, int x1, int y1, int w, int h) { this.h = h; this.w = w; this.y1 = y1; this.x1 = x1; this.fullImage = fullImage; optimize(); } public int getWidth() { return w; } public int getHeight() { return h; } public int getIIValue(int x, int y) { return fullImage.getIIValue(x + x1, y + y1); } public double getIIValue(double x, double y) { return fullImage.getIIValue(x + x1, y + y1); } public BufferedImage getBufferedImage() { return clipBufferedImage(fullImage.getBufferedImage(), x1, y1, w, h); } public void optimize() { if (fullImage instanceof IIBWVirtualClip) { x1 += ((IIBWVirtualClip) fullImage).x1; y1 += ((IIBWVirtualClip) fullImage).y1; fullImage = ((IIBWVirtualClip) fullImage).fullImage; } } } static public class HashBWImage implements IFieldsToList { public BWImage img; public HashBWImage() { } public HashBWImage(BWImage img) { this.img = img; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + img + ")"; } public Object[] _fieldsToList() { return new Object[] { img }; } public long hash; public long get() { if (img == null) return hash; int w = img.getWidth(), h = img.getHeight(); int n = w * h; byte[] pixels = img.pixels; addToHash(w); addToHash(h); for (int i = 0; i < n; i++) addToHash(0xFF000000 | rgbIntFromGrayscale(ubyteToInt(pixels[i]))); return hash; } public void addToHash(long x) { hash = boostHashCombine64(hash, x); } } static public class PadImageToAspectRatio extends Meta implements IFieldsToList { public BufferedImage img; public Ratio ratio; public Color color; public PadImageToAspectRatio() { } public PadImageToAspectRatio(BufferedImage img, Ratio ratio, Color color) { this.color = color; this.ratio = ratio; this.img = img; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + img + ", " + ratio + ", " + color + ")"; } public Object[] _fieldsToList() { return new Object[] { img, ratio, color }; } public BufferedImage out; public PadImageToAspectRatio(BufferedImage img, double ratio, Color color) { this.ratio = new Ratio(ratio); this.color = color; this.img = img; } public BufferedImage get() { int w = img.getWidth(), h = img.getHeight(); double actualRatio = doubleRatio(w, h); double targetRatio = this.ratio.get(); int w2 = w, h2 = h; if (targetRatio > actualRatio) w2 = iround(h2 * targetRatio); else h2 = iround(w2 / targetRatio); if (scaffolding()) printVars("w", w, "h", h, "w2", w2, "h2", h2, "actualRatio", actualRatio, "targetRatio", targetRatio, "ratio", this.ratio); if (w == w2 && h == h2) return img; out = isFullyTransparent(color) ? newTransparentImage(w2, h2) : newImage(w2, h2, color); drawImageOnImage(img, out, (w2 - w) / 2, (h2 - h) / 2); return out; } } static abstract public class VF1 implements IVF1 { public abstract void get(A a); } static abstract public class VF2 { abstract public void get(A a, B b); } static public class JE_RepElement extends JEInstantCompressor_AnyType> { public ICachedJavaXExpr compress(List data) { if (metaGet("scaffolding") != null) scaffoldCalled(this, "compress", data); boolean sc = scaffoldingEnabled(this); if (empty(data)) return null; A a = first(data); int n = l(data); for (int i = 1; i < n; i++) if (!eq(data.get(i), a)) { if (sc) scaffoldCalled(this, "diff at " + i + "/" + n); return null; } return javaExpr(functionCall("repSimple", n, elementToJava(a)), () -> repSimple(n, a)); } transient public IF1 elementToJava; public ICachedJavaXExpr elementToJava(A o) { return elementToJava != null ? elementToJava.get(o) : elementToJava_base(o); } final public ICachedJavaXExpr elementToJava_fallback(IF1 _f, A o) { return _f != null ? _f.get(o) : elementToJava_base(o); } public ICachedJavaXExpr elementToJava_base(A o) { var e = javaObjectToIJavaExpr(o); if (e == null) throw fail("elementToJava: " + className(o)); return e; } } static public class SynchronizedFloatBufferPresentingAsDoubles implements IDoubleBuffer { public float[] data; public int size; public SynchronizedFloatBufferPresentingAsDoubles() { } public SynchronizedFloatBufferPresentingAsDoubles(int size) { if (size != 0) data = new float[size]; } public SynchronizedFloatBufferPresentingAsDoubles(Iterable l) { addAll(l); } public SynchronizedFloatBufferPresentingAsDoubles(Collection l) { this(l(l)); addAll(l); } public SynchronizedFloatBufferPresentingAsDoubles(double... data) { this.data = doubleArrayToFloatArray(data); size = l(data); } public synchronized void add(double i) { if (size >= lFloatArray(data)) { data = resizeFloatArray(data, Math.max(1, toInt(Math.min(maximumSafeArraySize(), lFloatArray(data) * 2L)))); if (size >= data.length) throw fail(shortClassName(this) + " too large: " + size); } data[size++] = (float) i; } public synchronized void addAll(Iterable l) { if (l != null) for (double i : l) add(i); } public synchronized double[] toArray() { return size == 0 ? null : takeFirstFromFloatArrayAsDoubleArray(data, size); } public double[] toArrayNonNull() { return unnull(toArray()); } synchronized public List toList() { return floatArrayToDoubleList(data, 0, size); } synchronized public List asVirtualList() { return new RandomAccessAbstractList() { public int size() { return SynchronizedFloatBufferPresentingAsDoubles.this.size(); } public Double get(int i) { return SynchronizedFloatBufferPresentingAsDoubles.this.get(i); } public Double set(int i, Double val) { synchronized (SynchronizedFloatBufferPresentingAsDoubles.this) { Double a = get(i); data[i] = val.floatValue(); return a; } } }; } synchronized public void reset() { size = 0; } public void clear() { reset(); } public synchronized int size() { return size; } public synchronized boolean isEmpty() { return size == 0; } public synchronized double get(int idx) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); return data[idx]; } synchronized public void set(int idx, double value) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); data[idx] = (float) value; } public synchronized double popLast() { if (size == 0) throw fail("empty buffer"); return data[--size]; } public synchronized double first() { return data[0]; } public synchronized double last() { return data[size - 1]; } synchronized public double nextToLast() { return data[size - 2]; } public String toString() { return squareBracket(joinWithSpace(toList())); } public Iterator iterator() { return new IterableIterator() { public int i = 0; public boolean hasNext() { return i < size(); } public Double next() { synchronized (SynchronizedFloatBufferPresentingAsDoubles.this) { return (double) data[i++]; } } }; } public synchronized void trimToSize() { data = resizeFloatArray(data, size); } public synchronized int indexOf(double b) { for (int i = 0; i < size; i++) if (data[i] == (float) b) return i; return -1; } synchronized public double[] subArray(int start, int end) { return subFloatArrayAsDoubleArray(data, start, min(end, size)); } public synchronized void insertAt(int idx, double[] l) { int n = l(l); if (n == 0) return; float[] newData = new float[size + n]; arraycopy(data, 0, newData, 0, idx); for (int i = 0; i < n; i++) newData[idx + i] = (float) l[i]; arraycopy(data, idx, newData, idx + n, size - idx); data = newData; size = newData.length; } public void integrityCheck() { assertTrue("Size positive", size >= 0); assertTrue("Data length", l(data) >= size); } } static public interface ICachedJavaXExpr extends IMeta { public default A quickEval() { throw fail("Can't quick eval: " + toStringWithClassName(this)); } public default Object javaConstruct() { return this; } default public int sourceCodeLength() { return l(toString()); } } public interface IStackWithOptions extends IVStack { default public void options(B currentFrame, IVF1... options) { options(currentFrame, arrayIterator(options)); } public void options(B currentFrame, Iterable> options); default public void optionsOrReturn(B currentFrame, Collection> options) { if (empty(options)) _return(); else options(currentFrame, options); } } static public class RightAlignedLine extends JPanel { public RightAlignedLine(int spacing, Component... components) { this(components); setSpacing(spacing); } public RightAlignedLine(Component... components) { setLayout(LetterLayout.rightAlignedRow()); for (Component component : components) if (component != null) add(component); } public void setSpacing(int spacing) { ((LetterLayout) getLayout()).setSpacing(spacing, spacing); } public void add(String text) { add(new JLabel(text)); } } static public class GlobalID implements Comparable { public long a; public int b; public GlobalID() { } public GlobalID(String id) { assertGlobalID(id); BigInteger value = bigint(0); for (int i = 0; i < l(id); i++) value = plus(mul(value, 26), charDiff(id.charAt(i), 'a')); a = value.longValue(); value = value.shiftRight(64); b = value.shortValue(); } public String toString() { BigInteger value = bigint(b); value = value.shiftLeft(32); value = plus(value, (a >> 32) & 0xFFFFFFFFL); value = value.shiftLeft(32); value = plus(value, a & 0xFFFFFFFFL); return bigintToGlobalID(value); } public boolean equals(Object o) { if (!(o instanceof GlobalID)) return false; return ((GlobalID) o).a == a && ((GlobalID) o).b == b; } public int hashCode() { return (int) a; } public int compareTo(GlobalID id) { int diff = b - id.b; return diff != 0 ? diff : Long.compareUnsigned(a, id.a); } } static public class FastRegions_Hi15Image extends AbstractFastRegions { public int getColor(int pos) { return image.getHi15Pixel_noRangeCheck(pos); } public RGB rgbForRegion(ImageRegion r) { return hi15ToRGB((short) r.firstPixelLogicalColor()); } public FastRegions_Hi15Image(Hi15Image img) { super(img); } public FastRegions_Hi15Image(BufferedImage img) { this(new Hi15Image(img)); } } public interface IntSize { public int size(); default public boolean isEmpty() { return size() == 0; } } static public class FieldVar extends VarWithNotify { public IHasChangeListeners containingObject; public String fieldName; public IF0 getter; public IVF1 setter; public FieldVar(IHasChangeListeners containingObject, String fieldName, IF0 getter, IVF1 setter) { this.setter = setter; this.getter = getter; this.fieldName = fieldName; this.containingObject = containingObject; containingObject.onChangeAndNow(() -> _updateFromObject()); } public void _updateFromObject() { set(getter.get()); } public void fireChange() { setter.get(get()); super.fireChange(); } public FieldVar onChange(IVF1 r) { if (r != null) onChange(() -> r.get(get())); return this; } } static public class JFastLogView_noWrap extends JComponent implements Scrollable { public List lines = syncList(); public boolean endsWithNewLine, verbose; public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 20; } public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { return (direction == SwingConstants.HORIZONTAL ? visibleRect.width : visibleRect.height) * 5 / 6; } public boolean getScrollableTracksViewportWidth() { return false; } public boolean getScrollableTracksViewportHeight() { return false; } public void paint(Graphics g) { int w = getWidth(), h = getHeight(); g.setColor(getBackground()); g.fillRect(0, 0, w, h); g.setColor(getForeground()); FontMetrics fm = componentFontMetrics(this); int fh = fm.getHeight(); Rectangle clip = g.getClipBounds(); int start, end; if (clip == null) { start = 0; end = l(lines); } else { start = max(0, clip.y / fh); end = min(l(lines), idiv_ceil(clip.y + clip.height, fh)); } int y = fm.getAscent() + start * fh; for (int i = start; i < end; i++) { String s = get(lines, i); if (s != null) g.drawString(s, 0, y); y += fh; } } public Dimension getPreferredSize() { FontMetrics fm = componentFontMetrics(this); if (fm == null) return new Dimension(50, 50); int fh = fm.getHeight(); int w = 0; for (int i = 0; i < l(lines); i++) { String s = get(lines, i); w = max(w, fm.stringWidth(unnull(s))); } return new Dimension(w, fh * l(lines)); } public JFastLogView_noWrap() { } public JFastLogView_noWrap(String text) { setText(text); } { componentPopupMenuItem(this, "Copy full text", new Runnable() { public void run() { try { copyFullText(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyFullText();"; } }); } public boolean setLines(Collection lines) { List newList = asSyncList(lines); if (eq(this.lines, newList)) return false; this.lines = newList; _revalidate(this); return true; } public boolean setText(String text) { endsWithNewLine = endsWithNewLine(text); return setLines(lines(text)); } public void append(String text) { if (nempty(text)) setText(getText() + text); } public String getText() { return lines_rtrimIf(!endsWithNewLine, cloneList(lines)); } public void copyFullText() { copyTextToClipboard(getText()); } } static public class SimpleLeftToRightParser extends Meta { public String text; public List tok; final public ListAndIndex getPtr() { return ptr(); } public ListAndIndex ptr() { return ptr; } public ListAndIndex ptr; public ListAndIndex mainLoopPtr; public String currentToken; public boolean caseInsensitive = false; public List warnings = new ArrayList(); final public SimpleLeftToRightParser setInternIdentifiers(boolean internIdentifiers) { return internIdentifiers(internIdentifiers); } public SimpleLeftToRightParser internIdentifiers(boolean internIdentifiers) { this.internIdentifiers = internIdentifiers; return this; } final public boolean getInternIdentifiers() { return internIdentifiers(); } public boolean internIdentifiers() { return internIdentifiers; } public boolean internIdentifiers = false; public SimpleLeftToRightParser() { } public SimpleLeftToRightParser(String text) { this.text = text; } public SimpleLeftToRightParser(List tok) { this.tok = tok; } transient public IF1> tokenize; public List tokenize(String text) { return tokenize != null ? tokenize.get(text) : tokenize_base(text); } final public List tokenize_fallback(IF1> _f, String text) { return _f != null ? _f.get(text) : tokenize_base(text); } public List tokenize_base(String text) { return javaTok(text); } final public String token() { return t(); } public String t() { return currentToken; } public String token(int i) { return get(tok, ptr.idx() + i * 2); } final public String consume() { return next(); } final public String tpp() { return next(); } public String next() { var t = t(); next(1); return t; } final public String prevSpace() { return lastSpace(); } public String lastSpace() { return get(tok, ptr.idx() - 1); } public String nextSpace() { return get(tok, ptr.idx() + 1); } public String space(int i) { return get(tok, ptr.idx() + i * 2 + 1); } public void unconsume() { next(-1); } final public boolean eqTok(String a, String b) { return tokEq(a, b); } public boolean tokEq(String a, String b) { return eqOrEqic(caseInsensitive, a, b); } public boolean tokEqOneOf(String a, String... l) { return any(l, b -> tokEq(a, b)); } public boolean is(int i, String t) { return tokEq(token(i), t); } public boolean is(String t) { return tokEq(currentToken, t); } public boolean was(String t) { return tokEq(token(-1), t); } public boolean isOneOf(String... tokens) { return tokEqOneOf(currentToken, tokens); } public String[] consumeArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) array[i] = consume(); return array; } public boolean isInteger() { return isInteger(t()); } public boolean isInteger(String s) { return utils.isInteger(s); } public boolean isIdentifier() { return isIdentifier(t()); } public boolean isIdentifier(String s) { return utils.isIdentifier(s); } public String consumeIdentifier() { String s = assertIdentifier(consume()); if (internIdentifiers) s = intern(s); return s; } public String consumeIdentifierOpt() { return isIdentifier(t()) ? consumeIdentifier() : null; } public int consumeInteger() { return parseInt(assertInteger(consume())); } public boolean consumeOpt(String token) { if (!is(token)) return false; consume(); return true; } public void consume(String token) { if (!is(token)) throw fail("Expected " + quote(token) + ", got " + describeToken(token())); consume(); } public String describeToken(String token) { return token == null ? "EOF" : quote(token); } public String consumeOneOf(String... tokens) { if (!isOneOf(tokens)) throw fail("Expected one of " + asList(tokens)); return consume(); } public void ptr(ListAndIndex ptr) { this.ptr = ptr; fetch(); } final public int tokIdx() { return idx(); } public int idx() { return ptr.idx(); } public int lTok() { return l(tok); } public int nRemainingTokens() { return (lTok() - idx()) / 2; } final public boolean endOfText() { return atEnd(); } public boolean atEnd() { return ptr.atEnd(); } public void fetch() { currentToken = ptr.get(); } public boolean lineBreak() { return containsLineBreak(get(tok, ptr.idx() - 1)); } public boolean atEndOrLineBreak() { return atEnd() || lineBreak(); } public void init() { if (tok == null) tok = tokenize(text); if (ptr == null) ptr(new ListAndIndex(tok, 1)); } public boolean mainLoop() { init(); if (atEnd()) return false; if (eq(mainLoopPtr, ptr)) throw fail("main loop didn't advance (current token: " + quote(token()) + ")"); mainLoopPtr = ptr; return true; } public class AssureAdvance { public ListAndIndex cur; { init(); } public boolean get() { if (atEnd()) return false; if (eq(cur, ptr)) throw fail("Parse loop didn't advance (current token: " + quote(token()) + ")"); cur = ptr; return true; } } public void unknownToken() { warn("Unknown token: " + t()); } public void warn(String msg) { warnings.add(print(msg)); } final public void skip(int n) { next(n); } final public void consume(int n) { next(n); } public void next(int n) { ptr(min(lTok(), ptr.idx() + n * 2)); } public void ptr(int i) { ptr(new ListAndIndex(tok, min(i | 1, l(tok)))); } public LineAndColumn lineAndColumn() { return tokenToLineAndColumn(ptr); } public LineAndColumn lineAndColumn(int idx) { return tokenToLineAndColumn(ptr.plus(idx * 2)); } public String consumeUntilSpaceOr(IF0 pred) { int i = idx(); do next(); while (!atEnd() && empty(lastSpace()) && !pred.get()); return joinSubList(tok, i, idx() - 1); } public void setText(String text) { this.text = text; tok = null; ptr = null; } public int relativeIndexOf(String token) { int n = nRemainingTokens(); for (int i = 0; i < n; i++) if (eqTok(token(i), token)) return i; return -1; } } static public class TimeoutException extends RuntimeException implements IFieldsToList { public double timeoutSeconds; public Object function; public Thread thread; public TimeoutException() { } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + timeoutSeconds + ", " + function + ", " + thread + ")"; } public Object[] _fieldsToList() { return new Object[] { timeoutSeconds, function, thread }; } public TimeoutException(double timeoutSeconds, Object function, Thread thread) { super("Timeout after " + iceil(timeoutSeconds) + "s by " + shorten_str(function), exceptionForTimeoutedThread(thread)); this.thread = thread; this.function = function; this.timeoutSeconds = timeoutSeconds; } } abstract static public class JEInstantCompressor_AnyType extends AbstractCompressor_AnyType { abstract public ICachedJavaXExpr compress(Data data); public void step0() { search.submit(compress(search.inputData())); } } static public interface IRef extends IF0 { public default void replaceValue(A oldValue, A newValue) { } } static public class Flag implements Runnable { volatile public boolean up = false; public boolean raise() { if (up) return false; synchronized (this) { if (up) return false; up = true; notifyAll(); return true; } } public void run() { try { raise(); } catch (Exception __e) { throw rethrow(__e); } } public void waitUntilUp() { try { if (up) return; synchronized (this) { while (!up) wait(); } } catch (Exception __e) { throw rethrow(__e); } } public boolean waitUntilUp(double timeout) { if (timeout == infinity()) { waitUntilUp(); return isUp(); } else return waitUntilUp(toMS(timeout)); } public boolean waitUntilUp(long timeout) { try { if (up) return true; synchronized (this) { if (!up) wait(timeout); } return isUp(); } catch (Exception __e) { throw rethrow(__e); } } final public boolean get() { return isUp(); } public boolean isUp() { return up; } public String toString() { return isUp() ? "up" : "down"; } } public interface IRecognizedRegion extends IRecognizedBox { public IImageRegion region(); default public Rect bounds() { return region().bounds(); } } static public class UniquifyUsingHasher { final public UniquifyUsingHasher setHasher(IF1 hasher) { return hasher(hasher); } public UniquifyUsingHasher hasher(IF1 hasher) { this.hasher = hasher; return this; } final public IF1 getHasher() { return hasher(); } public IF1 hasher() { return hasher; } public IF1 hasher; final public UniquifyUsingHasher setEqualsPredicate(IF2 equalsPredicate) { return equalsPredicate(equalsPredicate); } public UniquifyUsingHasher equalsPredicate(IF2 equalsPredicate) { this.equalsPredicate = equalsPredicate; return this; } final public IF2 getEqualsPredicate() { return equalsPredicate(); } public IF2 equalsPredicate() { return equalsPredicate; } public IF2 equalsPredicate = (__1, __2) -> eq(__1, __2); public UniquifyUsingHasher(IF1 hasher) { this.hasher = hasher; } public UniquifyUsingHasher(IF1 hasher, IF2 equalsPredicate) { this.equalsPredicate = equalsPredicate; this.hasher = hasher; } public MultiMap byHash = new MultiMap(); final public List getList() { return list(); } public List list() { return list; } public List list = new ArrayList(); public boolean add(A a) { B hash = hasher.get(a); if (any(byHash.get(hash), x -> equalsPredicate.get(x, a))) return false; byHash.put(hash, a); list.add(a); return true; } public UniquifyUsingHasher addAll(Iterable l) { for (A a : unnullForIteration(l)) add(a); return this; } public List get() { return list; } public int nHashCollisions() { return l(keysWithMultipleValues(byHash)); } } static public class BijectiveMap extends CompactAbstractMap { public Map forward = new HashMap(); public Map backward = new HashMap(); public BijectiveMap() { } public BijectiveMap(boolean ordered) { if (ordered) { forward = new LinkedHashMap(); backward = new LinkedHashMap(); } } @Override public B put(A a, B b) { assertNotNull(a); assertNotNull(b); A oldKey = backward.get(b); if (eq(oldKey, a)) return b; if (oldKey != null) forward.remove(oldKey); B oldValue = forward.get(a); if (oldValue != null) backward.remove(b); backward.put(b, a); return forward.put(a, b); } @Override public B remove(Object a) { B b = forward.get(a); if (b != null) { forward.remove(a); backward.remove(b); } return b; } @Override public B get(Object a) { return forward.get(a); } public A inverseGet(B b) { return backward.get(b); } public Set keySet() { return immutableSet(forward.keySet()); } public Set valueSet() { return immutableSet(backward.keySet()); } public Set> entrySet() { return immutableSet(forward.entrySet()); } public int size() { return forward.size(); } public Map forwardMap() { return immutableMap(forward); } public Map backwardMap() { return immutableMap(backward); } } abstract static public class VStackComputableWithStep implements VStack.Computable { public int step; public void step(VStack stack, Object subComputationResult) { step(stack); } public void step(VStack stack) { } } static public interface Producer { public A next(); } static public class Gazelle22_ImageToRegions { public BufferedImage inputImage; public BWIntegralImage ii; public SnPSettings snpSettings; public BWImage posterized; public FastRegions_BWImage regions; public Map, Double> scoredRegions; public boolean wasRun = false; final public Gazelle22_ImageToRegions setWithDiagonals(boolean withDiagonals) { return withDiagonals(withDiagonals); } public Gazelle22_ImageToRegions withDiagonals(boolean withDiagonals) { this.withDiagonals = withDiagonals; return this; } final public boolean getWithDiagonals() { return withDiagonals(); } public boolean withDiagonals() { return withDiagonals; } public boolean withDiagonals = false; public FunctionTimings timings; public Gazelle22_ImageToRegions(FunctionTimings timings, BufferedImage inputImage, SnPSettings snpSettings) { this.snpSettings = snpSettings; this.inputImage = inputImage; this.timings = timings; } public Decolorizer decolorizer() { return snpSettings.decolorizer; } public void run() { try { wasRun = true; var decolorizer = decolorizer(); timings.dO(decolorizer != null ? "bwIntegralImage w/decolorizer" : "bwIntegralImage", () -> ii = bwIntegralImage_withMeta(inputImage, decolorizer)); timings.dO("scaleAndPosterize", () -> posterized = scaleAndPosterize(ii, snpSettings)); regions = new FastRegions_BWImage(posterized); regions.collectBounds(); regions.withDiagonals(withDiagonals); timings.dO("Regions", regions); } catch (Exception __e) { throw rethrow(__e); } } public ScreenShotMeta screenShotMeta() { return optCast(ScreenShotMeta.class, getMetaSrc(inputImage)); } public Pt coordinatesFromScreen(Pt p) { var meta = screenShotMeta(); if (meta == null) return null; var r = meta.bounds; if (!r.contains(p)) return null; p = translatePt(p, -r.x, -r.y); return scalePt(p, doubleRatio(snpSettings.pixelRows, r.h)); } public Pt coordinatesToScreen(Pt p) { var meta = screenShotMeta(); if (meta == null) return null; var r = meta.bounds; return translatePt(r.x, r.y, scalePt(p, doubleRatio(r.h, snpSettings.pixelRows))); } final public FastRegions_BWImage get() { return regions(); } public FastRegions_BWImage regions() { if (!wasRun) run(); return regions; } public int nRegions() { return regions().nRegions(); } } static public class CountHolesInRegion implements IFieldsToList { public IImageRegion region; public CountHolesInRegion() { } public CountHolesInRegion(IImageRegion region) { this.region = region; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + region + ")"; } public Object[] _fieldsToList() { return new Object[] { region }; } public int holes; public int get() { if (region == null) return 0; var borderWalker = new RegionBorder_innerPoints_v2(region); borderWalker.onNewTrace(isHole -> { if (isHole) holes++; }); borderWalker.run(); return holes; } } static public class SourceTriggeredStream extends Meta { public DoneFlag ended = new DoneFlag(true); volatile public A lastElement; public AtomicLong elementCount = new AtomicLong(); transient public Set> onNewElement; public SourceTriggeredStream onNewElement(IVF1 f) { onNewElement = createOrAddToSyncLinkedHashSet(onNewElement, f); return this; } public SourceTriggeredStream removeNewElementListener(IVF1 f) { utils.remove(onNewElement, f); return this; } public void newElement(A a) { lastElement = a; inc(elementCount); if (onNewElement != null) for (var listener : onNewElement) pcallF_typed(listener, a); } public void onNewElement(Runnable r) { onNewElement(runnableToIVF1(r)); } public A get() { return lastElement; } public long elementCount() { return elementCount.get(); } public void end() { ended.raise(); } public boolean ended() { return ended.isUp(); } public void catchError(Runnable r) { utils.catchError(ended, r); } public void directlyFeedInto(Consumer consumer) { if (consumer != null) onNewElement(a -> consumer.accept(a)); } } abstract static public class IProgressShower implements AutoCloseable { abstract public void setValue(double value); abstract public void setTotal(double total); public void setText(String text) { } } static public class FlexibleVarContext extends VarContext { public Map vars; public FlexibleVarContext() { } public FlexibleVarContext(VarContext parent) { super(parent); } public Object get(String name) { if (containsKey(vars, name)) return mapGet(vars, name); if (parent != null) return parent.get(name); return null; } public void set(String name, Object value) { vars = putOrCreateSyncMap(vars, name, value); } public AutoCloseable tempSet(String name, Object value) { initMap(); return utils.tempPut(vars, name, value); } public void unset(String name) { remove(vars, name); } public Map varMap() { return vars; } final public void initMap() { makeThreadSafe(); } public void makeThreadSafe() { if (vars == null) vars = syncHashMap(); } } static public class ButtonImageLoader { public DynamicStack stack; public Set loadedButtons = weakIdentityHashSet(); public DeQ loadQ; public JScrollPane scrollPane; public ChangeListener changeListener; final public ButtonImageLoader setImageHeight(int imageHeight) { return imageHeight(imageHeight); } public ButtonImageLoader imageHeight(int imageHeight) { this.imageHeight = imageHeight; return this; } final public int getImageHeight() { return imageHeight(); } public int imageHeight() { return imageHeight; } public int imageHeight = 128; public ButtonImageLoader(DynamicStack stack) { this.stack = stack; bindToComponent(stack, () -> { scrollPane = enclosingScrollPane(stack); changeListener = scrollPaneOnScroll(scrollPane, new Runnable() { public void run() { try { update(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "update()"; } }); update(); }, () -> { if (scrollPane != null) { scrollPane.getViewport().removeChangeListener(changeListener); scrollPane = null; changeListener = null; } }); } public void update() { swing(() -> { for (JButton b : reversed((List) (List) stackElementsShowing(stack))) { if (add_byContains(loadedButtons, b)) { try { TextImageAction tia = (TextImageAction) (metaGet(b, TextImageAction.class)); if (tia == null) { print("no tia"); continue; } File f = tia.file; if (f == null) { print("no file"); continue; } qAdd(new Runnable() { public void run() { try { setAButtonsImage(b, f); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setAButtonsImage(b, f)"; } }); } catch (Throwable __e) { pcallFail(__e); } } } }); } public void qAdd(Runnable r) { if (loadQ == null) loadQ = startDeQ(); loadQ.addFirst(r); } public void setAButtonsImage(JButton b, File f) { setButtonImage(b, loadPreviewImage(f)); } public BufferedImage loadPreviewImage(File f) { return loadPreviewImageWithExactHeight(imageHeight, f); } } static public class RollingAverage { public int windowSize = 50; public int recalcEvery = 1000; public int nRecalc; public double sum; public double[] list; public int start, len; public RollingAverage() { } public RollingAverage(int windowSize) { this.windowSize = windowSize; } synchronized public void add(double d) { init(); if (++nRecalc >= recalcEvery) { nRecalc = 0; sum = 0; for (int i = 0; i < len; i++) sum += _get(i); } if (len == windowSize) { sum -= _get(0); len--; start = (start + 1) % windowSize; } list[(start + len) % windowSize] = d; ++len; sum += d; } public double _get(int i) { return list[(start + i) % windowSize]; } synchronized public double get() { init(); return doubleRatio(sum, len); } public void init() { if (list == null) list = new double[windowSize]; } } static public class Timed extends Var { public double ms; final public Timed setDescription(String description) { return description(description); } public Timed description(String description) { this.description = description; return this; } final public String getDescription() { return description(); } public String description() { return description; } public String description; public Timed() { } public Timed(A value, long ms) { super(value); this.ms = ms; } public Timed(A value, double ms) { super(value); this.ms = ms; } public String toString() { return "[" + renderedTime() + "] " + joinNemptiesWithComma(description, super.toString()); } public double ms() { return ms; } public double nanos() { return msToNanos(ms); } final public String renderTime() { return renderedTime(); } public String renderedTime() { return renderElapsedSecondsPleasantly(msToSeconds(ms)); } } static public class UpdateTrigger implements Runnable, IFieldsToList { public Updateable target; public UpdateTrigger() { } public UpdateTrigger(Updateable target) { this.target = target; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + target + ")"; } public boolean equals(Object o) { if (!(o instanceof UpdateTrigger)) return false; UpdateTrigger __1 = (UpdateTrigger) o; return eq(target, __1.target); } public int hashCode() { int h = -1756880753; h = boostHashCombine(h, _hashCode(target)); return h; } public Object[] _fieldsToList() { return new Object[] { target }; } public void run() { try { { if (target != null) target.update(); } } catch (Exception __e) { throw rethrow(__e); } } } static public boolean NanoHTTPD_debug = false; static abstract public class NanoHTTPD implements AutoCloseable { public boolean decodePercentInURI = false; public boolean noQueryStringParameter = true; public boolean collectHeaderLines = false; static public ThreadLocal currentSession = new ThreadLocal(); static public List badClients = synchroList(); public interface AsyncRunner { public void closeAll(); public void closed(ClientHandler clientHandler); public void exec(ClientHandler code); } public class ClientHandler implements Runnable { final public InputStream inputStream; public OutputStream outputStream; final public Socket acceptSocket; public boolean specialHandler = false; public ClientHandler(InputStream inputStream, Socket acceptSocket) { this.inputStream = inputStream; this.acceptSocket = acceptSocket; } public void close() { if (NanoHTTPD_debug) printVars("ClientHandler.close", "specialHandler", specialHandler); if (specialHandler) return; safeClose(this.outputStream); safeClose(this.inputStream); safeClose(this.acceptSocket); } @Override public void run() { try { outputStream = this.acceptSocket.getOutputStream(); TempFileManager tempFileManager = NanoHTTPD.this.tempFileManagerFactory.create(); HTTPSession session = new HTTPSession(tempFileManager, acceptSocket, this.inputStream, outputStream, this.acceptSocket.getInetAddress()); if (NanoHTTPD_debug) print("NanoHTTPD: Have session"); while (!this.acceptSocket.isClosed() && !session.badClient) { if (NanoHTTPD_debug) print("session execute"); session.execute(); if (NanoHTTPD_debug) print("specialHandler", session.specialHandler); if (session.specialHandler) { specialHandler = true; return; } } } catch (Exception e) { print("NanoHTTPD: Error " + e); if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())) && !(e instanceof SocketTimeoutException)) { NanoHTTPD.LOG.log(Level.FINE, "Communication with the client broken", e); } } finally { close(); NanoHTTPD.this.asyncRunner.closed(this); if (NanoHTTPD_debug) print("NanoHTTPD: finally branch done"); } } } public static class Cookie { public static String getHTTPTime(int days) { Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); calendar.add(Calendar.DAY_OF_MONTH, days); return dateFormat.format(calendar.getTime()); } final public String n, v, e; public String domain, path; public Cookie(String name, String value) { this(name, value, 30); } public Cookie(String name, String value, int numDays) { this.n = name; this.v = value; this.e = getHTTPTime(numDays); } public Cookie(String name, String value, String expires) { this.n = name; this.v = value; this.e = expires; } public String getHTTPHeader() { StringBuilder buf = new StringBuilder(); buf.append(n).append("=").append(v).append("; expires=").append(e); if (nempty(domain)) buf.append("; Domain=").append(domain); if (nempty(path)) buf.append("; Path=").append(path); return buf.toString(); } } public class CookieHandler implements Iterable { final public HashMap cookies = new HashMap(); final public ArrayList queue = new ArrayList(); public CookieHandler(Map httpHeaders) { String raw = httpHeaders.get("cookie"); if (raw != null) { String[] tokens = raw.split(";"); for (String token : tokens) { String[] data = token.trim().split("="); if (data.length == 2) { this.cookies.put(data[0], data[1]); } } } } public void delete(String name) { set(name, "-delete-", -30); } @Override public Iterator iterator() { return this.cookies.keySet().iterator(); } public String read(String name) { return this.cookies.get(name); } public void set(Cookie cookie) { this.queue.add(cookie); } public Cookie set(String name, String value, int expires) { return addAndReturn(this.queue, new Cookie(name, value, Cookie.getHTTPTime(expires))); } public void unloadQueue(Response response) { for (Cookie cookie : this.queue) { response.addHeader("Set-Cookie", cookie.getHTTPHeader()); } } } public static class DefaultAsyncRunner implements AsyncRunner { public long requestCount; final public List running = Collections.synchronizedList(new ArrayList()); public List getRunning() { return running; } @Override public void closeAll() { for (ClientHandler clientHandler : new ArrayList(this.running)) { clientHandler.close(); } } @Override public void closed(ClientHandler clientHandler) { this.running.remove(clientHandler); } @Override public void exec(ClientHandler clientHandler) { ++this.requestCount; Thread t = new Thread(clientHandler); String clientIP = "?"; try { clientIP = clientHandler.acceptSocket.getInetAddress().getHostAddress().toString(); } catch (Throwable __e) { pcallFail(__e); } t.setName("NanoHttpd serving request #" + this.requestCount + " to " + clientIP); this.running.add(clientHandler); t.start(); } } public static class DefaultTempFile implements TempFile { final public File file; final public OutputStream fstream; public DefaultTempFile(String tempdir) throws IOException { this.file = File.createTempFile("NanoHTTPD-", "", new File(tempdir)); this.fstream = new FileOutputStream(this.file); System.err.println("Temp file created: " + file); } @Override public void delete() throws Exception { safeClose(this.fstream); System.err.println("Temp file deleted: " + file); if (!this.file.delete()) { throw new Exception("could not delete temporary file"); } } @Override public String getName() { return this.file.getAbsolutePath(); } @Override public OutputStream open() throws Exception { return this.fstream; } } public static class DefaultTempFileManager implements TempFileManager { final public String tmpdir; final public List tempFiles; public DefaultTempFileManager() { this.tmpdir = tempDir().getPath(); this.tempFiles = new ArrayList(); } @Override public void clear() { for (TempFile file : this.tempFiles) { try { file.delete(); } catch (Exception ignored) { NanoHTTPD.LOG.log(Level.WARNING, "could not delete file ", ignored); } } this.tempFiles.clear(); } @Override public TempFile createTempFile() throws Exception { DefaultTempFile tempFile = new DefaultTempFile(this.tmpdir); this.tempFiles.add(tempFile); return tempFile; } } public class DefaultTempFileManagerFactory implements TempFileManagerFactory { @Override public TempFileManager create() { return new DefaultTempFileManager(); } } static final public String CONTENT_DISPOSITION_REGEX = "([ |\t]*Content-Disposition[ |\t]*:)(.*)"; static final public Pattern CONTENT_DISPOSITION_PATTERN = Pattern.compile(CONTENT_DISPOSITION_REGEX, Pattern.CASE_INSENSITIVE); static final public String CONTENT_TYPE_REGEX = "([ |\t]*content-type[ |\t]*:)(.*)"; static final public Pattern CONTENT_TYPE_PATTERN = Pattern.compile(CONTENT_TYPE_REGEX, Pattern.CASE_INSENSITIVE); static final public String CONTENT_DISPOSITION_ATTRIBUTE_REGEX = "[ |\t]*([a-zA-Z]*)[ |\t]*=[ |\t]*['|\"]([^\"^']*)['|\"]"; static final public Pattern CONTENT_DISPOSITION_ATTRIBUTE_PATTERN = Pattern.compile(CONTENT_DISPOSITION_ATTRIBUTE_REGEX); public class HTTPSession implements IHTTPSession { public boolean badClient = false; public boolean specialHandler = false; public long opened = sysNow(); public static final int BUFSIZE = 8192; final public TempFileManager tempFileManager; public Socket socket; final public OutputStream outputStream; final public PushbackInputStream inputStream; public int splitbyte; public int rlen; public String uri; public Method method; public Map parms; public Map headers; public Map files = new HashMap(); public CookieHandler cookies; public String queryParameterString; public String remoteIp; public String protocolVersion; public String fullURI; public List headerLines = collectHeaderLines ? new ArrayList() : null; public HTTPSession(TempFileManager tempFileManager, Socket socket, InputStream inputStream, OutputStream outputStream) { this.socket = socket; this.tempFileManager = tempFileManager; this.inputStream = new PushbackInputStream(inputStream, HTTPSession.BUFSIZE); this.outputStream = outputStream; } public String getProtocolVersion() { return protocolVersion; } public String getFullURI() { return fullURI; } public List getHeaderLines() { return headerLines; } public HTTPSession(TempFileManager tempFileManager, Socket socket, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) { this.socket = socket; this.tempFileManager = tempFileManager; this.inputStream = new PushbackInputStream(inputStream, HTTPSession.BUFSIZE); this.outputStream = outputStream; this.remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString(); this.headers = new LinkedHashMap(); } public void badClient(boolean b) { badClient = b; } public void specialHandler(boolean b) { specialHandler = b; } private void decodeHeader(BufferedReader in, Map pre, Map parms, Map headers, Map files) throws ResponseException { try { String inLine = in.readLine(); if (inLine == null) { return; } StringTokenizer st = new StringTokenizer(inLine); if (!st.hasMoreTokens()) { throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html"); } pre.put("method", st.nextToken()); if (!st.hasMoreTokens()) { throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html"); } String uri = st.nextToken(); fullURI = uri; int qmi = uri.indexOf('?'); if (qmi >= 0) { String query = uri.substring(qmi + 1); files.put("query", query); decodeParms(query, parms); uri = uri.substring(0, qmi); } if (decodePercentInURI) uri = decodePercent(uri); if (st.hasMoreTokens()) { protocolVersion = st.nextToken(); } else { protocolVersion = "HTTP/1.1"; NanoHTTPD.LOG.log(Level.FINE, "no protocol version specified, strange. Assuming HTTP/1.1."); } String line = in.readLine(); while (line != null && line.trim().length() > 0) { { if (headerLines != null) headerLines.add(line); } int p = line.indexOf(':'); if (p >= 0) { headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim()); } line = in.readLine(); } pre.put("uri", uri); } catch (IOException ioe) { throw new ResponseException(Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe); } } private void decodeMultipartFormData(String boundary, java.nio.ByteBuffer fbuf, Map parms, Map files) throws ResponseException { try { int[] boundary_idxs = getBoundaryPositions(fbuf, boundary.getBytes()); if (boundary_idxs.length < 2) { throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but contains less than two boundary strings."); } final int MAX_HEADER_SIZE = 1024; byte[] part_header_buff = new byte[MAX_HEADER_SIZE]; for (int bi = 0; bi < boundary_idxs.length - 1; bi++) { fbuf.position(boundary_idxs[bi]); int len = (fbuf.remaining() < MAX_HEADER_SIZE) ? fbuf.remaining() : MAX_HEADER_SIZE; fbuf.get(part_header_buff, 0, len); ByteArrayInputStream bais = new ByteArrayInputStream(part_header_buff, 0, len); BufferedReader in = new BufferedReader(new InputStreamReader(bais, Charset.forName("US-ASCII"))); String mpline = in.readLine(); if (!mpline.contains(boundary)) { throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but chunk does not start with boundary."); } String part_name = null, file_name = null, content_type = null; mpline = in.readLine(); while (mpline != null && mpline.trim().length() > 0) { Matcher matcher = CONTENT_DISPOSITION_PATTERN.matcher(mpline); if (matcher.matches()) { String attributeString = matcher.group(2); matcher = CONTENT_DISPOSITION_ATTRIBUTE_PATTERN.matcher(attributeString); while (matcher.find()) { String key = matcher.group(1); if (key.equalsIgnoreCase("name")) { part_name = matcher.group(2); } else if (key.equalsIgnoreCase("filename")) { file_name = matcher.group(2); } } } matcher = CONTENT_TYPE_PATTERN.matcher(mpline); if (matcher.matches()) { content_type = matcher.group(2).trim(); } mpline = in.readLine(); } int part_header_len = len - (int) in.skip(MAX_HEADER_SIZE); if (part_header_len >= len - 4) { throw new ResponseException(Status.INTERNAL_ERROR, "Multipart header size exceeds MAX_HEADER_SIZE."); } int part_data_start = boundary_idxs[bi] + part_header_len; int part_data_end = boundary_idxs[bi + 1] - 4; fbuf.position(part_data_start); if (content_type == null) { byte[] data_bytes = new byte[part_data_end - part_data_start]; fbuf.get(data_bytes); parms.put(part_name, new String(data_bytes)); } else { String path = saveTmpFile(fbuf, part_data_start, part_data_end - part_data_start); if (!files.containsKey(part_name)) { files.put(part_name, path); } else { int count = 2; while (files.containsKey(part_name + count)) { count++; } files.put(part_name + count, path); } parms.put(part_name, file_name); } } } catch (ResponseException re) { throw re; } catch (Exception e) { throw new ResponseException(Status.INTERNAL_ERROR, e.toString()); } } private void decodeParms(String parms, Map p) { if (parms == null) { this.queryParameterString = ""; return; } this.queryParameterString = parms; StringTokenizer st = new StringTokenizer(parms, "&"); while (st.hasMoreTokens()) { String e = st.nextToken(); int sep = e.indexOf('='); if (sep >= 0) { p.put(decodePercent(e.substring(0, sep)).trim(), decodePercent(e.substring(sep + 1))); } else { p.put(decodePercent(e).trim(), ""); } } } @Override public void execute() throws IOException { Response r = null; try { byte[] buf = new byte[HTTPSession.BUFSIZE]; this.splitbyte = 0; this.rlen = 0; int read = -1; try { read = this.inputStream.read(buf, 0, HTTPSession.BUFSIZE); } catch (Exception e) { safeClose(this.inputStream); safeClose(this.outputStream); throw new SocketException("NanoHttpd Shutdown"); } if (read == -1) { safeClose(this.inputStream); safeClose(this.outputStream); throw new SocketException("NanoHttpd Shutdown"); } while (read > 0) { this.rlen += read; this.splitbyte = findHeaderEnd(buf, this.rlen); if (this.splitbyte > 0) break; if (rlen >= buf.length) { if (NanoHTTPD_debug) printWithIndent("HEADER> ", new String(buf)); throw fail("Header too big (" + rlen + " bytes)"); } read = this.inputStream.read(buf, this.rlen, HTTPSession.BUFSIZE - this.rlen); } if (this.splitbyte < this.rlen) { this.inputStream.unread(buf, this.splitbyte, this.rlen - this.splitbyte); } this.parms = new HashMap(); if (null == this.headers) { this.headers = new HashMap(); } else { this.headers.clear(); } if (null != this.remoteIp) { this.headers.put("remote-addr", this.remoteIp); this.headers.put("http-client-ip", this.remoteIp); } BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, this.rlen))); Map pre = new LinkedHashMap(); decodeHeader(hin, pre, this.parms, this.headers, this.files); this.method = Method.lookup(pre.get("method")); if (this.method == null) { throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Syntax error."); } this.uri = pre.get("uri"); this.cookies = new CookieHandler(this.headers); String connection = this.headers.get("connection"); boolean keepAlive = protocolVersion.equals("HTTP/1.1") && (connection == null || !connection.matches("(?i).*close.*")); r = serve(this); if (badClient || specialHandler) return; if (r == null) { throw new ResponseException(Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response."); } else { String acceptEncoding = this.headers.get("accept-encoding"); this.cookies.unloadQueue(r); r.setRequestMethod(this.method); r.setGzipEncoding(useGzipWhenAccepted(r) && acceptEncoding != null && acceptEncoding.contains("gzip")); r.setKeepAlive(keepAlive); r.send(this.outputStream); } if (!keepAlive || "close".equalsIgnoreCase(r.getHeader("connection"))) { throw new SocketException("NanoHttpd Shutdown"); } } catch (SocketException e) { throw e; } catch (SocketTimeoutException ste) { throw ste; } catch (IOException ioe) { Response resp = newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); resp.send(this.outputStream); safeClose(this.outputStream); } catch (ResponseException re) { Response resp = newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage()); resp.send(this.outputStream); safeClose(this.outputStream); } finally { if (badClient) badClients.add(this); else if (!specialHandler) safeClose(r); this.tempFileManager.clear(); } } private int findHeaderEnd(final byte[] buf, int rlen) { int splitbyte = 0; while (splitbyte + 3 < rlen) { if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') { return splitbyte + 4; } splitbyte++; } return 0; } private int[] getBoundaryPositions(java.nio.ByteBuffer b, byte[] boundary) { int[] res = new int[0]; if (b.remaining() < boundary.length) { return res; } int search_window_pos = 0; byte[] search_window = new byte[4 * 1024 + boundary.length]; int first_fill = (b.remaining() < search_window.length) ? b.remaining() : search_window.length; b.get(search_window, 0, first_fill); int new_bytes = first_fill - boundary.length; do { for (int j = 0; j < new_bytes; j++) { for (int i = 0; i < boundary.length; i++) { if (search_window[j + i] != boundary[i]) break; if (i == boundary.length - 1) { int[] new_res = new int[res.length + 1]; System.arraycopy(res, 0, new_res, 0, res.length); new_res[res.length] = search_window_pos + j; res = new_res; } } } search_window_pos += new_bytes; System.arraycopy(search_window, search_window.length - boundary.length, search_window, 0, boundary.length); new_bytes = search_window.length - boundary.length; new_bytes = (b.remaining() < new_bytes) ? b.remaining() : new_bytes; b.get(search_window, boundary.length, new_bytes); } while (new_bytes > 0); return res; } @Override public CookieHandler getCookies() { return this.cookies; } @Override public final Map getHeaders() { return this.headers; } @Override public final Map getFiles() { return this.files; } public Socket getSocket() { return socket; } @Override public final InputStream getInputStream() { return this.inputStream; } @Override public final OutputStream getOutputStream() { return this.outputStream; } @Override public final Method getMethod() { return this.method; } @Override public final Map getParms() { return this.parms; } @Override public String getQueryParameterString() { return this.queryParameterString; } private RandomAccessFile getTmpBucket() { try { TempFile tempFile = this.tempFileManager.createTempFile(); return new RandomAccessFile(tempFile.getName(), "rw"); } catch (Exception e) { throw new Error(e); } } @Override public final String getUri() { return this.uri; } @Override public void parseBody() throws IOException, ResponseException { final int REQUEST_BUFFER_LEN = 512; final int MEMORY_STORE_LIMIT = 1024; RandomAccessFile randomAccessFile = null; try { long size; if (this.headers.containsKey("content-length")) { size = Integer.parseInt(this.headers.get("content-length")); } else if (this.splitbyte < this.rlen) { size = this.rlen - this.splitbyte; } else { size = 0; } ByteArrayOutputStream baos = null; DataOutput request_data_output = null; if (size < MEMORY_STORE_LIMIT) { baos = new ByteArrayOutputStream(); request_data_output = new DataOutputStream(baos); } else { randomAccessFile = getTmpBucket(); request_data_output = randomAccessFile; } byte[] buf = new byte[REQUEST_BUFFER_LEN]; while (this.rlen >= 0 && size > 0) { this.rlen = this.inputStream.read(buf, 0, (int) Math.min(size, REQUEST_BUFFER_LEN)); size -= this.rlen; if (this.rlen > 0) { request_data_output.write(buf, 0, this.rlen); } } java.nio.ByteBuffer fbuf = null; if (baos != null) { fbuf = java.nio.ByteBuffer.wrap(baos.toByteArray(), 0, baos.size()); } else { fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length()); randomAccessFile.seek(0); } if (Method.POST.equals(this.method)) { String contentType = ""; String contentTypeHeader = this.headers.get("content-type"); StringTokenizer st = null; if (contentTypeHeader != null) { st = new StringTokenizer(contentTypeHeader, ",; "); if (st.hasMoreTokens()) { contentType = st.nextToken(); } } if ("multipart/form-data".equalsIgnoreCase(contentType)) { if (!st.hasMoreTokens()) { throw new ResponseException(Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html"); } String boundaryStartString = "boundary="; int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length(); String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length()); if (boundary.startsWith("\"") && boundary.endsWith("\"")) { boundary = boundary.substring(1, boundary.length() - 1); } decodeMultipartFormData(boundary, fbuf, this.parms, files); } else { byte[] postBytes = new byte[fbuf.remaining()]; if (NanoHTTPD_debug) print("NanoHTTPD: Handling POST data (" + l(postBytes) + " bytes)"); fbuf.get(postBytes); String postLine = new String(postBytes).trim(); if ("application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) { decodeParms(postLine, this.parms); } else if (postLine.length() != 0) { files.put("postData", postLine); } } } else if (Method.PUT.equals(this.method)) { files.put("content", saveTmpFile(fbuf, 0, fbuf.limit())); } } finally { safeClose(randomAccessFile); } } private String saveTmpFile(java.nio.ByteBuffer b, int offset, int len) { String path = ""; if (len > 0) { FileOutputStream fileOutputStream = null; try { TempFile tempFile = this.tempFileManager.createTempFile(); java.nio.ByteBuffer src = b.duplicate(); fileOutputStream = new FileOutputStream(tempFile.getName()); FileChannel dest = fileOutputStream.getChannel(); src.position(offset).limit(offset + len); dest.write(src.slice()); path = tempFile.getName(); } catch (Exception e) { throw new Error(e); } finally { safeClose(fileOutputStream); } } return path; } public String remoteIp() { return remoteIp; } } public interface IHTTPSession { public void badClient(boolean b); public void specialHandler(boolean b); public void execute() throws IOException; public CookieHandler getCookies(); public Map getHeaders(); public Map getFiles(); public Socket getSocket(); public InputStream getInputStream(); public OutputStream getOutputStream(); public Method getMethod(); public String getProtocolVersion(); public String getFullURI(); public List getHeaderLines(); public Map getParms(); public String getQueryParameterString(); public String getUri(); public void parseBody() throws IOException, ResponseException; public String remoteIp(); } public enum Method { GET, PUT, POST, DELETE, HEAD, OPTIONS, TRACE, CONNECT, PATCH; static public Method lookup(String method) { for (Method m : Method.values()) { if (m.toString().equalsIgnoreCase(method)) { return m; } } return null; } } public static class Response implements Closeable { public String toString() { return "HttpResponse " + status + " " + mimeType; } static public class ChunkedOutputStream extends FilterOutputStream { public ChunkedOutputStream(OutputStream out) { super(out); } @Override public void write(int b) throws IOException { byte[] data = { (byte) b }; write(data, 0, 1); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { if (len == 0) return; out.write(String.format("%x\r\n", len).getBytes()); out.write(b, off, len); out.write("\r\n".getBytes()); } public void finish() throws IOException { out.write("0\r\n\r\n".getBytes()); } } public IStatus status; public String mimeType; public InputStream data; public long contentLength; final public Map header = lithashmap("X-Powered-By", "JavaX"); public Method requestMethod; public boolean chunkedTransfer = false; public boolean encodeAsGzip = false; public boolean keepAlive = false; public Response(IStatus status, String mimeType, InputStream data, long totalBytes) { this.status = status; this.mimeType = mimeType; if (data == null) { this.data = new ByteArrayInputStream(new byte[0]); this.contentLength = 0L; } else { this.data = data; this.contentLength = totalBytes; } this.chunkedTransfer = this.contentLength < 0; keepAlive = true; } @Override public void close() throws IOException { if (this.data != null) { this.data.close(); } } public void addHeader(String name, String value) { this.header.put(name, value); } public InputStream getData() { return this.data; } public String getHeader(String name) { for (String headerName : header.keySet()) { if (headerName.equalsIgnoreCase(name)) { return header.get(headerName); } } return null; } public String getMimeType() { return this.mimeType; } public Method getRequestMethod() { return this.requestMethod; } public IStatus getStatus() { return this.status; } public void setGzipEncoding(boolean encodeAsGzip) { this.encodeAsGzip = encodeAsGzip; } public void setKeepAlive(boolean useKeepAlive) { this.keepAlive = useKeepAlive; } private boolean headerAlreadySent(Map header, String name) { boolean alreadySent = false; for (String headerName : header.keySet()) { alreadySent |= headerName.equalsIgnoreCase(name); } return alreadySent; } public void send(OutputStream outputStream) { String mime = this.mimeType; SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")); try { if (this.status == null) { throw new Error("sendResponse(): Status can't be null."); } PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")), false); pw.print("HTTP/1.1 " + this.status.getDescription() + " \r\n"); if (mime != null) { pw.print("Content-Type: " + mime + "\r\n"); } if (this.header == null || this.header.get("Date") == null) { pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n"); } if (this.header != null) { for (String key : this.header.keySet()) { String value = this.header.get(key); pw.print(key + ": " + value + "\r\n"); } } if (!headerAlreadySent(header, "connection")) { pw.print("Connection: " + (this.keepAlive ? "keep-alive" : "close") + "\r\n"); } if (headerAlreadySent(this.header, "content-length")) { encodeAsGzip = false; } if (encodeAsGzip) { pw.print("Content-Encoding: gzip\r\n"); setChunkedTransfer(true); } long pending = this.data != null ? this.contentLength : 0; if (this.requestMethod != Method.HEAD && this.chunkedTransfer) { pw.print("Transfer-Encoding: chunked\r\n"); } else if (!encodeAsGzip) { pending = sendContentLengthHeaderIfNotAlreadyPresent(pw, this.header, pending); } pw.print("\r\n"); pw.flush(); sendBodyWithCorrectTransferAndEncoding(outputStream, pending); outputStream.flush(); safeClose(this.data); } catch (IOException ioe) { NanoHTTPD.LOG.log(Level.SEVERE, "Could not send response to the client", ioe); } } private void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) throws IOException { if (this.requestMethod != Method.HEAD && this.chunkedTransfer) { ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream); sendBodyWithCorrectEncoding(chunkedOutputStream, -1); chunkedOutputStream.finish(); } else { sendBodyWithCorrectEncoding(outputStream, pending); } } private void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException { if (encodeAsGzip) { GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream); sendBody(gzipOutputStream, -1); gzipOutputStream.finish(); } else { sendBody(outputStream, pending); } } private void sendBody(OutputStream outputStream, long pending) throws IOException { long BUFFER_SIZE = 16 * 1024; byte[] buff = new byte[(int) BUFFER_SIZE]; boolean sendEverything = pending == -1; while (pending > 0 || sendEverything) { long bytesToRead = sendEverything ? BUFFER_SIZE : Math.min(pending, BUFFER_SIZE); int read = this.data.read(buff, 0, (int) bytesToRead); if (read <= 0) { break; } outputStream.write(buff, 0, read); if (!sendEverything) { pending -= read; } } } public long sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, Map header, long size) { for (String headerName : header.keySet()) { if (headerName.equalsIgnoreCase("content-length")) { try { return Long.parseLong(header.get(headerName)); } catch (NumberFormatException ex) { return size; } } } pw.print("Content-Length: " + size + "\r\n"); return size; } public void setChunkedTransfer(boolean chunkedTransfer) { this.chunkedTransfer = chunkedTransfer; } public void setData(InputStream data) { this.data = data; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public void setRequestMethod(Method requestMethod) { this.requestMethod = requestMethod; } public void setStatus(IStatus status) { this.status = status; } } public static final class ResponseException extends Exception { static final public long serialVersionUID = 6569838532917408380L; final public Status status; public ResponseException(Status status, String message) { super(message); this.status = status; } public ResponseException(Status status, String message, Exception e) { super(message, e); this.status = status; } public Status getStatus() { return this.status; } } public class ServerRunnable implements Runnable { final public int timeout; public IOException bindException; public boolean hasBinded = false; public ServerRunnable(int timeout) { this.timeout = timeout; } @Override public void run() { try { myServerSocket.bind(hostname != null ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); hasBinded = true; } catch (IOException e) { print("Was trying to bind to port: " + myPort + (hostname == null ? "" : " on " + hostname)); this.bindException = e; return; } do { try { final Socket finalAccept = NanoHTTPD.this.myServerSocket.accept(); if (NanoHTTPD_debug) print("NanoHTTPD: New socket."); if (this.timeout > 0) { finalAccept.setSoTimeout(this.timeout); } final InputStream inputStream = wrapStuff("SocketInputStream", finalAccept.getInputStream(), finalAccept, NanoHTTPD.this.myServerSocket); if (NanoHTTPD_debug) print("NanoHTTPD: Have input stream."); NanoHTTPD.this.asyncRunner.exec(createClientHandler(finalAccept, inputStream)); } catch (IOException e) { NanoHTTPD.LOG.log(Level.FINE, "Communication with the client broken", e); } } while (!NanoHTTPD.this.myServerSocket.isClosed()); } } public interface TempFile { public void delete() throws Exception; public String getName(); public OutputStream open() throws Exception; } public interface TempFileManager { public void clear(); public TempFile createTempFile() throws Exception; } public interface TempFileManagerFactory { public TempFileManager create(); } public static int SOCKET_READ_TIMEOUT = 24 * 3600 * 1000; public static final String MIME_PLAINTEXT = "text/plain; charset=utf-8"; public static final String MIME_HTML = "text/html; charset=utf-8"; static final public String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING"; static final public Logger LOG = Logger.getLogger(NanoHTTPD.class.getName()); public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException { SSLServerSocketFactory res = null; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(loadedKeyStore); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null); res = ctx.getServerSocketFactory(); } catch (Exception e) { throw new IOException(e.getMessage()); } return res; } public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException { SSLServerSocketFactory res = null; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(loadedKeyStore); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(loadedKeyFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); res = ctx.getServerSocketFactory(); } catch (Exception e) { throw new IOException(e.getMessage()); } return res; } public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException { SSLServerSocketFactory res = null; try { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath); keystore.load(keystoreStream, passphrase); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keystore); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keystore, passphrase); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); res = ctx.getServerSocketFactory(); } catch (Exception e) { throw new IOException(e.getMessage()); } return res; } private static final void safeClose(Object closeable) { try { if (closeable != null) { if (closeable instanceof Closeable) { ((Closeable) closeable).close(); } else if (closeable instanceof Socket) { ((Socket) closeable).close(); } else if (closeable instanceof ServerSocket) { ((ServerSocket) closeable).close(); } else { throw new IllegalArgumentException("Unknown object to close"); } } } catch (IOException e) { NanoHTTPD.LOG.log(Level.SEVERE, "Could not close", e); } } final public String hostname; final public int myPort; public ServerSocket myServerSocket; public SSLServerSocketFactory sslServerSocketFactory; public Thread myThread; public AsyncRunner asyncRunner; public TempFileManagerFactory tempFileManagerFactory; public NanoHTTPD(int port) { this(null, port); } public NanoHTTPD(String hostname, int port) { this.hostname = hostname; this.myPort = port; setTempFileManagerFactory(new DefaultTempFileManagerFactory()); setAsyncRunner(new DefaultAsyncRunner()); } public synchronized void closeAllConnections() { stop(); } public ClientHandler createClientHandler(final Socket finalAccept, final InputStream inputStream) { return new ClientHandler(inputStream, finalAccept); } public ServerRunnable createServerRunnable(final int timeout) { return new ServerRunnable(timeout); } public Map> decodeParameters(Map parms) { return this.decodeParameters(parms.get(NanoHTTPD.QUERY_STRING_PARAMETER)); } public Map> decodeParameters(String queryString) { Map> parms = new HashMap>(); if (queryString != null) { StringTokenizer st = new StringTokenizer(queryString, "&"); while (st.hasMoreTokens()) { String e = st.nextToken(); int sep = e.indexOf('='); String propertyName = sep >= 0 ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim(); if (!parms.containsKey(propertyName)) { parms.put(propertyName, new ArrayList()); } String propertyValue = sep >= 0 ? decodePercent(e.substring(sep + 1)) : null; { parms.get(propertyName).add(propertyValue); } } } return parms; } public String decodePercent(String str) { String decoded = null; try { decoded = URLDecoder.decode(str, "UTF8"); } catch (UnsupportedEncodingException ignored) { NanoHTTPD.LOG.log(Level.WARNING, "Encoding not supported, ignored", ignored); } return decoded; } public boolean useGzipWhenAccepted(Response r) { return r.getMimeType() != null && r.getMimeType().toLowerCase().contains("text/"); } public final int getListeningPort() { return this.myServerSocket == null ? -1 : this.myServerSocket.getLocalPort(); } public final boolean isAlive() { return wasStarted() && !this.myServerSocket.isClosed() && this.myThread.isAlive(); } public void join() throws InterruptedException { myThread.join(); } public void makeSecure(SSLServerSocketFactory sslServerSocketFactory) { this.sslServerSocketFactory = sslServerSocketFactory; } public static Response newChunkedResponse(IStatus status, String mimeType, InputStream data) { return new Response(status, mimeType, data, -1); } public static Response newFixedLengthResponse(IStatus status, String mimeType, InputStream data, long totalBytes) { return new Response(status, mimeType, data, totalBytes); } public static Response newFixedLengthResponse(IStatus status, String mimeType, String txt) { if (txt == null) { return newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(new byte[0]), 0); } else { byte[] bytes; try { bytes = txt.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { NanoHTTPD.LOG.log(Level.SEVERE, "encoding problem, responding nothing", e); bytes = new byte[0]; } return newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(bytes), bytes.length); } } public static Response newFixedLengthResponse(String msg) { return newFixedLengthResponse(Status.OK, NanoHTTPD.MIME_HTML, msg); } public Response serve(IHTTPSession session) { if (specialHandling(session)) { session.specialHandler(true); return null; } return serve_2(session); } public Response serve_2(IHTTPSession session) { currentSession.set(session); Method method = session.getMethod(); if (Method.PUT.equals(method) || Method.POST.equals(method)) { try { session.parseBody(); } catch (IOException ioe) { return newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); } catch (ResponseException re) { return newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage()); } } Map parms = session.getParms(); if (!noQueryStringParameter) parms.put(NanoHTTPD.QUERY_STRING_PARAMETER, session.getQueryParameterString()); return serve(session.getUri(), method, session.getHeaders(), parms, session.getFiles()); } @Deprecated public Response serve(String uri, Method method, Map headers, Map parms, Map files) { return newFixedLengthResponse(Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Not Found"); } public void setAsyncRunner(AsyncRunner asyncRunner) { this.asyncRunner = asyncRunner; } public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) { this.tempFileManagerFactory = tempFileManagerFactory; } public void start() throws IOException { start(NanoHTTPD.SOCKET_READ_TIMEOUT); } public void start(final int timeout) throws IOException { boolean ssl = this.sslServerSocketFactory != null; if (ssl) { SSLServerSocket ss = (SSLServerSocket) this.sslServerSocketFactory.createServerSocket(); ss.setNeedClientAuth(false); this.myServerSocket = ss; } else { this.myServerSocket = new ServerSocket(); } this.myServerSocket.setReuseAddress(true); ServerRunnable serverRunnable = createServerRunnable(timeout); this.myThread = new Thread(serverRunnable); this.myThread.setName("NanoHttpd Main Listener"); this.myThread.start(); while (!serverRunnable.hasBinded && serverRunnable.bindException == null) { try { Thread.sleep(10L); } catch (Throwable e) { } } if (serverRunnable.bindException != null) { throw serverRunnable.bindException; } System.out.println("HTTP" + (ssl ? "S" : "") + " server started (listening on port " + getListeningPort() + "!)"); printMyIPs(); } public void stop() { try { safeClose(this.myServerSocket); this.asyncRunner.closeAll(); if (this.myThread != null) { this.myThread.join(); } } catch (Exception e) { NanoHTTPD.LOG.log(Level.SEVERE, "Could not stop all connections", e); } } public final boolean wasStarted() { return this.myServerSocket != null && this.myThread != null; } static public void printMyIPs() { String ip; try { Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface iface = interfaces.nextElement(); if (iface.isLoopback() || !iface.isUp()) continue; Enumeration addresses = iface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); ip = addr.getHostAddress(); if (ip.startsWith("127.")) continue; boolean local = addr.isSiteLocalAddress() || ip.startsWith("fe"); System.out.println(iface.getDisplayName() + " " + ip + " " + (local ? "(private address)" : "(public address)")); } } } catch (Throwable e) { e.printStackTrace(); } } static public interface IStatus { public String getDescription(); public int getRequestStatus(); } static public enum Status implements IStatus { SWITCH_PROTOCOL(101, "Switching Protocols"), OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), PARTIAL_CONTENT(206, "Partial Content"), REDIRECT(301, "Moved Permanently"), NOT_MODIFIED(304, "Not Modified"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401, "Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), METHOD_NOT_ALLOWED(405, "Method Not Allowed"), REQUEST_TIMEOUT(408, "Request Timeout"), RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"), INTERNAL_ERROR(500, "Internal Server Error"), UNSUPPORTED_HTTP_VERSION(505, "HTTP Version Not Supported"); final public int requestStatus; final public String description; Status(int requestStatus, String description) { this.requestStatus = requestStatus; this.description = description; } @Override public String getDescription() { return "" + this.requestStatus + " " + this.description; } @Override public int getRequestStatus() { return this.requestStatus; } } public int getPort() { return myPort; } public void close() { stop(); } transient public IF1 specialHandling; public boolean specialHandling(IHTTPSession session) { return specialHandling != null ? specialHandling.get(session) : specialHandling_base(session); } final public boolean specialHandling_fallback(IF1 _f, IHTTPSession session) { return _f != null ? _f.get(session) : specialHandling_base(session); } public boolean specialHandling_base(IHTTPSession session) { return false; } } static public class ImageStreamFromVideoFile implements Steppable, AutoCloseable { transient public Set> onHaveImage; public ImageStreamFromVideoFile onHaveImage(IVF2 f) { onHaveImage = createOrAddToSyncLinkedHashSet(onHaveImage, f); return this; } public ImageStreamFromVideoFile removeHaveImageListener(IVF2 f) { utils.remove(onHaveImage, f); return this; } public void haveImage(BufferedImage image, Duration d) { if (onHaveImage != null) for (var listener : onHaveImage) pcallF_typed(listener, image, d); } final public ImageStreamFromVideoFile setStopped(boolean stopped) { return stopped(stopped); } public ImageStreamFromVideoFile stopped(boolean stopped) { this.stopped = stopped; return this; } final public boolean getStopped() { return stopped(); } public boolean stopped() { return stopped; } public boolean stopped = false; public AVFormatContext avfmtCtx; public AVStream videoStream; public AVPacket avpacket; public AVCodec codec; public AVCodecContext codecContext; public AVFrame yuv420Frame; public AVFrame rgbFrame; public BufferedImage img; public swscale.SwsContext sws_ctx; final public ImageStreamFromVideoFile setNFrames(long nFrames) { return nFrames(nFrames); } public ImageStreamFromVideoFile nFrames(long nFrames) { this.nFrames = nFrames; return this; } final public long getNFrames() { return nFrames(); } public long nFrames() { return nFrames; } public long nFrames; final public Duration getPosition() { return position(); } public Duration position() { return position; } public Duration position; public AVRational tb1000; public Thread decodeThread; { tb1000 = new AVRational(); tb1000.num(1); tb1000.den(1000); } public void open(File videoFile) throws IOException { if (avfmtCtx != null) throw fail("Already opened a file"); av_log_set_level(AV_LOG_VERBOSE); openInput(videoFile); findVideoStream(); initDecoder(); initRgbFrame(); initYuv420Frame(); getSwsContext(); avpacket = new avcodec.AVPacket(); } public int stage; public boolean step() { try { if (stopped()) return false; if (stage == 0) { if ((av_read_frame(avfmtCtx, avpacket)) >= 0) { if (avpacket.stream_index() == videoStream.index()) processAVPacket(avpacket); av_packet_unref(avpacket); } else stage = 1; return true; } if (stage == 1) { processAVPacket(null); stage = 2; return false; } return false; } catch (Exception __e) { throw rethrow(__e); } } private AVFormatContext openInput(File videoFile) throws IOException { avfmtCtx = new AVFormatContext(null); BytePointer filePointer = new BytePointer(videoFile.getPath()); int r = avformat.avformat_open_input(avfmtCtx, filePointer, null, null); filePointer.deallocate(); if (r < 0) { avfmtCtx.close(); throw new IOException("avformat_open_input error: " + r); } return avfmtCtx; } private void findVideoStream() throws IOException { int r = avformat_find_stream_info(avfmtCtx, (PointerPointer) null); if (r < 0) { avformat_close_input(avfmtCtx); avfmtCtx.close(); throw new IOException("error: " + r); } PointerPointer decoderRet = new PointerPointer<>(1); int videoStreamNumber = av_find_best_stream(avfmtCtx, AVMEDIA_TYPE_VIDEO, -1, -1, decoderRet, 0); if (videoStreamNumber < 0) { throw new IOException("failed to find video stream"); } if (decoderRet.get(AVCodec.class).id() != AV_CODEC_ID_H264) { throw new IOException("failed to find h264 stream"); } decoderRet.deallocate(); videoStream = avfmtCtx.streams(videoStreamNumber); } private void initDecoder() { codec = avcodec_find_decoder(AV_CODEC_ID_H264); codecContext = avcodec_alloc_context3(codec); if ((codec.capabilities() & avcodec.AV_CODEC_CAP_TRUNCATED) != 0) { codecContext.flags(codecContext.flags() | avcodec.AV_CODEC_CAP_TRUNCATED); } avcodec_parameters_to_context(codecContext, videoStream.codecpar()); if (avcodec_open2(codecContext, codec, (PointerPointer) null) < 0) { throw new RuntimeException("Error: could not open codec.\n"); } } private void initYuv420Frame() { yuv420Frame = av_frame_alloc(); if (yuv420Frame == null) { throw new RuntimeException("Could not allocate video frame\n"); } } private void initRgbFrame() { rgbFrame = av_frame_alloc(); rgbFrame.format(AV_PIX_FMT_BGR24); rgbFrame.width(codecContext.width()); rgbFrame.height(codecContext.height()); int ret = av_image_alloc(rgbFrame.data(), rgbFrame.linesize(), rgbFrame.width(), rgbFrame.height(), rgbFrame.format(), 1); if (ret < 0) { throw new RuntimeException("could not allocate buffer!"); } img = new BufferedImage(rgbFrame.width(), rgbFrame.height(), BufferedImage.TYPE_3BYTE_BGR); } private void getSwsContext() { sws_ctx = swscale.sws_getContext(codecContext.width(), codecContext.height(), codecContext.pix_fmt(), rgbFrame.width(), rgbFrame.height(), rgbFrame.format(), 0, null, null, (DoublePointer) null); } private void processAVPacket(AVPacket avpacket) throws IOException { int ret = avcodec.avcodec_send_packet(codecContext, avpacket); if (ret < 0) throw fail("Error sending a packet for decoding"); receiveFrames(); } private void receiveFrames() throws IOException { while (!stopped() && receiveFrame()) { } } public boolean receiveFrame() throws IOException { int ret = avcodec.avcodec_receive_frame(codecContext, yuv420Frame); if (ret == avutil.AVERROR_EAGAIN() || ret == org.bytedeco.javacpp.avutil.AVERROR_EOF()) return false; else if (ret < 0) throw fail("error during video decoding"); swscale.sws_scale(sws_ctx, yuv420Frame.data(), yuv420Frame.linesize(), 0, yuv420Frame.height(), rgbFrame.data(), rgbFrame.linesize()); rgbFrame.best_effort_timestamp(yuv420Frame.best_effort_timestamp()); processFrame(rgbFrame); return true; } private void processFrame(AVFrame rgbFrame) { DataBufferByte buffer = (DataBufferByte) (img.getRaster().getDataBuffer()); rgbFrame.data(0).get(buffer.getData()); long ptsMillis = av_rescale_q(rgbFrame.best_effort_timestamp(), videoStream.time_base(), tb1000); position = Duration.of(ptsMillis, ChronoUnit.MILLIS); ++nFrames; haveImage(img, position); } public void close() { try { stopped(true); if (decodeThread == null) _actualClose(); } catch (Exception __e) { throw rethrow(__e); } } public void _actualClose() { if (avpacket != null) av_packet_unref(avpacket); if (codecContext != null) { avcodec.avcodec_close(codecContext); avcodec.avcodec_free_context(codecContext); } swscale.sws_freeContext(sws_ctx); if (rgbFrame != null) av_frame_free(rgbFrame); if (yuv420Frame != null) av_frame_free(yuv420Frame); if (avfmtCtx != null) { avformat.avformat_close_input(avfmtCtx); avformat.avformat_free_context(avfmtCtx); } } public void stop() { stopped(true); interruptThread(decodeThread); } public void startDecodeThread() { if (decodeThread != null) return; decodeThread = startThread("Decode video", new Runnable() { public void run() { try { stepAll(ImageStreamFromVideoFile.this); if (stopped()) _actualClose(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "stepAll(ImageStreamFromVideoFile.this);\r\n if (stopped()) _actualClose();"; } }); } } public interface IMakeEmptyClone { public Object makeEmptyClone(); } static public class LetterLayout implements LayoutManager { public String[] lines; public Map map = new TreeMap(); public Map constraints = new HashMap(); public RC[] rows; public RC[] cols; public Cell[][] cells; public int spacingX = 10, spacingY = 10; public int insetTop, insetBottom, insetLeft, insetRight; public int template; public boolean formWideLeftSide, formWideRightSide; static final public int STALACTITE = 1, LEFT_ALIGNED_ROW = 2, CENTERED_ROW = 3, FORM = 4, RIGHT_ALIGNED_ROW = 5; public boolean debug = false; public void setLeftBorder(int border) { insetLeft = border; } public void setRightBorder(int border) { insetRight = border; } public static JComponent withBorder(JComponent component, int border) { JPanel panel = new JPanel(new LetterLayout("C").setBorder(border)); panel.add("C", component); return panel; } public static JPanel panel(String... lines) { return new JPanel(new LetterLayout(lines)); } public static JPanel stalactitePanel() { return new JPanel(stalactite()); } static public class DummyComponent extends JComponent { } static public class Cell { public boolean aux = false; public int minWidth, minHeight; public Component component; public int colspan, rowspan; public double weightX, weightY; } static public class RC { public int min; public double weightSum; public int start; public int minEnd; } public LetterLayout(int template) { this.template = template; } public LetterLayout(String... lines) { this.lines = lines; } public void layoutContainer(Container container) { prepareLayout(container); if (debug) System.out.println("Container size: " + container.getSize()); Insets insets = getInsets(container); for (int r = 0; r < rows.length; r++) { for (int i = 0; i < cols.length; ) { Cell cell = cells[i][r]; if (cell.aux) ++i; else { if (cell.component != null) { int x1 = cols[i].start; int y1 = rows[r].start; int x2 = i + cell.colspan < cols.length ? cols[i + cell.colspan].start - spacingX : container.getWidth() - insets.right; int y2 = r + cell.rowspan < rows.length ? rows[r + cell.rowspan].start - spacingY : container.getHeight() - insets.bottom; if (debug) System.out.println("Layouting (" + i + ", " + r + ", " + cell.component.getClass().getName() + "): " + x1 + " " + y1 + " " + x2 + " " + y2); cell.component.setBounds(x1, y1, x2 - x1, y2 - y1); } i += cells[i][r].colspan; } } } } private void prepareLayout(Container container) { applyTemplate(container); int numRows = lines.length, numCols = lines[0].length(); for (int i = 1; i < numRows; i++) if (lines[i].length() != numCols) throw new IllegalArgumentException("Lines have varying length"); cells = new Cell[numCols][numRows]; rows = new RC[numRows]; cols = new RC[numCols]; for (int r = 0; r < numRows; r++) rows[r] = new RC(); for (int i = 0; i < numCols; i++) cols[i] = new RC(); for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r] = new Cell(); for (int r = 0; r < numRows; r++) { String line = lines[r]; for (int i = 0; i < numCols; ) { Cell cell = cells[i][r]; if (cell.aux) { ++i; continue; } char ch = line.charAt(i); int iNext = i; do ++iNext; while (iNext < numCols && ch == line.charAt(iNext)); int rNext = r; do ++rNext; while (rNext < numRows && ch == lines[rNext].charAt(i)); cell.weightX = numCols == 1 || iNext > i + 1 ? 1.0 : 0.0; cell.weightY = numRows == 1 || rNext > r + 1 ? 1.0 : 0.0; Component c = map.get(String.valueOf(ch)); cell.component = c; if (c != null) { cell.minWidth = c.getMinimumSize().width + spacingX; cell.minHeight = getMinimumHeight(c) + spacingY; } cell.colspan = iNext - i; cell.rowspan = rNext - r; if (cell.colspan == 1) cols[i].min = Math.max(cols[i].min, cell.minWidth); if (cell.rowspan == 1) rows[r].min = Math.max(rows[r].min, cell.minHeight); for (int r2 = r; r2 < rNext; r2++) for (int i2 = i; i2 < iNext; i2++) if (r2 != r || i2 != i) cells[i2][r2].aux = true; i = iNext; } } while (true) { for (int i = 0; i < numCols; i++) { int minStart = i == 0 ? 0 : cols[i - 1].minEnd; double weightStart = i == 0 ? 0.0 : cols[i - 1].weightSum; for (int r = 0; r < numRows; r++) { Cell cell = cells[i][r]; if (!cell.aux) { RC rc = cols[i + cell.colspan - 1]; rc.minEnd = Math.max(rc.minEnd, minStart + cell.minWidth); rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightX); } } } for (int r = 0; r < numRows; r++) { int minStart = r == 0 ? 0 : rows[r - 1].minEnd; double weightStart = r == 0 ? 0.0 : rows[r - 1].weightSum; for (int i = 0; i < numCols; i++) { Cell cell = cells[i][r]; if (!cell.aux) { RC rc = rows[r + cell.rowspan - 1]; rc.minEnd = Math.max(rc.minEnd, minStart + cell.minHeight); rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightY); } } } if (allWeightsZero(cols)) { for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightX = 1.0; continue; } if (allWeightsZero(rows)) { for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightY = 1.0; continue; } break; } Insets insets = getInsets(container); determineStarts(cols, insets.left, container.getWidth() - insets.left - insets.right + spacingX, spacingX); determineStarts(rows, insets.top, container.getHeight() - insets.top - insets.bottom + spacingY, spacingY); } private boolean allWeightsZero(RC[] rcs) { for (int i = 0; i < rcs.length; i++) if (rcs[i].weightSum != 0.0) return false; return true; } private static int getMinimumHeight(Component c) { return c.getMinimumSize().height; } private void applyTemplate(Container container) { if (template == STALACTITE) { Component[] components = container.getComponents(); lines = new String[components.length + 2]; map.clear(); for (int i = 0; i < components.length; i++) { String s = String.valueOf(makeIndexChar(i)); map.put(s, components[i]); lines[i] = s; } lines[components.length] = lines[components.length + 1] = " "; } else if (template == FORM) { Component[] components = container.getComponents(); int numRows = components.length / 2; lines = new String[numRows + 2]; map.clear(); for (int row = 0; row < numRows; row++) { String lower = String.valueOf(makeIndexChar(row)); String upper = String.valueOf(makeAlternateIndexChar(row)); Component rightComponent = components[row * 2 + 1]; if (rightComponent instanceof DummyComponent) upper = lower; lines[row] = (formWideLeftSide ? lower + lower : lower) + (formWideRightSide ? upper + upper : upper); map.put(lower, components[row * 2]); if (!(rightComponent instanceof DummyComponent)) map.put(upper, rightComponent); } lines[numRows] = lines[numRows + 1] = (formWideLeftSide ? " " : " ") + (formWideRightSide ? " " : " "); } else if (template == LEFT_ALIGNED_ROW) { lines = new String[] { makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR }; } else if (template == CENTERED_ROW) { lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR }; } else if (template == RIGHT_ALIGNED_ROW) { lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) }; } } private String makeSingleRow(Container container) { Component[] components = container.getComponents(); StringBuffer buf = new StringBuffer(); map.clear(); for (int i = 0; i < components.length; i++) { var c = components[i]; String s = constraints.get(c); if (isOneOfSingleChars(s, LEFT_CHAR, RIGHT_CHAR)) continue; s = str(makeAlternateIndexChar(i)); setConstraints(c, s); buf.append(s); } return buf.toString(); } private static void determineStarts(RC[] rcs, int start, int totalSize, int spacing) { int minTotal = rcs[rcs.length - 1].minEnd; double weightSum = rcs[rcs.length - 1].weightSum; int spare = (int) ((totalSize - minTotal) / (weightSum == 0.0 ? 1.0 : weightSum)); int x = start, minSum = 0; double prevWeightSum = 0.0; for (int i = 0; i < rcs.length; i++) { int width = rcs[i].minEnd - minSum + (int) ((rcs[i].weightSum - prevWeightSum) * spare) - spacing; rcs[i].start = x; x += width + spacing; prevWeightSum = rcs[i].weightSum; minSum = rcs[i].minEnd; } } public void addLayoutComponent(String s, Component component) { setConstraints(component, s); } public void setConstraints(Component component, String s) { mapPutOrRemove(map, s, component); mapPutOrRemove(constraints, component, s); } public void removeLayoutComponent(Component component) { map.values().remove(component); constraints.remove(component); } public Dimension minimumLayoutSize(Container container) { prepareLayout(container); Insets insets = getInsets(container); Dimension result = new Dimension(insets.left + cols[cols.length - 1].minEnd + insets.right - spacingX, insets.top + rows[rows.length - 1].minEnd + insets.bottom - spacingY); return result; } private Insets getInsets(Container container) { Insets insets = container.getInsets(); return new Insets(insets.top + insetTop, insets.left + insetLeft, insets.bottom + insetBottom, insets.right + insetRight); } public Dimension preferredLayoutSize(Container container) { return minimumLayoutSize(container); } public LetterLayout setSpacing(int x, int y) { spacingX = x; spacingY = y; return this; } public LetterLayout setSpacing(int spacing) { return setSpacing(spacing, spacing); } public LetterLayout setBorder(int top, int left, int bottom, int right) { insetTop = top; insetLeft = left; insetBottom = bottom; insetRight = right; return this; } public LetterLayout setBorder(int inset) { return setBorder(inset, inset, inset, inset); } public LetterLayout setTopBorder(int inset) { insetTop = inset; return this; } public static LetterLayout stalactite() { return new LetterLayout(STALACTITE); } public static LetterLayout leftAlignedRow() { return new LetterLayout(LEFT_ALIGNED_ROW); } public static LetterLayout leftAlignedRow(int spacing) { return leftAlignedRow().setSpacing(spacing); } public static LetterLayout centeredRow() { return new LetterLayout(CENTERED_ROW); } public static LetterLayout rightAlignedRow() { return new LetterLayout(RIGHT_ALIGNED_ROW); } public static JPanel rightAlignedRowPanel(JComponent... components) { return makePanel(new LetterLayout(RIGHT_ALIGNED_ROW), components); } private static JPanel makePanel(LetterLayout letterLayout, JComponent[] components) { JPanel panel = new JPanel(letterLayout); for (JComponent component : components) { panel.add(component); } return panel; } public static LetterLayout form() { LetterLayout letterLayout = new LetterLayout(FORM); letterLayout.formWideLeftSide = true; letterLayout.formWideRightSide = true; return letterLayout; } public static LetterLayout formWideRightSide() { LetterLayout letterLayout = new LetterLayout(FORM); letterLayout.formWideRightSide = true; return letterLayout; } public static Component getDummyComponent() { return new DummyComponent(); } public static JPanel newPanel(String... lines) { return new JPanel(new LetterLayout(lines)); } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public static char makeIndexChar(int idx) { return (char) ('a' + idx * 2); } public static char makeAlternateIndexChar(int idx) { return (char) ('b' + idx * 2); } public static char LEFT_CHAR = ',', RIGHT_CHAR = '.'; public static void main(String[] args) { System.out.println((int) makeIndexChar(0)); System.out.println((int) makeAlternateIndexChar(0)); System.out.println((int) makeIndexChar(32000)); System.out.println((int) makeAlternateIndexChar(32000)); System.out.println((int) LEFT_CHAR); System.out.println((int) RIGHT_CHAR); } } public interface StringIO { public void readWrite(StringHead head); default public String saveToString() { return saveToString(new StringHead()); } default public String saveToString(StringHead head) { var writer = stringWriter(); head.writer(writer); readWrite(head); head.finish(); return str(writer); } default public File saveToTextFile(File file) { Writer out = bufferedFileWriter(file); try { var head = new StringHead(out); readWrite(head); head.finish(); return file; } finally { _close(out); } } default public StringIO fromString(String data) { return load(data); } default public StringIO load(String data) { readWrite(new StringHead(stringReader(data))); return this; } default public StringIO loadTextFile(File file) { var in = bufferedReader(file); try { readWrite(new StringHead(in)); return this; } finally { _close(in); } } } static public class BlockDiff { public CopyBlock asCopyBlock() { return null; } public NewBlock asNewBlock() { return null; } } static public class CopyBlock extends BlockDiff { public int firstLine, lines; public CopyBlock(int firstLine, int lines) { this.firstLine = firstLine; this.lines = lines; } public CopyBlock asCopyBlock() { return this; } public int getFirstLine() { return firstLine; } public int getLines() { return lines; } } static public class NewBlock extends BlockDiff { public int originalStart; public List contents; public NewBlock(int originalStart, List contents) { this.originalStart = originalStart; this.contents = contents; } public NewBlock asNewBlock() { return this; } public int getOriginalStart() { return originalStart; } public List getContents() { return contents; } } static public class ExplodedLine { public int type; public String left, right; public int leftIndex, rightIndex; public ExplodedLine(int type, String left, String right, int leftIndex, int rightIndex) { this.type = type; this.left = left; this.right = right; this.leftIndex = leftIndex; this.rightIndex = rightIndex; } public int getType() { return type; } public String getLeft() { return left; } public String getRight() { return right; } public int getLeftIndex() { return leftIndex; } public int getRightIndex() { return rightIndex; } } static public class BlockDiffer { public static final int IDENTICAL = 0; public static final int DIFFERENT = 1; public static final int LEFT_ONLY = 2; public static final int RIGHT_ONLY = 3; private static void printChange(EGDiff.change change) { if (change != null) { System.out.println("line0=" + change.line0 + ", line1=" + change.line1 + ", inserted=" + change.inserted + ", deleted=" + change.deleted); printChange(change.link); } } public static List generateUniDiff(List fileA, List fileB, int contextSize) { EGDiff diff = new EGDiff(fileA.toArray(), fileB.toArray()); EGDiff.change change = diff.diff_2(false); if (change != null) { int inserted, deleted; List hunkLines = new ArrayList(); int cumulExtraLinesBwrtA = 0; do { int line0 = change.line0, line1 = change.line1; int changeStart = ((line1 < line0) ? line1 : line0); int contextStart = ((changeStart > contextSize) ? changeStart - contextSize : 0); int headerPosn = hunkLines.size(); for (int i = contextStart; i < changeStart; i++) hunkLines.add(" " + fileA.get(i)); boolean hunkFinish = false; do { inserted = change.inserted; deleted = change.deleted; line0 = change.line0; line1 = change.line1; if (line1 < line0) while (inserted-- > 0) hunkLines.add("+" + fileB.get(line1++)); while (deleted-- > 0) hunkLines.add("-" + fileA.get(line0++)); while (inserted-- > 0) hunkLines.add("+" + fileB.get(line1++)); EGDiff.change nextChange = change.link; int nextChangeStart = fileA.size(); if (nextChange != null) nextChangeStart = ((nextChange.line1 < nextChange.line0) ? nextChange.line1 : nextChange.line0); if (nextChangeStart - line0 > contextSize * 2) { nextChangeStart = line0 + contextSize; hunkFinish = true; } if (nextChangeStart > fileA.size()) nextChangeStart = fileA.size(); while (line0 < nextChangeStart) { hunkLines.add(" " + fileA.get(line0++)); line1++; } change = change.link; } while (!hunkFinish && change != null); int hunkStartB = contextStart + cumulExtraLinesBwrtA; int hunkTotA = line0 - contextStart; int hunkTotB = line1 - hunkStartB; hunkLines.add(headerPosn, "@@ -" + (contextStart + 1) + ',' + hunkTotA + " +" + (hunkStartB + 1) + ',' + hunkTotB + " @@"); cumulExtraLinesBwrtA += hunkTotB - hunkTotA; } while (change != null); return hunkLines; } return null; } public static List diffLines(List lines, List reference) { List diffs = new ArrayList(); EGDiff diff = new EGDiff(reference.toArray(), lines.toArray()); EGDiff.change change = diff.diff_2(false); int l0 = 0, l1 = 0; while (change != null) { if (change.line0 > l0 && change.line1 > l1) diffs.add(new CopyBlock(l0, change.line0 - l0)); if (change.inserted != 0) diffs.add(new NewBlock(change.line1, lines.subList(change.line1, change.line1 + change.inserted))); l0 = change.line0 + change.deleted; l1 = change.line1 + change.inserted; change = change.link; } if (l0 < reference.size()) diffs.add(new CopyBlock(l0, reference.size() - l0)); return diffs; } public static List explode(List file1, List file2) { List lines = new ArrayList(); List diffs = BlockDiffer.diffLines(file2, file1); int lastLineCopied = 0, rightOnlyStart = -1, rightPosition = 0; for (int i = 0; i < diffs.size(); i++) { BlockDiff diff = diffs.get(i); if (diff instanceof CopyBlock) { CopyBlock copyBlock = (CopyBlock) diff; if (lastLineCopied < copyBlock.getFirstLine()) { if (rightOnlyStart >= 0) { int overlap = Math.min(lines.size() - rightOnlyStart, copyBlock.getFirstLine() - lastLineCopied); convertRightOnlyToDifferent(lines, rightOnlyStart, overlap, file1, lastLineCopied); lastLineCopied += overlap; } addBlock(lines, LEFT_ONLY, file1, lastLineCopied, copyBlock.getFirstLine(), lastLineCopied, -1); } addBlock(lines, IDENTICAL, file1, copyBlock.getFirstLine(), copyBlock.getFirstLine() + copyBlock.getLines(), copyBlock.getFirstLine(), rightPosition); rightPosition += copyBlock.getLines(); lastLineCopied = copyBlock.getFirstLine() + copyBlock.getLines(); rightOnlyStart = -1; } else if (diff instanceof NewBlock) { NewBlock newBlock = (NewBlock) diff; rightOnlyStart = lines.size(); addBlock(lines, RIGHT_ONLY, newBlock.getContents(), 0, newBlock.getContents().size(), -1, rightPosition); rightPosition += newBlock.getContents().size(); } } if (rightOnlyStart >= 0) { int overlap = Math.min(lines.size() - rightOnlyStart, file1.size() - lastLineCopied); convertRightOnlyToDifferent(lines, rightOnlyStart, overlap, file1, lastLineCopied); lastLineCopied += overlap; } addBlock(lines, LEFT_ONLY, file1, lastLineCopied, file1.size(), lastLineCopied, -1); return lines; } private static void convertRightOnlyToDifferent(List lines, int start, int numLines, List leftLines, int leftStart) { for (int i = 0; i < numLines; i++) { ExplodedLine line = lines.get(start + i); lines.set(start + i, new ExplodedLine(DIFFERENT, leftLines.get(i + leftStart), line.getRight(), i + leftStart, line.getRightIndex())); } } private static void addBlock(List lines, int type, List srcLines, int start, int end, int leftStart, int rightStart) { for (int i = start; i < end; i++) lines.add(new ExplodedLine(type, type == RIGHT_ONLY ? "" : srcLines.get(i), type == LEFT_ONLY ? "" : srcLines.get(i), type == RIGHT_ONLY ? -1 : i - start + leftStart, type == LEFT_ONLY ? -1 : i - start + rightStart)); } public static List condense(List lines) { List result = new ArrayList(); for (Iterator i = lines.iterator(); i.hasNext(); ) { ExplodedLine line = i.next(); if (line.getType() == IDENTICAL) { if (result.isEmpty() || result.get(result.size() - 1).getType() != IDENTICAL) result.add(new ExplodedLine(IDENTICAL, "[...]", "[...]", -1, -1)); } else result.add(line); } return result; } } public interface IF1_ObjectToDouble { public double get(A a); } static public class SynchronizedMap implements Map, Serializable { public SynchronizedMap() { } public Map m; public Object mutex; public SynchronizedMap(Map m) { this.m = Objects.requireNonNull(m); mutex = this; } public SynchronizedMap(Map m, Object mutex) { this.m = m; this.mutex = mutex; } public Map innerMap() { return m; } public int size() { synchronized (mutex) { return m.size(); } } public boolean isEmpty() { synchronized (mutex) { return m.isEmpty(); } } public boolean containsKey(Object key) { synchronized (mutex) { return m.containsKey(key); } } public boolean containsValue(Object value) { synchronized (mutex) { return m.containsValue(value); } } public V get(Object key) { synchronized (mutex) { return m.get(key); } } public V put(K key, V value) { synchronized (mutex) { return m.put(key, value); } } public V remove(Object key) { synchronized (mutex) { return m.remove(key); } } public void putAll(Map map) { synchronized (mutex) { m.putAll(map); } } public void clear() { synchronized (mutex) { m.clear(); } } transient public Set keySet; transient public Set> entrySet; transient public Collection values; public Set keySet() { synchronized (mutex) { if (keySet == null) keySet = new SynchronizedSet<>(m.keySet(), mutex); return keySet; } } public Set> entrySet() { synchronized (mutex) { if (entrySet == null) entrySet = new SynchronizedSet<>(m.entrySet(), mutex); return entrySet; } } public Collection values() { synchronized (mutex) { if (values == null) values = new SynchronizedCollection<>(m.values(), mutex); return values; } } public boolean equals(Object o) { if (this == o) return true; synchronized (mutex) { return m.equals(o); } } public int hashCode() { synchronized (mutex) { return m.hashCode(); } } public String toString() { synchronized (mutex) { return m.toString(); } } @Override public V getOrDefault(Object k, V defaultValue) { synchronized (mutex) { return m.getOrDefault(k, defaultValue); } } @Override public void forEach(BiConsumer action) { synchronized (mutex) { m.forEach(action); } } @Override public void replaceAll(BiFunction function) { synchronized (mutex) { m.replaceAll(function); } } @Override public V putIfAbsent(K key, V value) { synchronized (mutex) { return m.putIfAbsent(key, value); } } @Override public boolean remove(Object key, Object value) { synchronized (mutex) { return m.remove(key, value); } } @Override public boolean replace(K key, V oldValue, V newValue) { synchronized (mutex) { return m.replace(key, oldValue, newValue); } } @Override public V replace(K key, V value) { synchronized (mutex) { return m.replace(key, value); } } @Override public V computeIfAbsent(K key, java.util.function.Function mappingFunction) { synchronized (mutex) { return m.computeIfAbsent(key, mappingFunction); } } @Override public V computeIfPresent(K key, BiFunction remappingFunction) { synchronized (mutex) { return m.computeIfPresent(key, remappingFunction); } } @Override public V compute(K key, BiFunction remappingFunction) { synchronized (mutex) { return m.compute(key, remappingFunction); } } @Override public V merge(K key, V value, BiFunction remappingFunction) { synchronized (mutex) { return m.merge(key, value, remappingFunction); } } @java.io.Serial private void writeObject(ObjectOutputStream s) throws IOException { synchronized (mutex) { s.defaultWriteObject(); } } } static public interface Decolorizer { public int toGrayScale(int rgb); default public int toGrayScale(Color color) { return toGrayScale(colorToRGBInt(color)); } static public class Red implements Decolorizer, IFieldsToList { public Red() { } public String toString() { return shortClassName_dropNumberPrefix(this); } public boolean equals(Object o) { return o instanceof Red; } public int hashCode() { int h = 82033; return h; } public Object[] _fieldsToList() { return null; } public int toGrayScale(int rgb) { return (rgb >> 16) & 0xFF; } } static public class Green implements Decolorizer, IFieldsToList { public Green() { } public String toString() { return shortClassName_dropNumberPrefix(this); } public boolean equals(Object o) { return o instanceof Green; } public int hashCode() { int h = 69066467; return h; } public Object[] _fieldsToList() { return null; } public int toGrayScale(int rgb) { return (rgb >> 8) & 0xFF; } } static public class Blue implements Decolorizer, IFieldsToList { public Blue() { } public String toString() { return shortClassName_dropNumberPrefix(this); } public boolean equals(Object o) { return o instanceof Blue; } public int hashCode() { int h = 2073722; return h; } public Object[] _fieldsToList() { return null; } public int toGrayScale(int rgb) { return rgb & 0xFF; } } static public class Alpha implements Decolorizer, IFieldsToList { public Alpha() { } public String toString() { return shortClassName_dropNumberPrefix(this); } public boolean equals(Object o) { return o instanceof Alpha; } public int hashCode() { int h = 63357246; return h; } public Object[] _fieldsToList() { return null; } public int toGrayScale(int rgb) { return (rgb >> 24) & 0xFF; } } static public class Simple implements Decolorizer, IFieldsToList { public Simple() { } public String toString() { return shortClassName_dropNumberPrefix(this); } public boolean equals(Object o) { return o instanceof Simple; } public int hashCode() { int h = -1818419758; return h; } public Object[] _fieldsToList() { return null; } public int toGrayScale(int rgb) { int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = rgb & 0xFF; return (r + g + b + 1) / 3; } } } static public class CompressionSearch_AnyType extends Probabilistic { final public CompressionSearch_AnyType setRegime(CompressionRegime_AnyType regime) { return regime(regime); } public CompressionSearch_AnyType regime(CompressionRegime_AnyType regime) { this.regime = regime; return this; } final public CompressionRegime_AnyType getRegime() { return regime(); } public CompressionRegime_AnyType regime() { return regime; } public CompressionRegime_AnyType regime; final public Data getInputData() { return inputData(); } public Data inputData() { return inputData; } public Data inputData; final public CompressionSearch_AnyType setInputSize(long inputSize) { return inputSize(inputSize); } public CompressionSearch_AnyType inputSize(long inputSize) { this.inputSize = inputSize; return this; } final public long getInputSize() { return inputSize(); } public long inputSize() { return inputSize; } public long inputSize; final public CompressionSearch_AnyType setDoFullTesting(boolean doFullTesting) { return doFullTesting(doFullTesting); } public CompressionSearch_AnyType doFullTesting(boolean doFullTesting) { this.doFullTesting = doFullTesting; return this; } final public boolean getDoFullTesting() { return doFullTesting(); } public boolean doFullTesting() { return doFullTesting; } public boolean doFullTesting = false; transient public Set onNewBest; public CompressionSearch_AnyType onNewBest(Runnable r) { onNewBest = createOrAddToSyncLinkedHashSet(onNewBest, r); return this; } public CompressionSearch_AnyType removeNewBestListener(Runnable r) { utils.remove(onNewBest, r); return this; } public void newBest() { if (onNewBest != null) for (var listener : onNewBest) pcallF_typed(listener); } transient public Set> onDisqualified; public CompressionSearch_AnyType onDisqualified(IVF1 f) { onDisqualified = createOrAddToSyncLinkedHashSet(onDisqualified, f); return this; } public CompressionSearch_AnyType removeDisqualifiedListener(IVF1 f) { utils.remove(onDisqualified, f); return this; } public void disqualified(Submission s) { if (onDisqualified != null) for (var listener : onDisqualified) pcallF_typed(listener, s); } public Best best = new Best(); public List strategies = new ArrayList(); public CompressionSearch_AnyType() { init(); } public CompressionSearch_AnyType(CompressionRegime_AnyType regime) { this.regime = regime; init(); } public CompressionSearch_AnyType(CompressionRegime_AnyType regime, Data inputData, long inputSize) { this.inputSize = inputSize; this.inputData = inputData; this.regime = regime; init(); } public void init() { best.onChange = new Runnable() { public void run() { try { newBest(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "newBest();"; } }; } public Submission submit(A compression) { return submit(compression, null); } public Submission submit(A compression, Object notes) { return _submit(compression, notes); } public class Submission { final public Submission setNotes(Object notes) { return notes(notes); } public Submission notes(Object notes) { this.notes = notes; return this; } final public Object getNotes() { return notes(); } public Object notes() { return notes; } public Object notes; public String toString() { if (!correct()) return linesLL("BAD"); return linesLL((isTrue(isFullChecked()) ? "FULLCHECKED" : " ") + " " + ifloor(score() * 100), "Exact compression ratio: " + scoreRatio(), "Code:", indentx(shorten(500, str(decompressor()))), "Code as bytes:", indentx(shorten(500, bytesToHex(compressed())))); } public void setDecompressor(A decompressor) { this.decompressor_cache = decompressor; } public Data inputData() { return inputData; } public byte[] compressed_cache; public byte[] compressed() { if (compressed_cache == null) compressed_cache = compressed_load(); return compressed_cache; } public byte[] compressed_load() { return decompressor_cache == null ? null : regime.decompressorToBytes(decompressor_cache); } public A decompressor_cache; public A decompressor() { if (decompressor_cache == null) decompressor_cache = decompressor_load(); return decompressor_cache; } public A decompressor_load() { return compressed_cache == null ? null : regime.decompressorFromBytes(compressed_cache); } public String decompressor_str_cache; public String decompressor_str() { if (decompressor_str_cache == null) decompressor_str_cache = decompressor_str_load(); return decompressor_str_cache; } public String decompressor_str_load() { return strOrNull(decompressor()); } final public int nBytes() { return compressedSize(); } public int compressedSize() { return l(compressed()); } public Ratio scoreRatio_cache; public Ratio scoreRatio() { if (scoreRatio_cache == null) scoreRatio_cache = scoreRatio_load(); return scoreRatio_cache; } public Ratio scoreRatio_load() { return new Ratio(inputSize(), compressedSize()); } public Double score_cache; public double score() { if (score_cache == null) score_cache = score_load(); return score_cache; } public double score_load() { return scoreRatio().get(); } public boolean decompressed = false; public Object decompressedValue; public Object decompressed() { if (!decompressed) { decompressedValue = regime.runDecompressor(decompressor()); decompressed = true; } return decompressedValue; } public boolean checkUnder(CompressionRegime_AnyType regime) { return checkResult(regime.runDecompressor(decompressor())); } public Boolean isFullChecked_cache; public Boolean isFullChecked() { if (isFullChecked_cache == null) isFullChecked_cache = isFullChecked_load(); return isFullChecked_cache; } public Boolean isFullChecked_load() { if (!isTrue(correct())) return false; var fullRegime = fullRegime(); if (fullRegime == null) return true; return checkUnder(fullRegime); } public boolean checkResult(Object decompressed) { return eq(toByteList(decompressed), inputData()); } public Boolean correct_cache; public Boolean correct() { if (correct_cache == null) correct_cache = correct_load(); return correct_cache; } public Boolean correct_load() { return eq(toByteList(decompressed()), inputData()); } } public Submission _submit(A compression, Object notes) { if (compression == null) return null; print("Received submission"); print("Code: " + takeFirst(500, str(compression))); Submission s = new Submission(); s.notes(notes); print("Notes: " + takeFirst(500, str(notes))); s.setDecompressor(compression); print("Size: " + nBytes(s.nBytes())); if (s.score() > best.score()) if (!s.correct()) { warn("Compressor didn't verify"); disqualified(s); } else { print("Score: " + s.score()); best.put(s, s.score()); } return s; } public Submission bestSubmission() { methodForEach(__158 -> __158.flush(), strategies); return best.get(); } final public A get() { return bestCompression(); } public A bestCompression() { var s = bestSubmission(); return s == null ? null : s.decompressor(); } public boolean has() { return bestSubmission() != null; } public void addStrategy(AbstractCompressor_AnyType compressor) { if (compressor == null) return; initAction(compressor); compressor.setSearch(this); strategies.add(compressor); compressor.step0(); } transient public IF0 fullRegime; public CompressionRegime_AnyType fullRegime() { return fullRegime != null ? fullRegime.get() : fullRegime_base(); } final public CompressionRegime_AnyType fullRegime_fallback(IF0 _f) { return _f != null ? _f.get() : fullRegime_base(); } public CompressionRegime_AnyType fullRegime_base() { if (doFullTesting) return regime.fullRegime(); return null; } public void step0() { } } static public class InstantNeverHideToolTip extends MouseAdapter { public JComponent component; public JToolTip toolTip; public Popup popup; final public InstantNeverHideToolTip setOffset(Pt offset) { return offset(offset); } public InstantNeverHideToolTip offset(Pt offset) { this.offset = offset; return this; } final public Pt getOffset() { return offset(); } public Pt offset() { return offset; } public Pt offset = pt(20, 20); public int x, y; public String text; public IF0 calculateText; public IF1 calculateTextFromCoordinates; final public InstantNeverHideToolTip setVerbose(boolean verbose) { return verbose(verbose); } public InstantNeverHideToolTip verbose(boolean verbose) { this.verbose = verbose; return this; } final public boolean getVerbose() { return verbose(); } public boolean verbose() { return verbose; } public boolean verbose = false; public Pt mousePt = pt(0, 0); public InstantNeverHideToolTip(IF0 calculateText, JComponent component) { this(component); this.calculateText = calculateText; } public InstantNeverHideToolTip(IF1 calculateTextFromCoordinates, JComponent component) { this(component); this.calculateTextFromCoordinates = calculateTextFromCoordinates; } public InstantNeverHideToolTip(String text, JComponent component) { this(component); this.text = text; } public InstantNeverHideToolTip(JComponent component) { this.component = component; { swing(() -> { component.addMouseListener(InstantNeverHideToolTip.this); component.addMouseMotionListener(InstantNeverHideToolTip.this); toolTip = component.createToolTip(); bindToComponent(component, null, () -> hideToolTip()); }); } } @Override public void mouseEntered(MouseEvent e) { mousePt(ptFromEvent(e)); showToolTip(); } public void mousePt(Pt p) { mousePt = p; if (p != null) { var p2 = translatePt(convertPointToScreen(p, component), offset); x = p2.x; y = p2.y; } } @Override public void mouseDragged(MouseEvent e) { mouseMoved(e); } @Override public void mouseMoved(MouseEvent e) { mousePt(ptFromEvent(e)); if (verbose) printVars("mousePt", mousePt, "calculateTextFromCoordinates", calculateTextFromCoordinates); if (calculateTextFromCoordinates != null) { if (toolTipShowing()) text = null; updateText(); } } public void updateText() { swing(() -> { if (calculateText != null) setText(calculateText.get()); else if (calculateTextFromCoordinates != null) setText(calculateTextFromCoordinates.get(mousePt)); }); } public void showToolTip() { updateText(); showToolTip_noUpdateText(); } public void showToolTip_noUpdateText() { if (empty(text)) return; toolTip.setTipText(text); popup = PopupFactory.getSharedInstance().getPopup(component, toolTip, x, y); popup.show(); } public void mouseExited(MouseEvent e) { hideToolTip(); } public boolean toolTipShowing() { return popup != null; } public void hideToolTip() { if (popup != null) { popup.hide(); popup = null; } } public String getText() { return text; } public void setText(String text) { swing(() -> { if (verbose) printVars("setText", "text", text); if (eq(text, getText())) return; InstantNeverHideToolTip.this.text = text; if (verbose) printVars("setText", "showing", toolTipShowing(), "x", x, "y", y); if (toolTipShowing()) { hideToolTip(); showToolTip_noUpdateText(); } }); } public InstantNeverHideToolTip offset(int pixels) { return offset(pt(pixels, pixels)); } } abstract static public class AbstractBufferedImageOp implements BufferedImageOp, Cloneable { public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel dstCM) { if (dstCM == null) dstCM = src.getColorModel(); return new BufferedImage(dstCM, dstCM.createCompatibleWritableRaster(src.getWidth(), src.getHeight()), dstCM.isAlphaPremultiplied(), null); } public Rectangle2D getBounds2D(BufferedImage src) { return new Rectangle(0, 0, src.getWidth(), src.getHeight()); } public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) { if (dstPt == null) dstPt = new Point2D.Double(); dstPt.setLocation(srcPt.getX(), srcPt.getY()); return dstPt; } public RenderingHints getRenderingHints() { return null; } public int[] getRGB(BufferedImage image, int x, int y, int width, int height, int[] pixels) { int type = image.getType(); if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB) return (int[]) image.getRaster().getDataElements(x, y, width, height, pixels); return image.getRGB(x, y, width, height, pixels, 0, width); } public void setRGB(BufferedImage image, int x, int y, int width, int height, int[] pixels) { int type = image.getType(); if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB) image.getRaster().setDataElements(x, y, width, height, pixels); else image.setRGB(x, y, width, height, pixels, 0, width); } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { return null; } } } static public ThreadLocal> WebSocketHTTPD_headers = new ThreadLocal(); static public ThreadLocal WebSocketHTTPD_current = new ThreadLocal(); static public class WebSocketHTTPD extends NanoWebSocketServer { public WebSocketHTTPD(int port, WebSocketFactory factory) { this(port, (Object) factory); } public WebSocketHTTPD(String hostname, int port, WebSocketFactory factory) { super(hostname, port, webSocketFactory(factory)); nanohttpd_socketTimeoutFix(); } public WebSocketHTTPD(int port, Object factory) { super(port, webSocketFactory(factory)); nanohttpd_socketTimeoutFix(); } public Object onServe, onEndServe; volatile public long requests; transient public IF0 enter; public Object serveFunction = new F2, Object>() { public Object get(String uri, Map parms) { try { return callHtmlMethod2(getMainClass(), uri, parms); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callHtmlMethod2(getMainClass(), uri, parms)"; } }; static public class Serving { public String uri; public Map header, parms, files; } public Set currentlyServing = synchroSet(); public Response serve(String uri, Method method, Map header, Map parms, Map files) { try { AutoCloseable __1 = callF(enter); try { ++requests; AutoCloseable __2 = tempSetThreadLocal(WebSocketHTTPD_current, this); try { Serving serving = nu(Serving.class, "uri", uri, "header", header, "parms", parms, "files", files); currentlyServing.add(serving); pcallF(onServe, serving); try { String remoteAddr = getClientIPFromHeaders(header); String host = header.get("host"); print(formatDateAndTime() + " Serving URI: " + quote((nempty(host) ? "//" + host : "") + uri) + " to: " + remoteAddr); try { Object html; WebSocketHTTPD_headers.set(header); try { html = callF(serveFunction, uri, parms); } finally { WebSocketHTTPD_headers.set(null); } if (html != null) { if (html instanceof NanoHTTPD.Response) return ((NanoHTTPD.Response) html); else return serveHTML(strOrNull(html)); } return serve404(); } catch (Throwable e) { printStackTrace(e); return serveHTML("ERROR."); } } finally { pcallF(onEndServe, serving); currentlyServing.remove(serving); } } finally { _close(__2); } } finally { _close(__1); } } catch (Exception __e) { throw rethrow(__e); } } } static public class Test_ImageInfiller { public BufferedImage lastImageIn, lastImageOut; public void run() { try { int blue = 0xFF0000FF; assertPixels(infill(imageFromPixels(3, blue, blue, blue, blue, 0, blue, blue, blue, blue)), repIntArray(blue, 9)); } catch (Exception __e) { throw rethrow(__e); } } public BufferedImage infill(BufferedImage image) { return lastImageOut = new ImageInfiller(lastImageIn = image).get(); } } static public class WrappedMap extends AbstractMap { public Map map; public WrappedMap() { } public WrappedMap(Map map) { this.map = map; } public B get(Object key) { return map.get(key); } public B put(A key, B value) { return map.put(key, value); } public boolean containsKey(Object key) { return map.containsKey(key); } public Set> entrySet() { return map.entrySet(); } } static public class LongBuffer implements Iterable, ILongQueue, IntSize { public long[] data; public int size; public LongBuffer() { } public LongBuffer(int size) { if (size != 0) data = new long[size]; } public LongBuffer(Iterable l) { if (l instanceof Collection) allocate(((Collection) l).size()); addAll(l); } public void add(long i) { if (size >= lLongArray(data)) { data = resizeLongArray(data, Math.max(1, toInt(Math.min(maximumSafeArraySize(), lLongArray(data) * 2L)))); if (size >= data.length) throw fail("LongBuffer too large: " + size); } data[size++] = i; } public void allocate(int n) { data = resizeLongArray(data, max(n, size())); } public void addAll(Iterable l) { if (l != null) for (long i : l) add(i); } public long[] toArray() { return size == 0 ? null : resizeLongArray(data, size); } public List toList() { return longArrayToList(data, 0, size); } public List asVirtualList() { return listFromFunction(__152 -> get(__152), size); } public void reset() { size = 0; } public void clear() { reset(); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public long get(int idx) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); return data[idx]; } public void set(int idx, long value) { if (idx >= size) throw fail("Index out of range: " + idx + "/" + size); data[idx] = value; } public long popLast() { if (size == 0) throw fail("empty buffer"); return data[--size]; } public long last() { return data[size - 1]; } public long nextToLast() { return data[size - 2]; } public String toString() { return squareBracket(joinWithSpace(toList())); } public Iterator iterator() { return new IterableIterator() { public int i = 0; public boolean hasNext() { return i < size; } public Long next() { if (!hasNext()) throw fail("Index out of bounds: " + i); return data[i++]; } }; } public void trimToSize() { data = resizeLongArray(data, size); } public void remove(int idx) { arraycopy(data, idx + 1, data, idx, size - 1 - idx); --size; } public long poll() { return size == 0 ? -1 : data[--size]; } } public interface IBStack extends IStackWithOptions { default public void temp(AutoCloseable undo) { addUndo(undo); } public void addUndo(AutoCloseable undo); public IBStack backtrack(); public A nextResult(); public A nextResultWithPrintStruct(long maxSteps); } static public class ListCellRendererWithToolTip implements ListCellRenderer, IFieldsToList { public IF1 makeToolTip; public ListCellRenderer baseRenderer; public ListCellRendererWithToolTip() { } public ListCellRendererWithToolTip(IF1 makeToolTip, ListCellRenderer baseRenderer) { this.baseRenderer = baseRenderer; this.makeToolTip = makeToolTip; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + makeToolTip + ", " + baseRenderer + ")"; } public Object[] _fieldsToList() { return new Object[] { makeToolTip, baseRenderer }; } public Component getListCellRendererComponent(JList list, A value, int index, boolean isSelected, boolean cellHasFocus) { var c = baseRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (c instanceof JComponent) { try { ((JComponent) c).setToolTipText(makeToolTip == null ? null : makeToolTip.get((A) value)); } catch (Throwable __e) { pcallFail(__e); } } return ((JComponent) c); } } static public class JavaXPeepholeShortener implements IFieldsToList { public List tok; public JavaXPeepholeShortener() { } public JavaXPeepholeShortener(List tok) { this.tok = tok; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + tok + ")"; } public Object[] _fieldsToList() { return new Object[] { tok }; } public void run() { try { jreplace(tok, ", ", "+$3", (_tok, nIdx) -> eq(unquote(_get(tok, nIdx + 1)), _get(tok, nIdx + 5))); } catch (Exception __e) { throw rethrow(__e); } } } static public class JavaXClassLoaderWithParent extends JavaXClassLoader { public ClassLoader virtualParent; public JavaXClassLoaderWithParent(String progID, List files, ClassLoader virtualParent) { super(progID, files); this.virtualParent = virtualParent; } public Class findClass(String name) throws ClassNotFoundException { if (virtualParent != null && !eq(name, "main") && !name.startsWith("main$")) { try { return virtualParent.loadClass(name); } catch (ClassNotFoundException e) { } } return super.findClass(name); } public URL findResource(String name) { if (virtualParent != null) { URL url = virtualParent.getResource(name); if (url != null) return url; } return super.findResource(name); } public ClassLoader getVirtualParent() { return virtualParent; } } static public interface Transformable { public Object transformUsing(IF1 f); } static public class ClearForAutoRun extends Var { public ClearForAutoRun() { } public ClearForAutoRun(A code) { super(code); } } static public class SurfaceShowingAutoZoomedImage extends JVolatileImageSurface { final public BufferedImage getImage() { return image(); } public BufferedImage image() { return image; } public BufferedImage image; public SurfaceShowingAutoZoomedImage() { this(null); } public SurfaceShowingAutoZoomedImage(BufferedImage image) { volatileMode(false); setImage(image); } public void setImage(BufferedImage image) { this.image = image; setRenderable(new FitImageInComponentRenderable(image).backgroundColor(null)); repaint(); } public void noImage() { setImage(null); } } static public class FitImageInComponentRenderable implements Renderable, IFieldsToList { static final public String _fieldOrder = "srcImage backgroundColor"; public BufferedImage srcImage; public FitImageInComponentRenderable() { } public FitImageInComponentRenderable(BufferedImage srcImage) { this.srcImage = srcImage; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + srcImage + ")"; } public boolean equals(Object o) { if (!(o instanceof FitImageInComponentRenderable)) return false; FitImageInComponentRenderable __1 = (FitImageInComponentRenderable) o; return eq(srcImage, __1.srcImage); } public int hashCode() { int h = 443065758; h = boostHashCombine(h, _hashCode(srcImage)); return h; } public Object[] _fieldsToList() { return new Object[] { srcImage }; } final public FitImageInComponentRenderable setBackgroundColor(Color backgroundColor) { return backgroundColor(backgroundColor); } public FitImageInComponentRenderable backgroundColor(Color backgroundColor) { this.backgroundColor = backgroundColor; return this; } final public Color getBackgroundColor() { return backgroundColor(); } public Color backgroundColor() { return backgroundColor; } public Color backgroundColor = Color.white; public void renderOn(Graphics2D g, int w, int h) { if (backgroundColor != null) { g.setColor(Color.white); g.fillRect(0, 0, w, h); } if (srcImage == null) return; double scale = scaleToFitInside(srcImage, w, h); int x = (w - iround(srcImage.getWidth() * scale)) / 2; int y = (h - iround(srcImage.getHeight() * scale)) / 2; g.translate(x, y); g.scale(scale, scale); g.drawImage(srcImage, 0, 0, null); } } static public class ScaledBufferedImageFromIntegralImage implements ScalingImageOpResult, IFieldsToList { public IIntegralImage img; public int w; public int h; public ScaledBufferedImageFromIntegralImage() { } public ScaledBufferedImageFromIntegralImage(IIntegralImage img, int w, int h) { this.h = h; this.w = w; this.img = img; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + img + ", " + w + ", " + h + ")"; } public Object[] _fieldsToList() { return new Object[] { img, w, h }; } public BufferedImage result; public void run() { try { int[] pixels = img instanceof IntegralImage ? scaledPixelsFromIntegralImage(((IntegralImage) img), w, h) : scaledPixelsFromIntegralImage(img, w, h); result = bufferedImage(w, h, pixels); } catch (Exception __e) { throw rethrow(__e); } } public IIntegralImage scalingSrcImage() { return img; } } static public class ComponentDragger extends MouseAdapter implements IFieldsToList { public ComponentDragger() { } public String toString() { return shortClassName_dropNumberPrefix(this); } public Object[] _fieldsToList() { return null; } public Component component; public MouseEvent mouseDownEvent; public Component clickedOn; public Pt rel; final public ComponentDragger setDebug(boolean debug) { return debug(debug); } public ComponentDragger debug(boolean debug) { this.debug = debug; return this; } final public boolean getDebug() { return debug(); } public boolean debug() { return debug; } public boolean debug = false; final public ComponentDragger setBringToFront(boolean bringToFront) { return bringToFront(bringToFront); } public ComponentDragger bringToFront(boolean bringToFront) { this.bringToFront = bringToFront; return this; } final public boolean getBringToFront() { return bringToFront(); } public boolean bringToFront() { return bringToFront; } public boolean bringToFront = false; public ComponentDragger(Component component, MouseEvent mouseDownEvent) { this.mouseDownEvent = mouseDownEvent; this.component = component; } public void start() { if (mouseDownEvent == null) return; clickedOn = mouseDownEvent.getComponent(); if (bringToFront) { print("Bringing to front: " + component); componentToFront(component); repaint(getParent(component)); } rel = pt(mouseDownEvent.getXOnScreen() - component.getX(), mouseDownEvent.getYOnScreen() - component.getY()); addMouseAndMotionListener(clickedOn, this); } public void mouseDragged(MouseEvent e) { updatePosition(e); } public void mouseReleased(MouseEvent e) { if (e.getButton() != mouseDownEvent.getButton()) return; updatePosition(e); removeMouseAdapter(clickedOn, this); if (debug) printVars("ComponentDragger done"); dragDone(); } public void updatePosition(MouseEvent e) { int x = e.getXOnScreen() - rel.x, y = e.getYOnScreen() - rel.y; x = max(x, 0); y = max(y, 0); updatePosition(x, y); } transient public IVF2 updatePosition; public void updatePosition(int x, int y) { if (updatePosition != null) updatePosition.get(x, y); else updatePosition_base(x, y); } final public void updatePosition_fallback(IVF2 _f, int x, int y) { if (_f != null) _f.get(x, y); else updatePosition_base(x, y); } public void updatePosition_base(int x, int y) { if (debug) printVars("ComponentDragger", "rel", rel, "x", x, "y", y); component.setLocation(x, y); } public void dragDone() { } } static public class OnePath { public ByteBuffer steps = new ByteBuffer(); public OnePath() { } public OnePath(String path) { int n = l(path); steps.allocate(n); for (int i = 0; i < n; i++) steps.add(parseDigit(path, i)); } public OnePath(OnePath path) { steps = new ByteBuffer(path.steps); } public OnePath(Iterable points, boolean close) { fromPoints(points, close); } public void fromPoints(Iterable points, boolean close) { var it = iterator(points); if (empty(it)) return; Pt firstPoint = it.next(), p = firstPoint; while (it.hasNext()) { Pt p2 = it.next(); steps.add(ptToDigit(ptMinus(p2, p))); p = p2; } if (close) steps.add(ptToDigit(ptMinus(firstPoint, p))); } final public int length() { return size(); } final public int nSteps() { return size(); } public int size() { return steps.size(); } public String toString() { return pathString(); } public String pathString() { return singleDigitBytesToString(steps); } public IterableIterator pointIterator() { return pointIterator(origin()); } public IterableIterator pointIterator(Pt startPt) { return new IterableIterator() { public int i = 0, n = length(); public Pt p = startPt; public boolean hasNext() { return i <= n; } public Pt next() { var p = this.p; if (i < n) this.p = translatePt(this.p, getStepAsPt(i)); ++i; return p; } }; } final public List pointsList() { return pointList(); } public List pointList() { return ptBuffer(pointIterator()); } public int getStep(int i) { return steps.get(i); } public Pt getStepAsPt(int i) { return onePathDirections()[steps.get(i)]; } static public int ptToDigit(Pt p) { return p.y < 0 ? p.x < 0 ? 1 : p.x == 0 ? 2 : 3 : p.y == 0 ? p.x < 0 ? 8 : p.x == 0 ? 0 : 4 : p.x < 0 ? 7 : p.x == 0 ? 6 : 5; } public Pt origin() { return utils.origin(); } public Pt endPoint() { return last(pointIterator()); } public Pt drift() { return ptMinus(endPoint(), origin()); } public void addStep(int p_x, int p_y) { addStep(pt(p_x, p_y)); } public void addStep(Pt p) { int step = onePathLookupDirection(p); if (step < 0) throw fail("Invalid one path step: " + p); addStep(step); } public void addStep(int step) { assertBetween(0, 8, step); steps.add(step); } public void insertStep(int idx, int p_x, int p_y) { insertStep(idx, pt(p_x, p_y)); } public void insertStep(int idx, Pt p) { int step = onePathLookupDirection(p); if (step < 0) throw fail("Invalid one path step: " + p); insertStep(idx, step); } public void insertStep(int idx, int step) { assertBetween(0, 8, step); steps.add(idx, step); } public Rect bounds() { return boundsOfPts(pointIterator()); } } static public class PingSourceCancelledException extends RuntimeException implements IFieldsToList { public PingSource pingSource; public PingSourceCancelledException() { } public PingSourceCancelledException(PingSource pingSource) { this.pingSource = pingSource; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + pingSource + ")"; } public Object[] _fieldsToList() { return new Object[] { pingSource }; } } static public interface IMultiSet extends IntSize { public int add(A key); public int get(A key); public Set keySet(); } static public class FileBasedLock implements AutoCloseable { public File lockFile; public double timeout = 60.0; public boolean verbose = false; public boolean haveLock = false; public java.util.Timer touchTimer; final public FileBasedLock setContentsForLockFile(String contentsForLockFile) { return contentsForLockFile(contentsForLockFile); } public FileBasedLock contentsForLockFile(String contentsForLockFile) { this.contentsForLockFile = contentsForLockFile; return this; } final public String getContentsForLockFile() { return contentsForLockFile(); } public String contentsForLockFile() { return contentsForLockFile; } public String contentsForLockFile; public FileBasedLock() { } public FileBasedLock(File lockFile) { this.lockFile = lockFile; } public FileBasedLock(File lockFile, double timeout) { this.timeout = timeout; this.lockFile = lockFile; } synchronized public boolean tryToLock() { if (haveLock) return true; if (fileExists(lockFile)) { double age = fileAgeInSeconds(lockFile); double remaining = timeout - age; print("Lock file age: " + lockFile + ": " + iround(age) + " s" + (remaining <= 0 ? " - old, deleting" : " - please start again in " + nSeconds(iceil(remaining)))); if (remaining <= 0) { print("Deleting old lock file (program crashed?): " + lockFile + " (age: " + iround(age) + " seconds)"); deleteFile(lockFile); } } try { mkdirsForFile(lockFile); java.nio.file.Files.createFile(toPath(lockFile)); print("Created lock file: " + lockFile); if (nempty(contentsForLockFile)) writeContents(); acquired(); return true; } catch (Throwable e) { printExceptionShort("Can't lock", e); return false; } } public void writeContents() { saveTextFileWithoutTemp(lockFile, unnull(contentsForLockFile)); } private void acquired() { haveLock = true; startTouchTimer(); } public void forceLock() { try { print("Force-locking " + lockFile); writeContents(); acquired(); } catch (Exception __e) { throw rethrow(__e); } } public String lockError() { return "Couldn't aquire lock file: " + lockFile; } public void lockOrFail() { if (!tryToLock()) throw fail(lockError()); } synchronized public void startTouchTimer() { if (touchTimer != null) return; double interval = timeout / 2; touchTimer = doEvery(interval, new Runnable() { public void run() { try { doTouch(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "doTouch();"; } }); if (verbose) print("Touch timer started for " + lockFile + " (" + interval + "s)"); } synchronized public void doTouch() { try { if (haveLock) { if (verbose) print("Touching lock file: " + lockFile); touchFile(lockFile); } } catch (Throwable __e) { pcallFail(__e); } } public synchronized void close() { try { { cleanUp(touchTimer); touchTimer = null; } if (haveLock) { haveLock = false; if (verbose) print("Deleting lock file: " + lockFile); deleteFile(lockFile); } } catch (Throwable __e) { pcallFail(__e); } } synchronized public void _simulateCrash() { { cleanUp(touchTimer); touchTimer = null; } } public void deleteOnExit() { if (haveLock) lockFile.deleteOnExit(); } public String actualContents() { return loadTextFile(lockFile); } public boolean hasExpectedContents() { return eq(unnull(contentsForLockFile), actualContents()); } } static public class JSelfSwingable extends SingleComponentPanel implements Swingable { public JComponent visualize() { return this; } public A print(A a) { return print("", a); } public A print(String msg, A a) { return _print(msg, a); } } static public class ThreadPool implements AutoCloseable { public int max = numberOfCores(); public List all = new ArrayList(); public Set used = new HashSet(); public Set free = new HashSet(); public boolean verbose, retired; public class InternalPingSource extends PingSource { } public InternalPingSource internalPingSource = new InternalPingSource(); public MultiSleeper sleeper = new MultiSleeper(); public ThreadPool() { } public ThreadPool(int max) { this.max = max; } synchronized public int maxSize() { return max; } synchronized public int total() { return l(used) + l(free); } transient public Set onCustomerMustWaitAlert; public ThreadPool onCustomerMustWaitAlert(Runnable r) { onCustomerMustWaitAlert = createOrAddToSyncLinkedHashSet(onCustomerMustWaitAlert, r); return this; } public ThreadPool removeCustomerMustWaitAlertListener(Runnable r) { utils.remove(onCustomerMustWaitAlert, r); return this; } public void customerMustWaitAlert() { if (onCustomerMustWaitAlert != null) for (var listener : onCustomerMustWaitAlert) pcallF_typed(listener); } public void fireCustomerMustWaitAlert() { vmBus_send("customerMustWaitAlert", this, currentThread()); customerMustWaitAlert(); } public PooledThread acquireThreadOrQueue(Runnable action) { if (action == null) return null; PooledThread t; synchronized (this) { if (_hasFreeAfterCreating()) { t = _firstFreeThread(); markUsed(t); } else t = _anyThread(); } t.addWork(action); return t; } public boolean _hasFreeAfterCreating() { checkNotRetired(); if (nempty(free)) return true; if (total() < max) { PooledThread t = newThread(); all.add(t); free.add(t); return true; } return false; } public PooledThread acquireThreadOrWait(Runnable action) { try { if (action == null) return null; PooledThread t; while (true) { synchronized (this) { if (_hasFreeAfterCreating()) { t = _firstFreeThread(); break; } else _waitWaitWait(); } } t.addWork(action); return t; } catch (Exception __e) { throw rethrow(__e); } } public PooledThread _firstFreeThread() { return first(free); } public PooledThread _anyThread() { return random(used); } public class PooledThread extends Thread { public PooledThread(String name) { super(name); } public AppendableChain q; synchronized public Runnable _grabWorkOrSleep() { try { Runnable r = first(q); if (r == null) { markFree(this); if (verbose) print("Thread sleeps"); synchronized (this) { wait(); } if (verbose) print("Thread woke up"); return null; } q = popFirst(q); return r; } catch (Exception __e) { throw rethrow(__e); } } public void run() { try { pingSource_tl().set(internalPingSource); while (!retired()) { ping(); Runnable r = _grabWorkOrSleep(); if (verbose) print(this + " work: " + r); if (r != null) try { if (verbose) print(this + " running: " + r); r.run(); pingSource_tl().set(internalPingSource); if (verbose) print(this + " done"); } catch (Throwable e) { pingSource_tl().set(internalPingSource); if (verbose) print(this + " error"); printStackTrace(e); } finally { pingSource_tl().set(internalPingSource); if (verbose) print("ThreadPool finally"); } } } catch (Exception __e) { throw rethrow(__e); } } synchronized public boolean isEmpty() { return empty(q); } public void addWork(Runnable r) { if (verbose) print("Added work to " + this + ": " + r); synchronized (this) { q = chainPlus(q, r); notifyAll(); } } } public PooledThread newThread() { PooledThread t = new PooledThread("Thread Pool Inhabitant " + n2(total() + 1)); t.start(); return t; } synchronized public void markFree(PooledThread t) { used.remove(t); free.add(t); notifyAll(); } synchronized public void markUsed(PooledThread t) { free.remove(t); used.add(t); } synchronized public String toString() { return retired() ? "Retired ThreadPool" : "ThreadPool " + roundBracket(commaCombine(n2(used) + " used out of " + n2(total()), max <= total() ? null : "could grow to " + n2(max))); } synchronized public boolean retired() { return retired; } synchronized public void retire() { if (verbose) print("ThreadPool Retiring"); retired = true; for (var thread : free) syncNotifyAll(thread); } public void checkNotRetired() { if (retired()) throw fail("retired"); } synchronized public void close() { try { retire(); } catch (Exception __e) { throw rethrow(__e); } } public void _waitWaitWait() { try { do { fireCustomerMustWaitAlert(); wait(); checkNotRetired(); } while (empty(free)); } catch (Exception __e) { throw rethrow(__e); } } public void dO(String text, Runnable r) { if (r == null) return; new PingSource(this, text).dO(r); } public ISleeper_v2 sleeper() { return sleeper; } } static public class JForwardingLibDownloader implements Swingable { transient public SingleComponentPanel scp; final public JForwardingLibDownloader setLibraryName(String libraryName) { return libraryName(libraryName); } public JForwardingLibDownloader libraryName(String libraryName) { this.libraryName = libraryName; return this; } final public String getLibraryName() { return libraryName(); } public String libraryName() { return libraryName; } public String libraryName; final public JForwardingLibDownloader setLibIDs(List libIDs) { return libIDs(libIDs); } public JForwardingLibDownloader libIDs(List libIDs) { this.libIDs = libIDs; return this; } final public List getLibIDs() { return libIDs(); } public List libIDs() { return libIDs; } public List libIDs; final public JForwardingLibDownloader setSizeInformation(String sizeInformation) { return sizeInformation(sizeInformation); } public JForwardingLibDownloader sizeInformation(String sizeInformation) { this.sizeInformation = sizeInformation; return this; } final public String getSizeInformation() { return sizeInformation(); } public String sizeInformation() { return sizeInformation; } public String sizeInformation; transient public Set>> onAddingLibraries; public JForwardingLibDownloader onAddingLibraries(IVF1> f) { onAddingLibraries = createOrAddToSyncLinkedHashSet(onAddingLibraries, f); return this; } public JForwardingLibDownloader removeAddingLibrariesListener(IVF1> f) { utils.remove(onAddingLibraries, f); return this; } public void addingLibraries(Collection libIDs) { if (onAddingLibraries != null) for (var listener : onAddingLibraries) pcallF_typed(listener, libIDs); } public boolean supported() { return nempty(libIDs()); } public JForwardingLibDownloader forward(IF0 forward) { this.forward = forward; return this; } transient public IF0 forward; public JComponent forward() { return forward != null ? forward.get() : forward_base(); } final public JComponent forward_fallback(IF0 _f) { return _f != null ? _f.get() : forward_base(); } public JComponent forward_base() { return vstackWithSpacing(flattenToList(jcenteredlabel(libraryName() + " enabled"), map(file -> jcenteredline(jFilePathLabel(file).visualize()), libFiles()), jbutton("Delete " + libraryName(), runnableThread(new Runnable() { public void run() { try { if (!swingConfirm("Really?")) return; deleteFilesVerbose(libFiles()); scp.setComponent(makeComponent()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!swingConfirm(\"Really?\")) return;\r\n deleteFilesVerbose(libFiles())..."; } })))); } public List libFiles() { return map(__153 -> DiskSnippetCache_getLibrary(__153), libIDs()); } public boolean libDownloaded() { return filesExist(libFiles()); } public boolean hasLib() { boolean has = currentProgramHasLibraries(libFiles()); return has; } public void addLib() { if (supported()) { addingLibraries(libIDs()); if (addLibraries(libIDs())) print(libraryName() + " loaded: " + libIDs()); } } public transient JComponent visualize_cache; public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache; } public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); } public JComponent visualize_impl() { if (scp == null) scp = singleComponentPanel(makeComponent()); return scp; } public JComponent makeComponent() { if (!supported()) return jcenteredlabel(libraryName() + " is not yet supported on your platform"); if (libDownloaded()) { addLib(); return forward(); } else return jfullcenter(centerAndEastWithMargin(jcenteredlabel("Download " + libraryName() + " for " + platformName() + appendBracketed(sizeInformation()) + "?"), jbuttonWithDisable("OK", new Runnable() { public void run() { try { addLibWithProgressBar(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addLibWithProgressBar();"; } }))); } public void addLibWithProgressBar() { scp.setComponent(jcenteredlabel("Downloading " + libraryName() + "...")); try { addLib(); scp.setComponent(forward()); } catch (Throwable e) { printStackTrace(e); scp.setComponent(jErrorView(e)); } } public JForwardingLibDownloader libID(String libID) { return libIDs(llNonNulls(libID)); } public JForwardingLibDownloader libIDs(String... libIDs) { return libIDs(asList(libIDs)); } public void loadLibsIfDownloaded() { if (supported() && libDownloaded()) addLib(); } } static public class JS implements IF0, Htmlable { public JS() { } public String code; public Set requiredLibraries; public Set requiredLibraries() { return requiredLibraries; } public JS(String code, Object... dollarVars) { this.code = jsDollarVars(code, dollarVars); } public String get() { return code; } public String toString() { return unnull(code); } public void requireJQuery() { require("jquery"); } public void require(Object library) { requiredLibraries = addToSet_create(requiredLibraries, library); } public String html() { return hjs(code); } } static public class SubList extends AbstractList implements ISubList { public List root; public SubList parent; public int offset; public int size; public SubList(List root, int fromIndex, int toIndex) { if (root instanceof SubList) { this.parent = (SubList) root; this.root = ((SubList) root).root; this.offset = ((SubList) root).offset + fromIndex; } else { this.parent = null; this.root = root; this.offset = fromIndex; } this.size = toIndex - fromIndex; } public E set(int index, E element) { Objects.checkIndex(index, size); checkForComodification(); return root.set(offset + index, element); } public E get(int index) { Objects.checkIndex(index, size); checkForComodification(); return root.get(offset + index); } public int size() { checkForComodification(); return size; } public void add(int index, E element) { rangeCheckForAdd(index); checkForComodification(); root.add(offset + index, element); updateSizeAndModCount(1); } public E remove(int index) { Objects.checkIndex(index, size); checkForComodification(); E result = root.remove(offset + index); updateSizeAndModCount(-1); return result; } public void removeRange(int fromIndex, int toIndex) { checkForComodification(); root.subList(offset + fromIndex, offset + toIndex).clear(); updateSizeAndModCount(fromIndex - toIndex); } public boolean addAll(Collection c) { return addAll(size, c); } public boolean addAll(int index, Collection c) { rangeCheckForAdd(index); int cSize = c.size(); if (cSize == 0) return false; checkForComodification(); root.addAll(offset + index, c); updateSizeAndModCount(cSize); return true; } public Iterator iterator() { return listIterator(); } public ListIterator listIterator(int index) { checkForComodification(); rangeCheckForAdd(index); return new ListIterator() { final public ListIterator i = root.listIterator(offset + index); public boolean hasNext() { return nextIndex() < size; } public E next() { if (hasNext()) return i.next(); else throw new NoSuchElementException(); } public boolean hasPrevious() { return previousIndex() >= 0; } public E previous() { if (hasPrevious()) return i.previous(); else throw new NoSuchElementException(); } public int nextIndex() { return i.nextIndex() - offset; } public int previousIndex() { return i.previousIndex() - offset; } public void remove() { i.remove(); updateSizeAndModCount(-1); } public void set(E e) { i.set(e); } public void add(E e) { i.add(e); updateSizeAndModCount(1); } }; } public List subList(int fromIndex, int toIndex) { _subListRangeCheck(fromIndex, toIndex, size); return new SubList<>(this, fromIndex, toIndex); } private void rangeCheckForAdd(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: " + index + ", Size: " + size; } private void checkForComodification() { } private void updateSizeAndModCount(int sizeChange) { SubList slist = this; do { slist.size += sizeChange; slist = slist.parent; } while (slist != null); } public List rootList() { return root; } public List parentList() { return parent; } public int subListOffset() { return offset; } } static public interface IContentsIndexedList extends List { public int[] indicesOf(A o); } static public class DoLater implements AutoCloseable { public long targetSysTime; volatile public Runnable action; final public DoLater setSleeper(ISleeper_v2 sleeper) { return sleeper(sleeper); } public DoLater sleeper(ISleeper_v2 sleeper) { this.sleeper = sleeper; return this; } final public ISleeper_v2 getSleeper() { return sleeper(); } public ISleeper_v2 sleeper() { return sleeper; } transient public ISleeper_v2 sleeper; transient public Executor executor; transient public Flag enabled = new Flag(); transient public Flag cancelledOrExecuted = new Flag(); public DoLater() { } public DoLater(long targetSysTime, Runnable action) { this.action = action; this.targetSysTime = targetSysTime; } public void enable() { if (!enabled.raise()) return; if (sleeper == null) sleeper = defaultSleeper(); sleeper.doLater(targetSysTime, new Runnable() { public void run() { try { if (!cancelledOrExecuted.raise()) return; runWithExecutor(action, executor); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!cancelledOrExecuted.raise()) return;\r\n runWithExecutor(action, exec..."; } }); } public boolean cancel() { if (!cancelledOrExecuted.raise()) return false; { close(); return true; } } public void close() { cancelledOrExecuted.raise(); } } public interface ILongBuffer extends IntSize, Iterable, ILongQueue, IntegrityCheckable { public void add(long d); public void addAll(Iterable l); public long[] toArray(); public long get(int idx); public void trimToSize(); public long popLast(); public long last(); public boolean isEmpty(); public List asVirtualList(); public void insertAt(int idx, long[] l); } static public class DeQ extends Q { public DeQ() { q = new LinkedList(); } public void addFirst(Object r) { ((Deque) q).addFirst(toRunnable(r)); _trigger(); } } static public class SynchronizedRandomAccessList extends SynchronizedList implements RandomAccess { public SynchronizedRandomAccessList() { } public SynchronizedRandomAccessList(List list) { super(list); } public SynchronizedRandomAccessList(List list, Object mutex) { super(list, mutex); } public List subList(int fromIndex, int toIndex) { synchronized (mutex) { return new SynchronizedRandomAccessList<>(list.subList(fromIndex, toIndex), mutex); } } @java.io.Serial static final public long serialVersionUID = 1530674583602358482L; @java.io.Serial private Object writeReplace() { return new SynchronizedList<>(list); } } public interface IDoubleBuffer extends IntSize, Iterable, IntegrityCheckable { public void add(double d); public void addAll(Iterable l); public double[] toArray(); public double get(int idx); public void trimToSize(); public double popLast(); public double first(); public double last(); public boolean isEmpty(); public void insertAt(int idx, double[] l); public int indexOf(double d); default public boolean contains(double d) { return indexOf(d) >= 0; } } static public class JImageSwitch extends JLabel { public String onImageID, offImageID; public String offToolTip, onToolTip; public IVarWithNotify var; public boolean on = false; public InstantNeverHideToolTip toolTip; public JImageSwitch(String onImageID, String offImageID, IVarWithNotify var) { this.var = var; this.offImageID = offImageID; this.onImageID = onImageID; toolTip = new InstantNeverHideToolTip(this); bindListenerToComponent(this, var, new Runnable() { public void run() { try { set(var.get()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "set(var!)"; } }); on = var.get(); updateIcon(); onLeftClick(this, () -> flip()); } public JImageSwitch setToolTips(String onToolTip, String offToolTip) { this.onToolTip = onToolTip; this.offToolTip = offToolTip; updateIcon(); return this; } public void updateIcon() { toolTip.setText(on ? onToolTip : offToolTip); setIcon(imageIcon(loadImage2_cached(on ? onImageID : offImageID))); } public void flip() { set(!on); } public void set(boolean value) { swing(() -> { if (on != value) { on = value; updateIcon(); var.set(on); } }); } public boolean isOn() { return on; } } static public class ListAndIndex implements IFieldsToList { static final public String _fieldOrder = "list idx"; public List list; public int idx; public ListAndIndex() { } public ListAndIndex(List list, int idx) { this.idx = idx; this.list = list; } public boolean equals(Object o) { if (!(o instanceof ListAndIndex)) return false; ListAndIndex __1 = (ListAndIndex) o; return eq(list, __1.list) && idx == __1.idx; } public int hashCode() { int h = 276903961; h = boostHashCombine(h, _hashCode(list)); h = boostHashCombine(h, _hashCode(idx)); return h; } public Object[] _fieldsToList() { return new Object[] { list, idx }; } public boolean atEnd() { return idx >= l(list); } public A get() { return _get(list, idx); } public int size() { return l(list); } public String toString() { return subList(list, 0, idx) + ", then " + subList(list, idx); } public ListAndIndex plus(int ofs) { return new ListAndIndex(list, idx + ofs); } public ListAndIndex minus(int ofs) { return new ListAndIndex(list, idx - ofs); } public List list() { return list; } final public int idx() { return index(); } public int index() { return idx; } public ListAndIndex mapIdx(IF1_IntToInt f) { return new ListAndIndex(list, f.get(idx)); } } abstract static public class AbstractProfiler implements AutoCloseable { final public AbstractProfiler setInterval(int interval) { return interval(interval); } public AbstractProfiler interval(int interval) { this.interval = interval; return this; } final public int getInterval() { return interval(); } public int interval() { return interval; } public int interval = 40; final public AbstractProfiler setSkipSleeping(boolean skipSleeping) { return skipSleeping(skipSleeping); } public AbstractProfiler skipSleeping(boolean skipSleeping) { this.skipSleeping = skipSleeping; return this; } final public boolean getSkipSleeping() { return skipSleeping(); } public boolean skipSleeping() { return skipSleeping; } public boolean skipSleeping = false; public MultiSet stackTraceMultiSet = new MultiSet(); final public int getSamples() { return samples(); } public int samples() { return samples; } volatile public int samples; public java.util.Timer timer; public Lock lock = lock(); public void start() { Lock __0 = lock; lock(__0); try { assertCanStart(); printWithMS("Starting " + this); stop(); clear(); timer = doEvery_daemon("Profiler", interval, new Runnable() { public void run() { try { stepImpl(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "stepImpl();"; } }); } finally { unlock(__0); } } public void assertCanStart() { } abstract public void stepImpl(); final public void close() { stop(); } public void stop() { Lock __1 = lock; lock(__1); try { if (timer != null) { stopTimer(timer); timer = null; printWithMS("Stopped " + this); } } finally { unlock(__1); } } public void clear() { Lock __2 = lock; lock(__2); try { stackTraceMultiSet.clear(); samples = 0; } finally { unlock(__2); } } public MultiSet results() { Lock __3 = lock; lock(__3); try { return cloneMultiSet(stackTraceMultiSet); } finally { unlock(__3); } } public MultiSet stopAndGetResults() { Lock __4 = lock; lock(__4); try { stop(); return results(); } finally { unlock(__4); } } public String renderFullResults(boolean mostImportantLast) { var traces = results(); int n = traces.size(); int percent = ratioToIntPercent(l(traces), samples); return (samples == 0 ? "Nothing sampled" : percent + "% core activity [" + n2(samples, "sample") + " taken]") + "\n\n" + joinMap(mostImportantLast ? traces.lowestFirst() : traces.highestFirst(), trace -> traces.get(trace) + "/" + n + "\n" + trace + "\n\n"); } public void addSample(StackTraceElement[] stackTrace) { stackTraceMultiSet.add(stackTraceToString(stackTrace)); } } static public class RuntimeExceptionWithCustomStackTrace extends RuntimeException { public RuntimeExceptionWithCustomStackTrace(String msg, Throwable cause, StackTraceElement[] stackTrace) { super(msg, cause, false, true); setStackTrace(stackTrace); } } static public class BitHead extends ByteHead { final public int getAlign() { return align(); } public int align() { return align; } public int align = 8; final public int getCurrentByte() { return currentByte(); } public int currentByte() { return currentByte; } public int currentByte; final public BitHead setDebug(boolean debug) { return debug(debug); } public BitHead debug(boolean debug) { this.debug = debug; return this; } final public boolean getDebug() { return debug(); } public boolean debug() { return debug; } public boolean debug = false; public BitHead() { } public BitHead(InputStream inputStream) { super(inputStream); } public BitHead(OutputStream outputStream) { super(outputStream); } public boolean writeArraysSlowly() { return false; } public void write(byte[] data) { if (align == 0 && !writeArraysSlowly()) super.write(data); else for (var b : data) write(b); } public void writeByte(int i) { i &= 0xFF; if (debug) print("writeByte: align=" + align + ", byteCounter=" + byteCounter + ", value=" + i); if (align == 0) super.writeByte(i); else { currentByte |= i << align; super.writeByte(currentByte); currentByte = i >> (8 - align); } } public void writePartialByte(int i, int bits) { for (int bit = 0; bit < bits; bit++) { writeBit(i); i >>>= 1; } } public void writeBit(int i) { writeBit((i & 1) != 0); } public void writeBit(boolean b) { align &= 7; if (b) currentByte |= 1 << align; if (align == 7) { super.writeByte(currentByte); currentByte = align = 0; } else ++align; } public int readPartialByte(int bits) { int value = 0; for (int bit = 0; bit < bits; bit++) if (readBit()) value |= 1 << bit; return isEOF() ? -1 : value; } public int readByte() { if (debug) print("readByte: align=" + align + ", byteCounter=" + byteCounter); int value; if (align == 0) { value = currentByte; align = 8; } else if (align == 8) value = super.readByte(); else { value = currentByte >> align; int align = this.align; bufferNextByte(); if (isEOF()) return -1; this.align = align; value |= (currentByte << (8 - align)) & 0xFF; } if (debug) print("value: " + value); return value; } public boolean readBit() { boolean bitSet = peekBit(); advanceBit(); return bitSet; } public boolean peekBit() { if (currentByte < 0) throw fail("eof"); if (align == 8) bufferNextByte(); return (currentByte & (1 << align)) != 0; } public void bufferNextByte() { currentByte = super.readByte(); align = 0; } public void advanceBit() { if (currentByte < 0) return; if (align == 8) bufferNextByte(); ++align; } public boolean byteAligned() { return (align & 7) == 0; } final public void flushBits() { completeByte(); } final public void finishByte() { completeByte(); } final public void finish() { completeByte(); } public void completeByte() { completeByte(false); } final public void flushBits(boolean padWithOnes) { completeByte(padWithOnes); } final public void finishByte(boolean padWithOnes) { completeByte(padWithOnes); } final public void finish(boolean padWithOnes) { completeByte(padWithOnes); } public void completeByte(boolean padWithOnes) { if (debug) print("Finishing byte " + byteCounter + " (align " + align + ")"); if (byteAligned()) return; if (writeMode()) { if (padWithOnes) currentByte |= 0xFF << align; super.writeByte(currentByte); } currentByte = 0; align = readMode() ? 8 : 0; } final public void trailingBitCount() { writeTrailingBitCount(); } public void writeTrailingBitCount() { writeTrailingBitCount(false); } final public void trailingBitCount(boolean padWithOnes) { writeTrailingBitCount(padWithOnes); } public void writeTrailingBitCount(boolean padWithOnes) { if (!writeMode()) return; int bitCount = modRange_incl(align(), 1, 8); completeByte(padWithOnes); writeByte(bitCount); } public void exchange(BitIO writable) { if (writable != null) writable.readWrite(this); } public void exchangeBit(IF0 getter, IVF1 setter) { if (writeMode()) writeBit(getter.get()); if (readMode()) setter.get(readBit()); } public void exchangeBit(int i) { exchangeBit(odd(i)); } public void exchangeBit(boolean i) { exchangeBit(() -> i, j -> assertEquals(i, j)); } public void exchange(BitIO getter, Runnable setter) { if (writeMode()) getter.readWrite(this); if (readMode()) setter.run(); } public boolean isEOF() { return currentByte < 0; } } static public class ImageSurfaceDragger extends ImageSurfaceMouseHandler { static public boolean debug = true; public Point start, startScroll; public int dx, dy; public ImageSurfaceDragger() { } public ImageSurfaceDragger(ImageSurface is) { if (containsInstance(is.tools, ImageSurfaceDragger.class)) return; this.register(is); } public void mousePressed(MouseEvent e) { JScrollPane sp = enclosingScrollPane(is); if (sp == null) return; if (e.getButton() == MouseEvent.BUTTON1) { start = e.getLocationOnScreen(); startScroll = new Point(scrollBarValue(sp.getHorizontalScrollBar()), scrollBarValue(sp.getVerticalScrollBar())); } } public void mouseDragged(MouseEvent e) { if (start == null) return; JScrollPane sp = enclosingScrollPane(is); if (sp == null) return; Point p = e.getLocationOnScreen(); setScrollBarValue(sp.getHorizontalScrollBar(), -(p.x - start.x) + startScroll.x); setScrollBarValue(sp.getVerticalScrollBar(), -(p.y - start.y) + startScroll.y); } public void mouseReleased(MouseEvent e) { mouseDragged(e); start = null; } } static public interface IRGBImage extends MakesBufferedImage { public int getIntPixel(int x, int y); } static public class RegionToImage2B implements IFieldsToList { public IPixelSet region; public RegionToImage2B() { } public RegionToImage2B(IPixelSet region) { this.region = region; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + region + ")"; } public Object[] _fieldsToList() { return new Object[] { region }; } final public RegionToImage2B setBounds(Rect bounds) { return bounds(bounds); } public RegionToImage2B bounds(Rect bounds) { this.bounds = bounds; return this; } final public Rect getBounds() { return bounds(); } public Rect bounds() { return bounds; } public Rect bounds; public Image2B image; public void run() { try { if (bounds == null) bounds = region.bounds(); int x1 = bounds.x, y1 = bounds.y, w = bounds.w, h = bounds.h, i = 0; byte[] pixels = new byte[(w * h + 7) / 8]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { if (!region.contains(x1 + x, y1 + y)) pixels[i / 8] |= 1 << (i & 7); i++; } image = new Image2B(w, h, pixels); } catch (Exception __e) { throw rethrow(__e); } } public Image2B get() { if (image == null) run(); return image; } } abstract static public class AbstractBorderTracer extends AbstractSteppable { transient public Set> onNewTrace; public AbstractBorderTracer onNewTrace(IVF1 f) { onNewTrace = createOrAddToSyncLinkedHashSet(onNewTrace, f); return this; } public AbstractBorderTracer removeNewTraceListener(IVF1 f) { utils.remove(onNewTrace, f); return this; } public void newTrace(boolean isHole) { if (onNewTrace != null) for (var listener : onNewTrace) pcallF_typed(listener, isHole); } transient public Set> onFoundPoint; public AbstractBorderTracer onFoundPoint(IVF1 f) { onFoundPoint = createOrAddToSyncLinkedHashSet(onFoundPoint, f); return this; } public AbstractBorderTracer removeFoundPointListener(IVF1 f) { utils.remove(onFoundPoint, f); return this; } public void foundPoint(Pt p) { if (onFoundPoint != null) for (var listener : onFoundPoint) pcallF_typed(listener, p); } transient public Set onTraceDone; public AbstractBorderTracer onTraceDone(Runnable r) { onTraceDone = createOrAddToSyncLinkedHashSet(onTraceDone, r); return this; } public AbstractBorderTracer removeTraceDoneListener(Runnable r) { utils.remove(onTraceDone, r); return this; } public void traceDone() { if (onTraceDone != null) for (var listener : onTraceDone) pcallF_typed(listener); } final public AbstractBorderTracer setIncludeHoles(boolean includeHoles) { return includeHoles(includeHoles); } public AbstractBorderTracer includeHoles(boolean includeHoles) { this.includeHoles = includeHoles; return this; } final public boolean getIncludeHoles() { return includeHoles(); } public boolean includeHoles() { return includeHoles; } public boolean includeHoles = true; } abstract static public class SynchronizedArrayList_Base extends AbstractList { final public int modCount() { return modCount; } public void removeRange(int i, int j) { super.removeRange(i, j); } } static public interface IConceptCounter { public Class conceptClass(); public int countConcepts(); public Collection allConcepts(); } public interface IToolTipMaker { public String getToolTip(Pt p); } public interface IBest { public boolean put(A a, double score); } static public class ProbabilisticListAdapter implements ProbabilisticListListener { public void elementAdded(A a, double probability) { } } static public class GrabbableRGBBytePixels implements IFieldsToList { static final public String _fieldOrder = "data w h offset scanlineStride pixelStride"; public byte[] data; public int w; public int h; public int offset; public int scanlineStride; public int pixelStride; public GrabbableRGBBytePixels() { } public GrabbableRGBBytePixels(byte[] data, int w, int h, int offset, int scanlineStride, int pixelStride) { this.pixelStride = pixelStride; this.scanlineStride = scanlineStride; this.offset = offset; this.h = h; this.w = w; this.data = data; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + data + ", " + w + ", " + h + ", " + offset + ", " + scanlineStride + ", " + pixelStride + ")"; } public boolean equals(Object o) { if (!(o instanceof GrabbableRGBBytePixels)) return false; GrabbableRGBBytePixels __1 = (GrabbableRGBBytePixels) o; return eq(data, __1.data) && w == __1.w && h == __1.h && offset == __1.offset && scanlineStride == __1.scanlineStride && pixelStride == __1.pixelStride; } public int hashCode() { int h = 330924690; h = boostHashCombine(h, _hashCode(data)); h = boostHashCombine(h, _hashCode(w)); h = boostHashCombine(h, _hashCode(h)); h = boostHashCombine(h, _hashCode(offset)); h = boostHashCombine(h, _hashCode(scanlineStride)); h = boostHashCombine(h, _hashCode(pixelStride)); return h; } public Object[] _fieldsToList() { return new Object[] { data, w, h, offset, scanlineStride, pixelStride }; } } public interface ProbabilisticListListener { public void elementAdded(A a, double probability); } static public class ByteHead implements AutoCloseable { final public ByteHead setReadMode(boolean readMode) { return readMode(readMode); } public ByteHead readMode(boolean readMode) { this.readMode = readMode; return this; } final public boolean getReadMode() { return readMode(); } public boolean readMode() { return readMode; } public boolean readMode = false; final public ByteHead setWriteMode(boolean writeMode) { return writeMode(writeMode); } public ByteHead writeMode(boolean writeMode) { this.writeMode = writeMode; return this; } final public boolean getWriteMode() { return writeMode(); } public boolean writeMode() { return writeMode; } public boolean writeMode = false; final public InputStream getInputStream() { return inputStream(); } public InputStream inputStream() { return inputStream; } public InputStream inputStream; final public OutputStream getOutputStream() { return outputStream(); } public OutputStream outputStream() { return outputStream; } public OutputStream outputStream; final public ByteHead setByteCounter(long byteCounter) { return byteCounter(byteCounter); } public ByteHead byteCounter(long byteCounter) { this.byteCounter = byteCounter; return this; } final public long getByteCounter() { return byteCounter(); } public long byteCounter() { return byteCounter; } public long byteCounter; final public boolean getEof() { return eof(); } public boolean eof() { return eof; } public boolean eof = false; public ByteHead() { } public ByteHead(InputStream inputStream) { inputStream(inputStream); } public ByteHead(OutputStream outputStream) { outputStream(outputStream); } public ByteHead inputStream(InputStream inputStream) { this.inputStream = inputStream; readMode(true); return this; } public ByteHead outputStream(OutputStream outputStream) { this.outputStream = outputStream; writeMode(true); return this; } public void write(byte[] data) { try { ensureWriteMode(); { if (outputStream != null) outputStream.write(data); } byteCounter += data.length; } catch (Exception __e) { throw rethrow(__e); } } public void writeFloat(float f) { writeInt(Float.floatToIntBits(f)); } public void writeLong(long l) { writeInt((int) (l >> 32)); writeInt((int) l); } public void writeInt(int i) { write(i >> 24); write(i >> 16); write(i >> 8); write(i); } public void writeShort(int i) { write(i >> 8); write(i); } final public void write(int i) { writeByte(i); } public void writeByte(int i) { try { ensureWriteMode(); { if (outputStream != null) outputStream.write(i); } byteCounter++; } catch (Exception __e) { throw rethrow(__e); } } public void writeASCII(char c) { write(toASCII(c)); } public void writeASCII(String s) { write(toASCII(s)); } public void exchangeASCII(String s) { exchangeConstantBytes(toASCII(s)); } public void exchangeConstantBytes(byte[] data) { for (int i = 0; i < l(data); i++) exchangeByte(data[i]); } public long readLong() { long i = ((long) readInt()) << 32; return i | (readInt() & 0xFFFFFFFFL); } public float readFloat() { return Float.intBitsToFloat(readInt()); } public int readInt() { int i = read() << 24; i |= read() << 16; i |= read() << 8; return i | read(); } public short readShort() { int i = read() << 8; return (short) (i | read()); } public byte[] readBytes(int n) { byte[] data = new byte[n]; for (int i = 0; i < n; i++) { int b = read(); if (b < 0) throw fail("EOF"); data[i] = (byte) b; } return data; } public String readString() { int n = readInt(); if (eof()) return null; return fromUtf8(readBytes(n)); } public void writeString(String s) { byte[] utf8 = toUtf8(unnull(s)); writeInt(l(utf8)); write(utf8); } final public int read() { return readByte(); } public int readByte() { try { ensureReadMode(); ++byteCounter; int b = inputStream.read(); if (b < 0) eof = true; return b; } catch (Exception __e) { throw rethrow(__e); } } public void ensureReadMode() { if (!readMode) throw fail("Not in read mode"); } public void ensureWriteMode() { if (!writeMode) throw fail("Not in write mode"); } public void exchangeByte(byte getter, IVF1 setter) { exchangeByte(() -> getter, setter); } public void exchangeByte(IF0 getter, IVF1 setter) { if (writeMode()) writeByte(getter.get()); if (readMode()) setter.get(toUByte(readByte())); } public void exchangeShort(IF0 getter, IVF1 setter) { if (writeMode()) writeShort(getter.get()); if (readMode()) setter.get(readShort()); } public void exchangeLong(IVar var) { exchangeLong(var.getter(), var.setter()); } public void exchangeLong(IF0 getter, IVF1 setter) { if (writeMode()) writeLong(getter.get()); if (readMode()) setter.get(readLong()); } public void exchangeByte(byte i) { exchangeByte(() -> i, j -> assertEquals(i, j)); } public void exchangeInt(int i) { exchangeInt(() -> i, j -> assertEquals(i, j)); } public void exchangeInt(IF0 getter, IVF1 setter) { if (writeMode()) writeInt(getter.get()); if (readMode()) setter.get(readInt()); } public void exchange(ByteIO writable) { if (writable != null) writable.readWrite(this); } public void exchangeAll(Iterable writables) { if (writables != null) for (var writable : writables) exchange(writable); } public void exchangeWithSize(ByteIO writable) { if (writeMode()) { byte[] data = writable.saveToByteArray(); writeInt(l(data)); write(data); } if (readMode()) { int n = readInt(); writable.readWrite(this); } } public void finish() { } public void close() { utils.close(inputStream); utils.close(outputStream); finish(); } } static public class RemoteDB implements AutoCloseable { public DialogIO db; public String name; public RemoteDB(String s) { this(s, false); } public RemoteDB(String s, boolean autoStart) { name = s; if (isSnippetID(s)) name = dbBotName(s); db = findBot(name); if (db == null) if (autoStart) { nohupJavax(fsI(s)); waitForBotStartUp(name); assertNotNull("Weird problem", db = findBot(s)); } else throw fail("DB " + s + " not running"); } public boolean functional() { return db != null; } public List list() { return adopt((List) rpc(db, "xlist")); } public List list(String className) { return adopt((List) rpc(db, "xlist", className)); } public List xlist() { return list(); } public List xlist(String className) { return list(className); } public List adopt(List l) { if (l != null) for (RC rc : l) adopt(rc); return l; } public RC adopt(RC rc) { if (rc != null) rc.db = this; return rc; } public Object adopt(Object o) { if (o instanceof RC) return adopt((RC) o); return o; } public String xclass(RC o) { return (String) rpc(db, "xclass", o); } public Object xget(RC o, String field) { return adopt(rpc(db, "xget", o, field)); } public String xS(RC o, String field) { return (String) xget(o, field); } public RC xgetref(RC o, String field) { return adopt((RC) xget(o, field)); } public void xset(RC o, String field, Object value) { rpc(db, "xset", o, field, value); } public RC uniq(String className) { RC ref = first(list(className)); if (ref == null) ref = xnew(className); return ref; } public RC xuniq(String className) { return uniq(className); } public RC xnew(String className, Object... values) { return adopt((RC) rpc(db, "xnew", className, values)); } public void xdelete(RC o) { rpc(db, "xdelete", o); } public void xdelete(List l) { rpc(db, "xdelete", l); } public void close() { _close(db); } public String fullgrab() { return (String) rpc(db, "xfullgrab"); } public String xfullgrab() { return fullgrab(); } public void xshutdown() { rpc(db, "xshutdown"); } public long xchangeCount() { return (long) rpc(db, "xchangeCount"); } public int xcount() { return (int) rpc(db, "xcount"); } public void reconnect() { close(); db = findBot(name); } public RC rc(long id) { return new RC(this, id); } } static public interface ILongQueue { public boolean isEmpty(); public void add(long element); public long poll(); } static public boolean webSocket_debug = false; static public class WebSocketException extends IOException { public WebSocketFrame.CloseCode code; public String reason; public WebSocketException(Exception cause) { this(WebSocketFrame.CloseCode.InternalServerError, cause.toString(), cause); } public WebSocketException(WebSocketFrame.CloseCode code, String reason) { this(code, reason, null); } public WebSocketException(WebSocketFrame.CloseCode code, String reason, Exception cause) { super(code + ": " + reason, cause); this.code = code; this.reason = reason; } public WebSocketFrame.CloseCode getCode() { return code; } public String getReason() { return reason; } } static public class WebSocketFrame { public OpCode opCode; public boolean fin = false; public byte[] maskingKey; public byte[] payload; transient public int _payloadLength; transient public String _payloadString; public WebSocketFrame(OpCode opCode, boolean fin) { setOpCode(opCode); setFin(fin); } public WebSocketFrame(OpCode opCode, boolean fin, byte[] payload, byte[] maskingKey) { this(opCode, fin); setMaskingKey(maskingKey); setBinaryPayload(payload); } public WebSocketFrame(OpCode opCode, boolean fin, byte[] payload) { this(opCode, fin, payload, null); } public WebSocketFrame(OpCode opCode, boolean fin, String payload, byte[] maskingKey) throws CharacterCodingException { this(opCode, fin); setMaskingKey(maskingKey); setTextPayload(payload); } public WebSocketFrame(OpCode opCode, boolean fin, String payload) throws CharacterCodingException { this(opCode, fin, payload, null); } public WebSocketFrame(WebSocketFrame clone) { setOpCode(clone.getOpCode()); setFin(clone.isFin()); setBinaryPayload(clone.getBinaryPayload()); setMaskingKey(clone.getMaskingKey()); } public WebSocketFrame(OpCode opCode, List fragments) throws WebSocketException { setOpCode(opCode); setFin(true); long _payloadLength = 0; for (WebSocketFrame inter : fragments) { _payloadLength += inter.getBinaryPayload().length; } if (webSocket_debug) print("Payload length with " + nFragments(fragments) + ": " + _payloadLength); if (_payloadLength < 0 || _payloadLength > Integer.MAX_VALUE) { throw new WebSocketException(WebSocketFrame.CloseCode.MessageTooBig, "Max frame length has been exceeded."); } this._payloadLength = (int) _payloadLength; byte[] payload = new byte[this._payloadLength]; int offset = 0; for (WebSocketFrame inter : fragments) { System.arraycopy(inter.getBinaryPayload(), 0, payload, offset, inter.getBinaryPayload().length); offset += inter.getBinaryPayload().length; } setBinaryPayload(payload); } public OpCode getOpCode() { return opCode; } public void setOpCode(OpCode opcode) { this.opCode = opcode; } public boolean isFin() { return fin; } public void setFin(boolean fin) { this.fin = fin; } public boolean isMasked() { return maskingKey != null && maskingKey.length == 4; } public byte[] getMaskingKey() { return maskingKey; } public void setMaskingKey(byte[] maskingKey) { if (maskingKey != null && maskingKey.length != 4) { throw new IllegalArgumentException("MaskingKey " + Arrays.toString(maskingKey) + " hasn't length 4"); } this.maskingKey = maskingKey; } public void setUnmasked() { setMaskingKey(null); } public byte[] getBinaryPayload() { return payload; } public void setBinaryPayload(byte[] payload) { this.payload = payload; this._payloadLength = payload.length; this._payloadString = null; } public String getTextPayload() { if (_payloadString == null) { try { _payloadString = binary2Text(getBinaryPayload()); } catch (CharacterCodingException e) { throw new RuntimeException("Undetected CharacterCodingException", e); } } return _payloadString; } public void setTextPayload(String payload) throws CharacterCodingException { this.payload = text2Binary(payload); this._payloadLength = this.payload.length; if (webSocket_debug) print("payload length: " + _payloadLength + ", string length: " + l(payload)); this._payloadString = payload; } public static WebSocketFrame read(InputStream in) throws IOException { byte head = (byte) checkedRead(in.read()); boolean fin = ((head & 0x80) != 0); OpCode opCode = OpCode.find((byte) (head & 0x0F)); if ((head & 0x70) != 0) { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "The reserved bits (" + Integer.toBinaryString(head & 0x70) + ") must be 0."); } if (opCode == null) { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Received frame with reserved/unknown opcode " + (head & 0x0F) + "."); } else if (opCode.isControlFrame() && !fin) { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Fragmented control frame."); } WebSocketFrame frame = new WebSocketFrame(opCode, fin); frame.readPayloadInfo(in); frame.readPayload(in); if (frame.getOpCode() == WebSocketFrame.OpCode.Close) { return new WebSocketFrame.CloseFrame(frame); } else { return frame; } } private static int checkedRead(int read) throws IOException { if (read < 0) { throw new EOFException(); } return read; } private void readPayloadInfo(InputStream in) throws IOException { byte b = (byte) checkedRead(in.read()); boolean masked = ((b & 0x80) != 0); _payloadLength = (byte) (0x7F & b); if (_payloadLength == 126) { _payloadLength = (checkedRead(in.read()) << 8 | checkedRead(in.read())) & 0xFFFF; if (_payloadLength < 126) { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Invalid data frame 2byte length. (not using minimal length encoding)"); } } else if (_payloadLength == 127) { long _payloadLength = ((long) checkedRead(in.read())) << 56 | ((long) checkedRead(in.read())) << 48 | ((long) checkedRead(in.read())) << 40 | ((long) checkedRead(in.read())) << 32 | checkedRead(in.read()) << 24 | checkedRead(in.read()) << 16 | checkedRead(in.read()) << 8 | checkedRead(in.read()); if (_payloadLength < 65536) { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Invalid data frame 4byte length. (not using minimal length encoding)"); } if (_payloadLength < 0 || _payloadLength > Integer.MAX_VALUE) { throw new WebSocketException(WebSocketFrame.CloseCode.MessageTooBig, "Max frame length has been exceeded."); } this._payloadLength = (int) _payloadLength; } if (opCode.isControlFrame()) { if (_payloadLength > 125) { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Control frame with payload length > 125 bytes."); } if (opCode == OpCode.Close && _payloadLength == 1) { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Received close frame with payload len 1."); } } if (masked) { maskingKey = new byte[4]; int read = 0; while (read < maskingKey.length) { read += checkedRead(in.read(maskingKey, read, maskingKey.length - read)); } } } private void readPayload(InputStream in) throws IOException { payload = new byte[_payloadLength]; int read = 0; while (read < _payloadLength) { read += checkedRead(in.read(payload, read, _payloadLength - read)); } if (isMasked()) { for (int i = 0; i < payload.length; i++) { payload[i] ^= maskingKey[i % 4]; } } if (getOpCode() == WebSocketFrame.OpCode.Text) { _payloadString = binary2Text(getBinaryPayload()); } } public void write(OutputStream out) throws IOException { byte header = 0; if (fin) { header |= 0x80; } header |= opCode.getValue() & 0x0F; out.write(header); _payloadLength = getBinaryPayload().length; if (_payloadLength <= 125) { if (webSocket_debug) print("Sending short payload: " + _payloadLength); out.write(isMasked() ? 0x80 | (byte) _payloadLength : (byte) _payloadLength); } else if (_payloadLength <= 0xFFFF) { out.write(isMasked() ? 0xFE : 126); out.write(_payloadLength >>> 8); out.write(_payloadLength); } else { out.write(isMasked() ? 0xFF : 127); out.write(_payloadLength >>> 56 & 0); out.write(_payloadLength >>> 48 & 0); out.write(_payloadLength >>> 40 & 0); out.write(_payloadLength >>> 32 & 0); out.write(_payloadLength >>> 24); out.write(_payloadLength >>> 16); out.write(_payloadLength >>> 8); out.write(_payloadLength); } if (isMasked()) { out.write(maskingKey); for (int i = 0; i < _payloadLength; i++) { out.write(getBinaryPayload()[i] ^ maskingKey[i % 4]); } } else { out.write(getBinaryPayload()); } out.flush(); } public static final Charset TEXT_CHARSET = Charset.forName("UTF-8"); public static String binary2Text(byte[] payload) throws CharacterCodingException { return new String(payload, TEXT_CHARSET); } public static String binary2Text(byte[] payload, int offset, int length) throws CharacterCodingException { return new String(payload, offset, length, TEXT_CHARSET); } public static byte[] text2Binary(String payload) throws CharacterCodingException { return payload.getBytes(TEXT_CHARSET); } @Override public String toString() { final StringBuilder sb = new StringBuilder("WS["); sb.append(getOpCode()); sb.append(", ").append(isFin() ? "fin" : "inter"); sb.append(", ").append(isMasked() ? "masked" : "unmasked"); sb.append(", ").append(payloadToString()); sb.append(']'); return sb.toString(); } public String payloadToString() { if (payload == null) return "null"; else { final StringBuilder sb = new StringBuilder(); sb.append('[').append(payload.length).append("b] "); if (getOpCode() == WebSocketFrame.OpCode.Text) { String text = getTextPayload(); if (text.length() > 100) sb.append(text.substring(0, 100)).append("..."); else sb.append(text); } else { sb.append("0x"); for (int i = 0; i < Math.min(payload.length, 50); ++i) sb.append(Integer.toHexString((int) payload[i] & 0xFF)); if (payload.length > 50) sb.append("..."); } return sb.toString(); } } public static enum OpCode { Continuation(0), Text(1), Binary(2), Close(8), Ping(9), Pong(10); final public byte code; private OpCode(int code) { this.code = (byte) code; } public byte getValue() { return code; } public boolean isControlFrame() { return this == Close || this == Ping || this == Pong; } public static OpCode find(byte value) { for (OpCode opcode : values()) { if (opcode.getValue() == value) { return opcode; } } return null; } } public static enum CloseCode { NormalClosure(1000), GoingAway(1001), ProtocolError(1002), UnsupportedData(1003), NoStatusRcvd(1005), AbnormalClosure(1006), InvalidFramePayloadData(1007), PolicyViolation(1008), MessageTooBig(1009), MandatoryExt(1010), InternalServerError(1011), TLSHandshake(1015); final public int code; private CloseCode(int code) { this.code = code; } public int getValue() { return code; } public static WebSocketFrame.CloseCode find(int value) { for (WebSocketFrame.CloseCode code : values()) { if (code.getValue() == value) { return code; } } return null; } } public static class CloseFrame extends WebSocketFrame { public CloseCode _closeCode; public String _closeReason; public CloseFrame(WebSocketFrame wrap) throws CharacterCodingException { super(wrap); assert wrap.getOpCode() == OpCode.Close; if (wrap.getBinaryPayload().length >= 2) { _closeCode = CloseCode.find((wrap.getBinaryPayload()[0] & 0xFF) << 8 | (wrap.getBinaryPayload()[1] & 0xFF)); _closeReason = binary2Text(getBinaryPayload(), 2, getBinaryPayload().length - 2); } } public CloseFrame(CloseCode code, String closeReason) throws CharacterCodingException { super(OpCode.Close, true, generatePayload(code, closeReason)); } private static byte[] generatePayload(CloseCode code, String closeReason) throws CharacterCodingException { if (code != null) { byte[] reasonBytes = text2Binary(closeReason); byte[] payload = new byte[reasonBytes.length + 2]; payload[0] = (byte) ((code.getValue() >> 8) & 0xFF); payload[1] = (byte) ((code.getValue()) & 0xFF); System.arraycopy(reasonBytes, 0, payload, 2, reasonBytes.length); return payload; } else { return new byte[0]; } } public String payloadToString() { return (_closeCode != null ? _closeCode : "UnknownCloseCode[" + _closeCode + "]") + (_closeReason != null && !_closeReason.isEmpty() ? ": " + _closeReason : ""); } public CloseCode getCloseCode() { return _closeCode; } public String getCloseReason() { return _closeReason; } } } static public class WebSocket implements AutoCloseable { volatile public Object userObject; final public InputStream in; public OutputStream out; public WebSocketFrame.OpCode continuousOpCode = null; public List continuousFrames = new LinkedList(); public State state = State.UNCONNECTED; public static enum State { UNCONNECTED, CONNECTING, OPEN, CLOSING, CLOSED } final public NanoHTTPD.IHTTPSession handshakeRequest; final public NanoHTTPD.Response handshakeResponse = new NanoHTTPD.Response(NanoHTTPD.Status.SWITCH_PROTOCOL, null, (InputStream) null, -1) { @Override public void send(OutputStream out) { WebSocket.this.out = out; state = State.CONNECTING; super.send(out); state = State.OPEN; onOpen(); readWebsocket(); } }; public WebSocket(NanoHTTPD.IHTTPSession handshakeRequest) { this.handshakeRequest = handshakeRequest; this.in = handshakeRequest.getInputStream(); handshakeResponse.addHeader(NanoWebSocketServer.HEADER_UPGRADE, NanoWebSocketServer.HEADER_UPGRADE_VALUE); handshakeResponse.addHeader(NanoWebSocketServer.HEADER_CONNECTION, NanoWebSocketServer.HEADER_CONNECTION_VALUE); } public void readWebsocket() { try { while (state == State.OPEN) { handleWebsocketFrame(WebSocketFrame.read(in)); } } catch (CharacterCodingException e) { onException(e); doClose(WebSocketFrame.CloseCode.InvalidFramePayloadData, e.toString(), false); } catch (IOException e) { onException(e); if (e instanceof WebSocketException) { doClose(((WebSocketException) e).getCode(), ((WebSocketException) e).getReason(), false); } } finally { doClose(WebSocketFrame.CloseCode.InternalServerError, "Handler terminated without closing the connection.", false); } } public void handleWebsocketFrame(WebSocketFrame frame) throws IOException { if (frame.getOpCode() == WebSocketFrame.OpCode.Close) { handleCloseFrame(frame); } else if (frame.getOpCode() == WebSocketFrame.OpCode.Ping) { sendFrame(new WebSocketFrame(WebSocketFrame.OpCode.Pong, true, frame.getBinaryPayload())); } else if (frame.getOpCode() == WebSocketFrame.OpCode.Pong) { onPong(frame); } else if (!frame.isFin() || frame.getOpCode() == WebSocketFrame.OpCode.Continuation) { handleFrameFragment(frame); } else if (continuousOpCode != null) { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Continuous frame sequence not completed."); } else if (frame.getOpCode() == WebSocketFrame.OpCode.Text || frame.getOpCode() == WebSocketFrame.OpCode.Binary) { onMessage(frame); } else { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Non control or continuous frame expected."); } } public void handleCloseFrame(WebSocketFrame frame) throws IOException { WebSocketFrame.CloseCode code = WebSocketFrame.CloseCode.NormalClosure; String reason = ""; if (frame instanceof WebSocketFrame.CloseFrame) { code = ((WebSocketFrame.CloseFrame) frame).getCloseCode(); reason = ((WebSocketFrame.CloseFrame) frame).getCloseReason(); } if (state == State.CLOSING) { doClose(code, reason, false); } else { State oldState = state; state = State.CLOSING; if (oldState == State.OPEN) try { sendFrame(new WebSocketFrame.CloseFrame(code, reason)); } catch (Throwable _e) { } doClose(code, reason, true); } } public void handleFrameFragment(WebSocketFrame frame) throws IOException { if (frame.getOpCode() != WebSocketFrame.OpCode.Continuation) { if (continuousOpCode != null) { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Previous continuous frame sequence not completed."); } continuousOpCode = frame.getOpCode(); continuousFrames.clear(); continuousFrames.add(frame); } else if (frame.isFin()) { if (continuousOpCode == null) { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Continuous frame sequence was not started."); } onMessage(new WebSocketFrame(continuousOpCode, continuousFrames)); continuousOpCode = null; continuousFrames.clear(); } else if (continuousOpCode == null) { throw new WebSocketException(WebSocketFrame.CloseCode.ProtocolError, "Continuous frame sequence was not started."); } else { continuousFrames.add(frame); } } public synchronized void sendFrame(WebSocketFrame frame) throws IOException { frame.write(out); } public void close() { doClose(WebSocketFrame.CloseCode.GoingAway, "Internal closing", false); } public void doClose(WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote) { if (state == State.CLOSED) { return; } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } state = State.CLOSED; onClose(code, reason, initiatedByRemote); } public void onPong(WebSocketFrame pongFrame) { print("WebSocket pong"); } transient public IVF1 onMessage; public void onMessage(WebSocketFrame messageFrame) { if (onMessage != null) onMessage.get(messageFrame); else onMessage_base(messageFrame); } final public void onMessage_fallback(IVF1 _f, WebSocketFrame messageFrame) { if (_f != null) _f.get(messageFrame); else onMessage_base(messageFrame); } public void onMessage_base(WebSocketFrame messageFrame) { print("WebSocket msg: " + messageFrame.getTextPayload()); } transient public Runnable onOpen; public void onOpen() { if (onOpen != null) onOpen.run(); else onOpen_base(); } final public void onOpen_fallback(Runnable _f) { if (_f != null) _f.run(); else onOpen_base(); } public void onOpen_base() { } public void onClose(WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote) { print("WebSocket close"); onClose(); } transient public Runnable onClose; public void onClose() { if (onClose != null) onClose.run(); else onClose_base(); } final public void onClose_fallback(Runnable _f) { if (_f != null) _f.run(); else onClose_base(); } public void onClose_base() { } public void onException(IOException e) { printExceptionShort(e); } public void ping(byte[] payload) throws IOException { sendFrame(new WebSocketFrame(WebSocketFrame.OpCode.Ping, true, payload)); } public void send(byte[] payload) throws IOException { sendFrame(new WebSocketFrame(WebSocketFrame.OpCode.Binary, true, payload)); } public void send(String payload) throws IOException { sendFrame(new WebSocketFrame(WebSocketFrame.OpCode.Text, true, payload)); } public void close(WebSocketFrame.CloseCode code, String reason) throws IOException { State oldState = state; state = State.CLOSING; if (oldState == State.OPEN) { sendFrame(new WebSocketFrame.CloseFrame(code, reason)); } else { doClose(code, reason, false); } } public NanoHTTPD.IHTTPSession getHandshakeRequest() { return handshakeRequest; } public NanoHTTPD.Response getHandshakeResponse() { return handshakeResponse; } public String getUri() { return getHandshakeRequest().getUri(); } public Map getParms() { return getHandshakeRequest().getParms(); } public Object getUserObject() { return userObject; } public void setUserObject(Object o) { userObject = o; } } static public interface WebSocketFactory { public WebSocket openWebSocket(NanoHTTPD.IHTTPSession handshake); } static public class NanoWebSocketServer extends NanoHTTPD implements WebSocketFactory { public static final String HEADER_UPGRADE = "upgrade"; public static final String HEADER_UPGRADE_VALUE = "websocket"; public static final String HEADER_CONNECTION = "connection"; public static final String HEADER_CONNECTION_VALUE = "Upgrade"; public static final String HEADER_WEBSOCKET_VERSION = "sec-websocket-version"; public static final String HEADER_WEBSOCKET_VERSION_VALUE = "13"; public static final String HEADER_WEBSOCKET_KEY = "sec-websocket-key"; public static final String HEADER_WEBSOCKET_ACCEPT = "sec-websocket-accept"; public static final String HEADER_WEBSOCKET_PROTOCOL = "sec-websocket-protocol"; public final static String WEBSOCKET_KEY_MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; public WebSocketFactory webSocketFactory; public NanoWebSocketServer(int port) { super(port); webSocketFactory = null; } public NanoWebSocketServer(String hostname, int port) { super(hostname, port); webSocketFactory = null; } public NanoWebSocketServer(int port, WebSocketFactory webSocketFactory) { super(port); this.webSocketFactory = webSocketFactory; } public NanoWebSocketServer(String hostname, int port, WebSocketFactory webSocketFactory) { super(hostname, port); this.webSocketFactory = webSocketFactory; } @Override public Response serve_2(IHTTPSession session) { Map headers = session.getHeaders(); if (isWebsocketRequested(session)) { if (!HEADER_UPGRADE_VALUE.equalsIgnoreCase(headers.get(HEADER_UPGRADE)) || !isWebSocketConnectionHeader(session.getHeaders())) { return newFixedLengthResponse(Status.BAD_REQUEST, NanoHTTPD.MIME_PLAINTEXT, "Invalid Websocket handshake"); } if (!HEADER_WEBSOCKET_VERSION_VALUE.equalsIgnoreCase(headers.get(HEADER_WEBSOCKET_VERSION))) { return newFixedLengthResponse(Status.BAD_REQUEST, NanoHTTPD.MIME_PLAINTEXT, "Invalid Websocket-Version " + headers.get(HEADER_WEBSOCKET_VERSION)); } if (!headers.containsKey(HEADER_WEBSOCKET_KEY)) { return newFixedLengthResponse(Status.BAD_REQUEST, NanoHTTPD.MIME_PLAINTEXT, "Missing Websocket-Key"); } WebSocket webSocket = openWebSocket(session); try { webSocket.getHandshakeResponse().addHeader(HEADER_WEBSOCKET_ACCEPT, makeAcceptKey(headers.get(HEADER_WEBSOCKET_KEY))); } catch (NoSuchAlgorithmException e) { return newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "The SHA-1 Algorithm required for websockets is not available on the server."); } if (headers.containsKey(HEADER_WEBSOCKET_PROTOCOL)) { webSocket.getHandshakeResponse().addHeader(HEADER_WEBSOCKET_PROTOCOL, headers.get(HEADER_WEBSOCKET_PROTOCOL).split(",")[0]); } return webSocket.getHandshakeResponse(); } else { return super.serve_2(session); } } public WebSocket openWebSocket(IHTTPSession handshake) { if (webSocketFactory == null) { throw new Error("You must either override this method or supply a WebSocketFactory in the constructor"); } return webSocketFactory.openWebSocket(handshake); } public boolean isWebsocketRequested(IHTTPSession session) { Map headers = session.getHeaders(); String upgrade = headers.get(HEADER_UPGRADE); boolean isCorrectConnection = isWebSocketConnectionHeader(headers); boolean isUpgrade = HEADER_UPGRADE_VALUE.equalsIgnoreCase(upgrade); return (isUpgrade && isCorrectConnection); } private boolean isWebSocketConnectionHeader(Map headers) { String connection = headers.get(HEADER_CONNECTION); return (connection != null && connection.toLowerCase().contains(HEADER_CONNECTION_VALUE.toLowerCase())); } public static String makeAcceptKey(String key) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); String text = key + WEBSOCKET_KEY_MAGIC; md.update(text.getBytes(), 0, text.length()); byte[] sha1hash = md.digest(); return base64encode(sha1hash); } } public interface ByteIO { public void readWrite(ByteHead head); default public byte[] saveAsByteArray() { return saveToByteArray(); } default public byte[] toByteArray() { return saveToByteArray(); } default public byte[] saveToByteArray() { return saveToByteArray(new ByteHead()); } default public byte[] saveAsByteArray(ByteHead head) { return saveToByteArray(head); } default public byte[] toByteArray(ByteHead head) { return saveToByteArray(head); } default public byte[] saveToByteArray(ByteHead head) { var baos = byteArrayOutputStream(); head.outputStream(baos); readWrite(head); head.finish(); return baos.toByteArray(); } default public String toHexString() { return utils.toHexString(toByteArray()); } default public File saveToFile(File file) { OutputStream out = bufferedFileOutputStream(file); try { var head = new ByteHead(out); readWrite(head); head.finish(); return file; } finally { _close(out); } } default public ByteIO fromByteArray(byte[] data) { return load(data); } default public ByteIO load(byte[] data) { readWrite(new ByteHead(new ByteArrayInputStream(data))); return this; } default public ByteIO load(File file) { InputStream in = bufferedInputStream(file); try { readWrite(new ByteHead(in)); return this; } finally { _close(in); } } default public long byteIOLength() { JustCountingOutputStream out = new JustCountingOutputStream(); var head = new ByteHead(out); readWrite(head); head.finish(); return out.get(); } } public interface IBackgroundProcesses { public IBackgroundProcess tempAdd(String name); } public interface IPixelSet extends HasBounds { public boolean contains(int x, int y); default public boolean contains(Pt p) { return contains(p.x, p.y); } default public IterableIterator pixelIterator() { return filterI(utils.pixelIterator(bounds()), p -> contains(p)); } } public interface ISleeper_v2 { default public Sleeping doLater(long targetTime, Runnable r) { return doLater(sysTimeToTimestamp(targetTime), r); } public Sleeping doLater(Timestamp targetTime, Runnable r); public default Sleeping doAfter(double seconds, Runnable r) { return doLater(tsNow().plusSeconds(seconds), r); } } abstract static public class ShortIterator { abstract public boolean hasNext(); abstract public short next(); } public interface IBackgroundProcess extends AutoCloseable { public IBackgroundProcess setInterruptAction(Runnable action); } static public interface Htmlable { default public String headStuff() { return ""; } public String html(); } abstract static public class Sleeping implements AutoCloseable, IFieldsToList { public Timestamp targetTime; public Runnable action; public Sleeping() { } public Sleeping(Timestamp targetTime, Runnable action) { this.action = action; this.targetTime = targetTime; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + targetTime + ", " + action + ")"; } public Object[] _fieldsToList() { return new Object[] { targetTime, action }; } public long remainingMS() { return targetTime.minus(tsNow()); } } public interface IntegrityCheckable { public void integrityCheck(); } static public class MultiSleeper implements ISleeper_v2, AutoCloseable { public MultiSetMap entries = treeMultiSetMap(); public RestartableCountdown countdown = new RestartableCountdown(); private void check() { var time = nextWakeUpTime(); var action = firstValue(entries); countdown.setTargetTime(time == null ? 0 : time.sysTime(), new Runnable() { public void run() { try { Set toCall; synchronized (MultiSleeper.this) { toCall = entries.get(time); entries.remove(time); check(); } pcallFAll(toCall); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Set toCall;\r\n synchronized(MultiSleeper.this) {\r\n toCal..."; } }); } private synchronized void removeEntry(Timestamp targetTime, Runnable action) { entries.remove(targetTime, action); } synchronized public Timestamp nextWakeUpTime() { return firstKey(entries); } public synchronized Sleeping doLater(Timestamp targetTime, Runnable r) { if (r == null || targetTime == null) return null; targetTime = max(targetTime, tsNow()); entries.put(targetTime, r); check(); return new Sleeping(targetTime, r) { public void close() { try { removeEntry(targetTime, r); } catch (Exception __e) { throw rethrow(__e); } } }; } public void close() { try { { cleanUp(countdown); countdown = null; } } catch (Exception __e) { throw rethrow(__e); } } } static public interface ISubList { public List rootList(); public List parentList(); public int subListOffset(); } static public Lock dbLock() { return db_mainConcepts().lock; } static public Lock dbLock(Concepts cc) { return cc == null ? null : cc.lock; } static public Lock dbLock(Concept c) { return dbLock(c == null ? null : c._concepts); } static public boolean bareDBMode_on = false; static public void bareDBMode() { bareDBMode(null); } static public void bareDBMode(Integer autoSaveInterval) { bareDBMode_on = true; conceptsAndBot(autoSaveInterval); } static public Map getBracketMap(List tok) { return getBracketMap(tok, getBracketMap_opening, getBracketMap_closing); } static public Map getBracketMap(List tok, Collection opening, Collection closing) { return getBracketMap(tok, opening, closing, 0, l(tok)); } static public Map getBracketMap(List tok, Collection opening, Collection closing, int from, int to) { TreeMap map = new TreeMap(); List stack = new ArrayList(); for (int i = from | 1; i < to; i += 2) { Object t = tok.get(i); if (opening.contains(t)) stack.add(i); else if (closing.contains(t)) if (!empty(stack)) map.put(liftLast(stack), i); } return map; } static public Map getBracketMap(List tok, IF1 opening, IF1 closing) { return getBracketMap(tok, opening, closing, 0, l(tok)); } static public Map getBracketMap(List tok, IF1 opening, IF1 closing, int from, int to) { TreeMap map = new TreeMap(); List stack = new ArrayList(); for (int i = from | 1; i < to; i += 2) { String t = tok.get(i); if (opening.get(t)) stack.add(i); else if (closing.get(t)) if (!empty(stack)) map.put(liftLast(stack), i); } return map; } static public Set getBracketMap_opening = lithashset("{", "("); static public Set getBracketMap_closing = lithashset("}", ")"); static public boolean tokenRangeLongerThanNChars(List tok, int iStart, int iEnd, int maxChars) { int nChars = 0, n = l(tok); iStart = Math.max(0, iStart); iEnd = Math.min(n, iEnd); for (int i = iStart; i < iEnd; i++) { nChars += l(tok.get(i)); if (nChars > maxChars) return true; } return false; } static public String shortenJoinSubList(int max, List l, int i, int j) { return shortenJoin(max, subList(l, i, j)); } static public String shortenJoinSubList(int max, List l, int i) { return shortenJoin(max, subList(l, i)); } static public IterableIterator pixelIterator(Rect r) { return new IterableIterator() { public int x2 = r.x2(), y2 = r.y2(); public int x = r.x, y = r.y; public boolean hasNext() { return y < y2 && x < x2; } public Pt next() { Pt p = pt(x, y); if (++x >= x2) { x = r.x; ++y; } return p; } }; } static public OnePathWithOrigin g22_regionOutline(IImageRegion region) { List outlines = g22_allBorderTraces_autoDiagonals(region); return new OnePathWithOrigin(first(outlines), false); } static public A onResize(A c, Runnable r) { if (c != null && r != null) { swing(() -> { c.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { pcallF(r); } }); }); } return c; } static public A onResize(Runnable r, A c) { return onResize(c, r); } static public void componentPopupMenu2(A component, final VF2 menuMaker) { final WeakReference ref = new WeakReference<>(component); componentPopupMenu(component, new VF1() { public void get(JPopupMenu menu) { try { callF(menuMaker, ref.get(), menu); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(menuMaker, ref!, menu);"; } }); } static public JCheckBoxMenuItem jMenuItemStayCheckedOnClick(String text, IF0 checked, Runnable action) { var mi = swing(() -> new JCheckBoxMenuItem(text, isTrue(checked.get()))); 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 setChecked(mi, b);"; } }); addActionListener(mi, () -> { if (!isChecked(mi)) setChecked(mi, true); callF(action); }); return mi; } static public JFrame showFullScreen(JComponent c) { return showFullScreen(defaultFrameTitle(), c); } static public JFrame showFullScreen(final String title, final JComponent c) { return (JFrame) swingAndWait(new F0() { public Object get() { try { GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); if (!gd.isFullScreenSupported()) throw fail("No full-screen mode supported!"); boolean dec = JFrame.isDefaultLookAndFeelDecorated(); if (dec) JFrame.setDefaultLookAndFeelDecorated(false); final JFrame window = new JFrame(title); window.setUndecorated(true); if (dec) JFrame.setDefaultLookAndFeelDecorated(true); registerEscape(window, new Runnable() { public void run() { try { disposeWindow(window); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disposeWindow(window)"; } }); window.add(wrap(c)); gd.setFullScreenWindow(window); for (int i = 100; i <= 1000; i += 100) awtLater(i, new Runnable() { public void run() { try { window.toFront(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.toFront()"; } }); return window; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()\r\n ..."; } }); } static public void selectFile(final String msg, VF1 action) { selectFile(msg, userDir(), action); } static public void selectFile(final String msg, final File defaultFile, VF1 action) { inputFilePath(msg, defaultFile, action); } static public JComponent selectImageSnippet(VF1 onSelect) { return selectSnippetID_v1(onSelect); } static public JComponent selectImageSnippet(String defaultID, VF1 onSelect) { return selectSnippetID_v1(defaultID, onSelect); } static public void popup(final Throwable throwable) { popupError(throwable); } static public void popup(final String msg) { print(msg); SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(null, msg); } }); } static public Graphics2D cloneGraphics(Graphics2D g) { return (Graphics2D) g.create(); } static public A printIfScaffoldingEnabled(Object o, A a) { return printIfScaffoldingEnabled(o, "", a); } static public A printIfScaffoldingEnabled(Object o, String s, A a) { return printIf(scaffoldingEnabled(o), s, a); } static public BoolVar componentShowingVar(JComponent component) { return swing(() -> { BoolVar flag = new BoolVar(component.isShowing()); component.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { if (flag.get()) print("Warning: bindToComponent logic failure"); flag.set(true); } public void ancestorRemoved(AncestorEvent event) { if (!flag.get()) print("Warning: bindToComponent logic failure"); flag.set(false); } public void ancestorMoved(AncestorEvent event) { } }); return flag; }); } static public boolean imagesHaveSameSize(BufferedImage a, BufferedImage b) { return a != null && b != null && a.getWidth() == b.getWidth() && a.getHeight() == b.getHeight(); } static public String uploadPNGToImageServer(BufferedImage img, String name) { return uploadToImageServerIfNotThere(img, name); } static public String uploadPNGToImageServer(File f, BufferedImage img, String name) { return uploadToImageServerIfNotThere(f, img, name); } static public ImageSurface showFullScreenImageSurface(BufferedImage img) { ImageSurface is = jImageSurface(img); showFullScreen(jscroll_centered(disposeFrameOnClick(is))); return is; } static public > List allValues(Map map) { List out = new ArrayList(); for (var l : values(map)) addAll(out, l); return out; } static public NavigableMap synchroTreeMap() { return synchroNavigableMap(new TreeMap()); } static public boolean hasConcept(Class c, Object... params) { return hasConcept(db_mainConcepts(), c, params); } static public boolean hasConcept(Concepts cc, Class c, Object... params) { return findConceptWhere(cc, c, params) != null; } static public void clearConcepts() { db_mainConcepts().clearConcepts(); } static public void clearConcepts(Concepts concepts) { concepts.clearConcepts(); } static public Map unstructureMap(String s) { return (Map) unstructure(s); } static public Map unstructureMap(String text, boolean allDynamic, Object classFinder) { return (Map) unstructure(text, allDynamic, classFinder); } static public boolean exceptionMessageContains(Throwable e, String s) { return cic(getInnerMessage(e), s); } static public void printShortException(Throwable e) { print(exceptionToStringShort(e)); } static public void printShortException(String s, Throwable e) { print(s, exceptionToStringShort(e)); } static public RemoteDB connectToDBOpt(String dbNameOrID) { try { return new RemoteDB(dbNameOrID); } catch (Throwable __e) { return null; } } static public String dynShortName(Object o) { return shortDynamicClassName(o); } static public void callRunnableWithWrapper(Object wrapper, Runnable r) { if (wrapper == null) callF(r); else callF(wrapper, r); } static public List callFAll(Collection l, Object... args) { return callF_all(l, args); } static public String javaTokWordWrap(String s) { return javaTokWordWrap(120, s); } static public String javaTokWordWrap(int cols, String s) { int col = 0; List tok = javaTok(s); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && col >= cols && !containsNewLine(t)) tok.set(i, t = rtrimSpaces(t) + "\n"); int idx = t.lastIndexOf('\n'); if (idx >= 0) col = l(t) - (idx + 1); else col += l(t); } return join(tok); } static public int hours() { return hours(java.util.Calendar.getInstance()); } static public int hours(java.util.Calendar c) { return c.get(java.util.Calendar.HOUR_OF_DAY); } static public int hours(long time) { return hours(calendarFromTime(time)); } static public int hours(long time, TimeZone tz) { return hours(calendarFromTime(time, tz)); } static public int roundDownTo_rev(int x, int n) { return roundDownTo(n, x); } static public long roundDownTo_rev(long x, long n) { return roundDownTo(n, x); } static public int minutes() { return minutes(java.util.Calendar.getInstance()); } static public int minutes(java.util.Calendar c) { return c.get(java.util.Calendar.MINUTE); } static public void closeAllOpt(Iterable l) { if (l == null) return; for (Object c : l) { try { if (c instanceof AutoCloseable) close((AutoCloseable) c); } catch (Throwable __e) { pcallFail(__e); } } } static public void closeAllOpt(Object... l) { if (l == null) return; for (Object c : l) { try { if (c instanceof AutoCloseable) close((AutoCloseable) c); } catch (Throwable __e) { pcallFail(__e); } } } static public A firstOfType(Collection c, Class type) { for (Object x : c) if (isInstanceX(type, x)) return (A) x; return null; } static public List conceptsOfType(String type) { return db_mainConcepts().conceptsOfType(type); } static public List concatLists_conservative(List a, List b) { if (empty(a)) return b; if (empty(b)) return a; return concatLists(a, b); } static public List concatLists_conservative(Collection a, Collection b) { if (empty(a) && b instanceof List) return ((List) b); if (empty(b) && a instanceof List) return ((List) a); return concatLists(a, b); } static public List filterByType(Iterable c, Class type) { List l = new ArrayList(); if (c != null) for (Object x : c) if (isInstanceX(type, x)) l.add((A) x); return l; } static public List filterByType(Object[] c, Class type) { return filterByType(asList(c), type); } static public List filterByType(Class type, Iterable c) { return filterByType(c, type); } static public List filterByDynamicType(Collection c, String type) { List l = new ArrayList(); for (A x : c) if (eq(dynamicClassName(x), type)) l.add(x); return l; } static public boolean hasType(Collection c, Class type) { for (Object x : c) if (isInstanceX(type, x)) return true; return false; } static public A findBackRef(Concept c, Class type) { for (Concept.Ref r : c.backRefs) if (instanceOf(r.concept(), type)) return (A) r.concept(); return null; } static public A findBackRef(Class type, Concept c) { return findBackRef(c, type); } static public Concept cnew(String name, Object... values) { return cnew(db_mainConcepts(), name, values); } static public Concept cnew(Concepts concepts, String name, Object... values) { Class cc = findClass(name); concepts_unlisted.set(true); Concept c; try { c = cc != null ? nuObject(cc) : new Concept(name); } finally { concepts_unlisted.set(null); } csetAll(c, values); concepts.register(c); return c; } static public A cnew(Class cc, Object... values) { return cnew(db_mainConcepts(), cc, values); } static public A cnew(Concepts concepts, Class cc, Object... values) { concepts_unlisted.set(true); A c; try { c = nuObject(cc); } finally { concepts_unlisted.set(null); } csetAll(c, values); concepts.register(c); return c; } static public String loadConceptsStructure(String progID) { return loadTextFilePossiblyGZipped(getProgramFile(progID, "concepts.structure")); } static public String loadConceptsStructure() { return loadConceptsStructure(dbProgramID()); } static public String nConcepts(long n) { return n2(n, "concept"); } static public String nConcepts(Collection l) { return nConcepts(l(l)); } static public String nConcepts(Map map) { return nConcepts(l(map)); } static public List addDyn_quickSync(List l, A a) { if (l == null) l = new ArrayList(); syncAdd(l, a); return l; } static public List removeDyn_quickSync(List l, A a) { if (l == null) return null; synchronized (collectionMutex(l)) { l.remove(a); return empty(l) ? null : l; } } static public void crenameField_noOverwrite(Concept c, String oldField, String newField) { if (c == null || eq(oldField, newField)) return; Object value = cget(c, oldField); if (newField != null && cget(c, newField) == null) cset(c, newField, value); cset(c, oldField, null); } static public Collection scanConceptForRefs(Concept c) { Set refs = new HashSet(); if (c != null) for (Object o : values(objectToMap(c))) { if (o instanceof Concept.Ref) refs.add((Concept.Ref) o); else if (o instanceof Concept.RefL) addAll(refs, ((Concept.RefL) o).l); } return refs; } static public Concepts concepts(Concept c) { return c == null ? null : c._concepts; } static public UnsupportedOperationException unsupportedOperation() { throw new UnsupportedOperationException(); } static public IterableIterator concurrentlyIterateList(final List l) { return iteratorFromFunction_withEndMarker_f0(new F0() { public int i; public A get() { int _i = i++; synchronized (l) { if (_i < l(l)) { A a = l.get(_i); if (a == iteratorFromFunction_endMarker) throw fail("no"); return a; } return (A) iteratorFromFunction_endMarker; } } }); } static public void _subListRangeCheck(int fromIndex, int toIndex, int size) { subListRangeCheck(fromIndex, toIndex, size); } static public int lShortArray(short[] a) { return a == null ? 0 : a.length; } static public short[] resizeShortArray(short[] a, int n) { if (n == lShortArray(a)) return a; short[] b = new short[n]; arraycopy(a, 0, b, 0, Math.min(lShortArray(a), n)); return b; } static public short toShort(Object o) { if (o == null) return (short) 0; if (o instanceof Number) return ((Number) o).shortValue(); if (o instanceof String) return toShort(parseLong((String) o)); throw fail("not convertible to short: " + getClassName(o)); } static public short toShort(long l) { if (l != (short) l) throw fail("Too large for short: " + l); return (short) l; } static public int lLongArray(long[] a) { return a == null ? 0 : a.length; } static public long[] resizeLongArray(long[] a, int n) { if (n == lLongArray(a)) return a; long[] b = new long[n]; arraycopy(a, 0, b, 0, Math.min(lLongArray(a), n)); return b; } static public ArrayList longArrayToList(long[] a) { if (a == null) return null; return longArrayToList(a, 0, a.length); } static public ArrayList longArrayToList(long[] a, int from, int to) { if (a == null) return null; ArrayList l = new ArrayList<>(to - from); for (int i = from; i < to; i++) l.add(a[i]); return l; } static public boolean hasNext(Iterator it) { return it != null && it.hasNext(); } static public A syncPopFirst(List l) { if (empty(l)) return null; synchronized (l) { A a = first(l); l.remove(0); return a; } } static public ISleeper_v2 sleeper() { var ps = pingSource(); return ps == null ? new MultiSleeper() : ps.sleeper(); } static public ISleeper_v2 defaultSleeper() { return new ISleeper_v2() { public Sleeping doLater(Timestamp targetTime, Runnable r) { return new MultiSleeper().doLater(targetTime, r); } public void close() { try { } catch (Exception __e) { throw rethrow(__e); } } }; } static public double msIntervalToHertz(double ms) { return 1000 / ms; } static public GrabbableRGBBytePixels grabbableRGBBytePixels(BufferedImage img) { Raster raster = img.getRaster(); SampleModel _sampleModel = raster.getSampleModel(); if (!(_sampleModel instanceof PixelInterleavedSampleModel)) return null; var imageModel = img.getColorModel(); if (imageModel != ColorModel.getRGBdefault()) return null; PixelInterleavedSampleModel sampleModel = (PixelInterleavedSampleModel) _sampleModel; DataBufferByte dataBuffer = (DataBufferByte) (raster.getDataBuffer()); assertEquals(1, dataBuffer.getNumBanks()); assertEquals(DataBuffer.TYPE_BYTE, dataBuffer.getDataType()); int w = img.getWidth(), h = img.getHeight(); int pixelStride = sampleModel.getPixelStride(); int scanlineStride = sampleModel.getScanlineStride(); byte[] pixels = dataBuffer.getData(); int offset = dataBuffer.getOffset(); int translateX = raster.getSampleModelTranslateX(); int translateY = raster.getSampleModelTranslateY(); offset += -translateX - translateY * scanlineStride; return new GrabbableRGBBytePixels(pixels, w, h, offset, scanlineStride, pixelStride); } static public boolean isDefaultDecolorizer(Decolorizer decolorizer) { return decolorizer == null || decolorizer instanceof Decolorizer.Simple; } static public BufferedImage grayImageFromIBWIntegralImage(IBWIntegralImage img) { int w = img.getWidth(), h = img.getHeight(); byte[] pixels = new byte[w * h]; int i = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { int pixel = img.getPixelBrightness(x, y); pixels[i++] = clampToUByte(pixel); } return newGrayBufferedImage(w, h, pixels); } static public FixedRateTimer doEvery_daemon_highPriority(long delay, final Object r) { return doEvery_daemon_highPriority(delay, delay, r); } static public FixedRateTimer doEvery_daemon_highPriority(long delay, long firstDelay, final Object r) { return doEvery_daemon(delay, firstDelay, new Runnable() { public void run() { try { highThreadPriority(); callF(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "highThreadPriority();\r\n callF(r);"; } }); } static public FixedRateTimer doEvery_daemon_highPriority(double delaySeconds, final Object r) { return doEvery_daemon_highPriority(toMS(delaySeconds), r); } static public AutoCloseable tempAfterwards(final Object r) { return new AutoCloseable() { public void close() { callF(r); } }; } static public A jMinWidth0(A c) { return jMinWidth_pure(0, c); } static public JSplitPane jhsplit_minZero(Component l, Component r) { return jhsplit_minZero(l, r, 0.5); } static public JSplitPane jhsplit_minZero(Component l, Component r, double splitPoint) { return jhsplit(jMinWidth0(l), jMinWidth0(r), splitPoint); } static public JSplitPane jhsplit_minZero(double splitPoint, Component l, Component r) { return jhsplit_minZero(l, r, splitPoint); } static public List syncGetAndClear(Collection l) { return syncCloneAndClearList(l); } static public long stopTiming_defaultMin = 10; static public long startTiming_startTime; static public void startTiming() { startTiming_startTime = now(); } static public void stopTiming() { stopTiming(null); } static public void stopTiming(String text) { stopTiming(text, stopTiming_defaultMin); } static public void stopTiming(String text, long minToPrint) { long time = now() - startTiming_startTime; if (time >= minToPrint) { text = or2(text, "Time: "); print(text + time + " ms"); } } static public long sysNowPlusSeconds_noPing(double seconds) { return sysNow_noPing() + secondsToMS(seconds); } static public long sysNow_noPing() { return System.nanoTime() / 1000000; } static public boolean classIsExportedTo(Class c, java.lang.Module destModule) { if (c == null || destModule == null) return false; java.lang.Module srcModule = c.getModule(); String packageName = c.getPackageName(); return srcModule.isExported(packageName, destModule); } static public Set allInterfacesImplementedBy(Object o) { return allInterfacesImplementedBy(_getClass(o)); } static public Set allInterfacesImplementedBy(Class c) { if (c == null) return null; HashSet set = new HashSet(); allInterfacesImplementedBy_find(c, set); return set; } static public void allInterfacesImplementedBy_find(Class c, Set set) { if (c.isInterface() && !set.add(c)) return; do { for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set); } while ((c = c.getSuperclass()) != null); } static public Method findStaticMethod(Class c, String method, Object... args) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (!m.getName().equals(method)) continue; if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args)) continue; return m; } c = c.getSuperclass(); } return null; } static public boolean findStaticMethod_checkArgs(Method m, Object[] args) { Class[] types = m.getParameterTypes(); if (types.length != args.length) return false; for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) return false; return true; } static public long lround(double d) { return Math.round(d); } static public long lround(Number n) { return lround(toDouble(n)); } static public Runnable runAndReturn(Runnable r) { callF(r); return r; } static public int lByteArray(byte[] a) { return a == null ? 0 : a.length; } static public byte[] resizeByteArray(byte[] a, int n) { if (n == l(a)) return a; byte[] b = new byte[n]; arraycopy(a, 0, b, 0, min(l(a), n)); return b; } static public ArrayList byteArrayToList(byte[] a) { if (a == null) return null; return byteArrayToList(a, 0, a.length); } static public ArrayList byteArrayToList(byte[] a, int from, int to) { if (a == null) return null; ArrayList l = new ArrayList<>(to - from); for (int i = from; i < to; i++) l.add(a[i]); return l; } static public ByteArrayOutputStream byteArrayOutputStream() { return new ByteArrayOutputStream(); } static public int bufferedInputStream_bufferSize = 65536; static public BufferedInputStream bufferedInputStream(int bufSize, File f) { try { return bufferedInputStream(bufSize, newFileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedInputStream bufferedInputStream(File f) { try { return bufferedInputStream(newFileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedInputStream bufferedInputStream(InputStream in) { return new BufferedInputStream(in, bufferedInputStream_bufferSize); } static public BufferedInputStream bufferedInputStream(int bufSize, InputStream in) { return new BufferedInputStream(in, bufSize); } static public DynamicVStack verticalNiceButtons(Object... params) { return makeNiceButtons_usingStack((DynamicVStack) dynamicVStack().spacing(20), params); } static public List allButtons(Component c) { return childrenOfType(c, JButton.class); } static public void scrollIntoView(JComponent c) { if (c != null) { swing(() -> { c.scrollRectToVisible(new Rectangle(0, 0, c.getWidth(), c.getHeight())); }); } } static public Collection synchronizedCollection(Collection l) { return new SynchronizedCollection(l); } static public A lookupDynamicInterface_v2(Class intrface, Object o) { Object implementation = metaGet(o, intrface); if (isInstance(intrface, implementation)) return (A) implementation; if (isInstance(intrface, o)) return (A) o; return null; } static public A lookupDynamicInterface_v2(Object o, Class intrface) { return lookupDynamicInterface_v2(intrface, o); } static public void pcall_fail(Throwable e) { pcallFail(e); } static public List iotaZeroList(int n) { return intRangeList(0, n); } static public void metaPut(IMeta o, Object key, Object value) { metaMapPut(o, key, value); } static public void metaPut(Object o, Object key, Object value) { metaMapPut(o, key, value); } static public A bold(A c) { return makeBold(c); } static public Runnable rThread(final Object f) { return new Runnable() { public void run() { try { { startThread(new Runnable() { public void run() { try { callF(f); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(f);"; } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "thread { callF(f); }"; } }; } static public String renderLineAndColumnRange(LineAndColumn start, LineAndColumn end) { if (eq(start, end)) return str(start); return start + " to " + (end.line == start.line ? end.col : firstToLower(str(end))); } static public long clockTimeToSystemTime(long now) { return now == 0 ? 0 : now + clockToSysTimeDiff(); } static public int hashOfLong(long l) { return Long.hashCode(l); } static public NavigableSet navigableKeys(NavigableMap map) { return map == null ? new TreeSet() : map.navigableKeySet(); } static public NavigableSet navigableKeys(MultiSet ms) { return ((NavigableMap) ms.map).navigableKeySet(); } static public NavigableSet navigableKeys(MultiMap mm) { return ((NavigableMap) mm.data).navigableKeySet(); } static public Map> toMap(MultiMap m) { return multiMapToMap(m); } static public Duration duration(TimestampRange r) { return r == null ? Duration.ZERO : r.duration(); } static public WatchEvent.Kind[] jdk_watchService_allEventKinds() { return new WatchEvent.Kind[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW }; } static public List findAllDirs(File dir) { List out = new ArrayList(); findAllDirs(dir, out); return out; } static public void findAllDirs(File dir, List out) { out.add(dir); try { for (File f : listFiles(dir)) if (f.isDirectory()) findAllDirs(f, out); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } static public IterableIterator reversedIterator(final List l) { return new IterableIterator() { public int i = l(l) - 1; public boolean hasNext() { return i >= 0; } public A next() { return l.get(i--); } }; } static volatile public boolean framesBot_has = false; static public Android3 framesBot() { if (framesBot_has) return null; framesBot_has = true; Android3 android = new Android3(); android.greeting = programIDPlusHome() + " Frames."; android.console = false; android.responder = new Responder() { public String answer(String s, List history) { if (match("activate frames", s)) { swingLater(new Runnable() { public void run() { try { activateMyFrames(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// prevent blocking when called from same program's AWT thread\r\n act..."; } }); return "OK, activating " + programName(); } return null; } }; return makeBot(android); } static public List allBackRefs(Concept c) { IdentityHashMap l = new IdentityHashMap(); if (c != null && c.backRefs != null) for (Concept.Ref r : cloneList(c.backRefs)) l.put(r.concept(), true); return keysList(l); } static public List sortedByConceptID(Collection c) { return sortedByCalculatedField(__210 -> conceptID(__210), c); } static public A selectedConcept(JTable table, Class cc) { return (A) getConcept(toLong(selectedTableCell(table, 0))); } static public JScrollPane jBorderlessHigherHorizontalScrollPane(JComponent c) { var sp = borderlessScrollPane(jHigherScrollPane(c)); sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); return sp; } static public A ccopyFieldsExcept(Concept x, A y, Set dontCopyFields) { if (x == null || y == null) return y; return ccopyFields2(x, y, setMinusSet(conceptFields(x), dontCopyFields)); } static public AutoCloseable tempSetMCOpt(final String field, Object value) { final Object oldValue = getMCOpt(field); setMCOpt(field, value); return new AutoCloseable() { public String toString() { return "setMCOpt(field, oldValue);"; } public void close() throws Exception { setMCOpt(field, oldValue); } }; } static public A replaceConceptAndUpdateRefs(Concept a, A b) { assertTrue("object to replace with must be unlisted", isUnlisted(b)); Concepts cc = a.concepts(); assertTrue("object to replace must be listed", cc != null); List refs = allBackRefObjects(a); b.id = a.id; deleteConcept(a); cc.register_phase2(b); cset(a, "meta_migratedTo", b); for (Concept.Ref ref : refs) ref.set(b); return b; } static public Type genericFieldType(Object o, String field) { Field f = getField(o, field); return f == null ? null : f.getGenericType(); } static public Class getTypeArgumentAsClass(Type type) { if (type instanceof ParameterizedType) return typeToClass(first(((ParameterizedType) type).getActualTypeArguments())); return null; } static public JCheckBox jCenteredCheckBox() { return centerCheckBox(new JCheckBox()); } static public JCheckBox jCenteredCheckBox(boolean checked) { return centerCheckBox(new JCheckBox("", checked)); } static public JCheckBox jCenteredCheckBox(String text, boolean checked) { return centerCheckBox(new JCheckBox(text, checked)); } static public JCheckBox jCenteredCheckBox(String text) { return centerCheckBox(new JCheckBox(text)); } static public JCheckBox jCenteredCheckBox(String text, boolean checked, final Object onChange) { return centerCheckBox(jCheckBox(text, checked, onChange)); } static public JCheckBox jCenteredCheckBox(boolean checked, final Object onChange) { return centerCheckBox(jCheckBox(checked, onChange)); } static public boolean isSubtype(Class a, Class b) { return isSubclass(a, b); } static public JComboBox jcomboboxFromConcepts_str(Class cc) { return jcomboboxFromConcepts_str(db_mainConcepts(), cc); } static public JComboBox jcomboboxFromConcepts_str(Concepts concepts, Class cc) { return jcomboboxFromConcepts_str(concepts, cc, null); } static public JComboBox jcomboboxFromConcepts_str(Concepts concepts, Class cc, Concept selected) { List items = ll(""); String selectedItem = null; for (Concept c : list(concepts, cc)) { String item = c.id + " - " + c; if (c == selected) selectedItem = item; items.add(item); } return jcombobox(items, selectedItem); } static public JPasswordField jpassword() { return jpassword(""); } static public JPasswordField jpassword(final String pw) { return swing(new F0() { public JPasswordField get() { try { return new JPasswordField(pw); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return new JPasswordField(pw);"; } }); } static public String structureOrText_crud(Object o) { if (o == null) return ""; if (o instanceof Long) return str(o); if (o instanceof File) return ((File) o).getAbsolutePath(); return str(o); } static public AutoComboBox autoComboBox() { return autoComboBox(new ArrayList()); } static public AutoComboBox autoComboBox(final Collection items) { return swing(new F0() { public AutoComboBox get() { try { AutoComboBox cb = new AutoComboBox(); cb.setKeyWord(items); return cb; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new AutoComboBox cb;\r\n cb.setKeyWord(items);\r\n ret cb;"; } }); } static public AutoComboBox autoComboBox(String value, Collection items) { return setText(autoComboBox(items), value); } static public String trimIf(boolean b, String s) { return b ? trim(s) : s; } static public Object convertToField(Object o, Class c, String field) { Field f = setOpt_findField(c, field); if (f == null) return o; Class t = f.getType(); if (t == Long.class || t == long.class) return toLong(o); else if (t == Integer.class || t == int.class) return toInt(o); else if (t == Float.class || t == float.class) return toFloat(o); else if (t == Double.class || t == double.class) return toDouble(o); else if (t == String.class) return o instanceof String ? ((String) o) : str(o); else if (t == File.class) { if (o instanceof String) return new File((String) o).getAbsoluteFile(); } else if (t == Pt.class) { if (o instanceof String) return parsePt((String) o); } else if (t == Rect.class) { if (o instanceof String) return parseRect((String) o); } else if (t == GlobalID.class && o instanceof String) return new GlobalID((String) o); return o; } static public long parseFirstLong(String s) { return parseLong(jextract("", s)); } static public void cUpdatePNGFile(Concept c, String field, BufferedImage image, boolean deleteOldFile) { PNGFile png = (PNGFile) (cget(c, field)); if (image == null && png != null) cset(c, field, null); else if (image != null && (png == null || !imagesIdentical(png.getImage(), image))) { if (png != null && deleteOldFile) png.delete(); cset(c, field, new PNGFile(image)); } } static public List conceptFieldsInOrder(Concept c) { return conceptFieldsInOrder(c.getClass()); } static public List conceptFieldsInOrder(Class c) { String order = toStringOpt(getOpt(c, "_fieldOrder")); Set set = asTreeSet(conceptFields(c)); if (order == null) return asList(set); List fields = listIntersectSet(splitAtSpace(order), set); setAddAll(fields, set); return fields; } static public Set setPlus(Collection l, A... more) { Set set = similarEmptySet(l); addAll(set, l); for (A a : more) set.add(a); return set; } static public List moveItemFirst(A item, Collection l) { if (!contains(l, item)) return asList(l); List out = emptyList(l(l)); out.add(item); for (A a : l) if (!eq(a, item)) out.add(a); return out; } static public List dropTypeParameter(List l) { return l; } static public Collection dropTypeParameter(Collection l) { return l; } static public List> sortClassesByNameIC(Collection> l) { return sortedByCalculatedFieldIC(__211 -> shortClassName(__211), l); } static public List> myNonAbstractClassesImplementing(Class base) { List> l = new ArrayList(); for (String name : myInnerClasses()) { Class c = _getClass(mcName() + "$" + name); if (c != null && !isAbstract(c) && isSubtypeOf(c, base)) l.add(c); } return l; } static public JComboBox setComboBoxRenderer(JComboBox cb, ListCellRenderer renderer) { if (cb != null) { swing(() -> { cb.setRenderer(renderer); }); } return cb; } static public ListCellRenderer customToStringListCellRenderer(IF1 toString) { return (ListCellRenderer) new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { return super.getListCellRendererComponent(list, toString.get((A) value), index, isSelected, cellHasFocus); } }; } static public JPanel jhgridWithSpacing(Object... parts) { return hgridWithSpacing(parts); } static public A ccopyFields(Concept x, A y, String... fields) { if (x == null || y == null) return y; if (empty(fields)) { for (String field : conceptFields(x)) cset(y, field, cget(x, field)); } else for (String field : fields) { Object o = cget(x, field); if (o != null) cset(y, field, o); } return y; } static public boolean notNullOrEmptyString(Object o) { return o != null && !eq(o, ""); } static public boolean isSubclassOfAny(Class a, Collection b) { return any(b, x -> isSubclass(a, x)); } static public boolean isSubclassOfAny(Class a, Class... b) { return any(b, x -> isSubclass(a, x)); } static public IF0 if0_const(final A a) { return () -> a; } static public void addComponentInFront(Container c, Component... l) { containerAddFirst(c, l); } static public JTextArea typeWriterTextArea() { return newTypeWriterTextArea(); } static public JTextArea typeWriterTextArea(String text) { return newTypeWriterTextArea(text); } static public int clampUByteInt(long l) { return (int) clamp(l, 0, 255); } static public int clampUByteInt(int i) { return clamp(i, 0, 255); } static public BufferedImage grayImageFromIBWImage(IBWImage img) { int w = img.getWidth(), h = img.getHeight(); byte[] pixels = new byte[w * h]; int i = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { int pixel = iround(img.getFloatPixel(x, y) * 255); pixels[i++] = clampToUByte(pixel); } return newGrayBufferedImage(w, h, pixels); } static public BWImage iBWImageToBWImage(IBWImage img) { int w = img.getWidth(), h = img.getHeight(); BWImage out = new BWImage(w, h); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) out.setPixel(x, y, img.getFloatPixel(x, y)); return out; } static public Object renderForTable_noStruct(Object o) { { var __1 = toBufferedImageOpt(o); if (__1 != null) return __1; } if (o instanceof String && containsNewLine((String) o)) return escapeNewLines(dropTrailingNewLine((String) o)); if (o instanceof Collection) return joinWithComma((Collection) o); return strOrNull(o); } static public Map allConceptFieldsAsMapExcept(Concept c, Collection excludedFields) { Map map = new HashMap(); for (String field : unnullForIteration(listMinusSet(conceptFields(c), excludedFields))) map.put(field, cget(c, field)); return map; } static public String dynShortClassName(Object o) { return shortDynamicClassName(o); } static public JTable setTableFontSizes(float size, JTable table) { if (table == null) return null; { swing(() -> { setFontSize(table.getTableHeader(), size); setFontSize(table, size); }); } return table; } static public JTable setTableFontSizes(JTable table, float size) { return setTableFontSizes(size, table); } static public JTable setRowHeight(final int h, final JTable t) { if (t != null) { swing(() -> { t.setRowHeight(h); }); } return t; } static public JTable setRowHeight(JTable t, int h) { return setRowHeight(h, t); } static public void onTableSelectionChanged(final JTable table, final Runnable r) { { swing(() -> { table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { callF(r); } }); }); } } static public Set toSet(Object[] array) { return asSet(array); } static public Set toSet(String[] array) { return asSet(array); } static public Set toSet(Iterable l) { return asSet(l); } static public Set toSet(MultiSet ms) { return asSet(ms); } static public A postProcess(Object f, A a) { return callPostProcessor(f, a); } static public A postProcess(IF1 f, A a) { return callPostProcessor(f, a); } static public void tableColumnMaxWidth(final JTable table, final int columnIdx, final int width) { { swing(() -> { try { if (inRange(columnIdx, table.getColumnCount())) table.getColumnModel().getColumn(columnIdx).setMaxWidth(width); } catch (Throwable __e) { pcallFail(__e); } }); } } static public void setColumnName(final JTable table, final int idx, final String name) { if (table != null) { swing(() -> { if (table.getColumnCount() > idx) table.getColumnModel().getColumn(idx).setHeaderValue(name); }); } } static public String getColumnName(final JTable table, final int idx) { return table == null ? null : swing(new F0() { public String get() { try { return table.getColumnCount() <= idx ? null : str(table.getColumnModel().getColumn(idx).getHeaderValue()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return table.getColumnCount() <= idx ? null\r\n : str(table.getColumnModel..."; } }); } static public int tableRowCount(JTable table) { return tableRows(table); } static public List sortByConceptID(Collection l) { return sortConceptsByID(l); } static public Map orderedMapPutOrCreate(Map map, A key, B value) { if (key != null && value != null) { if (map == null) map = new LinkedHashMap(); map.put(key, value); } return map; } static public String nListeners(long n) { return n2(n, "listener"); } static public String nListeners(Collection l) { return nListeners(l(l)); } static public String nListeners(Map map) { return nListeners(l(map)); } static public File videosDir() { return userDir("Videos"); } static public File videosDir(String sub) { return newFile(videosDir(), sub); } static public String printCommaCombine(Object... l) { return print(commaCombine(l)); } static public List addListener(List list, A a) { return createOrAddToSyncList(list, a); } static public List syncLinkedList() { return synchroLinkedList(); } static public Runnable comboBoxAction(JComboBox cb, IVF1 action) { return () -> pcallF(action, getText(cb)); } static public JPanel jlineWithSpacing(int spacing, Component... components) { return swing(() -> { return new LeftAlignedLine(spacing, components); }); } static public boolean emptyContainer(Container c) { return isEmptyContainer(c); } static public void removeAllIC_useIterator(List l, String s) { if (l == null) return; var it = l.iterator(); while (it.hasNext()) if (eqic(it.next(), s)) it.remove(); } static public void removeFirst(List l) { if (nempty(l)) l.remove(0); } static public void removeFirst(int n, List l) { removeSubList(l, 0, n); } static public boolean addIfNotContained(Collection c, A a) { return setAdd(c, a); } static public int hashCodeFor(Object a) { return a == null ? 0 : a.hashCode(); } static public GridBagConstraints gridBagConstraints_hstack_1(int spacing) { GridBagConstraints gbc = new GridBagConstraints(); gbc.weighty = 1; gbc.fill = GridBagConstraints.VERTICAL; gbc.gridheight = GridBagConstraints.REMAINDER; gbc.insets = new Insets(0, spacing / 2, 0, spacing / 2); return gbc; } static public GridBagConstraints gridBagConstraints_hstack_rest() { GridBagConstraints gbc = gridBagConstraints_hstack_1(0); gbc.weightx = 1; return gbc; } static public String hreconnectingWebSockets() { return hjavascript_src_snippet(hreconnectingWebSockets_snippetID()); } static public String hscript(String script) { return hjavascript(script); } static public String hjssnippet(String snippetID, Object... __) { return hjavascript_src_snippet(snippetID, __); } static public String hreconnectingWebSockets_snippetID() { return "#2000597"; } static public String jsDollarVars(String s, Object... __) { return replaceDollarVars_js(s, __); } static public String js_evalOnWebSocketMessage() { return "\r\n function(event) {\r\n var data = JSON.parse(event.data);\r\n if (data.eval) {\r\n if (wsVerbose) console.log(\"Evaluating: \" + data.eval);\r\n var geval = eval; // use global scope\r\n geval(data.eval);\r\n if (wsVerbose) console.log(\"Evaluated.\");\r\n } else\r\n if (wsVerbose) console.log(\"WebSocket incoming: \" + event.data);\r\n }\r\n "; } static public int keysSize(MultiMap mm) { return lKeys(mm); } static public A reverseGet(List l, int idx) { if (l == null || idx < 0) return null; int n = l(l); return idx < n ? l.get(n - 1 - idx) : null; } static public boolean _eq(Object a, Object b) { return eq(a, b); } static public Object time(Object f) { long time = sysNow(); Object o = callF(f); done2_always(str(f), time); return o; } static public A time(F0 f) { return (A) time((Object) f); } static public A time(IF0 f) { return (A) time((Object) f); } static public A time(String msg, IF0 f) { long time = sysNow(); A o = f.get(); done2_always(msg, time); return o; } static public void time(Runnable f) { time(str(f), f); } static public void time(String msg, Runnable f) { time(msg, runnableToIF0(f)); } static public Map.Entry simpleMapEntry(A key, B value) { return new Map.Entry() { public A getKey() { return key; } public B getValue() { return value; } public B setValue(B newValue) { throw unimplemented(); } }; } static public Method hashMap_findKey_method; static public A hashMap_findKey(HashMap map, Object key) { try { if (hashMap_findKey_method == null) hashMap_findKey_method = findMethodNamed(HashMap.class, "getNode"); Map.Entry entry = (Map.Entry) hashMap_findKey_method.invoke(map, hashMap_internalHash(key), key); return entry == null ? null : entry.getKey(); } catch (Exception __e) { throw rethrow(__e); } } static public BufferedImage newTransparentImage(Dimension size) { return newTransparentImage(toWidthAndHeight(size)); } static public BufferedImage newTransparentImage(int size_w, int size_h) { return newTransparentImage(widthAndHeight(size_w, size_h)); } static public BufferedImage newTransparentImage(WidthAndHeight size) { return transparentBufferedImage(size); } static public float[] doubleArrayToFloatArray(double[] a) { int n = lDoubleArray(a); float[] b = new float[n]; for (int i = 0; i < n; i++) b[i] = (float) a[i]; return b; } static public int lFloatArray(float[] a) { return a == null ? 0 : a.length; } static public float[] resizeFloatArray(float[] a, int n) { return resizeArray(a, n); } static public double[] takeFirstFromFloatArrayAsDoubleArray(float[] a, int n) { double[] b = new double[n]; for (int i = 0; i < n; i++) b[i] = a[i]; return b; } static public ArrayList floatArrayToDoubleList(float[] a) { if (a == null) return null; return floatArrayToDoubleList(a, 0, a.length); } static public ArrayList floatArrayToDoubleList(float[] a, int from, int to) { if (a == null) return null; ArrayList l = new ArrayList<>(to - from); for (int i = from; i < to; i++) l.add((double) a[i]); return l; } static public double[] subFloatArrayAsDoubleArray(float[] b, int start) { return subFloatArrayAsDoubleArray(b, start, l(b)); } static public double[] subFloatArrayAsDoubleArray(float[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start >= end) return new double[0]; double[] x = new double[end - start]; for (int i = start; i < end; i++) x[i - start] = b[i]; return x; } static public String assertGlobalID(String s) { return assertPossibleGlobalID(s); } static public String bigintToGlobalID(BigInteger value) { char[] buf = new char[16]; for (int i = 16 - 1; i >= 0; i--) { buf[i] = charPlus('a', mod(value, 26).intValue()); value = div(value, 26); } return str(buf); } static public FontMetrics componentFontMetrics(JComponent c) { Font font = getFont(c); return font == null ? null : swing(new F0() { public FontMetrics get() { try { return c.getFontMetrics(font); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getFontMetrics(font);"; } }); } static public List asSyncList(Iterable l) { return asSynchroList(l); } static public String lines_rtrimIf(boolean rtrim, List lines) { return rtrim ? lines_rtrim(lines) : lines(lines); } static public boolean eqOrEqic(boolean caseInsensitive, String a, String b) { return caseInsensitive ? eqic(a, b) : eq(a, b); } static public String assertInteger(String s) { if (!isInteger(s)) throw fail("Not an integer: " + quote(s)); return s; } static public boolean containsLineBreak(String s) { return containsNewLine(s); } static public Throwable exceptionForTimeoutedThread(Thread thread) { var stackTrace = thread.getStackTrace(); var cause = new ThrowableWithCustomStackTrace("Still calculating", stackTrace); return cause; } static public Set weakIdentityHashSet() { return new WeakIdentityHashSet(); } static public ChangeListener scrollPaneOnScroll(final JScrollPane sp, final Object onScroll) { return swing(new F0() { public ChangeListener get() { try { ChangeListener l = changeListener(onScroll); sp.getViewport().addChangeListener(l); return l; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ChangeListener l = changeListener(onScroll);\r\n sp.getViewport().addChangeL..."; } }); } static public List stackElementsShowing(final DynamicStack stack) { return swing(new F0>() { public List get() { try { List l = new ArrayList(); if (!stack.isShowing()) return l; JScrollPane sp = enclosingScrollPane(stack); if (sp == null) return l; JViewport vp = sp.getViewport(); Rect vpRect = toRect(vp.getBounds()); for (Component c : stack.components()) if (rectsIntersect(vpRect, boundsInParent(c, vp))) l.add(c); return l; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new L l;\r\n if (!stack.isShowing()) ret l;\r\n JScrollPane sp =..."; } }); } static public boolean add_byContains(Collection c, A a) { if (c == null) return false; synchronized (collectionMutex(c)) { if (c.contains(a)) return false; c.add(a); return true; } } static public DeQ startDeQ() { return new DeQ(); } static public int loadPreviewImage_maxSize = 128; static public BufferedImage loadPreviewImage(File f) { return scaleBufferedImageToMax(loadBufferedImage(f), loadPreviewImage_maxSize); } static public BufferedImage loadPreviewImageWithExactHeight(int h, File f) { return scaleBufferedImageToHeight(h, loadBufferedImage(f)); } static public RGBImage toGrayScale(RGBImage img, int bits) { int steps = 1 << bits; int w = img.getWidth(), h = img.getHeight(); RGBImage bw = new RGBImage(w, h); for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { float b = img.getPixel(x, y).getBrightness(); int bx = (int) (b * steps); double b2 = Math.min(1f, Math.max(0f, bx / (float) steps)); bw.setPixel(x, y, new RGB(b2)); } return bw; } static public int colorToRGBInt(Color c) { return colorToInt(c); } static public Pt mousePt() { return toPt(mousePosition()); } static public Pt ptFromEvent(MouseEvent e) { return e == null ? null : pt(e.getX(), e.getY()); } static public Pt convertPointToScreen(Pt p, Component c) { if (c == null) return p; Point p2 = toPoint(p); SwingUtilities.convertPointToScreen(p2, c); return toPt(p2); } static public WebSocketFactory webSocketFactory(final Object factory) { if (factory instanceof WebSocketFactory) return ((WebSocketFactory) factory); if (factory == null) return null; return new WebSocketFactory() { public WebSocket openWebSocket(NanoHTTPD.IHTTPSession handshake) { return (WebSocket) callF(factory, handshake); } }; } static public void nanohttpd_socketTimeoutFix() { NanoHTTPD.SOCKET_READ_TIMEOUT = 24 * 3600 * 1000; } static public PtBuffer ptBuffer(Iterable l) { return new PtBuffer(l); } static public double fileAgeInSeconds(File f) { return f == null ? -1 : msToSeconds(now() - fileModificationTime(f)); } static public String nSeconds(long n) { return n2(n, "second"); } static public String nSeconds(Collection l) { return nSeconds(l(l)); } static public File saveTextFileWithoutTemp(File file, String contents) { try { mkdirsForFile(file); var fileOutputStream = newFileOutputStream(file); try { var outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); var printWriter = new PrintWriter(outputStreamWriter); printWriter.print(unnull(contents)); printWriter.close(); return file; } finally { _close(fileOutputStream); } } catch (Exception __e) { throw rethrow(__e); } } static public Chain chainPlus(Chain chain, A a) { return new Chain(a, chain); } static public Chain chainPlus(Chain chain, A... l) { for (A a : unnullForIteration(l)) chain = chainPlus(chain, a); return chain; } static public ReverseChain chainPlus(ReverseChain chain, A a) { return new ReverseChain(chain, a); } static public ReverseChain chainPlus(ReverseChain chain, A... l) { for (A a : unnullForIteration(l)) chain = chainPlus(chain, a); return chain; } static public AppendableChain chainPlus(AppendableChain chain, A a) { if (chain == null) return new AppendableChain(a); chain.add(a); return chain; } static public AppendableChain chainPlus(AppendableChain chain, A... l) { for (A a : unnullForIteration(l)) chain = chainPlus(chain, a); return chain; } static public void syncNotifyAll(Object o) { if (o != null) synchronized (o) { o.notifyAll(); } } static public List deleteFilesVerbose(File... files) { return deleteFilesVerbose(asList(files)); } static public List deleteFilesVerbose(List files) { List out = new ArrayList(); for (File f : unnull(files)) if (deleteFileVerbose(f)) out.add(f); return out; } static public boolean filesExist(Iterable l) { return all(__212 -> isFile(__212), l); } static public boolean currentProgramHasLibraries(Collection f) { return containsAll(myLibraryFiles(), f); } static public boolean addLibraries(Collection libIDs) { boolean change = false; for (String libID : unnullForIteration(libIDs)) change |= addLibrary(libID); return change; } static public Set addToSet_create(Set set, A a) { return createOrAddToSet(set, a); } static public String hjs(String script) { return hjs(script, (Object[]) null); } static public String hjs(String script, Object... __) { return hjavascript(script, __); } static public String hjs(JS script) { return hjs(script, (Object[]) null); } static public String hjs(JS script, Object... __) { return hjavascript(script == null ? null : script.get(), __); } static public void runWithExecutor(Runnable r, Executor e) { if (e == null) r.run(); else e.execute(r); } static public Map loadImage2_cached_cache = synchroTreeMap(); static public BufferedImage loadImage2_cached(String s) { BufferedImage img = loadImage2_cached_cache.get(s); if (img == null) loadImage2_cached_cache.put(s, img = loadBufferedImage(s)); return img; } static public int scrollBarValue(final JScrollBar sb) { return sb == null ? 0 : swing(new F0() { public Integer get() { try { return sb.getValue(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return sb.getValue();"; } }); } static public void setScrollBarValue(final JScrollBar sb, final int value) { if (sb != null) { swing(() -> { sb.setValue(value); }); } } static public byte[] toASCII(String s) { return s.getBytes(java.nio.charset.StandardCharsets.US_ASCII); } static public byte toASCII(char c) { return toASCII(str(new char[] { c }))[0]; } static public long waitForBotStartUp_timeoutSeconds = 60; static public String waitForBotStartUp(String botName) { for (int i = 0; i < waitForBotStartUp_timeoutSeconds; i++) { sleepSeconds(i == 0 ? 0 : 1); String addr = getBotAddress(botName); if (addr != null) return addr; } throw fail("Bot not found: " + quote(botName)); } static public Object rpc(String botName, String method, Object... args) { return unstructure_matchOK2OrFail(sendToLocalBot(botName, rpc_makeCall(method, args))); } static public Object rpc(DialogIO bot, String method, Object... args) { return unstructure_matchOK2OrFail(bot.ask(rpc_makeCall(method, args))); } static public String rpc_makeCall(String method, Object... args) { if (empty(args)) return "call " + method; return format("call *", concatLists((List) ll(method), asList(args))); } static public String nFragments(long n) { return n2(n, "fragment"); } static public String nFragments(Collection l) { return nFragments(l(l)); } static public String nFragments(Map map) { return nFragments(l(map)); } static public IterableIterator filterI(Iterator it, F1 f) { return filterIterator(it, f); } static public IterableIterator filterI(Iterator it, IF1 f) { return filterIterator(it, f); } static public IterableIterator filterI(F1 f, Iterator it) { return filterIterator(f, it); } static public IterableIterator filterI(IF1 f, Iterator it) { return filterIterator(f, it); } static public IterableIterator filterI(IF1 f, Iterable it) { return filterIterator(f, iterator(it)); } static public Timestamp sysTimeToTimestamp(long now) { return now == 0 ? null : new Timestamp(now - clockToSysTimeDiff()); } static public String shortenJoin(int max, Iterable l) { StringBuilder buf = new StringBuilder(); for (String s : unnullForIteration(l)) { buf.append(s); if (l(buf) > max) break; } return shorten(max, str(buf)); } static public List g22_allBorderTraces_autoDiagonals(IImageRegion region) { return region.createdWithDiagonals() ? g22_allBorderTraces_withDiagonals(region) : g22_allBorderTraces(region); } static public String defaultFrameTitle() { return autoFrameTitle(); } static public void defaultFrameTitle(String title) { autoFrameTitle_value = title; } static public void registerEscape(JFrame frame, final Runnable r) { registerEscape_rootPane(frame.getRootPane(), r); } static public void inputFilePath(final String msg, final Object action) { inputFilePath(msg, userDir(), action); } static public void inputFilePath(final String msg, final File defaultFile, final Object action) { swingLater(new Runnable() { public void run() { try { final JTextField tfPath = jtextfield(f2s(or(defaultFile, userDir()))); String title = joinStrings(" | ", msg, programName()); JComponent form = showFormTitled(title, unnull(msg), centerAndEast(tfPath, jbutton("Browse...", new Runnable() { public void run() { try { JFileChooser fileChooser = new JFileChooser(getTextTrim(tfPath)); if (fileChooser.showOpenDialog(tfPath) == JFileChooser.APPROVE_OPTION) { tfPath.setText(fileChooser.getSelectedFile().getAbsolutePath()); tfPath.requestFocus(); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFileChooser fileChooser = new JFileChooser(getTextTrim(tfPath));\r\n if..."; } })), new Runnable() { public void run() { try { callF(action, new File(getTextTrim(tfPath))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(action, new File(getTextTrim(tfPath)))"; } }); renameSubmitButton(form, "OK"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tfPath = jtextfield(f2s(or(defaultFile, userDir())));\r\n S..."; } }); } static public JComponent selectSnippetID_v1(final VF1 onSelect) { return selectSnippetID_v1("#", onSelect); } static public JComponent selectSnippetID_v1(String defaultID, final VF1 onSelect) { final JTextField tfSnippetID = jtextfield(defaultID); if (eq(defaultID, "#")) moveCaretToEnd(tfSnippetID); JComponent panel; renameSubmitButton(panel = showTitledForm("Select Snippet", "Snippet ID:", tfSnippetID, runnableThread(new Runnable() { public void run() { try { callF(onSelect, fsI(getTextTrim(tfSnippetID))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onSelect, fsI(getTextTrim(tfSnippetID)));"; } })), "Select snippet"); return panel; } static public void popupError(final Throwable throwable) { throwable.printStackTrace(); SwingUtilities.invokeLater(new Runnable() { public void run() { String text = throwable.toString(); JOptionPane.showMessageDialog(null, text); } }); } static public A printIf(boolean b, A a) { if (b) print(a); return a; } static public A printIf(boolean b, String s, A a) { if (b) print(s, a); return a; } static public ImageSurface jImageSurface() { return swingNu(ImageSurface.class); } static public ImageSurface jImageSurface(MakesBufferedImage img) { return swingNu(ImageSurface.class, img.getBufferedImage()); } static public ImageSurface jImageSurface(BufferedImage img) { return swingNu(ImageSurface.class, img); } static public A disposeFrameOnClick(final A c) { onClick(c, new Runnable() { public void run() { try { disposeFrame(c); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "disposeFrame(c)"; } }); return c; } static public List callF_all(Collection l, Object... args) { return map(l, f -> callF(f, args)); } static public java.util.Calendar calendarFromTime(long time, TimeZone tz) { java.util.Calendar c = java.util.Calendar.getInstance(tz); c.setTimeInMillis(time); return c; } static public java.util.Calendar calendarFromTime(long time) { java.util.Calendar c = java.util.Calendar.getInstance(); c.setTimeInMillis(time); return c; } static public String dynamicClassName(Object o) { if (o instanceof DynamicObject && ((DynamicObject) o).className != null) return "main$" + ((DynamicObject) o).className; return className(o); } static public void subListRangeCheck(int fromIndex, int toIndex, int size) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > size) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } static public BufferedImage newGrayBufferedImage(int w, int h) { return new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY); } static public BufferedImage newGrayBufferedImage(int w, int h, byte[] pixels) { return byteArrayToGrayBufferedImage(pixels, w, h); } static public void highThreadPriority() { currentThread().setPriority(Thread.NORM_PRIORITY + 1); } static public List syncCloneAndClearList(Collection l) { if (l == null) return emptyList(); synchronized (collectionMutex(l)) { List l2 = cloneList(l); l.clear(); return l2; } } static public long secondsToMS(double seconds) { return toMS(seconds); } static public DynamicVStack dynamicVStack() { return swingNu(DynamicVStack.class); } static public DynamicVStack dynamicVStack(Component... components) { DynamicVStack stack = dynamicVStack(); stack.addComponents(asList(components)); return stack; } static public List intRangeList(int b) { return intRangeList(0, b); } static public List intRangeList(final int a, final int b) { final int l = max(0, b - a); return new RandomAccessAbstractList() { public int size() { return l; } public Integer get(int i) { return i >= 0 && i < l ? a + i : null; } }; } static public long clockToSysTimeDiff() { return sysNow() - now(); } static public String programIDPlusHome() { return programIDPlusHome(programID(), userHomeIfNotActual()); } static public String programIDPlusHome(String programID, File home) { return programIDPlusHome(programID, f2s(home)); } static public String programIDPlusHome(String programID, String home) { if (home != null) programID += " " + quote(home); return programID; } static public List activateMyFrames() { final List l = myFrames(); { swing(() -> { for (JFrame f : l) activateFrame(f); }); } return l; } static public long conceptID(Concept c) { return c == null ? 0 : c.id; } static public long conceptID(Concept.Ref ref) { return conceptID(cDeref(ref)); } static public A ccopyFields2(Concept x, A y, Iterable fields) { if (x == null || y == null) return y; for (String field : unnull(fields)) { Object o = cget(x, field); if (o != null) cset(y, field, o); } return y; } static public Set setMinusSet(Set l, Collection stuff) { if (empty(stuff)) return l; Set set = asSet(stuff); Set l2 = similarEmptySet(l); for (A a : l) if (!set.contains(a)) l2.add(a); return l2; } static public Set setMinusSet(Collection l, Collection stuff) { return setMinusSet(asSet(l), stuff); } static public String[] conceptFields_drop = { "className", "fieldValues", "id", "created", "_modified", "refs", "backRefs", "_concepts" }; static public Set conceptFields(Concept c) { return setMinus(mergeSets(allNonStaticNonTransientFields(c), keys(c.fieldValues)), conceptFields_drop); } static public Set conceptFields(Class c) { return setMinus(allNonStaticNonTransientFields(c), conceptFields_drop); } static public Object getMCOpt(String field) { return getOptMC(field); } static public void setMCOpt(String field, Object value) { setOptMC(field, value); } static public boolean isUnlisted(Concept c) { return c != null && c.concepts() == null; } static public List allBackRefObjects(Concept c) { return cloneList(c == null ? null : c.backRefs); } static public JCheckBox centerCheckBox(JCheckBox cb) { return setHorizontalAlignment(SwingConstants.CENTER, cb); } static public float toFloat(Object o) { if (o == null) return 0f; if (o instanceof Number) return ((Number) o).floatValue(); if (o instanceof Boolean) return ((Boolean) o).booleanValue() ? 1f : 0f; throw fail("Not convertible to float: " + _getClass(o)); } static public Pt parsePt(String s) { var l = parseInts(splitAtComma_trim(s)); return empty(l) ? null : pt(first(l), second(l)); } static public Rect parseRect(String s) { List tok = javaTokC(s); assertEquals(7, l(tok)); return new Rect(parseInt(tok.get(0)), parseInt(tok.get(2)), parseInt(tok.get(4)), parseInt(tok.get(6))); } static public List listIntersectSet(Collection a, Collection b) { return listSetIntersection(a, b); } static public List sortedByCalculatedFieldIC(Iterable c, Object f) { return sortByCalculatedFieldIC(c, f); } static public List sortedByCalculatedFieldIC(Object f, Iterable c) { return sortedByCalculatedFieldIC(c, f); } static public List sortedByCalculatedFieldIC(IF1 f, Iterable c) { return sortedByCalculatedFieldIC((Object) f, c); } static public List sortedByCalculatedFieldIC(Iterable c, IF1 f) { return sortedByCalculatedFieldIC((Object) f, c); } static public JPanel hgridWithSpacing(Object... _parts) { return swing(() -> { int spacing = 6; Object[] parts = _parts; if (first(parts) instanceof Integer) { spacing = (Integer) first(parts); parts = dropFirst(parts); } JPanel panel = hgrid(parts); GridLayout gl = (GridLayout) (panel.getLayout()); gl.setHgap(spacing); gl.setVgap(spacing); return panel; }); } static public String escapeNewLines(String s) { return s == null ? null : fixNewLines(s).replace("\n", " | "); } static public String dropTrailingNewLine(String s) { int l = l(s); if (l > 0 && s.charAt(l - 1) == '\n') --l; if (l > 0 && s.charAt(l - 1) == '\r') --l; return takeFirst(s, l); } static public A callPostProcessor(Object f, A a) { return f == null ? a : (A) callF(f, a); } static public A callPostProcessor(IF1 f, A a) { return f == null ? a : f.get(a); } static public List createOrAddToSyncList(List list, A a) { if (list == null) list = syncList(); list.add(a); return list; } static public boolean isEmptyContainer(Container c) { return c != null && empty(getComponents(c)); } static public String hjavascript_src_snippet(String snippetID, Object... __) { return hfulltag("script", "", paramsPlus(__, "src", snippetRawURL(snippetID, "text/javascript"))); } static public String hjavascript(String scriptOrURL, Object... __) { if (isRelativeOrAbsoluteURL(scriptOrURL) && !startsWithOneOf(scriptOrURL, "//", "/*")) return hjavascript_src(scriptOrURL, __); else return tag("script", scriptOrURL, paramsPlus(__, "type", "text/javascript")); } static public String replaceDollarVars_js(String s, Object... __) { Map vars = paramsToMap_withNulls(__); if (empty(vars)) return s; var vars2 = mapKeys(__213 -> dropDollarPrefix(__213), vars); return replaceDollarVars_dyn(s, var -> { if (!vars2.containsKey(var)) return null; Object value = vars2.get(var); return jsonEncode_extended(value); }); } static public int lKeys(MultiMap mm) { return mm == null ? 0 : mm.keysSize(); } static public int hashMap_internalHash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } static public Object[] resizeArray(Object[] a, int n) { if (n == l(a)) return a; Object[] b = new Object[n]; arraycopy(a, 0, b, 0, min(l(a), n)); return b; } static public double[] resizeArray(double[] a, int n) { if (n == l(a)) return a; double[] b = new double[n]; arraycopy(a, 0, b, 0, min(l(a), n)); return b; } static public float[] resizeArray(float[] a, int n) { if (n == l(a)) return a; float[] b = new float[n]; arraycopy(a, 0, b, 0, min(l(a), n)); return b; } static public long[] resizeArray(long[] a, int n) { if (n == l(a)) return a; long[] b = new long[n]; arraycopy(a, 0, b, 0, min(l(a), n)); return b; } static public String assertPossibleGlobalID(String s) { if (!possibleGlobalID(s)) throw fail("Not an acceptable global ID: " + s); return s; } static public char charPlus(char a, int b) { return (char) (((int) a) + b); } static public char charPlus(int b, char a) { return charPlus(a, b); } static public List asSynchroList(Iterable l) { return syncList(cloneList(l)); } static public boolean rectsIntersect(Rect a, Rect b) { return rectsOverlap(a, b); } static public Rect boundsInParent(Component c, Class parentType) { return boundsInParent(c, parentOfType(c, parentType)); } static public Rect boundsInParent(Component _c, Component parent) { if (_c == null) return null; return swing(new F0() { public Rect get() { try { if (_c == parent) return new Rect(0, 0, _c.getWidth(), _c.getHeight()); Rect r = toRect(_c.getBounds()); Component c = _c; while (true) { c = c.getParent(); if (c == null) return null; if (c == parent) return r; r = translateRect(r, c.getX(), c.getY()); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (_c == parent) ret Rect(0, 0, _c.getWidth(), _c.getHeight());\r\n Rect r ..."; } }); } static public BufferedImage scaleBufferedImageToMax(int max, BufferedImage img) { return scaleBufferedImageToMaxWidthOrHeight(max, img); } static public BufferedImage scaleBufferedImageToMax(BufferedImage img, int max) { return scaleBufferedImageToMaxWidthOrHeight(img, max); } static public BufferedImage scaleBufferedImageToHeight(int height, BufferedImage img) { return scaleImage(img, height / (double) img.getHeight()); } static public Point mousePosition() { PointerInfo pi = MouseInfo.getPointerInfo(); return pi == null ? null : pi.getLocation(); } static public boolean containsAll(Collection a, Collection b) { for (A o : b) if (!a.contains(o)) return false; return true; } static public boolean containsAll(Collection a, A... b) { for (A o : b) if (!a.contains(o)) return false; return true; } static public boolean containsAll(String a, Collection b) { for (String o : unnullForIteration(b)) if (!contains(a, o)) return false; return true; } static public boolean containsAll(String a, String... b) { for (String o : unnullForIteration(b)) if (!contains(a, o)) return false; return true; } static public String getBotAddress(String bot) { List l = fullBotScan(bot); return empty(l) ? null : first(l).address; } static public Object unstructure_matchOK2OrFail(String s) { if (swic(s, "ok ")) return unstructure_startingAtIndex(s, 3); else throw fail(s); } static public List g22_allBorderTraces_withDiagonals(IImageRegion region) { RegionBorder_innerPoints_withDiagonals walker = new RegionBorder_innerPoints_withDiagonals(region); List out = new ArrayList(); walker.onNewTrace(hole -> out.add(new PtBuffer())); walker.onFoundPoint(p -> last(out).add(p)); walker.run(); return out; } static public List g22_allBorderTraces(IImageRegion region) { RegionBorder_innerPoints_v2 walker = new RegionBorder_innerPoints_v2(region); List out = new ArrayList(); walker.onNewTrace(hole -> out.add(new PtBuffer())); walker.onFoundPoint(p -> last(out).add(p)); walker.run(); return out; } static public void registerEscape_rootPane(JComponent rootPane, final Runnable r) { String name = "Escape"; Action action = abstractAction(name, r); KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); rootPane.getActionMap().put(name, action); rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name); } static public A moveCaretToEnd(A ta) { setCaretPosition(ta, textAreaTextLength(ta)); return ta; } static public BufferedImage byteArrayToGrayBufferedImage(byte[] pixels, int w, int h) { PixelInterleavedSampleModel sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, w, h, 1, w, new int[] { 0 }); DataBufferByte db = new DataBufferByte(pixels, pixels.length); WritableRaster wr = Raster.createWritableRaster(sm, db, new Point()); return new BufferedImage(grayColorModel(), wr, false, null); } static public String userHomeIfNotActual() { String home = userHome(); return eq(home, actualUserHome()) ? null : home; } static public Set setMinus(Set set, Object... stuff) { Set s2 = cloneSet(set); for (Object o : stuff) s2.remove(o); return s2; } static public Set mergeSets(Collection... l) { return joinSets(l); } static public Set allNonStaticNonTransientFields(Object o) { TreeSet fields = new TreeSet(); Class _c = _getClass(o); do { for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) == 0) fields.add(f.getName()); _c = _c.getSuperclass(); } while (_c != null); return fields; } static public void setOptMC(String field, Object value) { setOpt(mc(), field, value); } static public List parseInts(Iterable l) { return lambdaMap(__214 -> parseInt(__214), l); } static public List sortByCalculatedFieldIC(Iterable c, final Object f) { List l = cloneList(c); sort(l, new Comparator() { public int compare(A a, A b) { return compareIC((String) callF(f, a), (String) callF(f, b)); } }); return l; } static public String snippetRawURL(String snippetID) { return snippetRawURL(snippetID, null); } static public String snippetRawURL(String snippetID, String contentType) { return "https://botcompany.de/serve/" + psI(snippetID) + htmlQuery("ct", contentType); } static public boolean isRelativeOrAbsoluteURL(String s) { return isAbsoluteURL(s) || isRelativeURL(s); } static public String hjavascript_src(String src, Object... __) { return hfulltag("script", "", paramsPlus(__, "src", src)); } static public Map paramsToMap_withNulls(Object... params) { int n = l(params); if (l(params) == 1 && params[0] instanceof Map) return (Map) params[0]; LinkedHashMap map = new LinkedHashMap(); for (int i = 0; i + 1 < n; i += 2) map.put(params[i], params[i + 1]); return map; } static public String dropDollarPrefix(String s) { return dropPrefix("$", s); } static public String replaceDollarVars_dyn(String s, IF1 f) { if (f == null) return s; return regexpReplaceIC(s, "\\$(\\w+)", matcher -> { String var = matcher.group(1); String val = f.get(var); return val == null ? matcher.group() : str(val); }); } static public String jsonEncode_extended(Object o) { StringBuilder buf = new StringBuilder(); jsonEncode_extended(o, buf); return str(buf); } static public void jsonEncode_extended(Object o, StringBuilder buf) { if (o == null) buf.append("null"); else if (o instanceof JS) buf.append(((JS) o).get()); 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_extended(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_extended(element, buf); } buf.append("]"); } else throw fail("Unknown object for JSON encoding: " + className(o)); } static public boolean possibleGlobalID(String s) { return l(s) == globalIDLength() && allLowerCaseCharacters(s); } static public class ScannedBot implements IFieldsToList { static final public String _fieldOrder = "helloString address"; public String helloString; public String address; public ScannedBot() { } public ScannedBot(String helloString, String address) { this.address = address; this.helloString = helloString; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + helloString + ", " + address + ")"; } public boolean equals(Object o) { if (!(o instanceof ScannedBot)) return false; ScannedBot __1 = (ScannedBot) o; return eq(helloString, __1.helloString) && eq(address, __1.address); } public int hashCode() { int h = 1660478935; h = boostHashCombine(h, _hashCode(helloString)); h = boostHashCombine(h, _hashCode(address)); return h; } public Object[] _fieldsToList() { return new Object[] { helloString, address }; } } static public List fullBotScan() { return fullBotScan(""); } static public List fullBotScan(String searchPattern) { List bots = new ArrayList(); for (ProgramScan.Program p : quickBotScan()) { String botName = firstPartOfHelloString(p.helloString); boolean isVM = startsWithIgnoreCase(p.helloString, "This is a JavaX VM."); boolean shouldRecurse = swic(botName, "Multi-Port") || isVM; if (swic(botName, searchPattern)) bots.add(new ScannedBot(botName, "" + p.port)); if (shouldRecurse) try { Map subBots = (Map) unstructure(sendToLocalBotQuietly(p.port, "list bots")); for (Number vport : subBots.keySet()) { botName = subBots.get(vport); if (swic(botName, searchPattern)) bots.add(new ScannedBot(botName, p.port + "/" + vport)); } } catch (Exception e) { e.printStackTrace(); } } return bots; } static public Object unstructure_startingAtIndex(String s, int i) { return unstructure_tok(javaTokC_noMLS_iterator(s, i), false, null); } static public int textAreaTextLength(JTextComponent ta) { return l(getText(ta)); } static public ColorModel grayColorModel_cache; static public ColorModel grayColorModel() { if (grayColorModel_cache == null) grayColorModel_cache = grayColorModel_load(); return grayColorModel_cache; } static public ColorModel grayColorModel_load() { return newGrayBufferedImage(1, 1).getColorModel(); } static public Set cloneSet(Collection set) { if (set == null) return new HashSet(); synchronized (collectionMutex(set)) { Set s = similarEmptySet(set); s.addAll(set); return s; } } static public int compareIC(String s1, String s2) { return compareIgnoreCase_jdk(s1, s2); } static public boolean isRelativeURL(String s) { return startsWithOneOf(s, "/", "./", "../"); } static public String regexpReplaceIC(String s, String pat, Object f) { return regexReplaceIC(s, pat, f); } static public String regexpReplaceIC(String s, String pat, String replacement) { return regexReplaceIC(s, pat, replacement); } static public String regexpReplaceIC(String s, String pat, IF1 f) { return regexReplaceIC(s, pat, f); } static public boolean allLowerCaseCharacters(String s) { for (int i = 0; i < l(s); i++) if (Character.getType(s.charAt(i)) != Character.LOWERCASE_LETTER) return false; return true; } static public int compareIgnoreCase_jdk(String s1, String s2) { if (s1 == null) return s2 == null ? 0 : -1; if (s2 == null) return 1; int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) return c1 - c2; } } } return n1 - n2; } static public String regexReplaceIC(String s, String pat, Object f) { return regexReplace(regexpMatcherIC(pat, s), f); } static public String regexReplaceIC(String s, String pat, String replacement) { return regexpReplaceIC_direct(s, pat, replacement); } static public Matcher regexpMatcherIC(String pat, String s) { return compileRegexpIC(pat).matcher(unnull(s)); } static public String regexpReplaceIC_direct(String s, String pat, String replacement) { Matcher m = regexpIC(pat, s); StringBuffer buf = new StringBuffer(); while (m.find()) m.appendReplacement(buf, replacement); m.appendTail(buf); return str(buf); } static public class ThrowableWithCustomStackTrace extends Throwable { public ThrowableWithCustomStackTrace(String msg, StackTraceElement[] stackTrace) { super(msg, null, false, true); setStackTrace(stackTrace); } } static public class Chain implements Iterable { public A element; public Chain next; public int size; public Chain() { } public Chain(A element) { this.element = element; size = 1; } public Chain(A element, Chain next) { this.next = next; this.element = element; size = next != null ? next.size + 1 : 1; } public String toString() { return str(toList()); } public ArrayList toList() { ArrayList l = emptyList(size); Chain c = this; while (c != null) { l.add(c.element); c = c.next; } return l; } public Iterator iterator() { return toList().iterator(); } } static public class PNGFile extends Concept { public String pngPath; public Rect r; public PNGFile() { } public PNGFile(String pngPath) { this.pngPath = pngPath; } public PNGFile(RGBImage img) { this(img.getBufferedImage()); } public File pngFile() { if (pngPath == null) { pngPath = _programID() + "/" + id + ".png"; change(); } return prepareFile(new File(javaxDataDir(), pngPath)); } public PNGFile(BufferedImage img) { savePNG(pngFile(), img); } public BufferedImage loadImage() { return loadImage2(pngFile()); } public BufferedImage getImage() { return loadImage(); } public BufferedImage getImageSafe() { try { return loadImage(); } catch (Throwable __e) { pcallFail(__e); } return null; } public String md5() { try { return md5OfBufferedImage(getImage()); } catch (Throwable __e) { pcallFail(__e); } return "-"; } public boolean hasImage() { return pngFile().exists(); } } static public class AutoComboBox extends JComboBox { public String[] keyWord; public Vector myVector = new Vector(); public boolean acceptOnTab = false; public AutoComboBox() { setModel(new DefaultComboBoxModel(myVector)); setSelectedIndex(-1); setEditable(true); JTextField text = (JTextField) this.getEditor().getEditorComponent(); text.setFocusable(true); text.setText(""); text.addKeyListener(new ComboListener(this, myVector)); if (acceptOnTab) text.setFocusTraversalKeysEnabled(false); setMyVector(); } public void setKeyWord(String[] keyWord) { this.keyWord = keyWord; setMyVector(); } public void setKeyWord(Collection keyWord) { setKeyWord(toStringArray(keyWord)); } private void setMyVector() { copyArrayToVector(keyWord, myVector); } public class ComboListener extends KeyAdapter { public JComboBox cb; public Vector vector; public ComboListener(JComboBox cb, Vector vector) { this.vector = vector; this.cb = cb; } public void keyPressed(KeyEvent key) { if (key.getKeyCode() == KeyEvent.VK_ENTER) return; if (key.getKeyCode() == KeyEvent.VK_ESCAPE) { cb.hidePopup(); return; } if (acceptOnTab && key.getKeyCode() == KeyEvent.VK_TAB) { _print("Have tab event (modifiers=" + key.getModifiers() + ")"); if ((key.getModifiers() & ActionEvent.SHIFT_MASK) == 0 && cb.isPopupVisible()) { cb.setSelectedIndex(0); cb.hidePopup(); } else swing_standardTabBehavior(key); return; } JTextField tf = (JTextField) (cb.getEditor().getEditorComponent()); if (tf.getCaretPosition() != l(tf.getText())) return; String text = ((JTextField) key.getSource()).getText(); Vector list = getFilteredList(text); if (nempty(list)) { cb.setModel(new DefaultComboBoxModel(list)); cb.setSelectedIndex(-1); tf.setText(text); cb.showPopup(); } else cb.hidePopup(); } public Vector getFilteredList(String text) { return emptyAfterTrim(text) ? vector : new Vector(scoredSearch(text, vector)); } } } static public class ReverseChain implements Iterable { public A element; public ReverseChain prev; public int size; public ReverseChain() { } public ReverseChain(ReverseChain prev, A element) { this.element = element; this.prev = prev; if (prev == null) size = 1; else { prev.check(); size = prev.size + 1; } } public void check() { if (size < 1) throw fail("You called the ReverseChain default constructor. Don't do that"); } public String toString() { return str(toList()); } public ArrayList toList() { check(); ArrayList l = emptyList(size); for (int i = 0; i < size; i++) l.add(null); int i = size; ReverseChain c = this; while (c != null) { l.set(--i, c.element); c = c.prev; } return l; } public Iterator iterator() { return toList().iterator(); } } static public class DynamicVStack extends DynamicStack { transient public IF0 _componentConstraints; public GridBagConstraints _componentConstraints() { return _componentConstraints != null ? _componentConstraints.get() : _componentConstraints_base(); } final public GridBagConstraints _componentConstraints_fallback(IF0 _f) { return _f != null ? _f.get() : _componentConstraints_base(); } public GridBagConstraints _componentConstraints_base() { return gridBagConstraints_vstack_1(spacing); } public GridBagConstraints _fillerConstraints() { return gridBagConstraints_vstack_rest(); } } static public class WeakIdentityHashSet extends AbstractSet { public Map map = newWeakIdentityHashMap(); public int size() { return map.size(); } public Iterator iterator() { return keys(map).iterator(); } public boolean contains(Object o) { return map.containsKey(o); } public boolean add(A a) { return map.put(a, Boolean.TRUE) != null; } public boolean remove(Object o) { return map.remove(o) != null; } public Object mutex() { return collectionMutex(map); } } static public File prepareFile(File file) { return mkdirsForFile(file); } static public File prepareFile(File dir, String name) { return mkdirsForFile(newFile(dir, name)); } static public String md5OfBufferedImage(BufferedImage img) { return img == null ? null : rgbMD5(new RGBImage(img)); } static public void setSelectedIndex(final JList l, final int i) { if (l != null) { swing(() -> { l.setSelectedIndex(i); }); } } static public void setSelectedIndex(final JComboBox cb, final int i) { if (cb != null) { swing(() -> { cb.setSelectedIndex(i); }); } } static public void copyArrayToVector(Object[] array, Vector v) { v.clear(); v.addAll(toList(array)); } static public void swing_standardTabBehavior(KeyEvent key) { if ((key.getModifiers() & ActionEvent.SHIFT_MASK) != 0) KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent(); else KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(); } static public boolean emptyAfterTrim(String s) { return empty(trim(s)); } static public List scoredSearch(String query, Iterable data) { Map scores = new HashMap(); List searchTerms = scoredSearch_prepare(query); if (empty(searchTerms)) return asList(data); for (String s : data) { int score = scoredSearch_score(s, searchTerms); if (score != 0) scores.put(s, score); } return keysSortedByValuesDesc(scores); } static public GridBagConstraints gridBagConstraints_vstack_1(int spacing) { return gridBagConstraints_vstack_1(spacing / 2, spacing / 2); } static public GridBagConstraints gridBagConstraints_vstack_1(int spacingTop, int spacingBottom) { GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.insets = new Insets(spacingTop, 0, spacingBottom, 0); return gbc; } static public GridBagConstraints gridBagConstraints_vstack_rest() { GridBagConstraints gbc = gridBagConstraints_vstack_1(0); gbc.weighty = 1; return gbc; } static public WeakIdentityHashMap newWeakIdentityHashMap() { return new WeakIdentityHashMap(); } static public String rgbMD5(RGBImage img) { return md5OfRGBImage(img); } static public List keysSortedByValuesDesc(final Map map) { List l = new ArrayList(map.keySet()); sort(l, mapComparatorDesc(map)); return l; } static public Comparator mapComparatorDesc(final Map map) { return new Comparator() { public int compare(A a, A b) { return cmp(map.get(b), map.get(a)); } }; } }