//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 java.awt.datatransfer.StringSelection; import java.text.*; import java.text.SimpleDateFormat; import javax.swing.undo.UndoManager; import org.eclipse.collections.impl.map.mutable.primitive.*; import org.eclipse.collections.impl.set.mutable.primitive.*; import org.eclipse.collections.api.tuple.primitive.*; import org.eclipse.collections.api.iterator.*; import java.nio.charset.Charset; import java.text.NumberFormat; import java.util.TimeZone; import javax.imageio.metadata.*; import javax.imageio.stream.*; import java.awt.geom.*; import java.nio.file.Files; import java.nio.file.Path; import javax.swing.border.*; import javax.swing.event.AncestorListener; import javax.swing.event.AncestorEvent; import javax.swing.Timer; import java.awt.datatransfer.*; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.util.function.BiConsumer; import java.util.function.BiFunction; import javax.swing.Icon; 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 java.awt.dnd.*; import java.awt.image.DataBufferByte; import java.util.jar.*; import static x30_pkg.x30_util.VF1; import x30_pkg.x30_util.DynamicObject; import x30_pkg.x30_util.BetterThreadLocal; public class utils { 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 __16 = lock; lock(__16); try { if (loaded == 0) { value = make(); changeCount++; loaded = sysNow(); } return value; } finally { unlock(__16); } } public void clear() { Lock __17 = lock; lock(__17); try { if (debug && loaded != 0) print("Clearing cache"); value = null; changeCount++; loaded = 0; } finally { unlock(__17); } } public void clear(double seconds) { Lock __18 = lock; lock(__18); try { if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000) clear(); } finally { unlock(__18); } } public void set(A a) { Lock __19 = lock; lock(__19); try { value = a; ++changeCount; loaded = sysNow(); } finally { unlock(__19); } } public A make() { return (A) callF(maker); } } static abstract public class DynModule extends DynamicObject implements Enterable, ChangeTriggerable { 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, __32 -> cancelTimerOrInterruptThread(__32)); 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 __22 : _entrySet(getAndClearMap(timers))) { Object timer = __22.getKey(); IVF1 closerHelper = __22.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 __28 = enter(); try { try { if (eq(get(this, name), value)) return false; } catch (Throwable __e) { pcallFail(__e); } return setField_noCheck(name, value, noPersist); } finally { _close(__28); } } 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 __29 = enter(); try { setOpt(this, name, value); pcallFAll(onFieldChange, name); if (!noPersist && dm_isPersistentField(me(), name)) _change(); return true; } finally { _close(__29); } } 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 void onChange(Runnable r) { Lock __24 = lock; lock(__24); try { if (onChange == null) onChange = synchroList(); addIfNotThere(onChange, r); } finally { unlock(__24); } } public void removeChangeListener(Runnable r) { remove(onChange, r); } public void onFieldChange(VF1 r) { Lock __25 = lock; lock(__25); try { if (onFieldChange == null) onFieldChange = synchroList(); addIfNotThere(onFieldChange, r); } finally { unlock(__25); } } public void removeFieldChangeListener(VF1 r) { remove(onFieldChange, r); } public void onChangeAndNow(Runnable r) { onChange(r); callF(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 __30 = enter(); try { update(); } finally { _close(__30); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter(); update();"; } }); return rstUpdate; } public Q q() { AutoCloseable __31 = enter(); try { if (q == null) { Lock __26 = lock; lock(__26); try { if (q == null) q = dm_startQ(); } finally { unlock(__26); } } return q; } finally { _close(__31); } } 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(); } } 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 __39 = enter(); try { dm_clearModulePrintLog(); } finally { _close(__39); } } 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 __36 = updatePrintLog_lock; lock(__36); 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(__36); } }); } 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(__75 -> strOrEmpty(__75), 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 __43 = enter(); try { setModuleName(programTitle() + " (" + count() + ")"); } finally { _close(__43); } } public JComponent visualize() { List l = map(itemToMap, data); table = dataToTable_uneditable(sexyTable(), l); onDoubleClickOrEnter(table, new VF1() { public void get(Integer row) { try { AutoCloseable __44 = enter(); try { A a = _get(data, row); if (a != null) onDoubleClick(a); } finally { _close(__44); } } 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 __45 = 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(__45); } } 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 __50 = enter(); try { try { File f = autoSaveImageFile(); if (fileExists(f)) { print("Auto-loading " + f); setImage(loadImage2(f), true); } } catch (Throwable __e) { pcallFail(__e); } } finally { _close(__50); } } public void autoSaveNow() { AutoCloseable __51 = enter(); try { try { File f = autoSaveImageFile(); savePNG(f, image); infoBox("Auto-saved " + renderFileInfo(f)); } catch (Throwable __e) { pcallFail(__e); } } finally { _close(__51); } } 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 __52 = tempSetField(imageSurface, "onNewImage", null); try { imageSurface.setImage(image); if (zoomToWindowOnSetImage) imageSurface.zoomToWindow(); if (autoSaveToDisk && !loadingFromAutoSave) autoSaveNow(); } finally { _close(__52); } } 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 __57 = enter(); try { if (list != null || calculateWhenHidden) fillListWithStrings(list, results = calc()); } finally { _close(__57); } } 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() { return (Concepts) call(assertNotNull("No real MC", realMC()), "db_mainConcepts"); } 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 boolean readLocally_useTwoThreads = true; 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; CloseablesHolder ch = new CloseablesHolder(); try { Producer tokenizer = gzFileTokenReaderForUnstruct(structureGZFile, ch); if (readLocally_useTwoThreads) { tokenizer = moveProducerToNewThread(tokenizer, ch); } Object o = unstructure_tok(tokenizer, allDynamic, readLocally2_classFinder.get()); readLocally_set(obj, variableName, o); return; } finally { _close(ch); } } 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 > 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 > IterableIterator nestedI(Iterable c, F1 makeInnerIterator) { return nestedIterator(c, makeInnerIterator); } static public > IterableIterator nestedI(Collection c, IF1 makeInnerIterator) { return nestedIterator(c, makeInnerIterator); } static public > IterableIterator nestedI(Iterator it1, IF1 makeInnerIterator) { return nestedIterator(it1, makeInnerIterator); } static public > IterableIterator nestedI(Iterator it1, F1 makeInnerIterator) { return nestedIterator(it1, makeInnerIterator); } static public > IterableIterator nestedI(IF1 makeInnerIterator, Iterator it1) { return nestedIterator(makeInnerIterator, it1); } static public > IterableIterator nestedI(IF1 makeInnerIterator, Collection l) { return nestedIterator(makeInnerIterator, l); } static public Map nonStaticNonTransientFieldObjects_cachedArray_cache = dangerousWeakMap(); static public Field[] nonStaticNonTransientFieldObjects_cachedArray(Object o) { if (o == null) return null; Class c = _getClass(o); Field[] fields = nonStaticNonTransientFieldObjects_cachedArray_cache.get(c); if (fields == null) { List l = new ArrayList(); Class _c = c; do { for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) == 0) l.add(makeAccessible(f)); _c = _c.getSuperclass(); } while (_c != null); fields = toArrayOfType(Field.class, l); nonStaticNonTransientFieldObjects_cachedArray_cache.put(c, fields); } return fields; } static public List myInnerClasses_list = litlist(null, "IVarWithNotify", "StructureStringIndenter", "ImageSurface", "ConceptClassesDependentValue", "talkToThisVM_IO", "IFieldIndex", "SimpleLiveValue", "SingleComponentPanel", "OnNewDialog", "Stringable", "IWebRequest", "AbstractLayoutManager", "IterableIterator", "betterCIComparator_C", "SynchronizedArrayList", "MakesBufferedImage", "CloseableIterableIterator", "ForEach_vstack", "CustomBotStep", "Enterable", "Matches", "WithTimestamp", "HCRUD_Concepts", "TableWithTooltips", "allSpreads_StackEntry", "Dyn_FieldWatcher", "DoubleRect", "Surface", "Q", "FlexThreadLocal", "OrError", "EvtCallSubroutine", "SnippetTitles", "RestartableCountdown", "VStack", "ReliableSingleThread_Multi", "TransientObject", "CompactHashSet", "MultiSetMapWithTopTen", "Htmlable", "DynObjectTable", "VarContext", "IConceptCounter", "ActiveSequence", "BetterLabel", "componentPopupMenu_Adapter", "BWIntegralImage", "IVStack", "UndoState", "FailedRule", "IHasTokenRangeWithSrc", "JSection", "ValueConverterForField", "IF0WithChangeListeners", "FullChange", "MultiSleeper", "ReliableSingleThread", "ListAndIndex", "WithPollValue", "Eval", "DoubleBuffer", "DeliveredDomain", "ProgramScan", "allSpreads_Data", "BotClearStack", "F0", "Snippet", "F1", "DynImageSurface", "RandomAccessAbstractList", "F2", "RGB", "F3", "BoolVar", "WidthAndHeightFinal", "IHasGlobalID", "DefaultValueConverterForField", "StringBufferWithMaxSize", "AbstractAvatar", "ConceptFieldIndexCI", "tablePopupMenu_Maker", "ShowComboBoxForm", "Cache", "SynchronizedList", "_MethodCache", "PingSourceCancelledException", "Form", "BotOutgoingQuestion", "LiveValue", "BotSaveFeedback", "Eq", "BotNewDialog", "Language", "MMOPattern", "proxy_InvocationHandler", "MetaTransformer", "UserPost", "MethodMaker", "HTMLFramer1", "JavaXClassLoader", "FlexibleRateTimer", "RuleWithParams", "Avatar", "TransferableImage", "Sleeping", "ConversationFeedback", "IConceptIndex", "Updateable", "WebPushSubscription", "BotSendTyping", "MRUAndAllTimeTop_optimized", "SubList", "SecretValue", "GenericArrayTypeImpl", "HTMLAceEditor", "AppendableChain", "CompactLinkedHashSet", "FixedRateTimer", "Settings", "CMissingObject", "OnUserMessage", "GrabbableRGBBytePixels", "MethodOnObject", "XRef", "HTMLPopDownButton", "IntegralImage", "IIntPred", "SynchronizedNavigableSet", "Chain", "CountryDialCode", "MechListDependentCache", "ThreadPool", "JS", "Conversation", "IDialogHandler", "IHasChangeListeners", "CreatedDeletedChanged", "Worker", "ScheduledActionOnConversation", "ScoredSearcher", "IIntegralImage", "DialogIO", "SimpleCRUD", "SynchronizedArrayList_Base", "IAutoCloseableF0", "ISleeper_v2", "AlphanumComparator", "AbstractBotImage", "PersistableThrowable", "talkToSubBot_IO", "IDoublePt", "HasIndex", "WidthAndHeight", "ISubList", "Responder", "TableSearcher", "IMultiSet", "JavaXHyperlinker", "mapI_It", "ConceptsChange", "TokCondition", "BotGoBack", "listPopupMenu_Maker", "ConceptFieldIndexCI_certainValues", "SynchronizedCollection", "UploadedImage", "HTMLForm", "ImageSurfaceSelector", "Sentence", "Concept", "IRGBImage", "LASToByteCode", "HAbstractRenderable", "RegisteredReference", "TreeMultiMap", "ConceptsShadowLogger", "ContentsIndexedList", "FileTransferable", "ClassMaker", "IContentsIndexedList2", "EvtMatchedUserKeyword", "And", "Value", "Evt", "OKOrError", "FileBasedLock", "Symbol", "IMeta", "BetterThread", "InputHandled", "Lowest", "Action_NextStep", "HTMLPaginator", "TokenIndexedList3", "UploadedSound", "ChangeTrigger", "DynPrintLog", "MinimalChain", "SynchronizedSortedSet", "Explain", "IBest", "jLiveValueSection_class", "BotDoNothing", "RealmCopy", "DoubleRange", "NotTooOften", "Exp", "DynamicMethods", "BotImage", "Meta", "JVMStackCellType", "RandomAvatar", "InMemoryClassLoader", "DefunctClassLoader", "ConceptsRefChecker", "IntVar", "BWImage", "PingSource", "BotRandomAction", "ConceptFieldIndexDesc", "HasTokenRangeWithSrc", "VarMatches", "DynModule", "ConceptL", "Rect", "Pt", "BufferedImageWithMeta", "RemoteDB", "RiddleWithSolution", "SynchronizedNavigableMap", "Concepts", "RC", "PCallPolicy", "Hasher", "IBWIntegralImage", "ExpiringMap2", "PostReferenceable", "PNGFile", "getOpt_Map", "IFieldsToList", "IResponder", "IInputHandler", "structure_Data", "jsonDecode_Y", "IVar", "LazyVar", "DynPrintLogAndEnabled", "TokenRangeWithSrc", "ConceptWithGlobalID", "DynCalculatedList", "HPopDownButton", "ParameterizedTypeImpl", "Timestamp", "GazelleV_LeftArrowScriptParser", "ILASClassLoader", "DoLater", "ConceptFieldIndexBase", "LongRange", "RandomAccessSubList", "OnEnclosingScrollPaneResize", "BreadthFirstPathFinder_withLinkType", "MultiSet", "OptimizedMultiSet", "BotStep", "T3", "IResourceHolder", "CloseablesHolder", "StringTree2", "HCRUD_Data", "SteppableAndIF0", "IntRange", "UnsynchronizedCompactHashSet", "JavaXClassLoaderWithParent2", "InternationalPhoneValidator", "ScheduledAction", "RGBImage", "SmartTimerTask", "ConceptFieldIndexCI_withTopTen", "Visitable", "ConceptDelete", "BotSwitchLanguage", "Literal", "unstructure_Handler", "IMultiMap", "IF1_IntToInt", "IBWImage", "PtInComponent", "AutoComboBox", "ConceptFieldIndex", "Sentence2", "BotMessage", "GrabbableGrayPixels", "IHasBackRefs", "MapI", "BotIdleMode", "IfThen", "unstructure_Receiver", "Not", "IF0", "BaseXRef", "IF2", "IF1", "IVF3", "IVF1", "IVF2", "Domain", "IPartialFieldIndex", "Options", "IConcept", "HDivWithVerticalExpandButton", "structure_ClassInfo", "Func", "TimedCache", "ISetAndGet", "LASClassDef", "QuickException", "SynchronizedSet", "DialogHandler", "_PrintIndent", "JavaScript", "Steppable", "G2Drawable", "Pair", "ExecutedStep", "ImageSurfaceMouseHandler", "Swingable", "BotPause", "UniqueString", "LineAndColumn", "ChangeTriggerable", "GrabbableIntPixels", "IIVirtualClip", "SimpleCircularBuffer", "UploadedFile", "ReverseChain", "ConceptCreate", "Seconds", "TokenRange", "SynchronizedSortedMap", "HInitWebSocket", "LASValueDescriptor", "MultiSetMap", "Var", "ClassNameResolver", "Scorer", "ITokCondition", "PopupMenuMaker", "CountingOutputStream", "CancelToCancelPoint", "SynchronizedRandomAccessList", "ConceptChange", "CompactAbstractMap", "ExpNot", "Fail", "ResolvableLASClass", "ISetter", "IResolvableClass", "Out", "ScannedBot", "GazelleV_LeftArrowScript", "MechMode", "CompactHashMap", "ConceptID", "Complex", "MultiMap", "HTMLTabs", "CriticalAction", "IResourceLoader", "WeakHasherMap", "Lead", "Either", "SortedArrayBasedMap", "BotSaveLead", "CompilerBot", "Msg", "JMenuScroller", "MRUCache", "TransitiveHull", "Scored", "VF2", "HTML", "RightAlignedLine", "GlobalID", "HCRUD", "ConceptFieldIndexBase_certainValues", "findCodeTokens_Matcher", "Unstructurer", "IntSize", "tempAdd_undo", "EvtJumpTo", "JFastLogView_noWrap", "SimpleLeftToRightParser", "UserKeyword", "IRef", "Sequence", "Flag", "generalizedCIComparator_C", "VStackComputableWithStep", "BotEndConversation", "Producer", "DynNewBot2", "talkTo_IO", "DynGazelleRocks", "User", "FlexibleVarContext", "Timed", "UpdateTrigger", "IContentsIndexedList", "IMakeEmptyClone", "LetterLayout", "AuthedDialogID", "ConceptShadow", "SynchronizedMap", "Decolorizer", "WrappedMap", "JavaXClassLoaderWithParent", "Transformable", "CannedAnswer", "CancelPoint", "FieldIndicator", "UserCreatedObject", "Android3", "replaceKeywordBlock_dyn_IReplacer"); 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 void makeAndCall_setInitInThread(Object f) { makeAndCall_initChild.set(f); } 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 addPrefixOptIfNempty(String prefix, String s) { return addPrefixIfNotEmpty2(prefix, s); } static public List callTokenizer(Object tokenizer, String s) { return (List) callF(tokenizer, s); } static public String dropStuffBeforeVerticalBar(String s) { int i = indexOf(s, '|'); return i < 0 ? s : substring(s, i + 1); } 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 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 UnsupportedOperationException unsupportedOperation() { throw new UnsupportedOperationException(); } 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 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 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 Object subBot_serveJavaScript(String html) { return subBot_serveWithContentType(html, "text/javascript"); } static public String dm_require(String moduleLibID) { return dm_makeModule(moduleLibID); } 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 HashSet litset(A... items) { return lithashset(items); } static public String spaceRoundBracketed(String s) { return spacePlusRoundBracketedIfNempty(s); } 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 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 String pnlToStringWithEmptyLines(Iterable l) { return pnlToString(map(l, o -> o + "\n")); } static public int toInt_checked(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } static public String spanTitle(String title, Object contents) { return empty(title) ? str(contents) : span(contents, "title", title); } static public Object[] litObjectArray(Object... l) { return l; } 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 psI_str(String snippetID) { return str(psI(snippetID)); } static public String loadJQuery2() { return ""; } 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 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 synchroTreeSet() { return Collections.synchronizedSet(new TreeSet()); } static public Set synchroTreeSet(TreeSet set) { return Collections.synchronizedSet(set); } static public A replaceIfEqual(A a, A b, A c) { return eq(a, b) ? c : a; } static public String codePointToString(int codePoint) { return new String(Character.toChars(codePoint)); } 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 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 buttonsInGroup(ButtonGroup g) { if (g == null) return ll(); return asList(g.getElements()); } 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 A[] itemPlusArray(A a, A[] l) { return singlePlusArray(a, l); } static public String nPosts(long n) { return n2(n, "post"); } static public String nPosts(Collection l) { return nPosts(l(l)); } static public String nPosts(Map map) { return nPosts(l(map)); } static public TokCondition toTokCondition(ITokCondition condition) { return condition == null ? null : condition instanceof TokCondition ? (TokCondition) condition : new TokCondition() { public boolean get(List tok, int i) { return condition.get(tok, i); } }; } static public File associatedInfosFile(File f) { return replaceExtension(f, ".infos"); } static public String or2_trim(String a, String b) { a = trim(a); if (nempty(a)) return a; return trim(b); } static public String or2_trim(String a, String b, String c) { return or2_trim(or2_trim(a, b), c); } static public A lastThat(List l, Object pred) { for (int i = l(l) - 1; i >= 0; i--) { A a = l.get(i); if (checkCondition(pred, a)) return a; } return null; } static public A lastThat(Object pred, List l) { return lastThat(l, pred); } static public A lastThat(IF1 pred, List l) { return lastThat((Object) pred, l); } static public A lastThat(List l, IF1 pred) { return lastThat(pred, l); } static public String addPrefix(String prefix, String s) { return s.startsWith(prefix) ? s : prefix + s; } static public String targetBlank(String link, Object contents, Object... params) { return hrefBlank(link, contents, params); } static public boolean isCurlyBraced(String s) { List tok = tok_combineCurlyBrackets_keep(javaTok(s)); return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}"); } static public void setComponentID(Component c, String id) { if (c != null) componentID_map.put(c, id); } static public String b(Object contents, Object... params) { return fulltag("b", contents, params); } 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 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 void closeRandomAccessFile(RandomAccessFile f) { if (f != null) try { f.close(); callJavaX("dropIO", f); } catch (Throwable e) { printStackTrace(e); } } static public String i(String s, Object... params) { return tag("i", s, params); } 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 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 List javaTokPlusBrackets2(String s) { return tok_combineRoundCurlySquareBrackets_keep(javaTok(s)); } static public String p(Object contents, Object... params) { return hfulltag("p", contents, params) + "\n"; } static public String p() { return p(""); } static public List reverseInPlace(List l) { return reverseList(l); } static public String nChanges(long n) { return n2(n, "change"); } static public String nChanges(Collection l) { return nChanges(l(l)); } static public GlobalID asGlobalID(String id) { return id == null ? null : new GlobalID(id); } 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 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 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 List tok_splitAtAsterisk(String s) { return tok_splitAtAsterisk(javaTokWithAllBrackets_cached(s)); } static public List tok_splitAtAsterisk(List tok) { return splitAtTokens(tok, "*"); } 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 startsWithIgnoreCase(String a, String b) { return regionMatchesIC(a, 0, b, 0, b.length()); } static public String addParamToURL(String url, Map params) { return appendQueryToURL(url, params); } static public String addParamToURL(String url, Object... data) { return appendQueryToURL(url, data); } static public boolean isJavaxModuleSnippetType(int type) { return type == snippetType_javaxModule() || type == snippetType_javaxDesktopModule(); } 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 Iterator emptyIterator() { return Collections.emptyIterator(); } static public Boolean trueOrNull(Boolean b) { return eq(b, false) ? null : b; } 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 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 void markAsSrcLib(String snippetID) { saveTextFile(javaxCodeDir("srclibs/" + psI(snippetID)), ""); } static public void setConsoleInput(String text) { consoleSetInput(text); } static public String jsDropTrailingComments(String s) { return javaTokDropTrailingN(s); } 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 boolean empty(Collection c) { return c == null || c.isEmpty(); } static public boolean empty(Iterable c) { return c == null || !c.iterator().hasNext(); } static public boolean empty(CharSequence s) { return s == null || s.length() == 0; } static public boolean empty(Map map) { return map == null || map.isEmpty(); } static public boolean empty(Object[] o) { return o == null || o.length == 0; } static public boolean empty(BitSet bs) { return bs == null || bs.isEmpty(); } static public boolean empty(Object o) { if (o instanceof Collection) return empty((Collection) o); if (o instanceof String) return empty((String) o); if (o instanceof Map) return empty((Map) o); if (o instanceof Object[]) return empty((Object[]) o); if (o instanceof byte[]) return empty((byte[]) o); if (o == null) return true; throw fail("unknown type for 'empty': " + getType(o)); } static public boolean empty(Iterator i) { return i == null || !i.hasNext(); } static public boolean empty(double[] a) { return a == null || a.length == 0; } static public boolean empty(float[] a) { return a == null || a.length == 0; } static public boolean empty(int[] a) { return a == null || a.length == 0; } static public boolean empty(long[] a) { return a == null || a.length == 0; } static public boolean empty(byte[] a) { return a == null || a.length == 0; } static public boolean empty(short[] a) { return a == null || a.length == 0; } static public boolean empty(MultiSet ms) { return ms == null || ms.isEmpty(); } static public boolean empty(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(DoubleBuffer 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 cancelAndInterruptThread(Thread t) { if (t == null) return; cancelThread(t); t.interrupt(); } 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 Comparator caseInsensitiveComparator() { return betterCIComparator(); } 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 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 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 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 List syncCloneAndClearList(Collection l) { if (l == null) return emptyList(); synchronized (collectionMutex(l)) { List l2 = cloneList(l); l.clear(); return l2; } } static public boolean containsAngleBracketVars(String s) { List tok = javaTokWithAngleBrackets(s); return nempty(indicesOfAngleBracketVars(tok)); } 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 hasMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args) != null; } 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 prependIfNempty(String prefix, String s) { return empty(s) ? unnull(s) : prefix + s; } static public java.lang.management.OperatingSystemMXBean osMXBean() { return ManagementFactory.getOperatingSystemMXBean(); } 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 byte[] toUtf8(String s) { try { return s.getBytes(utf8charset()); } catch (Exception __e) { throw rethrow(__e); } } static public Object[] dropEntryFromParams(Object[] params, int i) { int n = l(params); if (i < 0 || i >= n) return params; if (n == 2) return null; Object[] p = new Object[n - 2]; System.arraycopy(params, 0, p, 0, i); System.arraycopy(params, i + 2, p, i, n - i - 2); return p; } static public boolean 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 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 String stringUnless(boolean b, String s) { return b ? "" : s; } 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 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 String getTranspiledStandardFunctionsIfCached(TreeSet functionSet) { try { File f = transpiledStandardFunctions_file(functionSet); return loadTextFile(f); } catch (Throwable __e) { return null; } } static public Set reflection_classesNotToScan_value = litset("jdk.internal.loader.URLClassPath"); static public Set reflection_classesNotToScan() { return reflection_classesNotToScan_value; } 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); } 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 String ymd_minus_hm() { return ymd() + "-" + hhmm(); } static public com.sun.management.OperatingSystemMXBean advancedOSMXBean() { return optCast(com.sun.management.OperatingSystemMXBean.class, osMXBean()); } 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 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 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 String hselect(String name, Map map, Object... params) { return hselect(map, paramsPlus_skipFirst(params, "name", name)); } static public String hselect(Map map, Object... params) { StringBuilder buf = new StringBuilder(); String selected = null; if (odd(l(params))) { selected = str(first(params)); params = dropFirst(params); } int i = indexOf(params, "allowEmpty"); if (even(i)) { buf.append("\n"); params[i] = params[i + 1] = null; } if (nempty(map)) for (Object key : keys(map)) { Object value = map.get(key); String k = str(key); buf.append(tag("option", htmlencode(str(or(value, ""))), "value", k, "selected", eq(selected, k) ? "selected" : null)).append("\n"); } return tag("select", buf, params) + "\n"; } static public String firstToken(String s) { return firstJavaToken(s); } static public String firstToken(List tok) { return get(tok, 1); } 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 String htitle_noEncode(String title) { return tag("title", title); } 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 List dm_listStems() { return (List) dm_callOS("onModules"); } static public Integer find3_levenWithSwapsDistance(String pat, String input) { List tokPat = parse3_cachedPattern(pat); List tok = parse3_cachedInput(input); int end = tok.size() - tokPat.size() + 1; Integer min = null; for (int idx = 0; idx < end; idx += 2) { int score = 0; for (int i = 1; i < tokPat.size(); i += 2) { String p = tokPat.get(i), t = tok.get(idx + i); score += levenWithSwapsIC(p, t); } min = min_withNull(min, score); } return min; } 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 String addSlash(String s) { return empty(s) || s.endsWith("/") ? s : s + "/"; } static public String dm_makeModule(String moduleLibID) { return (String) dm_callOS("makeModule", moduleLibID); } 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 int toIntPercent(double ratio) { return roundToInt(ratio * 100); } static public int toIntPercent(float ratio) { return toIntPercent((double) ratio); } static public String containerTag(String tag) { return containerTag(tag, ""); } static public String containerTag(String tag, Object contents, Object... params) { String openingTag = hopeningTag(tag, params); String s = str(contents); return openingTag + s + ""; } static public char charAt(String s, int i) { return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0'; } 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 List collectSorted(Iterable c, String field) { return sorted(collect(c, field)); } static public List collectSorted(String field, Iterable c) { return collectSorted(c, field); } static public StringBuilder stringBuilder(String s) { return new StringBuilder(unnull(s)); } static public String regexpCaseInsensitivePrefix() { return "(?i)"; } static public List tok_identifiersInOrder(String s) { return filter(__76 -> isIdentifier(__76), javaTokC(s)); } static public List tok_identifiersInOrder(List tok) { return filter(__77 -> isIdentifier(__77), codeTokens(tok)); } static public boolean getSnippetTitles_verbose = false; static public Map getSnippetTitles(Collection ids) { try { if (empty(ids)) return new HashMap(); String url = tb_mainServer() + "/tb-int/get-titles.php"; String ids2 = join(" ", parseSnippetIDs(ids)); return trimValues(transformKeys(jsonDecodeMap(doPost(mapPlus(standardCredentialsMap(), "ids", ids2), url)), new F1() { public Object get(String id) { try { return fsI(id); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "fsI(id)"; } })); } catch (Exception __e) { throw rethrow(__e); } } static public A grabValueAndCancel(VF1> r) { Var var = new Var(); withCancelPoint(new VF1() { public void get(CancelPoint cp) { try { callF(r, new VF1() { public void get(A a) { try { var.set(a); cancelTo(cp); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var.set(a); cancelTo(cp)"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(r, voidfunc(A a) { var.set(a); cancelTo(cp) });"; } }); return var.get(); } static public JButton jPopDownButton_noText(final Object... menuParams) { return toolTip("Additional commands", jPopDownButton("", menuParams)); } static public String hhead_title(String title) { return hhead(htitle(title)); } static public void printShortException(Throwable e) { print(exceptionToStringShort(e)); } static public void printShortException(String s, Throwable e) { print(s, exceptionToStringShort(e)); } static public String hcrud_mergeTables(String table1, String table2, String connector) { List tok1 = htmlTok(table1), tok2 = htmlTok(table2); List tbl1 = first(findContainerTag(tok1, "table")); List tbl2 = first(findContainerTag(tok2, "table")); if (tbl1 == null) return table2; if (tbl2 == null) return table1; List> rows1 = findContainerTag(tbl1, "tr"); List> rows2 = findContainerTag(tbl2, "tr"); print("rows1: " + l(rows1) + ", rows2: " + l(rows2)); int nRows = max(l(rows1), l(rows2)); List rows = new ArrayList(); for (int i = 0; i < nRows; i++) { List row1 = dropFirstTwoAndLastTwo(get(rows1, i)); List row2 = dropFirstTwoAndLastTwo(get(rows2, i)); row2 = dropFirst(row2, indexOfIC(row2, "") + 1); rows.add(tr(join(concatLists(row1, ll(td(connector)), row2)))); } replaceTokens(tbl1, 2, l(tbl1) - 2, lines(rows)); return join(tok1); } 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 javaTokNPunctuation_plusAsterisk(String s) { List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { int j = i; String t; while (j < l(tok) && l(t = tok.get(j)) == 1 && !Character.isLetterOrDigit(t.charAt(0)) && t.charAt(0) != '*') j += 2; if (j > i) replaceSubList(tok, i - 1, j, ll(joinSubList(tok, i - 1, j))); } return tok; } static public String[] asStringArray(Collection c) { return toStringArray(c); } static public String[] asStringArray(Object o) { return toStringArray(o); } 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 dropTrailingSlash(String s) { return dropSuffix("/", s); } 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 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 String tok_unCurlyBracket(String s) { return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s; } static public void dbIndexing(Object... params) { db(); indexConceptFields(params); } 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 List text_multipleChoiceSplit(String input, String multipleChoiceSeparator) { return trimAll(splitAt(input, dropSpaces(multipleChoiceSeparator))); } 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 Object[] html_massageAutofocusParam(Object[] params) { Object autofocus = optPar("autofocus", params); return changeParam(params, "autofocus", eqOneOf(autofocus, html_valueLessParam(), true, 1, "1", "autofocus") ? html_valueLessParam() : null); } 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 String defaultTimerName_name; static public String defaultTimerName() { if (defaultTimerName_name == null) defaultTimerName_name = "A timer by " + programID(); return defaultTimerName_name; } static public long toK(long l) { return (l + 1023) / 1024; } 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 Object dm_callModule(Object moduleOrID, String method, Object... args) { Object mod = dm_getModule(moduleOrID); if (mod == null) return null; AutoCloseable __1 = dm_enter(mod); try { return call(mod, method, args); } finally { _close(__1); } } static public void logStructure(File logFile, Object o) { logQuoted(logFile, structure(o)); } static public void logStructure(String fileName, Object o) { logStructure(getProgramFile(fileName), o); } static public void logStructure(String progID, String fileName, Object o) { logStructure(getProgramFile(progID, fileName), o); } static public void dm_assertFirstSibling() { if (!dm_isFirstSiblingModule(dm_current_mandatory_generic())) throw fail("Don't start this module (" + dm_moduleLibID() + ") multiple times. This instance will exit."); } 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 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 String hstyle_sourceCodeLikeInRepo() { return "padding-left: 1em; padding-top: 0.5em; padding-bottom: 0.5em; background-color: #EEEEEE; border-style: solid; border-color: #666666; border-width: 1px 0px 1px 0px;"; } 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 volatile public boolean ping_pauseAll = false; static public int ping_sleep = 100; static volatile public boolean ping_anyActions = false; static public Map ping_actions = newWeakHashMap(); static public ThreadLocal ping_isCleanUpThread = new ThreadLocal(); static public boolean ping(PingSource pingSource) { return ping(); } static public boolean ping() { newPing(); if (ping_pauseAll || ping_anyActions) ping_impl(true); return true; } static public boolean ping_impl(boolean okInCleanUp) { try { if (ping_pauseAll && !isAWTThread()) { do Thread.sleep(ping_sleep); while (ping_pauseAll); return true; } if (ping_anyActions) { if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get())) failIfUnlicensed(); Object action = null; synchronized (ping_actions) { if (!ping_actions.isEmpty()) { action = ping_actions.get(currentThread()); if (action instanceof Runnable) ping_actions.remove(currentThread()); if (ping_actions.isEmpty()) ping_anyActions = false; } } if (action instanceof Runnable) ((Runnable) action).run(); else if (eq(action, "cancelled")) throw fail("Thread cancelled."); } return false; } catch (Exception __e) { throw rethrow(__e); } } static public 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 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 _eq(Object a, Object b) { return eq(a, b); } static public String formatDateAndTime(long timestamp) { return formatDate(timestamp); } static public String formatDateAndTime() { return formatDate(); } static public List mapNonCodeTokens(Object f, List l) { List out = emptyList(l); for (int i = 0; i < l(l); i++) { Object o = l.get(i); out.add(even(i) ? callF(f, o) : o); } return out; } static public List mapNonCodeTokens(List l, Object f) { return mapNonCodeTokens(f, l); } static public List mapNonCodeTokens(List tok, IF1 f) { return mapNonCodeTokens(tok, (Object) f); } static public List mapNonCodeTokens(IF1 f, List tok) { return mapNonCodeTokens(tok, f); } static public int getScreenWidth() { return getScreenSize().width; } 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 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 ahref_onClick(String js, Object contents, Object... params) { return ahref_js(js, contents, params); } static public String defaultVMArgs() { return javaxDefaultVMArgs(); } 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 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 int localMonth(long time) { return parseInt(simpleDateFormat_local("MM").format(time)); } static public int localMonth() { return localMonth(now()); } static public String getDBProgramID_id; static public String getDBProgramID() { return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase(); } static public int countConceptsCI(Concepts cc, Class c, Object... params) { if (empty(params)) return countConcepts(cc, c); return l(conceptsWhereCI(cc, c, params)); } static public int countConceptsCI(Class c, Object... params) { return countConceptsCI(db_mainConcepts(), c, params); } static public List tok_combineAngleBrackets_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 = findEndOfAngleBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } static public String[] flattenStringArray2(Object... a) { List l = new ArrayList(); if (a != null) for (Object x : a) if (x instanceof String[]) l.addAll(asList((String[]) x)); else if (x instanceof Collection) l.addAll((Collection) x); else l.add(x); return asStringArray(l); } static public String div_center(Object contents, Object... __) { return hcenter3(contents, __); } static public Object safeUnstructureAllowingClasses(String s, Class... allowedClasses) { final Set allowedClassesSet = mapToSet(__78 -> className(__78), allowedClasses); Object classFinder = new F1() { public Object get(String name) { try { if (!allowedClassesSet.contains(name)) throw fail("Class not allowed to unstructure: " + name); return classForName(name); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!allowedClassesSet.contains(name)) fail(\"Class not allowed to unstructure..."; } }; return unstructure(s, false, classFinder); } static public Object getConsoleTextArea_gen() { return getOpt(get(getJavaX(), "console"), "textArea"); } static public List> ai_spreadCertainIndices_2(List tokPat, List tokS, List indices) { int extra = (l(tokS) - l(tokPat)) / 2; if (extra < 0 || empty(indices)) return emptyList(); List> results = new ArrayList(); for (List spread : allSpreads(extra, l(indices))) { List tok = new ArrayList(); int pos = 0, iSpread = 0, iIndices = 0; for (int i = 0; i < l(tokPat); i++) if (!eq(get(indices, iIndices), i)) tok.add(tokS.get(pos++)); else { ++iIndices; int take = spread.get(iSpread++) * 2; tok.add(joinSubList(tokS, pos, pos + take + 1)); pos += take + 1; } results.add(tok); } return results; } static public boolean isJavaxCompilableSnippetTypeExceptInclude(int type) { return isJavaxApplicationSnippetType(type) || isJavaxModuleSnippetType(type) || type == snippetType_dynModule(); } static public String htmlEncode(String s) { return htmlencode(s); } 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 String divUnlessEmpty(String s, Object... params) { return empty(s) ? "" : div(s, params); } 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 putIfNotThere(Map map, A key, B value) { if (map != null && key != null && value != null && !map.containsKey(key)) map.put(key, value); } static public String renderDBLoadTime() { return renderDBLoadTime(db_mainConcepts()); } static public String renderDBLoadTime(Concepts cc) { if (cc == null) return null; return cc.loadTook < 0 ? "unknown" : n2(cc.loadTook) + " ms"; } static public long raf_findBeginningOfLine(RandomAccessFile raf, long pos, int bufSize) { try { byte[] buf = new byte[bufSize]; while (pos > 0) { long start = Math.max(pos - bufSize, 0); raf.seek(start); raf.readFully(buf, 0, (int) Math.min(pos - start, bufSize)); int idx = lastIndexOf_byteArray(buf, (byte) '\n'); if (idx >= 0) return start + idx + 1; pos = start; } return 0; } catch (Exception __e) { throw rethrow(__e); } } static public Map applyFunctionToMapValue(A key, Object f, Map map) { if (map.containsKey(key)) map.put(key, (B) callF(f, map.get(key))); return map; } 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 GlobalID aGlobalIDObjUnlessLoading() { return dynamicObjectIsLoading() ? null : aGlobalIDObj(); } static public Pair uniqCI2(Class c, Object... params) { return uniqCI2(db_mainConcepts(), c, params); } static public Pair uniqCI2(Concepts cc, Class c, Object... params) { params = expandParams(c, params); A x = findConceptWhereCI(cc, c, params); if (x == null) { x = unlisted(c); csetAll(x, params); cc.register(x); return pair(x, true); } return pair(x, false); } 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 String js_setRedirect() { return "$('input[name=redirect]').val(window.location.toString());"; } 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 List synchroLinkedList() { return synchroList(new LinkedList()); } static public Type type_LS() { return new ParameterizedTypeImpl(null, List.class, String.class); } 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(Set s) { return asList(s); } static public ArrayList toList(Iterable s) { return asList(s); } 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 Map> javaTokWithAllBrackets_cached_cache = synchronizedMRUCache(defaultTokenizerCacheSize()); static public List javaTokWithAllBrackets_cached(String s) { List tok = javaTokWithAllBrackets_cached_cache.get(s); if (tok == null) javaTokWithAllBrackets_cached_cache.put(s, tok = javaTokWithAllBrackets(s)); return tok; } static public List unquoteAll(List l) { List t = cloneList(l); for (int i = 0; i < l(t); i++) if (isQuoted(t.get(i))) t.set(i, unquote(t.get(i))); return t; } static public boolean tok_tokenBeforeLonelyReturnValue(List tok, int i) { String t = get(tok, i); if (l(t) == 1 && "{};".contains(t) || eq(t, "else")) return true; if (!eq(t, ")")) return false; int level = 0; while (i > 0) { if (eq(tok.get(i), ")")) ++level; if (eq(tok.get(i), "(")) --level; if (level == 0) return eq(get(tok, i - 2), "if"); i -= 2; } return false; } 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 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 isEitherB(Either e) { return eitherIsB(e); } static public void replaceACCInClassLoader(Object o, AccessControlContext newACC) { } 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 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 File localMechListFile(String listName) { return newFile(localMechListsDir(), uniqueFileNameUsingMD5_80_v2(listName) + ".text"); } static public String dropTags(String html) { return dropAllTags(html); } static public List dropTags(List tok) { return dropAllTags(tok); } 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 Map withoutKey(Map map, A key) { return mapWithoutKey(map, key); } static public Map withoutKey(A key, Map map) { return withoutKey(map, key); } static public DynModule dm_currentModuleMandatory() { return dm_current_mandatory(); } 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(__79 -> isClosingBracket(__79), l); } static public int syncLengthLevel2(Collection l) { int sum = 0; for (Collection c : cloneList(l)) sum += syncL(c); return sum; } static public String roundBracket(String s) { return "(" + s + ")"; } static public String roundBracket(Object s) { return roundBracket(str(s)); } 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 String pageNav2(String baseLink, int count, int value, int step, String nVar, Object... __) { List l = new ArrayList(); baseLink = unnull(baseLink) + (contains(baseLink, "?") ? "&" : "?") + urlencode(nVar) + "="; if (value > 0) l.add(ahref(baseLink + max(0, value - step), stringPar("leftArrow", __, htmlencode(unicode_leftPointingTriangle())))); for (int i = 0; i < count; i += step) { int n = i / step + 1; if (pageNav2_showPage(value, i, step, count)) if (value == i) l.add(b(n)); else l.add(ahref(baseLink + i, n)); } if (value + step < count) l.add(ahref(baseLink + (value + step), stringPar("rightArrow", __, htmlencode(unicode_rightPointingTriangle())))); return p("Pages: " + lines(l)); } static public boolean pageNav2_showPage(int actual, int i, int step, int count) { int diff = abs(actual - i) / step; return i == 0 || i >= (count - 1) / step * step || diff <= 10 || diff <= 100 && ((i / step) % 10) == 9 || diff <= 1000 && ((i / step) % 100) == 99 || ((i / step) % 1000) == 999; } static public List getMultiPorts() { return (List) callOpt(getJavaX(), "getMultiPorts"); } 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 Collection concatCollections_conservative(Collection a, Collection b) { if (empty(a)) return b; if (empty(b)) return a; return concatLists(a, b); } static public String emptyToNull(String s) { return eq(s, "") ? null : s; } static public Map emptyToNull(Map map) { return empty(map) ? null : map; } static public String joinWithBR(Iterable l) { return join("
\n", l); } static public String joinWithBR(String... l) { return joinWithBR(asList(l)); } static public File computerIDFile() { return javaxDataDir("Basic Info/computer-id.txt"); } static public void cancelThread(Thread t) { if (t == null) return; ping(); synchronized (ping_actions) { ping_actions.put(t, "cancelled"); ping_anyActions = true; } } static public void mreplace(Matcher m, StringBuffer buf, String s) { m.appendReplacement(buf, Matcher.quoteReplacement(s)); } 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 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 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 void _registerIO(Object object, String path, boolean opened) { } static public int stdHash2(Object a) { if (a == null) return 0; return stdHash(a, toStringArray(allFields(a))); } static public String hAddToHead(String html, String tag) { List tok = htmlTok(html); List head = first(findContainerTag(tok, "head")); if (head == null) return tag + html; head.set(2, addLineBreak(tag) + head.get(2)); return join(tok); } static public File javaxDataDir_dir; static public File javaxDataDir() { return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data"); } static public File javaxDataDir(String... subs) { return newFile(javaxDataDir(), subs); } static public String tok_deRoundBracket(String s) { return tok_isRoundBracketed(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s; } 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 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 void clickButton(final JButton b) { if (b != null) { swing(() -> { if (b.isEnabled()) b.doClick(); }); } } static public boolean anyIntRangeContains(Iterable ranges, int i) { return any(ranges, r -> intRangeContains(r, i)); } 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 List rgbToIntList(RGB rgb) { return rgb == null ? null : ll(rgb.redInt(), rgb.greenInt(), rgb.blueInt()); } 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 Map flexMatchAngleBracketVarsIC_first(String pat, String input) { return grabValueAndCancel(new VF1>>() { public void get(VF1> onMatch) { try { flexMatchAngleBracketVarsIC_iterate(pat, input, onMatch); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "flexMatchAngleBracketVarsIC_iterate(pat, input, onMatch);"; } }); } static public Object subBot_serveFile(File file) { return call(getMainBot(), "serveFile", file); } static public Object subBot_serveFile(File file, String mimeType) { return call(getMainBot(), "serveFile", file, mimeType); } static public MMOPattern mmo2_parsePattern(String s) { s = trim(tok_deRoundBracket(trim(s))); List tok = javaTokWithBrackets(s); List l = tok_splitAtComma(tok); if (l(l) > 1) return new MMOPattern.Or(lambdaMap(__80 -> mmo2_parsePattern(__80), l)); l = tok_splitAtPlus(tok); if (l(l) > 1) return new MMOPattern.And(lambdaMap(__81 -> mmo2_parsePattern(__81), l)); if (startsWith(s, "!")) return new MMOPattern.Not(mmo2_parsePattern(dropFirst(s))); if (startsWith(s, "^")) return new MMOPattern.StartOfLine(mmo2_parsePattern(dropFirst(s))); if (endsWith(s, "$")) return new MMOPattern.EndOfLine(mmo2_parsePattern(dropLast(s))); l = tok_splitAtAsterisk(tok); if (l(l) == 2) return new MMOPattern.Weighted(parseDouble(second(l)), mmo2_parsePattern(first(l))); return new MMOPattern.Phrase(unquote(s), isQuoted(s)); } 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 String javascriptQuote(String s) { return quote(s); } static public boolean isMD5(String s) { return l(s) == 32 && isLowerHexString(s); } 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 Object postJSONPage(String url, Object... params) { return jsonDecode(postPage(url, params)); } static public List syncListPlus(Collection l, A... more) { if (l == null) return asList(more); synchronized (collectionMutex(l)) { return concatLists(l, asList(more)); } } static public String str_toK(long l) { return n2(toK(l)) + " K"; } 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 void mapPutInRange(Map map, int start, int end, A value) { if (map != null && value != null) for (int i = start; i < end; i++) map.put(i, value); } static public String unicode_rightPointingTriangle() { return charToString(0x25B8); } static public boolean tok_isRoundBracketed(String s) { List tok = tok_combineRoundBrackets_keep(javaTok(s)); return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "(", ")"); } static public A getConceptOpt(Class cc, long id) { return getConceptOpt(db_mainConcepts(), cc, id); } static public A getConceptOpt(Concepts concepts, Class cc, long id) { return concepts == null ? null : optCast(cc, concepts.getConcept(id)); } static public String str_toM(long l) { return n2(toM(l)) + " MB"; } static public String hhtml(Object contents) { return containerTag("html", contents); } 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 boolean isInRAMDisk(File f) { return startsWithOneOf(f2s(f), "/dev/shm/", "/run/shm/"); } 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 String muricaCredentialsQuery() { return htmlQuery(muricaCredentials()); } 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 boolean containsNewLines(String s) { return containsNewLine(s); } static public String appendBracketed(Object o) { String b = strOrNull(o); return empty(b) ? "" : "" + " (" + b + ")"; } static public String appendBracketed(String a, String b) { return a + appendBracketed(b); } static public String 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 File imageSnippetsCacheDir() { return javaxCachesDir("Image-Snippets"); } static public String aGlobalID() { return randomID(globalIDLength()); } static public String aGlobalID(Random random) { return randomID(random, globalIDLength()); } 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 spacePlusRoundBracketedIfNempty(String s) { return nempty(s) ? " " + roundBracket(s) : ""; } static public int preferredWidth(Component c) { return c == null ? 0 : getPreferredSize(c).width; } static public String jsonEncode_shallowLineBreaks(Object o) { return jsonEncode_breakAtLevel1(o); } static public void jsonEncode_shallowLineBreaks(Object o, StringBuilder buf, int level) { jsonEncode_breakAtLevel1(o, buf, level); } static public String hcss_responstableForForms() { return hcss("\r\n .responstableForForms {\r\n margin: 1em 0;\r\n /*width: 100%;*/\r\n overflow: hidden;\r\n background: #FFF;\r\n color: #024457;\r\n border-radius: 10px;\r\n border: 1px solid #167F92;\r\n }\r\n \r\n .responstableForForms tr {\r\n border: 1px solid #D9E4E6;\r\n }\r\n .responstableForForms tr:nth-child(odd) {\r\n background-color: #EAF3F3;\r\n }\r\n .responstableForForms th {\r\n display: none;\r\n border: 1px solid #FFF;\r\n background-color: #167F92;\r\n color: #FFF;\r\n padding: 1em;\r\n }\r\n .responstableForForms th:first-child {\r\n display: table-cell;\r\n text-align: center;\r\n }\r\n .responstableForForms th:nth-child(2) {\r\n display: table-cell;\r\n }\r\n .responstableForForms th:nth-child(2) span {\r\n display: none;\r\n }\r\n .responstableForForms th:nth-child(2):after {\r\n content: attr(data-th);\r\n }\r\n @media (min-width: 480px) {\r\n .responstableForForms th:nth-child(2) span {\r\n display: block;\r\n }\r\n .responstableForForms th:nth-child(2):after {\r\n display: none;\r\n }\r\n }\r\n .responstableForForms td {\r\n display: block;\r\n word-wrap: break-word;\r\n /*max-width: 7em;*/\r\n }\r\n .responstableForForms td:first-child {\r\n display: table-cell;\r\n text-align: center;\r\n border-right: 1px solid #D9E4E6;\r\n }\r\n @media (min-width: 480px) {\r\n .responstableForForms td {\r\n border: 1px solid #D9E4E6;\r\n }\r\n }\r\n .responstableForForms th, .responstableForForms td {\r\n text-align: left;\r\n margin: .5em 1em;\r\n }\r\n @media (min-width: 480px) {\r\n .responstableForForms th, .responstableForForms td {\r\n display: table-cell;\r\n padding: 1em;\r\n }\r\n }\r\n "); } static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) { return print_byThread().get() == null ? tempInterceptPrint(f) : null; } 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 String jsonEncode_breakAtLevels(Object o) { return jsonEncode_breakAtLevels(5, o); } static public String jsonEncode_breakAtLevels(int levels, Object o) { StringBuilder buf = new StringBuilder(); jsonEncode_breakAtLevels(levels, o, buf, 1); return str(buf); } static public void jsonEncode_breakAtLevels(int levels, Object o, StringBuilder buf, int level) { 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(","); if (level == 1) buf.append("\n" + spaces(level * 2)); buf.append(quote((String) key)); buf.append(":"); jsonEncode_breakAtLevels(levels, map.get(key), buf, level + 1); } if (level <= levels) buf.append("\n" + spaces((level - 1) * 2)); 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(","); if (level <= levels) buf.append("\n" + spaces(level * 2)); jsonEncode_breakAtLevels(levels, element, buf, level + 1); } if (level <= levels) buf.append("\n" + spaces((level - 1) * 2)); buf.append("]"); } else throw fail("Unknown object for JSON encoding: " + className(o)); } static public Set listFields(Object c) { TreeSet fields = new TreeSet(); for (Field f : _getClass(c).getDeclaredFields()) fields.add(f.getName()); return fields; } static public boolean eqOrSame(Object a, Object b) { return a == null ? b == null : a == b || b != null && a.equals(b); } 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); 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 Object callFunction(Object f, Object... args) { return callF(f, args); } static public String nConversations(long n) { return n2(n, "conversation"); } static public String nConversations(Collection l) { return nConversations(l(l)); } static public String nConversations(Map map) { return nConversations(l(map)); } static public CancelPoint newCancelPoint() { return new CancelPoint(); } static public void flexMatchAngleBracketVarsIC_honorPunctuation_iterate(String pat, String input, VF1> onMatch) { List vars = new ArrayList(); String starsPat = angleBracketVarsToStars(pat, vars); flexMatchIC_iterate(starsPat, javaTokWithBrackets(starsPat), javaTokWithBrackets(input), new VF1() { public void get(Matches m) { try { Map map = matchesToMapUsingVarList_ciMap(m, vars); if (map != null) callF(onMatch, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "SS map = matchesToMapUsingVarList_ciMap(m, vars);\r\n if (map != null) callF..."; } }); } static public Set synchroWeakHashSet() { return Collections.newSetFromMap((Map) newWeakHashMap()); } 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 void replaceListPart(List l, int i, int j, List l2) { replaceSublist(l, i, j, l2); } 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 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 boostHashCombine(int a, int b) { return a ^ (b + 0x9e3779b9 + (a << 6) + (a >>> 2)); } static public String formatDoubleArrowMap_horizontallyAligned(Map map) { return formatDoubleArrowPairs_horizontallyAligned(mapToPairs(map)); } 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 boolean equalsIgnoreCase(String a, String b) { return eqic(a, b); } static public boolean equalsIgnoreCase(char a, char b) { return eqic(a, b); } static public List tok_combineRoundCurlySquareBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eqOneOf(t, "{", "(", "[")) { int j = findEndOfBracketPart2(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } 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 int numberOfFunctionArguments(Object f) { if (f instanceof F0) return 0; if (f instanceof F1) return 1; if (f instanceof F2) return 2; if (f instanceof VF1) return 1; if (f instanceof VF2) return 2; if (f instanceof String) return numberOfMethodArguments(mc(), (String) f); return numberOfMethodArguments(f, "get"); } 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 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 String dottedSpan(String contents, String title) { return span(contents, "title", title, "style", "border-bottom: dotted 1px"); } 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 String hPopDownButton(String... entries) { String id = "dropdown-" + aGlobalID(), outerID = "outer-" + id; String onclick = replaceDollarVars("\r\n var x = document.getElementById($id);\r\n x.style.display = window.getComputedStyle(x).display === \"none\" ? \"block\" : \"none\";\r\n console.log(\"popup \" + id + \" display: \" + x.style.display);\r\n ", "$id", jsQuote(id)); return hstyle(replaceDollarVars("\r\n #$id ul {\r\n list-style-type: none;\r\n margin: 0;\r\n padding: 0;\r\n width: 200px;\r\n background-color: #f1f1f1;\r\n }\r\n \r\n #$id {\r\n position: absolute;\r\n display:none;\r\n background-color: #f9f9f9;\r\n width:auto;\r\n height:200px;\r\n overflow: auto;\r\n \r\n min-width: 160px;\r\n box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);\r\n \r\n z-index: 99;\r\n }\r\n \r\n #$id li a {\r\n text-decoration: none;\r\n color: #000;\r\n }\r\n\r\n #$id li { \r\n display: block;\r\n border-bottom: 1px solid #555;\r\n padding: 8px 16px;\r\n color: #000;\r\n }\r\n " + "\r\n #$id li:hover, #$id li:hover > a {\r\n background-color: #3399ff;\r\n color: white;\r\n }\r\n ", "$id", id)) + hdiv(span(htmlEncode2(unicode_smallDownPointingTriangle()), "onclick", onclick) + hdiv(ul(entries), "id", id), "style", "position: relative; display: inline-block; cursor: context-menu", "id", outerID) + hscript(replaceDollarVars("\r\n if (typeof $ !== 'undefined')\r\n $('body').click(function(e) {\r\n //console.log(\"target=\" + e.target + \", outerID=$outerID\");\r\n if (!$(e.target).closest('#$outerID').length) {\r\n //console.log(\"hiding $id\");\r\n $(\"#$id\").hide();\r\n }\r\n });\r\n ", "id", id, "outerID", outerID)); } static public String hPopDownButton(Collection entries) { return hPopDownButton(toStringArray(entries)); } 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 String hcenter3(Object contents, Object... __) { return tag("div", contents, params_stylePlus(__, "width: 100%; text-align: center")); } 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 boolean shortClassNameIs(Object o, String name) { return eq(shortClassName(o), name); } static public boolean shortClassNameIs(String name, Object o) { return shortClassNameIs(o, name); } static public String shortName(Object o) { return shortClassName(o); } static public String camelCase(List words) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < l(words); i++) { String word = words.get(i); word = toLower(word); buf.append(i == 0 ? word : firstToUpper(word)); } return str(buf); } static public String camelCase(String words) { return camelCase(words(words)); } static public int lastIndexOf_byteArray(byte[] a, byte b) { for (int i = l(a) - 1; i >= 0; i--) if (a[i] == b) return i; return -1; } static public Object subBot_noCacheHeaders(Object r) { call(r, "addHeader", "Cache-Control", "no-cache, must-revalidate, max-age=0"); return r; } 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 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 boolean containsLowerCase(String s) { for (int i = 0; i < l(s); i++) if (isLowerCase(s.charAt(i))) return true; return false; } static public String dropAfterSubstring(String s, String b) { return substring(s, 0, smartIndexOf(s, b)); } 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 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 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 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 boolean conceptsWithFieldGreaterThan_sorted_verbose = false; static public Collection conceptsWithFieldGreaterThan_sorted(Class c, String field, Object value) { return conceptsWithFieldGreaterThan_sorted(db_mainConcepts(), c, field, value); } static public Collection conceptsWithFieldGreaterThan_sorted(Concepts concepts, Class c, String field, Object value) { IFieldIndex index = concepts.getFieldIndex(c, field); if (index instanceof ConceptFieldIndexDesc) return reverseInPlace(((ConceptFieldIndexDesc) index).objectsWithValueGreaterThan(value)); if (conceptsWithFieldGreaterThan_sorted_verbose) print("conceptsWithFieldGreaterThan: table scan of " + c + " for field " + field); return sortByFieldInPlace(field, objectsWhereFieldGreaterThan(concepts.list(c), field, value)); } static public String replaceDollarVars(String s, Object... params) { if (empty(params)) return s; Map vars = mapKeys(__82 -> dropDollarPrefix(__82), (Map) litcimap(params)); return replaceDollarVars_dyn(s, var -> strOrNull(vars.get(var))); } static public String replaceDollarVars(String s, IF1 f) { return replaceDollarVars_dyn(s, f); } static public List splitAtVerticalBar(String s) { return s == null ? new ArrayList() : trimAll(asList(s.split("\\|"))); } 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 List indicesOf(List l, A a) { if (l == null) return null; if (l instanceof IContentsIndexedList) return intArrayToList(((IContentsIndexedList) l).indicesOf(a)); if (l instanceof IContentsIndexedList2) return map(h -> ((HasIndex) h).idx, ((IContentsIndexedList2) l).indicesOf_treeSetOfHasIndex(a)); List x = new ArrayList(); for (int i = 0; i < l(l); i++) if (eq(l.get(i), a)) x.add(i); return x; } static public List indicesOf(String s, String x) { int i = -1; List out = new ArrayList(); while ((i = indexOf(s, x, i + 1)) >= 0) out.add(i); return out; } static public String postPage(String url, Object... params) { return doPost(litmap(params), url); } 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 boolean startsAndEndsWith(String a, char c) { return startsWith(a, c) && endsWith(a, c) && l(a) >= 2; } static public boolean startsAndEndsWith(String a, String b) { return startsWith(a, b) && endsWith(a, b) && l(a) >= l(b) * 2; } 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 String tdTop(Object contents, Object... params) { return tag("td", contents, arrayPlus(params, "valign", "top")); } static public String tryToReadErrorStreamFromURLConnection(URLConnection conn) { try { if (conn instanceof HttpURLConnection) return stream2string(((HttpURLConnection) conn).getErrorStream()); return null; } catch (Throwable __e) { return null; } } 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 ourSubList_noRangeCheck(l, startIndex, endIndex); } static public List subList(List l, IntRange r) { return subList(l, r.start, r.end); } 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 List sortConceptsByID(Collection l) { return sortedByCalculatedField(l, c -> c.id); } 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 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 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 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 boolean cicWithSmartWordBoundary(String a, String b) { return containsRegexpIC(a, phraseToRegExp(b)); } 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 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 void addFirst(List c, A a) { if (c != null) c.add(0, a); } static public A nextToLast(List l) { return get(l, l(l) - 2); } static public boolean frameTooSmall(JFrame frame) { return frame.getWidth() < 100 || frame.getHeight() < 50; } static public String unquoteAllLines(String s) { return linesPreservingTrailingNewLine(s, unquoteAll(lines(s))); } static public String ahref(String link, Object contents, Object... params) { return link == null ? str(contents) : href(link, contents, params); } 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 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 Object serveWithContentType(String text, String contentType) { return serveByteArray(toUtf8(text), contentType); } 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 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 Object serveJSON_breakAtLevels(int levels, Object... data) { return serveText(jsonEncode_breakAtLevels(levels, jsonPrepareData(data))); } 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 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 public String pre(Object contents, Object... params) { return tag("pre", contents, params); } 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 replaceVars(String s, Map map) { return empty(map) ? s : join(replaceVars(javaTok(s), map)); } static public List replaceVars(List tok, Map map) { if (empty(map)) return tok; tok = cloneList(tok); for (Map.Entry __0 : _entrySet(map)) { String var = __0.getKey(); Object val = __0.getValue(); jreplace(tok, var, str(val)); } return tok; } static public String replaceVars(String s, Object... params) { return replaceVars(s, paramsToMap(params)); } 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 double last(DoubleBuffer l) { return l.last(); } static public A last(CompactLinkedHashSet set) { return set == null ? null : set.last(); } static public String classNameToVM(String name) { return name.replace(".", "$"); } static public TreeSet caseInsensitiveSet() { return caseInsensitiveSet_treeSet(); } static public TreeSet caseInsensitiveSet(Collection c) { return caseInsensitiveSet_treeSet(c); } 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 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 List objectsWhereIC(Collection c, Object... data) { if (c == null) return null; List l = new ArrayList(); for (A x : c) if (checkFieldsIC(x, data)) l.add(x); return l; } static public String addPlusToCount(long max, long n, String s) { if (n != max) return s; return insertString(s, smartIndexOfSpaceEtc(s), "+"); } static public List filesWithExtension(String ext, List files) { return filesEndingWith(files, addPrefixIfNotEmpty2(".", ext)); } static public List splitAtTokens(String s, List tokens) { return splitAtTokens(javaTok(s), tokens); } static public List splitAtTokens(List tok, List tokens) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { int j = indexOfSubList(tok, tokens, i); if (i >= l(tok)) break; if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j + l(tokens); } return l; } static public List splitAtTokens(List tok, String... tokens) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { int j = indexOfSubList(tok, tokens, i); if (i >= l(tok)) break; if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j + l(tokens); } return l; } 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 List indicesOfAngleBracketVars(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) if (isAngleBracketVar(tok.get(i))) l.add(i); return l; } 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 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 List flattenList2(Object... a) { List l = new ArrayList(); if (a != null) for (Object x : a) if (x instanceof Collection) for (Object sub : (Collection) x) l.addAll(flattenList2(sub)); else if (x != null) l.add(x); return l; } static public boolean isStringList(Object o) { if (!(o instanceof List)) return false; List l = (List) o; for (Object x : l) if (!(x instanceof String)) return false; return true; } static public Object[] paramsPlus_noOverwrite(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) mapPut_noOverwrite(map, a2[i], a2[i + 1]); return mapToParams(map); } static public String plural(String s) { return getPlural(s); } static public String h3_htmlEncode(Object contents, Object... params) { return h3(htmlEncode2(str(contents)), params); } static public String javaVersion() { return System.getProperty("java.version"); } 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 gazelle_server() { return "https://gazelle.rocks/"; } 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 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 String htmldecode_dropAllTags(String html) { return htmldecode(dropAllTags(html)); } static public boolean isJavaxCompilableSnippetType(int type) { return isJavaxCompilableSnippetTypeExceptInclude(type) || type == javaxIncludeSnippetType(); } static public Map codeAnalysis_identifierSafetyMap() { return mechHashMap("JavaX Identifier Safety"); } static public String rpad(String s, int l) { return rpad(s, l, ' '); } static public String rpad(String s, int l, char c) { return lengthOfString(s) >= l ? s : s + rep(c, l - lengthOfString(s)); } static public String rpad(int l, String s) { return rpad(s, l); } 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 String nTests(long n) { return n2(n, "test"); } static public String nTests(Collection l) { return nTests(l(l)); } static public boolean isString(Object o) { return o instanceof String; } static public String angleBracketed(String s) { return angleBracket(s); } 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 Collection distinctCIFieldValuesOfConcepts(Class c, String field) { return distinctCIFieldValuesOfConcepts(db_mainConcepts(), c, field); } static public Collection distinctCIFieldValuesOfConcepts(Concepts concepts, Class c, String field) { IFieldIndex index = concepts.getCIFieldIndex(c, field); if (index != null) return index.allValues(); Set set = ciSet(); for (A x : concepts.list(c)) set.add((String) getOpt(x, field)); return set; } static public Object firstElementNotSubclassing(Iterable l, Class c) { return firstThat(l, o -> !isInstanceOf(o, c)); } static public Q dm_ownQ(Q q) { q.rst.enter = dm_rEnter(dm_current_mandatory()); dm_ownResource(q); return q; } static public AutoCloseable temp_loadPage_silent() { return tempSetThreadLocal(loadPage_silent, true); } static public List listToTopTenCI(Collection l) { return asCIMultiSet(l).highestFirst(); } static public Q startQ() { return new Q(); } static public Q startQ(String name) { return new Q(name); } 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 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 Map filterKeys(Map map, Object f) { return filterMapByFunctionOnKey(map, f); } static public Map filterKeys(Object f, Map map) { return filterMapByFunctionOnKey(f, map); } static public Map filterKeys(IF1 f, Map map) { return filterMapByFunctionOnKey((Object) f, map); } static public Map filterKeys(Map map, IF1 f) { return filterKeys(f, map); } 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 String afterLastSpace(String s) { return s == null ? null : substring(s, s.lastIndexOf(' ') + 1); } 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 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 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 String joinWithVBar(Iterable l) { return join(" | ", l); } static public String joinWithVBar(String... l) { return joinWithVBar(asList(l)); } static public String regexp_findSnippetIDs() { return "(?:#|\\blib\\s+|(?:^|\\n)\\s*!)([0-9]+)"; } static public String htmlencode(Object o) { return htmlencode(str(o)); } static public String htmlencode(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 == '&') { int cp = s.codePointAt(i); out.append("&#x"); out.append(intToHex_flexLength(cp)); out.append(';'); i += Character.charCount(cp) - 1; } else out.append(c); } return out.toString(); } 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 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 String hbutton(String text, Object... params) { return hfulltag("button", text, params); } 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 String hbuttonLink(String url, String text, Object... params) { return hbuttonOnClick(text, "location.href=" + jsQuote(url) + ";", params); } 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 String structureOrText(Object o) { return o instanceof String ? (String) o : structure(o); } static public boolean isOpeningBracket(String s) { return eqOneOf(s, "(", "{", "["); } static public File tempDir() { return makeTempDir(); } 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 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 String rawLink(String pageName) { return "/" + parseSnippetID(getProgramID()) + "/raw" + addPrefix("/", pageName); } static public String rawLink() { return "/" + parseSnippetID(getProgramID()) + "/raw"; } static public String rawLink(String pageName, String contents) { return ahref(rawLink(pageName), contents); } 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 A listGet(List l, int idx) { return l != null && idx >= 0 && idx < l.size() ? l.get(idx) : null; } static public String curlyBrace(String s) { return "{" + s + "}"; } static public long parseFirstLong(String s) { return parseLong(jextract("", s)); } 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 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
asForPairsWithB(B b, Iterable> l) { List out = new ArrayList(); for (Pair p : unnullForIteration(l)) if (eq(pairB(p), b)) out.add(pairA(p)); return out; } static public List asForPairsWithB(Iterable> l, B b) { return asForPairsWithB(b, l); } 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 String htmlQuery(Map params) { return empty(params) ? "" : "?" + makePostData(params); } static public String htmlQuery(Object... data) { return empty(data) ? "" : "?" + makePostData(data); } static public String formatLocalDateWithMinutes(long time) { return localDateWithMinutes(time); } static public String formatLocalDateWithMinutes() { return localDateWithMinutes(); } static public String firstWhereFirstLongIs(Collection l, long i) { return firstThat(l, s -> parseFirstLong(s) == i); } 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 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 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 String anchorFromURL(String url) { return substring(url, smartIndexOf(url, "#")); } 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 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 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 String regexpQuote(String s) { return s.length() == 0 ? "" : Pattern.quote(s); } 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 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 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 double ratioToPercent(double x, double y) { return x * 100 / y; } static public void typeWriterConsole() { if (isHeadless()) return; Font f = typeWriterFont(); consoleFont(f); consoleInputFont(f); } static public int snippetType_javaxDesktopModule() { return 58; } 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 Map parseColonPropertyCIMap(String text) { return parseColonProperties(text, ciMap()); } static public SecretValue secretValueOrNull(A a) { return a == null ? null : new SecretValue(a); } 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 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 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 String unquoteUsingCharArray(String s, char[] buf) { if (s == null) return null; if (startsWith(s, '[')) { int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; if (i < s.length() && s.charAt(i) == '[') { String m = s.substring(1, i); if (s.endsWith("]" + m + "]")) return s.substring(i + 1, s.length() - i - 1); } } if (s.length() > 1) { char c = s.charAt(0); if (c == '\"' || c == '\'') { int l = endsWith(s, c) ? s.length() - 1 : s.length(); if (l > buf.length) return unquote(s); int n = 0; for (int i = 1; i < l; i++) { char ch = s.charAt(i); if (ch == '\\') { char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1); if (nextChar >= '0' && nextChar <= '7') { String code = "" + nextChar; i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; } } buf[n++] = (char) Integer.parseInt(code, 8); continue; } switch(nextChar) { case '\"': ch = '\"'; break; case '\\': ch = '\\'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\'': ch = '\''; break; case 'u': if (i >= l - 5) { ch = 'u'; break; } int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16); char[] x = Character.toChars(code); int lx = x.length; for (int j = 0; j < lx; j++) buf[n++] = x[j]; i += 5; continue; default: ch = nextChar; } i++; } buf[n++] = ch; } return new String(buf, 0, n); } } return s; } static public boolean fileNotEmpty(File f) { return isFile(f) && fileSize(f) > 0; } 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 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 String standardCredentialsUser() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username")))); } static public List javaTokPlusBrackets(String s) { return tok_combineRoundOrCurlyBrackets_keep(javaTok(s)); } static public String mL_raw(String name) { return mechList_raw(name); } 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 long conceptID(Concept c) { return c == null ? 0 : c.id; } static public long conceptID(Concept.Ref ref) { return conceptID(cDeref(ref)); } static public boolean isSubclassOf(Class a, Class b) { return isSubclass(a, b); } static public Map parseCSSParameter(String s) { Map map = new LinkedHashMap(); for (String x : trimAll(splitAt(s, ";"))) { List y = trimAll(splitAtColon(x)); if (l(y) == 2) map.put(first(y), second(y)); } return map; } 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 String hcheckbox(String name, boolean checked, Object... params) { return tag("input", "", paramsPlus(params, "type", "checkbox", "name", name, checked ? "checked" : null, "1")); } static public String hcheckbox(String name) { return hcheckbox(name, false); } static public String hcheckbox(String name, String text) { return hcheckboxWithText(name, text); } static public MultiMap treeMultiMapIndexByField(Collection c, String field) { MultiMap map = treeMultiMap(); for (Object a : c) { Object val = getOpt(a, field); if (val != null) map.put(val, a); } return map; } static public MultiMap treeMultiMapIndexByField(String field, Collection c) { return treeMultiMapIndexByField(c, field); } 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 int _hashCode(Object a) { return a == null ? 0 : a.hashCode(); } 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 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 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 boolean isValidEmailAddress_simple(String s) { return l(s) <= 254 && regexpMatches("^\\S+@\\S+(\\.[^\\.\\s]+)+$", s); } static public JavaScript hjs_copyToClipboard() { return new JavaScript("\r\n const copyToClipboard = str => {\r\n const el = document.createElement('textarea');\r\n el.value = str;\r\n el.setAttribute('readonly', '');\r\n el.style.position = 'absolute';\r\n el.style.left = '-9999px';\r\n document.body.appendChild(el);\r\n const selected =\r\n document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;\r\n el.select();\r\n document.execCommand('copy');\r\n document.body.removeChild(el);\r\n if (selected) {\r\n document.getSelection().removeAllRanges();\r\n document.getSelection().addRange(selected);\r\n }\r\n };\r\n "); } static public String baseClassName(String className) { return substring(className, className.lastIndexOf('.') + 1); } static public String baseClassName(Object o) { return baseClassName(getClassName(o)); } 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 void pcallOpt_noArgs(Object o, String method) { try { callOpt_noArgs(o, method); } catch (Throwable __e) { pcallFail(__e); } } static public int iround(double d) { return (int) Math.round(d); } static public int iround(Number n) { return iround(toDouble(n)); } 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 isAngleBracketed(String s) { return s.startsWith("<") && s.endsWith(">"); } static public List codeTokens(List tok) { return codeTokensOnly(tok); } static public boolean isJavaxApplicationSnippetType(int type) { return type == snippetType_javaxSource() || type == snippetType_JavaXDesktop(); } static public List mechList_opt_tlft(String name) { return mechList_opt_tlft_cached(name); } static public List listPlus(Collection l, A... more) { return concatLists(l, asList(more)); } static public List sortByFieldInPlace(List l, String field) { sort(l, fieldComparator(field)); return l; } static public List sortByFieldInPlace(String field, List l) { return sortByFieldInPlace(l, field); } static public A dm_ownResource(A resource) { dm_currentModuleMandatory().ownResource(resource); return resource; } 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 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 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 String fromSingleQuoteIdentifier(String s) { return isSingleQuoteIdentifier(s) ? substring(s, 1) : s; } static public long collectMaxLong(Collection c, String field) { long x = Long.MIN_VALUE; for (Object o : unnull(c)) { Long l = (Long) (getOpt(o, field)); if (l != null) x = max(x, (long) l); } return x; } 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> zipTwoListsToPairs_lengthOfFirst(List l1, List l2) { int n = l(l1); List> out = emptyList(n); for (int i = 0; i < n; i++) addPair(out, l1.get(i), get(l2, i)); return out; } static public boolean containsAnythingNeq(Collection l, A a) { for (A x : unnull(l)) if (neq(x, a)) return true; return false; } 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 final public boolean loadPageThroughProxy_enabled = false; static public String loadPageThroughProxy(String url) { return null; } 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 small(Object contents, Object... params) { return tag("small", contents, params); } static public String h2_title(String s) { return htitle_h2(s); } static public List sortedIC(Collection l) { return sortedIgnoreCase(l); } static public String addAnchorToURL(String url, String anchor) { int i = smartIndexOf(url, '#'); url = takeFirst(url, i); if (nempty(anchor)) url += "#" + anchor; return url; } static public List sortByFieldDesc(Collection c, final String field) { return sortedByFieldDesc(c, field); } static public List sortByFieldDesc(String field, Collection c) { return sortedByFieldDesc(field, c); } static public List> zipTwoListsToPairs_longer(List l1, List l2) { int n = max(l(l1), l(l2)); List> out = emptyList(n); for (int i = 0; i < n; i++) addPair(out, _get(l1, i), _get(l2, i)); return out; } 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 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 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 void ownResource(AutoCloseable c) { _registerAutoCloseable(c); } 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 ThreadLocal dynamize_linkParams = new ThreadLocal(); static public String dynamize_noEncode(String html) { List tok = htmlTok(html); Pattern p = Pattern.compile(regexp_findSnippetIDs()); for (int i = 0; i < l(tok); i += 2) { Matcher m = p.matcher(tok.get(i).replace("&#", "&~~~")); StringBuffer buf = new StringBuffer(); while (m.find()) { String id = m.group(1); String link = m.group(); try { link = ahref(snippetLink(id), link, concatArrays(new Object[] { "title", getSnippetTitle_cached(id) }, dynamize_linkParams.get())); } catch (Throwable __e) { pcallFail(__e); } mreplace(m, buf, link); } m.appendTail(buf); String s = str(buf).replace("&~~~", "&#"); tok.set(i, s); } dynamize_linkParams.set(null); return join(tok); } 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 String hbuttonOnClick_returnFalse(String text, String onClick, Object... params) { return hfulltag("button", text, paramsPlus(params, "onclick", addSuffix(trim(onClick), ";") + " return false;")); } static public File loadLibrary(String snippetID) { return loadBinarySnippet(snippetID); } static public String regexpFirstGroupIC(String pat, String s) { Matcher m = regexpIC(pat, s); if (m.find()) return m.group(1); else return null; } static public List tlft_j(String text) { return toLinesFullTrim_java(text); } 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 Object[] paramsPlus_skipFirst(Object[] a1, Object... a2) { if (odd(l(a1))) return itemPlusArray(first(a1), paramsPlus(dropFirst(a1), a2)); return paramsPlus(a1, a2); } static public boolean endsWithNewLine(String s) { return endsWith(s, "\n"); } static public String wrapInDiv(String html, Object... __) { String tag = getTag(firstToken(htmlTok(html))); return eqicOneOf(tag, "div", "p") ? html : div(html, __); } static public void syncRemoveLast(List l) { if (l != null) synchronized (l) { removeLast(l); } } static public void syncRemoveLast(List l, int n) { if (l != null) synchronized (l) { removeLast(l, n); } } static public void syncRemoveLast(int n, List l) { syncRemoveLast(l, n); } static public String strUnnull(Object o) { return o == null ? "" : str(o); } static public A eitherAOpt(Either e) { return e != null && e.isA() ? e.a() : null; } static public ContentsIndexedList ciContentsIndexedList() { return new ContentsIndexedList(ciMap()); } 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 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 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 void htmlencode_forParams_useV2() { htmlencode_forParams_useV2.set(true); } static public boolean vmBus_anyFalse(String msg, Object... args) { return contains(vmBus_queryAll(msg, args), false); } static public String ukTimeZone_string() { return "Europe/London"; } static public JMenuItem jMenuItem(final String text) { return jmenuItem(text); } static public JMenuItem jMenuItem(String text, Object r) { return jmenuItem(text, r); } 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 TreeSet ciSet() { return caseInsensitiveSet(); } static public String getClassName(Object o) { return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName(); } 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 String pUnlessEmpty(String s, Object... __) { return empty(s) ? "" : p(s, __); } static public IterableIterator> iterateWithIndex1(Collection l) { return iterateListWithIndex(l, 1); } static public IterableIterator> iterateWithIndex1(A[] l) { return iterateListWithIndex(asVirtualList(l), 1); } 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 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 MechMode mechMode_value = new MechMode(); static public MechMode mechMode() { return mechMode_value; } static public Object vmBus_wrapArgs(Object... args) { return empty(args) ? null : l(args) == 1 ? args[0] : args; } 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 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 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 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 String unicodeFromCodePoint(int codePoint) { return codePointToString(codePoint); } static public boolean isLetter(char c) { return Character.isLetter(c); } static public long parseLongOpt(String s) { return isInteger(s) ? parseLong(s) : 0; } static public void litmap_impl_noOverwrite(Map map, Object... x) { if (x != null) for (int i = 0; i < x.length - 1; i += 2) putIfNotThere(map, x[i], x[i + 1]); } static public void toggleAlwaysOnTop(Window frame) { if (frame == null) return; { swing(() -> { frame.setAlwaysOnTop(!frame.isAlwaysOnTop()); }); } } static public List objectsWhereFieldGreaterThan(Collection c, String field, Object value) { List l = new ArrayList(); for (A x : unnull(c)) if (cmp(getOpt(x, field), value) > 0) l.add(x); return l; } 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 Cache> countryDialCodesMultiMap_cache = new Cache<>(() -> countryDialCodesMultiMap_load()); static public MultiMap countryDialCodesMultiMap() { return countryDialCodesMultiMap_cache.get(); } static public MultiMap countryDialCodesMultiMap_load() { return treeMultiMapIndexByField("dialCode", countryDialCodes()); } 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 BufferedInputStream bufferedFileInputStream(File f) { return bufferedInputStream(f); } static public BufferedInputStream bufferedFileInputStream(File f, int bufSize) { try { return new BufferedInputStream(new FileInputStream(f), bufSize); } catch (Exception __e) { throw rethrow(__e); } } 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 String formatSnippetIDOpt(String s) { return isSnippetID(s) ? formatSnippetID(s) : s; } static public Dimension getScreenSize() { return Toolkit.getDefaultToolkit().getScreenSize(); } static public Dimension getScreenSize(int iScreen) { return toDimension(screenBounds(iScreen).widthAndHeight()); } 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 Object process(String processorID, Object in) { return process(processorID, in, "in"); } static public Object process(String processorID, Object in, String outVar) { try { Class processor = hotwire(processorID); set(processor, "in", in); call(processor, "main", new Object[] { new String[0] }); return get(processor, outVar); } catch (Exception e) { throw new RuntimeException("Error in #" + parseSnippetID(processorID), e); } } 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 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 boolean syncNempty(Collection l) { return !syncEmpty(l); } static public void clear(Collection c) { if (c != null) c.clear(); } static public void clear(Map map) { if (map != null) map.clear(); } 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 hbody(Object contents, Object... params) { return tag("body", contents, params); } 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 String stringIf(boolean b, String s) { return stringIfTrue(b, s); } static public String stringIf(String s, boolean b) { return stringIf(b, s); } 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 Integer min_withNull(Integer a, Integer b) { return a == null ? b : b == null ? a : (Integer) min(a, b); } static public String hsansserif() { return hcss("body { font-family: Sans-Serif; }"); } static public void withCancelPoint(VF1 r) { CancelPoint cp = newCancelPoint(); try { try { callF(r, cp); } catch (Throwable e) { e = innerException(e); if (!(e instanceof CancelToCancelPoint && ((CancelToCancelPoint) e).cp == cp)) rethrow(e); } } finally { _close(cp); } } static public void withCancelPoint(IVF1 r) { CancelPoint cp = newCancelPoint(); try { try { r.get(cp); } catch (Throwable e) { e = innerException(e); if (!(e instanceof CancelToCancelPoint && ((CancelToCancelPoint) e).cp == cp)) rethrow(e); } } finally { _close(cp); } } 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 A setThreadLocal(ThreadLocal tl, A value) { if (tl == null) return null; A old = tl.get(); tl.set(value); return old; } static public String div_vbar(String... items) { return div_vbar(asList(items)); } static public String div_vbar(Collection items, Object... params) { return divUnlessEmpty(joinNemptiesWithVBar(items), params); } static public List lookupPossiblyIgnoreCase(MultiMap map, String key) { if (map == null) return null; List value = map.get(key); return !value.isEmpty() ? value : lookupIgnoreCase(map, key); } static public A lookupPossiblyIgnoreCase(Map map, String key) { if (map == null) return null; A value = map.get(key); return value != null ? value : lookupIgnoreCase(map, key); } static public boolean isSingleQuoteIdentifier(String s) { if (l(s) < 2 || s.charAt(0) != '\'' || !Character.isJavaIdentifierStart(s.charAt(1))) return false; for (int i = 2; i < l(s); i++) if (!Character.isJavaIdentifierPart(s.charAt(i))) return false; return true; } static public List javaTokWithAngleBrackets(String s) { return tok_combineAngleBrackets_keep(javaTok(s)); } 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 boolean containsRegexpIC(String s, String pat) { return compileRegexpIC(pat).matcher(s).find(); } 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 Collection conceptsWhereCI(Class c, Object... params) { return findConceptsWhereCI(c, params); } static public Collection conceptsWhereCI(String c, Object... params) { return findConceptsWhereCI(c, params); } static public Collection conceptsWhereCI(Concepts concepts, Class c, Object... params) { return findConceptsWhereCI(concepts, c, params); } static public List conceptsWhereCI(Concepts concepts, String c, Object... params) { return findConceptsWhereCI(concepts, c, params); } 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 List htmlTok(String s) { return htmlcoarsetok(s); } 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 String joinNemptiesWithSemicolon(String... strings) { return joinNempties("; ", strings); } static public String joinNemptiesWithSemicolon(Collection strings) { return joinNempties("; ", strings); } static public String newLinesToSpaces_trim(String s) { return s == null ? null : trim(s).replaceAll("\\s*\r?\n\\s*", " "); } static public String javaTokDropTrailingN(String s) { List tok = javaTok(s); return empty(last(tok)) ? unnull(s) : join(dropLast(tok)); } static public String hms() { return hms(now()); } static public String hms(long time) { return new SimpleDateFormat("HHmmss").format(time); } static public int min3(int a, int b, int c) { return min(min(a, b), c); } static public double min3(double a, double b, double c) { return min(min(a, b), c); } 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 boolean eqic_gen(Object a, Object b) { return a instanceof String && b instanceof String && eqic((String) a, (String) b); } 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 List record_list = synchroList(); static public void record(Object o) { record_list.add(o); } static public String replaceAngleBracketVars_curly(String s, Map map) { return replaceAngleBracketVars(s, mapValues(__83 -> curly(__83), map)); } static public List replaceAngleBracketVars_curly(List tok, Map map) { return replaceAngleBracketVars(tok, mapValues(__84 -> curly(__84), map)); } static public String replaceAngleBracketVars_curly(String s, Object... params) { return replaceAngleBracketVars_curly(s, paramsToMap(params)); } static public File secretProgramFile(String progID, String fileName) { return new File(getSecretProgramDir(progID), fileName); } static public File secretProgramFile(String fileName) { return secretProgramFile(getProgramID(), fileName); } static public int numberOfWords2(String s) { return l(words2(s)); } 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 boolean phraseCache(String pattern, String s) { return mmo2_match(pattern, s); } static public boolean phraseCache(MMOPattern pattern, String s) { return mmo2_match(pattern, s); } static public IF1 phraseCache(String pattern) { return phraseCache(mmo2_parsePattern(pattern)); } static public IF1 phraseCache(MMOPattern pattern) { return s -> phraseCache(pattern, s); } static public Map mechMap(String listName) { return mechMapCI(listName); } static public String fsI_flex(String s) { return startsWithDigit(s) ? "#" + s : s; } static public String shortenSnippetID(String snippetID) { if (snippetID.startsWith("#")) snippetID = snippetID.substring(1); String httpBlaBla = "http://tinybrain.de/"; if (snippetID.startsWith(httpBlaBla)) snippetID = snippetID.substring(httpBlaBla.length()); return "" + parseLong(snippetID); } static public String tok_firstClassName(List tok) { int i = jfind(tok, "class "); return i < 0 ? null : tok.get(i + 2); } static public String newLinesToSpaces(String s) { return s == null ? null : fixNewLines(s).replace("\n", " "); } 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 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 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 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 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 String htitle_h2(String s) { return htitle_noEncode(dropTags(s)) + h2(s); } static public String htitle_h1(String s) { return htitle_noEncode(dropTags(s)) + h1(s); } 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 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 String formatWithThousands(long l) { return formatWithThousandsSeparator(l); } static public String domain() { return domainName(); } static public String domain(String url) { return hostNameFromURL(url); } static public List tokSplitAtComma(String s) { List tok = javaTok(s); List l = new ArrayList(); while (l(tok) > 1) { int i = smartIndexOf(tok, ","); l.add(trim(join(subList(tok, 0, i)))); tok = subList(tok, i + 1); } return l; } 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 String hdesktopNotifications() { return hscript("\r\n function sendDesktopNotification(text, options) {\r\n if (\"Notification\" in window && Notification.permission === \"granted\")\r\n new Notification(text, options);\r\n }\r\n window.sendDesktopNotification = sendDesktopNotification;\r\n \r\n function initDesktopNotifications() {\r\n if (!(\"Notification\" in window))\r\n $(\"#notiStatus\").html(\"Desktop notifications not supported in this browser\");\r\n else if (Notification.permission === \"granted\")\r\n $(\"#notiStatus\").html(\"Desktop notifications enabled\");\r\n else if (Notification.permission === \"denied\")\r\n $(\"#notiStatus\").html(\"Desktop notifications denied\");\r\n else {\r\n $(\"#notiStatus\").html(\"Requesting permission for desktop notifications\");\r\n Notification.requestPermission().then(function (permission) {\r\n initDesktopNotifications();\r\n sendDesktopNotification(\"Notifications will look like this!\");\r\n });\r\n }\r\n }\r\n \r\n $(document).ready(initDesktopNotifications);\r\n "); } 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 void showConsole() { callOpt(get(javax(), "console"), "showConsole"); } 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 Map parseColonProperties(String text) { return parseColonProperties(text, new LinkedHashMap()); } static public Map parseColonProperties(String text, Map map) { for (String s : tlft(text)) { int i = indexOf(s, ':'); if (i > 0) map.put(trimSubstring(s, 0, i), trimSubstring(s, i + 1)); } return map; } static public boolean regexpFindsIC(String pat, String s) { return regexpIC(pat, s).find(); } static public String mapToLines_rtrim(Object f, Map map) { return lines_rtrim(map(map, f)); } static public String mapToLines_rtrim(Object f, Iterable l) { return lines_rtrim(map(f, l)); } static public String mapToLines_rtrim(Iterable l, IF1 f) { return mapToLines_rtrim(f, l); } static public Object subBot_serve404() { return call(getMainBot(), "serve404"); } static public Object subBot_serve404(String msg) { return call(getMainBot(), "serve404", msg); } 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 List splitAtColon(String s) { return empty(s) ? emptyList() : asList(s.split(":")); } static public String htmlencode2(String s) { return htmlencode_noQuotes(s); } 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 boolean isDollarVar(String s) { return startsWith(s, '$') && l(s) > 1; } 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 boolean find3(String pat, String s) { return find3(pat, s, null); } static public boolean find3(String pat, String s, Matches matches) { return find3(pat, parse3_cachedInput(s), matches); } static public boolean find3(String pat, List toks, Matches matches) { List tokpat = parse3_cachedPattern(pat); String[] m = find2(tokpat, toks); if (m == null) return false; if (matches != null) matches.m = m; return true; } static public String loadSnippet_cached(String id) { return loadSnippet_simpleCache(id); } static public String[] find2(List pat, List tok) { for (int idx = 0; idx < tok.size(); idx += 2) { String[] result = find2(pat, tok, idx); if (result != null) return result; } return null; } static public String[] find2(List pat, List tok, int idx) { if (idx + pat.size() > tok.size()) return null; List result = new ArrayList(); for (int i = 1; i < pat.size(); i += 2) { String p = pat.get(i), t = tok.get(idx + i); if (eq(p, "*")) result.add(t); else if (!p.equalsIgnoreCase(t)) return null; } return toStringArray(result); } static public String hreconnectingWebSockets() { return hjavascript_src_snippet(hreconnectingWebSockets_snippetID()); } static public String pre_htmlencode(Object contents, Object... params) { return pre(htmlencode_noQuotes(str(contents)), params); } static public Rectangle rectangleUnion(Rectangle a, Rectangle b) { return a == null ? b : b == null ? a : a.union(b); } static public String addSlashPrefix(String s) { return addPrefix("/", s); } static public void duplicateThisProgram() { nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs")))); } static public String hscript(String script) { return hjavascript(script); } 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 ipToCountry2020_safe(String ip) { try { return or2(ipToCountry2020(ip), "?"); } catch (Throwable __e) { pcallFail(__e); } return "?"; } 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 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 String td_valignTop(Object contents, Object... params) { return tdTop(contents, params); } static public String fileInfo(File f) { return renderFileInfo(f); } static public String fileInfo(String f) { return renderFileInfo(newFile(f)); } 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 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 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 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 boolean intRangeContains(IntRange r, int i) { return r != null && i >= r.start && i < r.end; } static public LinkedHashMap mapToOrderedMap(Object f, Iterable l) { LinkedHashMap map = new LinkedHashMap(); for (Object o : unnullForIteration(l)) { Pair p = (Pair) (callF(f, o)); map.put(p.a, p.b); } return map; } static public LinkedHashMap mapToOrderedMap(IF1> f, Iterable l) { LinkedHashMap map = new LinkedHashMap(); for (A o : unnullForIteration(l)) { Pair p = callF(f, o); map.put(p.a, p.b); } return map; } static public LinkedHashMap mapToOrderedMap(Iterable l, IF1> f) { return mapToOrderedMap(f, l); } static public HashMap instanceFieldsMap(Object o) { return (HashMap) getOpt_getFieldMap(o); } static public String hreplaceTitle(String html, String newTitle) { return hreplacetag(html, "title", htitle(newTitle)); } static public String toString(Object o) { return strOrNull(o); } static public long collectMinLong(Collection c, String field) { long x = Long.MAX_VALUE; for (Object o : unnull(c)) { Long l = (Long) (getOpt(o, field)); if (l != null) x = min(x, (long) l); } return x; } 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 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 jsBool(boolean b) { return b ? "true" : "false"; } static public boolean isOpeningTag(String token, String tag) { return isTag(token, tag) && !token.endsWith("/>"); } static public boolean isOpeningTag(String token) { return token.startsWith("<") && token.endsWith(">") && !token.endsWith("/>") && isLetter(token.charAt(1)); } 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 byte[] loadBinaryFromZip(File inZip, String fileName) { try { ZipFile zip = new ZipFile(inZip); try { ZipEntry entry = zip.getEntry(fileName); if (entry == null) return null; InputStream fin = zip.getInputStream(entry); ByteArrayOutputStream baos = new ByteArrayOutputStream(); copyStream(fin, baos); fin.close(); return baos.toByteArray(); } finally { zip.close(); } } catch (Exception __e) { throw rethrow(__e); } } static public String div(Object contents, Object... params) { return hdiv(contents, params); } static public String div() { return hdiv(); } 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 String squareBracket(String s) { return "[" + s + "]"; } static public void addComponentsFirst(Container c, Component... l) { containerAddFirst(c, l); } static public String hdivWithID(String id, Object contents, Object... params) { return hdiv(contents, paramsPlus(params, "id", id)); } 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 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 Chain toChain(Iterable l) { Iterator it = iterator(l); if (!it.hasNext()) return null; Chain c = new Chain<>(it.next()); Chain last = c; int size = 1; while (it.hasNext()) { ++size; Chain x = new Chain(it.next()); last.next = x; last = x; } Chain x = c; while (x != null) { x.size = size--; x = x.next; } return c; } static public Object[] arrayPlus(Object[] a1, Object... a2) { return concatArrays(a1, a2); } static public List tok_splitAtPlus(String s) { return tok_splitAtPlus(javaTokWithAllBrackets_cached(s)); } static public List tok_splitAtPlus(List tok) { return splitAtTokens(tok, "+"); } 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 String getProgramTitle() { return getProgramName(); } static public List filterConceptsIC(Collection list, Object... params) { List l = new ArrayList(); if (list != null) for (A x : list) if (checkConceptFieldsIC(x, params)) l.add(x); return l; } static public List sortedByConceptIDDesc(Collection c) { return sortedByCalculatedFieldDesc(__85 -> conceptID(__85), c); } static public String renderVars_struct(Object... params) { List l = new ArrayList(); for (int i = 0; i + 1 < l(params); i += 2) l.add(params[i] + "=" + struct(params[i + 1]) + ". "); return trim(join(l)); } static public String formatLocalDateWithSeconds(long time) { return localDateWithSeconds(time); } static public String formatLocalDateWithSeconds() { return localDateWithSeconds(); } static public String joinNemptiesWithColon(String... strings) { return joinNempties(": ", strings); } static public String joinNemptiesWithColon(Collection strings) { return joinNempties(": ", strings); } static public String snippetRawURL_maxCache(String snippetID) { return snippetRawURL_maxCache(snippetID, null); } static public String snippetRawURL_maxCache(String snippetID, String contentType) { return "https://botcompany.de/serve/" + psI(snippetID) + htmlQuery("ct", contentType, "maxCache", 1); } static public Map parseDoubleLeftArrowMapCI(List l) { return parseDoubleLeftArrowMap((Map) ciMap(), l); } static public String joinNemptiesWithSpace(String... strings) { return joinNempties(" ", strings); } static public String joinNemptiesWithSpace(Collection strings) { return joinNempties(" ", strings); } static public boolean forbiddenPort(int port) { return port == 5037; } static public String dbBotName(String progIDWithCase) { return fsI_flex(progIDWithCase) + " Concepts"; } static public Collection conceptsWhereIC(Class c, Object... params) { return findConceptsWhereCI(c, params); } static public List conceptsWhereIC(String c, Object... params) { return findConceptsWhereCI(c, params); } static public Collection conceptsWhereIC(Concepts concepts, Class c, Object... params) { return findConceptsWhereCI(concepts, c, params); } static public List conceptsWhereIC(Concepts concepts, String c, Object... params) { return findConceptsWhereCI(concepts, c, params); } static public HashSet lithashset(A... items) { HashSet set = new HashSet(); for (A a : items) set.add(a); return set; } 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 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 boolean isOK(String s) { s = trim(s); return swic(s, "ok ") || eqic(s, "ok") || matchStart("ok", s); } 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 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 Object[] unrollParams(Object[] params) { if (l(params) == 1 && params[0] instanceof Map) return mapToParams((Map) params[0]); return params; } static public String dropLoadableUtilsPackageFromStruct(String s) { String prefix = "loadableUtils.utils$"; if (!contains(s, "loadableUtils.utils$")) return s; List tok = javaTokForStructure(s); for (int i = 5; i < l(tok); i += 2) if (eqGet(tok, i - 4, "loadableUtils") && eqGet(tok, i - 2, ".")) replaceTokens(tok, i - 4, i + 1, dropPrefix("utils$", tok.get(i))); return join(tok); } static public String optionalCurlyBrace(String s) { return isCurlyBraced(s) ? s : curlyBrace(s); } static public void setOptIfNotNull(Object o, String field, Object value) { if (value != null) setOpt(o, field, value); } 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 void warnIfOddCount(Object... list) { if (odd(l(list))) printStackTrace("Odd list size: " + list); } 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 String joinWithPlus(Collection c) { return join("+", c); } static public String joinWithPlus(String... c) { return join("+", c); } 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 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 String hcomment(String text) { return hcommentSafe(text); } 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 htd(Object contents, Object... params) { return htag("td", contents, params); } 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 List loadLibraries(List snippetIDs) { return map(__86 -> loadLibrary(__86), snippetIDs); } 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 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 String htextfield(String name, Object... params) { return htextinput(name, params); } static public List syncInstancesOf(Iterable i, Class c) { if (i == null) return new ArrayList(); synchronized (i) { return collectInstances(i, c); } } static public List syncInstancesOf(Class c, Iterable i) { return syncInstancesOf(i, c); } static public List map_ping(Iterable l, Object f) { return map_ping(f, l); } static public List map_ping(Object f, Iterable l) { List x = emptyList(l); if (l != null) for (Object o : l) x.add(callF(f, o)); return x; } static public List map_ping(Iterable l, F1 f) { return map_ping(f, l); } static public List map_ping(F1 f, Iterable l) { List x = emptyList(l); if (l != null) for (A o : l) x.add(callF(f, o)); return x; } static public List map_ping(IF1 f, Iterable l) { return map_ping(l, f); } static public List map_ping(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : l) { ping(); x.add(f.get(o)); } return x; } static public List map_ping(IF1 f, A[] l) { return map_ping(l, f); } static public List map_ping(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_ping(Object f, Object[] l) { return map_ping(f, asList(l)); } static public List map_ping(Object[] l, Object f) { return map_ping(f, l); } static public List map_ping(Object f, Map map) { return map_ping(map, f); } static public List map_ping(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_ping(Map map, IF2 f) { return map_ping(map, (Object) f); } static public String hhidden(String name, Object value, Object... params) { return tag("input", "", concatArrays(new Object[] { "type", "hidden", "name", name, "value", value }, params)); } static public String hhidden(Map map, String... keys) { return hiddenFields(map, keys); } 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)); } }; } 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 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 A bindLiveValueListenerToComponent(A component, IHasChangeListeners lv, Runnable listener) { return bindHasChangeListenersToComponent(component, lv, listener); } static public boolean isOfflineMode() { return eq("1", trim(loadProgramTextFile("#1005806", "offline-mode"))); } 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 void focusConsole(String s) { setConsoleInput(s); focusConsole(); } static public void focusConsole() { JComponent tf = consoleInputFieldOrComboBox(); if (tf != null) { tf.requestFocus(); } } 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 MultiSet multiSetMapToMultiSet(MultiSetMap mm) { MultiSet ms = new MultiSet(); for (A a : keys(mm)) ms.add(a, l(mm.get(a))); return ms; } static public String ulIfNempty(Collection list, Object... params) { return empty(list) ? "" : ul(list, params); } static public Object callAndMake_orDirect(String functionName, List args) { return callAndMake_orDirect(functionName, toObjectArray(args)); } static public Object callAndMake_orDirect(String functionName, Object... args) { if (functionName == null) return null; if (hasMethod(mc(), functionName, args)) return callMC(functionName, args); else return makeAndCall_cached(functionName, args); } static public GZIPInputStream newGZIPInputStream(File f) { return gzInputStream(f); } static public GZIPInputStream newGZIPInputStream(InputStream in) { return gzInputStream(in); } static public File touchFile(File file) { try { closeRandomAccessFile(newRandomAccessFile(mkdirsForFile(file), "rw")); return file; } catch (Exception __e) { throw rethrow(__e); } } static public int totalPreferredHeight(List l) { int h = 0; for (Component c : unnull(l)) h += c.getPreferredSize().height; return h; } static public Rectangle toRectangle(Rect r) { return r == null ? null : r.getRectangle(); } static public Object[] assertEvenLength(Object[] a) { assertTrue(even(l(a))); return a; } 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 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 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 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 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 JFrame consoleFrame() { return (JFrame) getOpt(get(getJavaX(), "console"), "frame"); } 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 IterableIterator> mapPairs(Map map) { final Iterator> it = map.entrySet().iterator(); return iteratorFromFunction(new F0>() { public Pair get() { try { if (it.hasNext()) { Map.Entry entry = it.next(); return pair(entry.getKey(), entry.getValue()); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (it.hasNext()) {\r\n Map.Entry entry = it.next();\r\n ret pair..."; } }); } static public List mapPairs(Iterable> l, IF2 f) { return mapPairsToList(l, f); } static public int identityHashCode(Object o) { return System.identityHashCode(o); } static public A assertBiggerThan(A a, A b) { assertTrue(cmp(b, a) > 0); return b; } static public String dropUriPrefix(String prefix, String uri) { prefix = dropTrailingSlash(prefix); if (empty(prefix)) return uri; if (eq(uri, prefix) || startsWith(uri, prefix + "/")) return substring(uri, l(prefix)); return uri; } 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 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 String hframeset_cols(String cols, Object contents, Object... params) { return tag("frameset", contents, paramsPlus(params, "cols", cols)); } static public WeakReference weakRef(A a) { return newWeakReference(a); } static public int globalIDLength() { return 16; } static public void closeAllWriters(Collection l) { for (Writer w : unnull(l)) { try { w.close(); } catch (Throwable __e) { pcallFail(__e); } } } static public A swingNu(final Class c, final Object... args) { return swingConstruct(c, args); } static public String firstToLower(String s) { if (empty(s)) return s; return Character.toLowerCase(s.charAt(0)) + s.substring(1); } 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 htmlEncode2_gen(Object o) { return htmlEncode2(strOrEmpty(o)); } 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 String simpleSpacesTrim_javaTok(String s) { return trim(simpleSpaces_javaTok(s)); } static public List concatLists_syncIndividual(Iterable... lists) { List l = new ArrayList(); if (lists != null) for (Iterable list : lists) syncAddAll(l, list); return l; } static public List concatLists_syncIndividual(Collection> lists) { List l = new ArrayList(); if (lists != null) for (Iterable list : lists) syncAddAll(l, list); return l; } 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 ThreadLocal makeAndCall_initChild = new ThreadLocal(); static public Object makeAndCall_cached(String functionName, Object... args) { Class c = loadFunctions_cached(functionName); AutoCloseable closer = (AutoCloseable) (callF(makeAndCall_initChild.get(), c)); AutoCloseable __1 = closer; try { return preciseCall(c, functionName, args); } finally { _close(__1); } } static public JTextArea jtextarea() { return jTextArea(); } static public JTextArea jtextarea(String text) { return jTextArea(text); } static public boolean isSubtypeOf(Class a, Class b) { return a != null && b != null && b.isAssignableFrom(a); } 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 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(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 String hpostform(Object contents, Object... params) { return tag("form", contents, concatArrays(new Object[] { "method", "POST" }, params)); } static public boolean emptyString(String s) { return s == null || s.length() == 0; } static public String charToString(char c) { return String.valueOf(c); } static public String charToString(int c) { return String.valueOf((char) c); } static public Map>> mechList_opt_tlft_cached_cache = ciMap(); static public Lock mechList_opt_tlft_cached_lock = lock(); static public List mechList_opt_tlft_cached(String name) { MechListDependentCache> listCache; { Lock __0 = mechList_opt_tlft_cached_lock; lock(__0); try { listCache = mechList_opt_tlft_cached_cache.get(name); if (listCache == null) mechList_opt_tlft_cached_cache.put(name, listCache = new MechListDependentCache(name, new F1>() { public List get(String x) { try { return tlft(x); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tlft(x)"; } })); } finally { unlock(__0); } } return listCache.get(); } 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 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 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 Class loadFunction_cached(String function) { return loadFunctions_cached(function); } static public A assertLessThan(A a, A b) { assertTrue(cmp(b, a) < 0); return b; } 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 boolean isAGIBlueDomain(String domain) { return domainIsUnder(domain, theAGIBlueDomain()); } static public void syncRemoveAllExceptLast(List l) { if (l == null) return; synchronized (collectionMutex(l)) { removeSubList(l, 0, l(l) - 1); } } static public ArrayList litlist(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } 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 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 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 String escapeNewLines(String s) { return s == null ? null : fixNewLines(s).replace("\n", " | "); } static public int methodApplicabilityScore(Method m, Object[] args) { Class[] types = m.getParameterTypes(); if (types.length != args.length) return Integer.MAX_VALUE; int score = 0; for (int i = 0; i < types.length; i++) { Object a = args[i]; Class c = types[i]; if (a == null) ++score; else if (c == a.getClass()) { } else if (isInstanceX(c, a)) ++score; else return Integer.MAX_VALUE; } return score; } 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 boolean endsWithLetter(String s) { return nempty(s) && isLetter(last(s)); } 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 boolean isStringCollection(Object o) { if (!(o instanceof Collection)) return false; Collection l = (Collection) o; for (Object x : l) if (!(x instanceof String)) return false; return true; } static public boolean matchEnd(String pat, String s) { return matchEnd(pat, s, null); } static public boolean matchEnd(String pat, String s, Matches matches) { if (s == null) return false; List tokpat = parse3(pat), toks = parse3(s); if (toks.size() < tokpat.size()) return false; String[] m = match2(tokpat, takeLast(l(tokpat), toks)); if (m == null) return false; if (matches != null) { matches.m = new String[m.length + 1]; arraycopy(m, matches.m); matches.m[m.length] = join(dropLast(l(tokpat), toks)); } return true; } 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 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 addParamsToURL(String url, Map params) { return appendQueryToURL(url, params); } static public String addParamsToURL(String url, Object... data) { return appendQueryToURL(url, data); } 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 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 TreeMap asCIMap(Map map) { return asCaseInsensitiveMap(map); } static public String hscriptsrc(String src) { return hjavascript_src(src); } static public boolean startsWithDigit(String s) { return nempty(s) && isDigit(s.charAt(0)); } static public String unicode_downPointingTriangle() { return charToString(0x25BC); } 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 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 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 List htmlcoarsetok(String s) { List 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 (s.charAt(j) != '<') ++j; else if (s.substring(j, Math.min(j + 4, l)).equals("")); j = Math.min(j + 3, l); } else { char d = charAt(s, j + 1); if (d == '/' || isLetter(d)) break; else ++j; } } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); if (c == '<') { ++j; while (j < l && s.charAt(j) != '>') ++j; if (j < l) ++j; } tok.add(s.substring(i, j)); i = j; } if ((tok.size() & 1) == 0) tok.add(""); return tok; } 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); } } 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 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 int addAndReturnIndex(List l, A a) { if (l == null) return -1; int idx = l.size(); l.add(a); return idx; } static public String javaValueToHTML(Object value) { return javaValueToHTML(value, identityHashSet()); } static public String javaValueToHTML(Object value, Set seen) { if (!seen.add(value)) return "see above"; if (value instanceof String) return htmlEncode_quote((String) value); else if (value instanceof List) return ol(map(((List) value), v -> javaValueToHTML(v, seen))); else return htmlEncode(shorten(str(value))); } static public boolean isAllUpperCase(String s) { return hasLettersAllUpperCase(s); } static public String regexReplace(String s, String pat, Object f) { Matcher m = Pattern.compile(pat).matcher(s); return regexReplace(m, 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 List flexMatchIC_getVarIndices(List tokPat, List tokInput) { List varIndices = new ArrayList(); for (int i = 1; i < l(tokPat); i += 2) { String t = tokPat.get(i); if (eq(t, "*")) varIndices.add(i); else if (isIdentifier(t) && !cicAtOddPosition(tokInput, t)) { return null; } } return varIndices; } 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 boolean isAllDigits(String s) { int n = l(s); for (int i = 0; i < n; i++) if (!isDigit(s.charAt(i))) return false; return true; } static public B mapPut_returnValue(Map map, A key, B value) { mapPut(map, key, value); return value; } 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 boolean publicCommOn() { return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication"))); } static public Cache> countryDialCodes_cache = new Cache<>(() -> countryDialCodes_load()); static public List countryDialCodes() { return countryDialCodes_cache.get(); } static public List countryDialCodes_load() { return sortedByField("dialCode", filter(c -> nempty(c.dialCode), map((List>) loadJSONFile(loadLibrary("#1400429")), m -> new CountryDialCode(m.get("name"), m.get("code"), m.get("dial_code"))))); } 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 boolean isTrue_getOpt(String field, Object o) { return isTrue(getOpt(field, o)); } static public List syncList() { return synchroList(); } static public List syncList(List l) { return synchroList(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 String formatColonProperties(Map map) { return mapToLines(__87 -> joinPairWithColon(__87), mapToPairs(map)); } static public String formatColonProperties(List> l) { return mapToLines(__88 -> joinPairWithColon(__88), l); } static public String formatColonProperties(Object... params) { return formatColonProperties(paramsToPairs(params)); } 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 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 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 String htmlEncode_quote(Object o) { return htmlEncode2(quote(o)); } static public A showWindow(A w) { if (w != null) { swing(() -> { w.setVisible(true); }); } return w; } 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 Object subBot_serveByteArray(byte[] data, String mimeType) { return call(mainBot(), "serveByteArray", data, mimeType); } static public void disposeInternalFrame(Component c) { final JInternalFrame f = getInternalFrame(c); if (f != null) { swing(() -> { vmBus_send("disposingInternalFrame", f); f.dispose(); }); } } static public ConceptFieldIndexCI indexConceptFieldIC(Class c, String field) { return indexConceptFieldCI(c, field); } static public ConceptFieldIndexCI indexConceptFieldIC(Concepts concepts, Class c, String field) { return indexConceptFieldCI(concepts, c, field); } static public void dm_watchField(String field, Runnable onChange) { new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange); } 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 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 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 int levenWithSwapsIC(String s, String t) { if (s.equals(t)) return 0; int ls = s.length(), lt = t.length(); if (ls == 0) return lt; if (lt == 0) return ls; int[] vx = new int[lt + 1]; int[] v0 = new int[lt + 1]; int[] v1 = new int[lt + 1]; for (int i = 0; i < v0.length; i++) v0[i] = i; for (int i = 0; i < ls; i++) { v1[0] = i + 1; for (int j = 0; j < lt; j++) { int cost = equalsIgnoreCase(s.charAt(i), t.charAt(j)) ? 0 : 1; int d = min3(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost); if (i > 0 && j > 0 && equalsIgnoreCase(s.charAt(i), t.charAt(j - 1)) && equalsIgnoreCase(s.charAt(i - 1), t.charAt(j))) d = min(d, vx[j - 1] + 1); v1[j + 1] = d; } int[] v = vx; vx = v0; v0 = v1; v1 = v; } return v0[lt]; } 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 isUpperCaseLetter(char c) { return Character.isUpperCase(c); } static public Object deref(Object o) { if (o instanceof IRef) return ((IRef) o).get(); return o; } 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 Map matchesToMapUsingVarList_ciMap(Matches m, List vars) { if (m == null) return null; Map map = ciMap(); int n = min(l(m.m), l(vars)); for (int i = 0; i < n; i++) if (!strictPutIC(map, vars.get(i), m.get(i))) return null; return map; } static public List cloneAndClear(Collection l) { return cloneAndClearList(l); } 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 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 A printHidingCredentials(A o) { print(hideCredentials(str(o))); return o; } static public A println(A a) { return print(a); } 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 MetaTransformer metaTransformer_transformableAndList() { return new MetaTransformer(new MetaTransformer.StructureHandler() { public Object transform(Object o, IF1 recurse) { if (o instanceof Transformable) return ((Transformable) o).transformUsing(recurse); if (o instanceof List) return map_ping(recurse, ((List) o)); return null; } public void visit(Object o, IVF1 recurse) { if (o instanceof Visitable) ((Visitable) o).visitUsing(recurse); else if (o instanceof List) for (Object x : ((List) o)) { ping(); recurse.get(x); } } }); } 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 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 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 Object[] expandParams(Class c, Object[] params) { if (l(params) == 1) params = new Object[] { singleFieldName(c), params[0] }; else warnIfOddCount(params); return params; } static public String sourceCodeToHTML_noEncode(String html) { return "
" + html + "
"; } 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 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 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 String dropSuffix(String suffix, String s) { return nempty(suffix) && endsWith(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } 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 boolean startsWithLetterOrDigit(String s) { return nempty(s) && Character.isLetterOrDigit(s.charAt(0)); } static public String getTag(String s) { if (!startsWith(s, "<")) return null; int i = 1; if (charAt(s, i) == '/') ++i; while (" \t>/\0".indexOf(charAt(s, i)) < 0) ++i; return substring(s, 1, i); } 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 List hotwire_libraryIDsFromJar_deleteJarOnFail(File jar) { try { return hotwire_libraryIDsFromJar(jar); } catch (Throwable _e) { jar.delete(); throw rethrow(_e); } } static public Object subBot_serveWithContentType(String text, String contentType) { return callMainBot("serveByteArray", toUtf8(unnull(text)), contentType); } static public
Collection> cForwardAndBackRefsWithFieldIndicator(Concept c, Class type) { return concatLists_conservative(mapPairsB(cForwardRefsWithFieldNames(c, type), f -> new FieldIndicator(f, true)), mapPairsB(findBackRefsWithFieldNames(c, type), f -> new FieldIndicator(f, false))); } static public Collection> cForwardAndBackRefsWithFieldIndicator(Class type, Concept c) { return cForwardAndBackRefsWithFieldIndicator(c, type); } 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 File makeTempDir() { return (File) call(getJavaX(), "TempDirMaker_make"); } 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 String renderDBSaveTime() { return renderDBSaveTime(db_mainConcepts()); } static public String renderDBSaveTime(Concepts cc) { if (cc == null) return null; return cc.lastSaveTook < 0 ? "unknown" : n2(cc.lastSaveTook) + " ms"; } static public Set synchroHashSet() { return synchronizedSet(new HashSet()); } 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 Object serve404() { return subBot_serve404(); } static public Object serve404(String msg) { return subBot_serve404(msg); } static public List objectsWhereCI(Collection c, Object... data) { return objectsWhereIC(c, data); } 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 String getStringOpt(Map map, Object key) { return map == null ? null : optCast(String.class, map.get(key)); } static public String getStringOpt(List l, int idx) { return optCast(String.class, get(l, idx)); } static public String getStringOpt(Object o, Object key) { if (o instanceof Map) return getStringOpt((Map) o, key); if (key instanceof String) return optCast(String.class, getOpt(o, (String) key)); throw fail("Not a string key: " + getClassName(key)); } static public String getStringOpt(String key, Object o) { return getStringOpt(o, (Object) key); } static public List splitAtDoubleArrow_tok; static public List splitAtDoubleArrow_tok() { if (splitAtDoubleArrow_tok == null) splitAtDoubleArrow_tok = ll("=", "", ">"); return splitAtDoubleArrow_tok; } static public boolean isCurlyBracketed(String s) { return isCurlyBraced(s); } static public String pIfNempty(String contents, Object... params) { return nempty(contents) ? p(contents, params) : ""; } 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 int snippetType_dynModule() { return 57; } 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 Map flexMatchAngleBracketVarsIC_honorPunctuation_first(String pat, String input) { return grabValueAndCancel(new VF1>>() { public void get(VF1> onMatch) { try { flexMatchAngleBracketVarsIC_honorPunctuation_iterate(pat, input, onMatch); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "flexMatchAngleBracketVarsIC_honorPunctuation_iterate(pat, input, onMatch);"; } }); } 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 double elapsedSeconds_sysNow(long time) { return elapsedSeconds(time); } static public JMenuItem disableMenuItem(final JMenuItem mi) { if (mi != null) { swing(() -> { mi.setEnabled(false); }); } return mi; } 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 Throwable getException(Runnable r) { try { callF(r); return null; } catch (Throwable e) { return e; } } static public Object costCenter() { return mc(); } 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 void replaceCollection(Collection dest, Collection src) { if (dest == src) return; dest.clear(); if (src != null) dest.addAll(src); } static public Map parseDoubleLeftArrowMapCI_tlft(String s) { return parseDoubleLeftArrowMapCI(tlft(s)); } static public List pairsB(Collection> l) { return secondOfPairs(l); } static public List pairsA(Collection> l) { return firstOfPairs(l); } static public void ensureConceptClassesAreIndexed(Collection classes) { ensureConceptClassesAreIndexed(db_mainConcepts(), classes); } static public void ensureConceptClassesAreIndexed(Concepts cc, Collection classes) { for (Class c : unnullForIteration(classes)) ensureConceptClassIsIndexed(cc, c); } static public void ensureConceptClassesAreIndexed(Class... classes) { ensureConceptClassesAreIndexed(db_mainConcepts(), classes); } static public void ensureConceptClassesAreIndexed(Concepts cc, Class... classes) { ensureConceptClassesAreIndexed(cc, asList(classes)); } 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 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 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 boolean checkFieldsIC(Object x, Object... data) { for (int i = 0; i < l(data); i += 2) if (!eqicOrEq(getOpt(x, (String) data[i]), data[i + 1])) return false; return true; } static volatile public String caseID_caseID; static public String caseID() { return caseID_caseID; } static public void caseID(String id) { caseID_caseID = id; } static public Map cgetAll_cloneLists(Concept c, Collection fields) { return mapToValues(fields, f -> cloneIfList(cget(c, f))); } static public boolean swic_notSame(String a, String b) { return swic_notSame(a, b, null); } static public boolean swic_notSame(String a, String b, Matches m) { return l(a) > l(b) && swic(a, b, m); } 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 String x30JarServerURL() { return "https://botcompany.de:9898/x30.jar"; } static public File getCachedTranspilationFile(String id) { return newFile(getCodeProgramDir(id), "Transpilation"); } 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 List> cForwardRefsWithFieldNames(Concept c, Class type) { return mapNonNulls(scanConceptForRefsWithFieldNames(c), p -> isInstanceOf(derefRef(p.a), type) ? pair((A) derefRef(p.a), p.b) : null); } static public boolean nemptyString(String s) { return s != null && s.length() > 0; } static public String hstyle(Object contents) { return hcss(contents); } static public TreeMap asCaseInsensitiveMap(Map map) { if (isCIMap(map)) return (TreeMap) map; TreeMap m = ciMap(); putAll(m, map); return m; } 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 IntObjectHashMap refs = new IntObjectHashMap(); public IntObjectHashMap tokrefs = new IntObjectHashMap(); 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("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("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 String uncurly(String s) { return tok_unCurlyBracket(s); } static public String replaceSquareBracketVars(String s, Object... params) { if (empty(params)) return s; Map vars = mapKeys(__89 -> deSquareBracket(__89), (Map) litcimap(params)); return regexpReplaceIC(s, "\\[(.+?)\\]", matcher -> { String var = matcher.group(1); Object val = vars.get(var); return val == null ? matcher.group() : str(val); }); } 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 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 List keysList(Map map) { return cloneListSynchronizingOn(keys(map), map); } static public List keysList(MultiSet ms) { return ms == null ? null : keysList(ms.map); } static public Object[] dropParam(Object key, Object[] params) { return paramsWithout(params, key); } 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 boolean isValidInternationalPhoneNumber(String s) { InternationalPhoneValidator v = new InternationalPhoneValidator(s); v.run(); if (v.error != null) print(v.error); return v.valid; } static public List parseBusinessHours_pcall(String s) { try { return parseBusinessHours(s); } catch (Throwable __e) { pcallFail(__e); } return null; } 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 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 String htmlTable2_noHtmlEncode(Object data, Object... __) { return htmlTable2(data, paramsPlus(__, "htmlEncode", false)); } static public long parseSecondLong(String s) { List tok = javaTokC(s); int i = 0; while (i < l(tok) && !isInteger(tok.get(i))) ++i; ++i; while (i < l(tok) && !isInteger(tok.get(i))) ++i; if (i < l(tok)) return parseLong(tok.get(i)); return 0; } 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 List sortedByConceptID(Collection c) { return sortedByCalculatedField(__90 -> conceptID(__90), c); } static public String nErrors(long n) { return n2(n, "error"); } static public String nErrors(Collection l) { return nErrors(l(l)); } static public String nErrors(Map map) { return nErrors(l(map)); } 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 List reversedList(Iterable l) { List x = cloneList(l); Collections.reverse(x); return x; } static public String getSnippetTitleOpt(String s) { try { return isSnippetID(s) ? getSnippetTitle(s) : s; } catch (Throwable __e) { pcallFail(__e); } return s; } static public String hostNameFromURL(String url) { try { return empty(url) ? null : new URL(url).getHost(); } catch (Exception __e) { throw rethrow(__e); } } 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 int localYear() { return localYear(now()); } static public int localYear(long time) { return parseInt(simpleDateFormat_local("yyyy").format(time)); } static public A ifThenElse(boolean b, A trueValue, A falseValue) { return b ? trueValue : falseValue; } static public String stringPar(Object[] params, String name) { return stringOptPar(params, name); } static public String stringPar(String name, Object[] params) { return stringOptPar(params, name); } static public String stringPar(String name, Map params) { return (String) optPar(name, params); } static public String stringPar(String name, Object[] params, String defaultValue) { return optPar(name, params, defaultValue); } static public boolean domainIsUnder(String domain, String mainDomain) { return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain); } static public int getScreenHeight() { return getScreenSize().height; } static public boolean directoryIsEmpty(File f) { return !fileExists(f) || isDirectory(f) && empty(listFiles(f)); } static public File getGlobalCache() { File file = new File(javaxCachesDir(), "Binary Snippets"); file.mkdirs(); return file; } static public List simplifySafetyTags(Collection tags) { List l = uniquifyList(tags); if (l.contains("safe") && containsAnythingNeq(l, "safe")) return listMinus(l, "safe"); return l; } static public String simplifySafetyTags(String tags) { List l = tokSplitAtComma(tags); Collection l2 = simplifySafetyTags(l); return l(l2) != l(l) ? joinWithComma(l2) : tags; } static public A keyWithBiggestValue(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 String himgsnippet(String imageID, Object... params) { return hsnippetimg(imageID, params); } static public String jsBackLink() { return "javascript:history.go(-1)"; } static public String jsQuote(String s) { return javascriptQuote(s); } static public Object jsonPrepareData(Object... data) { if (l(data) == 1) return data[0]; return litorderedmap(data); } static public boolean isSpace(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } static public void closeAllKeysAndClear(Map map) { closeAllAndClear(keys(map)); } static public String htmlEncode2_nlToBr(String s) { return htmlEncode_nlToBr(s); } 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 formatSnippetID(String id) { return "#" + parseSnippetID(id); } static public String formatSnippetID(long id) { return "#" + id; } static public boolean isCodeSafe(String code) { return isSafeCodeFragment(code); } static public String getSelectedItem(JList l) { return (String) l.getSelectedValue(); } static public String getSelectedItem(JComboBox cb) { return strOrNull(cb.getSelectedItem()); } static public void saveTranspiledStandardFunctions(TreeSet functionSet, String transpiledSrc) { try { saveTextFile(transpiledStandardFunctions_file(functionSet), transpiledSrc); } catch (Throwable __e) { pcallFail(__e); } } static public boolean startsWithAndEndsWith(String s, String prefix, String suffix) { return startsWith(s, prefix) && endsWith(s, suffix); } static public Comparator descFieldComparator(final String field) { return new Comparator() { public int compare(A a, A b) { return cmp(getOpt(b, field), getOpt(a, field)); } }; } 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 String ymd_minus_hms() { return ymd_minus_hms(now()); } static public String ymd_minus_hms(long now) { return ymd(now) + "-" + hms(now); } 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 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 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 List callF_all(Collection l, Object... args) { return map(l, f -> callF(f, args)); } static public List> findContainerTag(List tok, String tag) { List> l = new ArrayList(); for (int i = 1; i < l(tok); i += 2) if (isOpeningTag(tok.get(i), tag)) { int j, level = 1; for (j = i + 2; j < tok.size(); j += 2) if (isOpeningTag(tok.get(j), tag)) ++level; else if (isTag(tok.get(j), "/" + tag)) { --level; if (level == 0) { l.add(subList(tok, i - 1, j + 2)); break; } } i = j; } return l; } static public List> findContainerTag(String html, String tag) { return findContainerTag(htmlTok(html), tag); } static public GlobalID aGlobalIDObj() { return asGlobalID(randomID(16)); } static public GlobalID aGlobalIDObj(Random random) { return asGlobalID(randomID(random, 16)); } 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 B mapGet2(Map map, A a) { return map == null ? null : map.get(a); } static public B mapGet2(A a, Map map) { return map == null ? null : map.get(a); } static public String hsnippetimg_scaleToWidth(int width, String imageID, int originalWidth, int originalHeight, Object... params) { return hsnippetimg(imageID, paramsPlus(params, "width", width, "height", calcHeight(originalWidth, originalHeight, width))); } static public String nlToBr(String s) { return s.replace("\n", "
\n"); } 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 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 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 boolean cicAtOddPosition(List l, String s) { int n = l(l); for (int i = 1; i < n; i += 2) if (eqic(l.get(i), s)) return true; return false; } 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 void dm_setModuleName(Object module, String name) { dm_callModule(module, "setModuleName", name); } static public void dm_setModuleName(String name) { dm_setModuleName(dm_current_mandatory_generic(), name); } 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 String loadJQuery() { return ""; } 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 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 Object addHeader(String header, String value, Object response) { call(response, "addHeader", header, value); return response; } static public ReentrantLock fairLock() { return new ReentrantLock(true); } 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 A firstOfPair(Pair p) { return p == null ? null : p.a; } 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 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 String addLineBreak(String s) { return addSuffix(s, "\n"); } static public String multiLineQuoteWithSpaces(String s) { return multiLineQuote(" " + s + " "); } 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 boolean addDefaultVMOption(String option) { String s = defaultVMArgs(), old = s; if (!s.contains(option)) s = trim(s + " " + option); if (eq(old, s)) return false; { setDefaultVMArgs(s); return true; } } 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 String hfileupload(Object... params) { return hinputtag("", paramsPlus_noOverwrite(params, "type", "file", "name", "thefile")); } 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 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 String dialCodeStringForCountryCode(String countryCode) { CountryDialCode cdc = countryDialCodeByCountryCode(countryCode); return cdc == null ? null : cdc.dialCode; } static public A nuStubInnerObject(Class c) { return nuStubInnerObject(c, null); } static public A nuStubInnerObject(Class c, Object classFinder) { try { return (A) nuStubInnerObject_findConstructor(c, classFinder).newInstance(new Object[] { null }); } catch (Exception __e) { throw rethrow(__e); } } static public Set newWeakHashSet() { return synchroWeakHashSet(); } 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 String struct_noStringSharing(Object o) { structure_Data d = new structure_Data(); d.noStringSharing = true; return structure(o, d); } static public A keyWithHighestValue(Map map) { return keyWithBiggestValue(map); } 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 Object callOptMC(String method, Object... args) { return callOpt(mc(), method, args); } static public JPanel showFormTitled_customLayout(final F1 layouter, final String title, final Object... parts) { return showFormTitled_customArrangement(false, 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)"; } }, title, parts); } static public String squareBracketed(String s) { return "[" + s + "]"; } static public List javaTokWithAllPlusAngleBracketsC(String s) { return codeTokens(javaTokWithAllPlusAngleBrackets(s)); } 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 String hjssrc(String src) { return hjavascript_src(src); } static public List lookupPossiblyCI(MultiMap map, String key) { return lookupPossiblyIgnoreCase(map, key); } static public A lookupPossiblyCI(Map map, String key) { return lookupPossiblyIgnoreCase(map, key); } static public String programName() { return getProgramName(); } public static List parseSnippetIDs(Collection snippetIDs) { List l = new ArrayList(); for (String id : snippetIDs) l.add(str(parseSnippetID(id))); return l; } static public String strOrNull(Object o) { return o == null ? null : str(o); } 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 void addToStringTree(StringTree2 tree, List tokC, A leafValue) { if (leafValue == null) return; if (empty(tokC)) { tree.leafValue = leafValue; return; } String s = first(tokC); StringTree2 t = tree.getOrAdd(s); addToStringTree(t, dropFirst(tokC), leafValue); } static public String repLine(int n, String s) { return lines(rep(n, s)); } static public boolean useDummyMainClasses() { return true; } static public String nSteps(long n) { return n2(n, "step"); } static public String nSteps(Collection l) { return nSteps(l(l)); } 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 hInitWebSocket(Object... __) { String wsVar = optPar("wsVar", __, "ws"); String onOpen = (String) (optPar("onOpen", __)); String onMessage = (String) (optPar("onMessage", __)); String readyMsg = optPar("readyMsg", __, "WebSocket ready!"); return hreconnectingWebSockets() + hscript("\r\n var wsReady = false;\r\n var wsInitialMsgs = [];\r\n var wsVerbose = false;\r\n var " + wsVar + " = new ReconnectingWebSocket(((window.location.protocol === \"https:\") ? \"wss://\" : \"ws://\") + window.location.host + \"/\");\r\n \r\n " + wsVar + ".onopen = function(event) {\r\n wsReady = true;\r\n console.log(" + jsQuote(readyMsg) + ");\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 " + jsDropTrailingComments(onOpen) + " };\r\n \r\n " + wsVar + ".onmessage = function(event) {\r\n " + unnull(onMessage) + "\r\n };\r\n \r\n // add an initial message to send when websocket opens\r\n // also send it now if ws is open already\r\n function wsInitialMsg(msg) {\r\n wsInitialMsgs.push(msg);\r\n if (wsReady) {\r\n if (wsVerbose) console.log(\"Sending initial msg: \" + msg);\r\n ws.send(msg);\r\n }\r\n }\r\n "); } static public String defaultThreadName_name; static public String defaultThreadName() { if (defaultThreadName_name == null) defaultThreadName_name = "A thread by " + programID(); return defaultThreadName_name; } 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 boolean isJavaXClassLoader(ClassLoader cl) { return startsWithOneOf(className(cl), "main$JavaXClassLoader", "x30$JavaXClassLoader"); } 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 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 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 ExpiringMap2 loadSnippet_simpleCache_map = new ExpiringMap2(10000); static public Lock loadSnippet_simpleCache_lock = lock(); static public int loadSnippet_simpleCache_timeout = 60000; static public String loadSnippet_simpleCache(String id) { if (id == null) return null; Lock __0 = loadSnippet_simpleCache_lock; lock(__0); try { id = fsI(id); String src = loadSnippet_simpleCache_map.get(id); if (src != null) return src; Integer oldTimeout = setThreadLocal(loadPage_forcedTimeout_byThread, loadSnippet_simpleCache_timeout); try { src = loadSnippet(id); if (src != null) loadSnippet_simpleCache_map.put(id, src); return src; } finally { loadPage_forcedTimeout_byThread.set(oldTimeout); } } finally { unlock(__0); } } 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 boolean isAngleBracketVar(String s) { return isAngleBracketed(s); } static public void upgradeJavaXAndRestart() { run("#1001639"); restart(); sleep(); } static public boolean anyFileWithExtensionInDir(File dir, String ext) { return nempty(filesWithExtension(ext, findAllFiles_noDirs(dir))); } static public List replaceSubList(List l, List x, List y) { return replaceSublist(l, x, y); } static public List replaceSubList(List l, int fromIndex, int toIndex, List y) { return replaceSublist(l, fromIndex, toIndex, y); } static public String serveSnippetURL(String snippetID) { return "https://botcompany.de/serve/" + psI(snippetID); } 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 void _close(AutoCloseable c) { if (c != null) try { c.close(); } catch (Throwable e) { if (c instanceof javax.imageio.stream.ImageOutputStream) return; else throw rethrow(e); } } static public String starsToAngleBracketedNumbers(String s) { List tok = javaTokWithAngleBrackets(s); int count = 0; for (int idx : indicesOf(tok, "*")) tok.set(idx, angleBracketed(str(++count))); return join(tok); } 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 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 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 List splitBusinessHoursAtMidnight(List l) { return concatLists(map(l, r -> r.end < r.start && r.start > 12 ? ll(intRange(r.start, 24 * 60), intRange(0, r.end)) : ll(r))); } 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 Collection getCodeFragmentSafety(String code) { Map map = codeAnalysis_identifierSafetyMap(); Set identifiers = tok_allIdentifiers(code); Collection tags = treeSet(); for (String id : identifiers) { String tag; if (codeAnalysis_isSafeIdentifier(id)) tag = "safe"; else tag = or2(map.get(id), "?"); tags.addAll(tokSplitAtComma(tag)); } tags = simplifySafetyTags(tags); if (empty(tags)) tags.add("safe"); return tags; } static public Object serveJSON_shallowLineBreaks(Object data) { return serveText(jsonEncode_shallowLineBreaks(data)); } static public void printExceptionShort(Throwable e) { printExceptionShort("", e); } static public void printExceptionShort(String prefix, Throwable e) { print(prefix, exceptionToStringShort(e)); } static public String getInnerMessage(Throwable e) { if (e == null) return null; return getInnerException(e).getMessage(); } static public Set putSetElementsFirst(Collection cl, Collection elements) { Set inputSet = asSet(cl); LinkedHashSet set = new LinkedHashSet(); for (A a : unnullForIteration(elements)) if (contains(inputSet, a)) set.add(a); addAll(set, cl); return set; } static public Set putSetElementsFirst(Collection cl, A... elements) { return putSetElementsFirst(cl, asList(elements)); } static public void close_pcall(AutoCloseable c) { if (c != null) { try { c.close(); } catch (Throwable __e) { pcallFail(__e); } } } static public List sortedByFieldDesc(Collection c, String field) { List l = new ArrayList(c); sort(l, descFieldComparator(field)); return l; } static public List sortedByFieldDesc(String field, Collection c) { return sortedByFieldDesc(c, field); } static public String renderConceptDate(Concept cc) { if (cc == null) return ""; String c = formatLocalDateWithSeconds(cc.created); String m = formatLocalDateWithSeconds(cc._modified); String s = "Created " + c; if (neq(c, m)) s += ", modified " + m; return s; } 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 A syncNextToLast(List l) { if (l == null) return null; synchronized (l) { return nextToLast(l); } } 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 hpassword(String name, Object... params) { return hpasswordfield(name, params); } static public String hpassword(String name) { return hpasswordfield(name); } static public String intToHex_flexLength(int i) { return Integer.toHexString(i); } static public Map.Entry firstEntry(Map map) { return empty(map) ? null : first(map.entrySet()); } 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 internIfLongerThan(String s, int l) { return s == null ? null : l(s) >= l ? intern(s) : s; } 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 boolean hasLock(Lock lock) { return ((ReentrantLock) lock).isHeldByCurrentThread(); } 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 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 double toM_double(long l) { return l / (1024 * 1024.0); } static public File getProgramDir() { return programDir(); } static public File getProgramDir(String snippetID) { return programDir(snippetID); } 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 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 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 Set> _entrySet(Map map) { return map == null ? Collections.EMPTY_SET : map.entrySet(); } 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 List listZIP(File inZip) { return listZip(inZip); } static public Object first(Object list) { return first((Iterable) list); } static public A first(List list) { return empty(list) ? null : list.get(0); } static public A first(A[] bla) { return bla == null || bla.length == 0 ? null : bla[0]; } static public Pair first(Map map) { return mapEntryToPair(first(entrySet(map))); } static public Pair first(MultiMap mm) { if (mm == null) return null; var e = first(mm.data.entrySet()); if (e == null) return null; return pair(e.getKey(), first(e.getValue())); } static public A first(IterableIterator i) { return first((Iterator) i); } static public A first(Iterator i) { return i == null || !i.hasNext() ? null : i.next(); } static public A first(Iterable i) { if (i == null) return null; Iterator it = i.iterator(); return it.hasNext() ? it.next() : null; } static public Character first(String s) { return empty(s) ? null : s.charAt(0); } static public Character first(CharSequence s) { return empty(s) ? null : s.charAt(0); } static public A first(Pair p) { return p == null ? null : p.a; } static public A first(T3 t) { return t == null ? null : t.a; } static public Byte first(byte[] l) { return empty(l) ? null : l[0]; } static public Double first(double[] l) { return empty(l) ? null : l[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 span(Object contents, Object... params) { return hfulltag("span", contents, params); } static public String span() { return span(""); } static public String asciiSideBySide(List texts) { if (l(texts) < 2) return unnull(first(texts)); if (l(texts) > 2) return asciiSideBySide(ll(asciiSideBySide(dropLast(texts)), last(texts))); List l1 = lines(first(texts)), l2 = lines(second(texts)); int col1 = maxStringLength(l1), n = max(l(l1), l(l2)); StringBuilder buf = new StringBuilder(); for (int i = 0; i < n; i++) buf.append(rpad(unnull(get(l1, i)), col1)).append(unnull(get(l2, i))).append("\n"); return str(buf); } static public LinkedHashMap litorderedmap(Object... x) { LinkedHashMap map = new LinkedHashMap(); litmap_impl(map, x); return map; } static public int indexOfSpaceEtc(String s) { int n = l(s); for (int i = 0; i < n; i++) if (isSpace(s.charAt(i))) return i; return -1; } 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 List tok_subListWithoutBorderNTokens(List tok, int i, int j) { List tok2 = cloneSubList(tok, i & (~1), j | 1); tok2.set(0, ""); tok2.set(l(tok2) - 1, ""); return tok2; } static public boolean networkAllowanceTest(String url) { return isAllowed("networkAllowanceTest", url); } 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 List allChildren(Component c) { return childrenOfType(c, Component.class); } 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 List mechList_opt(String name) { return mechList_opt_tlft(name); } 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 Map filterMapByFunctionOnKey(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 filterMapByFunctionOnKey(Object f, Map map) { return filterMapByFunctionOnKey(map, f); } static public String ahref_unstyled(String link, Object contents, Object... params) { if (link == null) return str(contents); return ahref(link, contents, paramsPlus(params, "style", unparseCSSParameter(mapPlus_noOverwrite(parseCSSParameter(stringPar("style", params)), "text-decoration", "none", "color", "inherit")))); } static public List sortFilesByName(List l) { sort(l, (a, b) -> stdcompare(a.getName(), b.getName())); return l; } static public VF2 ivf2ToVF2(IVF2 f) { return f == null ? null : new VF2() { public void get(A a, B b) { try { f.get(a, b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.get(a, b)"; } }; } static public A syncLast(List l) { if (l == null) return null; synchronized (l) { return last(l); } } 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 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 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 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 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, 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 String nlToBr_withIndents(String s) { s = nlToBr(s); StringBuilder buf = new StringBuilder(); int i = 0; while (i < l(s)) { while (charAt(s, i) == ' ') { ++i; buf.append(" "); } int j = smartIndexOf(s, i, '\n') + 1; buf.append(substring(s, i, j)); i = j; } return str(buf); } static public String hsnippetimg(String imageID, Object... params) { return himg(snippetImageLink(imageID), params); } static public AutoCloseable vmBus_onMessage(String msg, IVF1 onMessage) { return vmBus_onMessage(msg, ivf1ToVF1(onMessage)); } static public AutoCloseable vmBus_onMessage(final String msg, final VF1 onMessage) { Map map = vm_busListenersByMessage_live(); synchronized (map) { Set listeners = map.get(msg); if (listeners == null) map.put(msg, listeners = syncIdentityHashSet()); return tempAdd(listeners, new VF2() { public void get(String _msg, Object arg) { try { callF(onMessage, arg); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, arg)"; } }); } } static public AutoCloseable vmBus_onMessage(String msg, final VF2 onMessage) { return vmBus_onMessage(msg, new VF1() { public void get(Object[] o) { try { callF(onMessage, first(o), second(o)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, first(o), second(o));"; } }); } static public AutoCloseable vmBus_onMessage(String msg, final IVF2 onMessage) { return vmBus_onMessage(msg, new VF1() { public void get(Object[] o) { try { callF(onMessage, first(o), second(o)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(onMessage, first(o), second(o));"; } }); } static public AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) { return vmBus_onMessage(msg, runnableToVF1(onMessage)); } static public String getUpToDateSnippetTranspilationMD5(String snippetID) { try { return loadPageSilently(tb_mainServer() + "/tb-int/get-transpilation-md5.php?id=" + psI(snippetID) + standardCredentials_noCookies()); } catch (Exception __e) { throw rethrow(__e); } } static public String renderEqualsCommaProperties(Map map) { return joinWithComma(map(map, (key, value) -> key + "=" + value)); } 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 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 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 remoteMechListMirrorsDir() { return javaxDataDir("Remote Mech Lists"); } static public MultiSetMap treeMultiSetMap() { return new MultiSetMap(true); } static public MultiSetMap treeMultiSetMap(Comparator comparator) { return new MultiSetMap(new TreeMap>(comparator)); } static public String utf8streamToString(InputStream in) { return readerToString(utf8bufferedReader(in)); } 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 String hjs_autoExpandingTextAreas() { return hjs_autoExpandingTextAreas(false); } static public String hjs_autoExpandingTextAreas(boolean verbose) { return hcss("\r\n .auto-expand {\r\n max-height: 30em; vertical-align: top;\r\n }\r\n ") + hjs(replaceDollarVars("\r\n var autoExpandVerbose = $verbose;\r\n \r\n var autoExpandTextArea = function (ta) {\r\n ta.style.height = \"1px\";\r\n \r\n // Get the computed styles for the element\r\n var computed = window.getComputedStyle(ta);\r\n \r\n var h = ta.scrollHeight\r\n + parseInt(computed.getPropertyValue('border-top-width'))\r\n + parseInt(computed.getPropertyValue('border-bottom-width'));\r\n \r\n if (autoExpandVerbose)\r\n console.log(\"Calculated auto-expand height \" + h + \" for \" + ta);\r\n ta.style.height = h + 'px';\r\n };\r\n \r\n document.addEventListener('input', function (event) {\r\n if (!event.target.classList.contains(\"auto-expand\")) return;\r\n autoExpandTextArea(event.target);\r\n }, false);\r\n \r\n //$(document).ready(function() {\r\n document.addEventListener(\"DOMContentLoaded\", function(event) { \r\n $(\".auto-expand\").each(function() { autoExpandTextArea(this); });\r\n });\r\n ", "verbose", verbose)); } 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 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 AbstractAction abstractAction(String name, final Object runnable) { return new AbstractAction(name) { public void actionPerformed(ActionEvent evt) { pcallF(runnable); } }; } static public String hmobilefix() { return ""; } static public String hmobilefix(String html) { return hAddToHead(html, hmobilefix()); } 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 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 boolean conceptsSortedByFieldCI_verbose = false; static public Collection conceptsSortedByFieldCI(Class c, String field) { return conceptsSortedByFieldCI(db_mainConcepts(), c, field); } static public Collection conceptsSortedByFieldCI(Concepts concepts, Class c, String field) { IFieldIndex index = concepts.getCIFieldIndex(c, field); if (index instanceof ConceptFieldIndexCI) return (Collection) asList(((ConceptFieldIndexCI) index).objectIterator()); if (conceptsSortedByFieldCI_verbose) print("conceptsSortedByFieldCI_verbose: Manual sort of " + c + " for " + field); return sortedByFieldIC(field, concepts.list(c)); } static public String dropDollarPrefix(String s) { return dropPrefix("$", s); } static public int latestInstalledJavaX() { File[] files = new File(userHome(), ".javax").listFiles(); int v = 0; if (files != null) for (File f : files) { Matcher m = regexpMatcher("x(\\d\\d\\d?)\\.jar", f.getName()); if (m.matches()) v = Math.max(v, Integer.parseInt(m.group(1))); } return v; } static public void printVars_str(Object... params) { print(renderVars_str(params)); } static public Throwable innerException(Throwable e) { return getInnerException(e); } static public File remoteMechListMirrorNameFile(String listName) { return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".name"); } static public boolean isCurrentThread(Thread t) { return t != null && t == currentThread(); } 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 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 { Class c = (Class) (call(j, "hotwire", src)); hotwire_copyOver(c); return c; } } 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 hasSuperclassShortNamed(Object o, String name) { Class c = _getClass(o); while (c != null) if (shortClassNameIs(c, name)) return true; else c = c.getSuperclass(); return false; } 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 void syncReplaceCollection(Collection dest, Collection src) { if (dest == src) return; synchronized (collectionMutex(dest)) { dest.clear(); if (src != null) dest.addAll(src); } } static public String deSquareBracket(String s) { if (startsWith(s, "[") && endsWith(s, "]")) return substring(s, 1, l(s) - 1); return s; } static public String hexColorToCSSRGB(String hex) { return empty(hex) ? null : "rgb(" + joinWithComma(rgbToIntList(new RGB(hex))) + ")"; } static public Class veryQuickJava(CharSequence mainJava) { return veryQuickJava3(str(mainJava)); } 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 boolean eqicOrSwicPlusSpace(String a, String b) { return swic(a, b) && (l(a) == l(b) || a.charAt(l(b)) == ' '); } static public void revalidateFrame(Component c) { revalidate(getFrame(c)); } static public A lowestByField(Iterable l, String field) { A lowest = null; Object lowestValue = null; for (A a : unnull(l)) { Object val = getOpt(a, field); if (lowest == null || cmp(val, lowestValue) < 0) { lowest = a; lowestValue = val; } } return lowest; } static public A lowestByField(String field, Iterable l) { return lowestByField(l, field); } static public boolean isTag(String token, String tag) { return token.regionMatches(true, 0, "<" + tag + " ", 0, tag.length() + 2) || token.regionMatches(true, 0, "<" + tag + ">", 0, tag.length() + 2); } 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 RandomAccessFile randomAccessFileForReading(File path) { try { return newRandomAccessFile(path, "r"); } catch (Exception __e) { throw rethrow(__e); } } static public A syncPopLast(List l) { if (l == null) return null; synchronized (l) { return popLast(l); } } static public List syncPopLast(int n, List l) { if (l == null) return null; synchronized (l) { return popLast(n, l); } } static public Map weakHashMap() { return newWeakHashMap(); } 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 char lastChar(String s) { return empty(s) ? '\0' : s.charAt(l(s) - 1); } static public void consoleInputFont(final Font f) { { swing(() -> { JTextField input = consoleInputField(); if (input != null) { input.setFont(f); revalidateFrame(input); } }); } } static public String span_title(String title, Object contents) { return spanTitle(title, contents); } static public Pair, List> filterAntiFilter(Iterable c, Object pred) { List yes = new ArrayList(); List no = new ArrayList(); if (c != null) for (A o : c) (isTrue(callF(pred, o)) ? yes : no).add(o); return pair(yes, no); } static public Pair, List> filterAntiFilter(Iterable c, IF1 pred) { return filterAntiFilter(c, (Object) pred); } static public Pair, List> filterAntiFilter(IF1 pred, Iterable c) { return filterAntiFilter(c, pred); } static public Pair, List> filterAntiFilter(Object pred, Iterable c) { return filterAntiFilter(c, pred); } 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 String dropParamFromURL(String url, String key) { Map params = paramsFromURL(url); if (!containsKey(params, key)) return url; params.remove(key); return addAnchorToURL(appendParamsToURL(urlWithoutQueryAndAnchor(url), params), anchorFromURL(url)); } static public int defaultTokenizerCacheSize() { return 1000; } static public Map decodeURIParams(String query) { return decodeHQuery(query); } 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 String hNotificationPopups() { return hStylesheetSnippet_maxCache("#1029723") + hjssnippet_maxCache("#1029726") + hjs("\r\n function successNotification(text) {\r\n window.createNotification({ theme: 'success', showDuration: 3000 })({ message: text });\r\n }\r\n \r\n function errorNotification(text) {\r\n window.createNotification({ theme: 'error', showDuration: 3000 })({ message: text });\r\n }\r\n "); } static public Object subBot_serveInputStream(InputStream in, String mimeType) { return call(mainBot(), "serveInputStream", in, mimeType); } static public A firstNotNull(Iterable c) { Iterator it = c.iterator(); while (it.hasNext()) { A a = it.next(); if (a != null) return a; } return null; } static public int strL(String s) { return s == null ? 0 : s.length(); } static public String reverseString(String s) { return empty(s) ? s : new StringBuilder(s).reverse().toString(); } static public float score(Scored s) { return s == null ? 0 : s.score(); } static public int howManySecondsAgo(long timestamp) { return iround(toSeconds(now() - timestamp)); } static public Object subBot_httpd() { Object httpd = getThreadLocal((ThreadLocal) getOpt(mainBot(), "MyHTTPD_current")); if (httpd == null) httpd = getThreadLocal((ThreadLocal) getOpt(mainBot(), "WebSocketHTTPD_current")); return httpd; } 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 String htmlEncode_nlToBr_withIndents(String s) { return nlToBr_withIndents(htmlEncode(s)); } static public void clearToken(List tok, int i) { tok.set(i, ""); } static public String sortLinesAlphaNumIC(String s) { return lines_possiblyRTrim(s, sortedAlphanumIC(lines(s))); } static public ThreadLocal htmlTable2_cellEncoder = new ThreadLocal(); static public String htmlTable2(Object data, Object... __) { boolean htmlEncode = optPar("htmlEncode", __, true); boolean useBr = boolPar("useBr", __); Map paramsByColName = (Map) (optPar("paramsByColName", __)); Object[] tableParams = (Object[]) (optPar("tableParams", __)); Object[] trParams = (Object[]) (optPar("trParams", __)); Object[] tdParams = (Object[]) (optPar("tdParams", __)); Map replaceHeaders = (Map) (optPar("replaceHeaders", __)); boolean noHeader = boolPar("noHeader", __); 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(structureOrText(key), structureOrText(value))); } } else print("Unknown data type: " + data); int w = 0; for (List row : rows) w = max(w, l(row)); StringBuilder buf = new StringBuilder(); buf.append(hopeningtag("table", paramsPlus(tableParams, "border", html_valueLessParam())) + "\n"); if (!noHeader) { buf.append("\n"); for (String cell : padList(cols, w, "")) buf.append(" " + htmlTable2_encodeCell(getOrKeep(replaceHeaders, cell), htmlEncode, useBr) + "\n"); buf.append("\n"); } for (List row : rows) { buf.append(hopeningtag("tr", trParams)); int i = 0; for (String cell : padList(row, w, "")) { String col = get(cols, i++); Object[] params = paramsPlus(tdParams, mapGet(paramsByColName, col)); buf.append(" " + tag("td", htmlTable2_encodeCell(cell, htmlEncode, useBr), params) + "\n"); } buf.append("\n"); } buf.append("\n"); return buf.toString(); } static public String htmlTable2_encodeCell(String cell, boolean useHtmlEncode, boolean useBr) { if (htmlTable2_cellEncoder.get() != null) return (String) callF(htmlTable2_cellEncoder.get(), cell); if (useHtmlEncode) cell = htmlEncode2(cell); if (useBr) cell = nlToBr(cell); return cell; } 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 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 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 String newLinesToSpaces2(String s) { return newLinesToSpaces_trim(s); } 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 boolean hasLetters(String s) { for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i))) return true; return false; } static public TimeZone timeZone(String name) { return TimeZone.getTimeZone(name); } static public String hframeset_rows(String rows, Object contents, Object... params) { return tag("frameset", contents, paramsPlus(params, "rows", rows)); } static public String fullRawLink(String pageName) { return (subBot_isHttps() ? "https" : "http") + "://" + domain() + rawLink(pageName); } static public JTextField setTextAndSelectAll(final JTextField tf, final String text) { if (tf != null) { swing(() -> { tf.setText(text); tf.selectAll(); }); } return tf; } static public boolean contains(Collection c, Object o) { return c != null && c.contains(o); } static public boolean contains(Iterable it, Object a) { if (it != null) for (Object o : it) if (eq(a, o)) return true; return false; } static public boolean contains(Object[] x, Object o) { if (x != null) for (Object a : x) if (eq(a, o)) return true; return false; } static public boolean contains(String s, char c) { return s != null && s.indexOf(c) >= 0; } static public boolean contains(String s, String b) { return s != null && s.indexOf(b) >= 0; } static public boolean contains(BitSet bs, int i) { return bs != null && bs.get(i); } static public boolean contains(Producer p, A a) { if (p != null && a != null) while (true) { A x = p.next(); if (x == null) break; if (eq(x, a)) return true; } return false; } static public boolean contains(Rect r, Pt p) { return rectContains(r, p); } static public List 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 String standardCredentials_noCookies() { return standardCredentials() + "&noCookies=1"; } static public List splitAtDoubleArrow_bothDirections(String s) { return splitAtDoubleArrow_bothDirections(javaTok(s)); } static public List splitAtDoubleArrow_bothDirections(List tok) { List l = splitAtDoubleArrow(tok); if (l(l) != 2) l = reversedList(splitAtDoubleLeftArrow(tok)); return l; } static public int countConceptsWhereCI(Concepts cc, Class c, Object... params) { return countConceptsCI(cc, c, params); } static public int countConceptsWhereCI(Class c, Object... params) { return countConceptsCI(c, params); } static public String renderHowLongAgoPlusModified(long timestamp, long timestamp2, Object... __) { String spacer = optPar("spacer", __, ", modified "); if (timestamp2 == 0) timestamp2 = timestamp; String s = renderHowLongAgo(timestamp); String s2 = renderHowLongAgo(timestamp2); return eq(s, s2) ? s : s + ", modified " + s2; } static public boolean isRunnable(Object o) { return o instanceof Runnable || hasMethod(o, "get"); } 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 String jsonEncodeMap(Object... __) { return jsonEncode(paramsToMap(__)); } static public Set emptySet() { return new HashSet(); } 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 String div_floatRight(Object contents, Object... params) { return div(contents, params_stylePlus("float: right", params)); } static public A lookupOrKeep(Map map, A key) { return map != null && map.containsKey(key) ? map.get(key) : key; } static public String unCurlyBracket(String s) { return tok_unCurlyBracket(s); } static public boolean isImageServerSnippet(long id) { return id >= 1100000 && id < 1200000; } 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 Collection allConcepts() { return db_mainConcepts().allConcepts(); } static public Collection allConcepts(Concepts concepts) { return concepts.allConcepts(); } 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 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 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 boolean isA(Either e) { return eitherIsA(e); } 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 String mp3mimeType() { return "audio/mpeg"; } static public boolean isB(Either e) { return eitherIsB(e); } static public String programIDWithCase() { return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID(); } static public Object subBot_serveRedirect(String url) { return call(getMainBot(), "serveRedirect", url); } static public Object subBot_serveRedirect(String url, String contentType) { return call(getMainBot(), "serveRedirect", url, contentType); } 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 List uniquifyCI(Collection l) { TreeSet set = ciSet(); List out = new ArrayList(); for (String a : unnull(l)) if (set.add(a)) out.add(a); return out; } static public void close(AutoCloseable c) { _close(c); } 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 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 void assertStartsWith(List a, List b) { if (!startsWith(a, b)) throw fail(a + " does not start with " + b); } static public void assertStartsWith(String a, String b) { if (!startsWith(a, b)) throw fail(quote(a) + " does not start with " + quote(b)); } static public File tempDirPossiblyInRAMDisk() { File f = linux_fileInRamDisk(aGlobalID()); if (f != null) { f.mkdirs(); return f; } return makeTempDir(); } static public boolean isFile(File f) { return f != null && f.isFile(); } static public boolean isFile(String path) { return isFile(newFile(path)); } static public int javaxIncludeSnippetType() { return 42; } 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 boolean ewicOneOf(String s, String... l) { if (s != null) for (String x : l) if (ewic(s, x)) return true; return false; } 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 Map standardClassesMap() { return standardClassesMap_uncached(); } 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 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 RuntimeException todo() { throw new RuntimeException("TODO"); } static public RuntimeException todo(Object msg) { throw new RuntimeException("TODO: " + msg); } static public A conceptWhereIC(Class c, Object... params) { return findConceptWhereCI(c, params); } static public Concept conceptWhereIC(String c, Object... params) { return findConceptWhereCI(db_mainConcepts(), c, params); } static public A conceptWhereIC(Concepts concepts, Class c, Object... params) { return findConceptWhereCI(concepts, c, params); } static public Concept conceptWhereIC(Concepts concepts, String c, Object... params) { return findConceptWhereCI(concepts, c, params); } static public Object serveCSVWithFileName(String fileName, String text) { Object response = serveWithContentType(text, "text/csv"); call(response, "addHeader", "Content-Disposition", "inline; filename=\"" + fileName + "\""); return response; } 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 MultiSetMap ciMultiSetMap() { MultiSetMap mm = new MultiSetMap(); mm.data = ciMap(); return mm; } 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 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 byte[] bytesFromHex(String s) { return hexToBytes(s); } static public List sortByMap_inPlace(List l, Map map) { sort(l, mapComparator(map)); return l; } 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 String readLineFromReaderWithClose(BufferedReader r) { try { String s = r.readLine(); if (s == null) r.close(); return s; } catch (Exception __e) { throw rethrow(__e); } } 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 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 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 hjavascript_src(String src, Object... __) { return hfulltag("script", "", paramsPlus(__, "src", src)); } static public Either eitherB(B b) { return new Either(2, b); } 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 void replaceMap(Map dest, Map src) { if (dest == src) return; dest.clear(); dest.putAll(src); } static public Either eitherA(A a) { return new Either(1, a); } static public List syncShallowCloneElements(List l) { return syncLambdaMap(__91 -> shallowClone(__91), l); } static public String indentStructureString_firstLevels(int levelsToIndent, String s) { if (s == null) return null; List tok = javaTokForStructure(s); StringBuilder buf = new StringBuilder(); int level = 0; for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (isOpeningBracket(t)) { int j = i + 5; if (containsClosingBracket(subList(tok, i + 2, i + 5))) { buf.append(joinSubList(tok, i, j)); i = j - 1; } else { buf.append(t); ++level; if (level <= levelsToIndent) buf.append("\n").append(spaces(level * 2)); } } else if (isClosingBracket(t)) { if (level-- <= levelsToIndent) buf.append("\n").append(spaces(level * 2)); buf.append(t); } else if (eq(t, ",")) { buf.append(t); if (level <= levelsToIndent) buf.append("\n").append(spaces(level * 2)); i++; } else buf.append(t); } return str(buf); } 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 String asciiSideBySideWithSeparator(String sep, List texts) { if (empty(texts)) return asciiSideBySide(texts); int rows = maxLineCount(texts); List out = new ArrayList(); for (int i = 0; i < l(texts); i++) { if (i != 0) out.add(repLine(rows, sep)); out.add(texts.get(i)); } return asciiSideBySide(out); } static public Either either2(B b) { return new Either(2, b); } static public Either either1(A a) { return new Either(1, a); } 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 Map paramsFromURL(String url) { return decodeHQuery(getQueryFromURL(url)); } 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 List splitAtComma_trim(String s) { return nempties(trimAll(splitAtComma(s))); } 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 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 SimpleDateFormat simpleDateFormat_local(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(localTimeZone()); return sdf; } 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 MultiMap ciMultiMap() { return caseInsensitiveMultiMap(); } static public URLConnection openConnection(String url) { try { return openConnection(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } static public URLConnection openConnection(URL url) { try { ping(); callOpt(javax(), "recordOpenURLConnection", str(url)); return url.openConnection(); } catch (Exception __e) { throw rethrow(__e); } } static public void 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 JPanel showFormTitled_customArrangement(final boolean internalFrame, final F1, JPanel> arrange, final String title, final Object... _parts) { return swing(new F0() { public JPanel get() { try { List out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts)); JPanel panel = callF(arrange, out); showForm_makeFrame(title, panel); return panel; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "L out = showForm_arrange1(showForm_makeComponents(internalFrame, ..."; } }); } 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 String hcss(Object contents) { if (contents instanceof String && isRelativeOrAbsoluteURL((String) contents)) return hstylesheetsrc((String) contents); else return htag("style", contents); } 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 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 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 boolean java10OrHigher() { return parseFirstInt(javaVersion()) >= 10; } static public List splitAtJavaToken(String s, String splitToken) { return splitByJavaToken(s, splitToken); } static public Object subBot_serve500() { return call(getMainBot(), "serve500"); } static public Object subBot_serve500(String msg) { return call(getMainBot(), "serve500", msg); } static public Object subBot_serve500(Throwable error) { return subBot_serve500(renderStackTrace(error)); } 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 Object subBot_maxCacheHeaders(Object response) { return callMainBot("maxCacheHeaders", response); } static public Object serveByteArray(byte[] data, String mimeType) { return subBot_serveByteArray(data, mimeType); } 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 A printStruct(String prefix, A a) { printStructure(prefix, a); return a; } static public A printStruct(A a) { printStructure(a); return a; } 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 String hhiddenWithID(String id) { return hhiddenWithID(id, null); } static public String hhiddenWithID(String id, Object value, Object... params) { return tag("input", "", paramsPlus(params, "type", "hidden", "id", id, "value", value)); } static public String htmlEncode2If(boolean b, String s) { return b ? htmlEncode2(s) : s; } static public Object loadJSONFile(File f) { return jsonDecode(loadTextFile(f)); } static public int findEndOfAngleBracketPart(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 CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; static public CloseableIterableIterator emptyCloseableIterableIterator() { return emptyCloseableIterableIterator_instance; } static public Object mainBot() { return getMainBot(); } static public Map mapPlus(Map m, Object... data) { m = cloneMap(m); litmap_impl(m, data); return m; } static public Map decodeHQuery(String query) { Map map = new HashMap(); for (String s : splitAtAmpersand(query)) { int i = s.indexOf('='); if (i >= 0) map.put(urldecode(s.substring(0, i)), urldecode(s.substring(i + 1))); } return map; } static public A conceptWhereCI(Class c, Object... params) { return findConceptWhereCI(c, params); } static public Concept conceptWhereCI(String c, Object... params) { return findConceptWhereCI(db_mainConcepts(), c, params); } static public A conceptWhereCI(Concepts concepts, Class c, Object... params) { return findConceptWhereCI(concepts, c, params); } static public Concept conceptWhereCI(Concepts concepts, String c, Object... params) { return findConceptWhereCI(concepts, c, params); } static public A lowestConceptByField(Class c, String field) { return lowestConceptByField(db_mainConcepts(), c, field); } static public A lowestConceptByField(Concepts concepts, Class c, String field) { IFieldIndex index = concepts.getFieldIndex(c, field); if (index instanceof ConceptFieldIndexDesc) { Map.Entry e = ((NavigableMap) ((ConceptFieldIndexDesc) index).valueToObject.data).lastEntry(); return e == null ? null : (A) first((Collection) e.getValue()); } return lowestByField(field, concepts.list(c)); } 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 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 boolean addToCollection(Collection c, A a) { return c != null && c.add(a); } 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 dropFirstThreeAndLastThree(List l) { return dropFirstAndLast(3, l); } 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 deleteFile(File file) { return file != null && file.delete(); } static public String tok_expandIfQuoted(String s) { return applyTranspilationFunction(__92 -> tok_expandIfQuoted(__92), s); } static public void tok_expandIfQuoted(List tok) { jreplace(tok, "if || ", "if (matchOneOf(s, m, $2, $5))"); jreplace_dyn(tok, "if ", new F2, Integer, String>() { public String get(List tok, Integer cIdx) { try { String s = unquote(tok.get(cIdx + 2)); List l = new ArrayList(); for (String pat : splitAtJavaToken(s, "|")) { if (pat.contains("...")) l.add("matchX(" + quote(trim(pat)) + ", s, m)"); else if (javaTok(pat).contains("*")) l.add("match(" + quote(trim(pat)) + ", s, m)"); else l.add("match(" + quote(trim(pat)) + ", s)"); } return "if (" + join(" || ", l) + ")"; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "S s = unquote(tok.get(cIdx+2));\r\n //print(\"multimatch: \" + quote(s));\r\n ..."; } }, new TokCondition() { public boolean get(final List tok, final int i) { return javaTokC(unquote(tok.get(i + 3))).contains("|"); } }); tok_transpileIfQuoted_dollarVars(tok); jreplace(tok, "if ", "if (find3plusRestsX($2, s, m))", new TokCondition() { public boolean get(final List tok, final int i) { return startsAndEndsWith(unquote(tok.get(i + 3)), "..."); } }); jreplace(tok, "if ", "if (matchStartX($2, s, m))", new TokCondition() { public boolean get(final List tok, final int i) { return unquote(tok.get(i + 3)).endsWith("..."); } }); jreplace(tok, "if ", "if (match($2, s))", new TokCondition() { public boolean get(final List tok, final int i) { return !javaTokC(unquote(tok.get(i + 3))).contains("*"); } }); jreplace(tok, "if ", "if (match($2, s, m))"); jreplace(tok, "if match ", "if (match($3, s, m))"); } 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 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(Object o) { return !empty(o); } static public boolean nempty(IntRange r) { return !empty(r); } 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 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 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 int lengthOfString(String s) { return s == null ? 0 : s.length(); } static public long ipToInt(String ip) { Matches m = new Matches(); assertTrue(jmatch("*.*.*.*", ip, m)); return parseLong(m.unq(3)) | parseLong(m.unq(2)) << 8 | parseLong(m.unq(1)) << 16 | parseLong(m.unq(0)) << 24; } static public Object dm_os() { { var __1 = vm_generalMap_get("stefansOS"); if (__1 != null) return __1; } return creator(); } static public Object serveText(Object s) { return call(getMainBot(), "serveByteArray", toUtf8(str(s)), "text/plain; charset=utf8"); } static public boolean standardFunctionsCacheUpToDate(TreeSet functionSet) { File f = transpiledStandardFunctions_file(functionSet); long date = recommendedTranspilationDateForStandardFunctions(functionSet); return date != 0 && f.lastModified() >= date; } 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 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 Object dm_getStemByID(Object id) { return dm_callOS("getModuleByID", str(id)); } static public int hashCodeFor(Object a) { return a == null ? 0 : a.hashCode(); } static public List sortByConceptID(Collection l) { return sortConceptsByID(l); } static public ExpiringMap2 mechList_raw_cache = new ExpiringMap2(10000).setMap(ciMap()); static public Lock mechList_raw_lock = lock(); static public int mechList_raw_timeout = 60000; static public String mechList_raw(String name) { try { Lock __0 = mechList_raw_lock; lock(__0); try { if (empty(name)) return ""; String src = mechList_raw_cache.get(name); if (src != null) return src; src = mechList_raw_fresh(name); if (src != null) mechList_raw_cache.put(name, src); return src; } finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } } static public void _onLoad_mechList_raw() { ownResource(vmBus_onMessage("mechChange", listName -> mechList_raw_cache.remove((String) listName))); } static public Object serveFile(File file) { return subBot_serveFile(file); } static public Object serveFile(File file, String mimeType) { return subBot_serveFile(file, mimeType); } 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 boolean reflection_isForbiddenMethod(Method m) { return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives"); } 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 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 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 Map vm_threadInterruptionReasonsMap() { return vm_generalWeakSubMap("Thread interruption reasons"); } static public int iceil(double d) { return (int) Math.ceil(d); } static public String smallestTransparentGIFDataURI() { return "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; } static public List uniquify(Collection l) { return uniquifyList(l); } static public String asString(Object o) { return o == null ? null : o.toString(); } static public List jfindAll(List tok, String pat) { return jfindAll(tok, pat, null); } static public List jfindAll(List tok, String pat, ITokCondition condition) { return jfindAll(tok, jfind_preprocess(javaTok(pat)), condition); } static public List jfindAll(List tok, List tokPat) { return jfindAll(tok, tokPat, null); } static public List jfindAll(List tok, List tokPat, ITokCondition condition) { TokCondition cond = toTokCondition(condition); String[] toks = toStringArray(codeTokensOnly(tokPat)); int i = -1; List l = new ArrayList(); while ((i = findCodeTokens(tok, i + 1, false, toks, cond)) >= 0) l.add(i); return l; } static public Object vm_generalMap_put(Object key, Object value) { return mapPutOrRemove(vm_generalMap(), key, value); } static public String hjs_imgUploadBase64Encoder() { return hscript("\r\n var imgConverted = false;\r\n \r\n function submitWithImageConversion(form) {\r\n console.log(\"imgConverted: \" + imgConverted + \", form: \" + form);\r\n if (imgConverted) return true;\r\n imgConverted = true;\r\n var file = $('#imgUploader')[0].files[0];\r\n if (file == null) return true;\r\n var reader = new FileReader();\r\n\r\n // delay form submit until reader is done\r\n reader.onloadend = function () {\r\n var b64 = reader.result.replace(/^data:.+;base64,/, '');\r\n $(\"#f_img_base64\").val(b64);\r\n console.log(\"Got base64 data: \" + b64.length);\r\n setTimeout(function() {\r\n $(form).submit();\r\n }, 1000);\r\n };\r\n\r\n reader.readAsDataURL(file);\r\n return false;\r\n }\r\n "); } 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 dm_isFirstSiblingModule_debug = false; static public boolean dm_isFirstSiblingModule(Object mod) { String libID = dm_moduleLibID(mod); if (libID == null) return false; List siblings = dm_modulesWithLibID(libID); if (dm_isFirstSiblingModule_debug) printVars("libID", libID, "siblings", siblings); if (empty(siblings)) return true; return eq(dm_moduleID(mod), lowestByAlphaNum(siblings)); } static public String windowsLineBreaks(String s) { return s == null ? null : s.replaceAll("(? 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 Set weakSet() { return synchroWeakHashSet(); } static public String snippetImageLink(String snippetID) { return snippetImageURL(snippetID); } 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 Map safeUnstructMapAllowingClasses(String s, Class... allowedClasses) { return (Map) safeUnstructureAllowingClasses(s, allowedClasses); } static public int minuteInDay() { return minuteInDay(java.util.Calendar.getInstance()); } static public int minuteInDay(java.util.Calendar c) { return hours(c) * 60 + minutes(c); } static public int minuteInDay(long time) { return minuteInDay(calendarFromTime(time)); } static public int minuteInDay(TimeZone tz) { return minuteInDay(now(), tz); } static public int minuteInDay(long time, TimeZone tz) { return minuteInDay(calendarFromTime(time, tz)); } 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 Object _defaultClassFinder_value = defaultDefaultClassFinder(); static public Object _defaultClassFinder() { return _defaultClassFinder_value; } static public void touchConcept(Concept c) { if (c != null) c.change(); } static public Object getOptMC(String field) { return getOpt(mc(), field); } static public B getAndRemove(Map map, A a) { if (!containsKey(map, a)) return null; B b = map.get(a); map.remove(a); return b; } static public B getAndRemove(A a, Map map) { return getAndRemove(map, a); } static public List stringToStringListOpt(IF1> f, Object o) { if (o instanceof String) return f.get((String) o); return (List) o; } 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 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 String htmlQuote(String s) { return "\"" + htmlencode_forParams(s) + "\""; } static public List> findBackRefsWithFieldNames(Concept c, Class type) { List> l = new ArrayList(); if (c != null && c.backRefs != null) for (Concept.Ref r : cloneList(c.backRefs)) if (instanceOf(r.concept(), type)) l.add(pair((A) r.concept(), fieldNameForConceptLink(r.concept(), c))); return l; } static public boolean _inCore() { return false; } static public ClassLoader myClassLoader() { return _getClass(mc()).getClassLoader(); } 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 Collection findConceptsWhereCI(Class c, Object... params) { return findConceptsWhereCI(db_mainConcepts(), c, params); } static public List findConceptsWhereCI(String c, Object... params) { return findConceptsWhereCI(db_mainConcepts(), c, params); } static public Collection findConceptsWhereCI(Concepts concepts, Class c, Object... params) { Collection l = findConceptsWhereCI_noParent(concepts, c, params); if (concepts.parent == null) return l; return concatCollections_conservative(l, findConceptsWhereCI(concepts.parent, c, params)); } static public Collection findConceptsWhereCI_noParent(Concepts concepts, Class c, Object... params) { params = expandParams(c, params); if (concepts.ciFieldIndices != null) for (int i = 0; i < l(params); i += 2) { IFieldIndex index = concepts.getCIFieldIndex(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 (checkConceptFieldsIC(x, params)) l.add(x); return l; } } return filterConceptsIC(concepts.list(c), params); } static public List findConceptsWhereCI(Concepts concepts, String c, Object... params) { return filterConceptsIC(concepts.list(c), params); } 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 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 void loadFunctions_clearCache() { callOptMC("loadFunctions_cached_clearCache"); } static public String stringIfTrue(boolean b, String s) { return b ? s : ""; } static public List dependentClasses() { return cleanUpAndGetWeakReferencesList(hotwire_classes); } static public File pathToJavaxJar() { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.pathToJavaXJar(); return pathToJavaxJar_noResourceLoader(); } static public File pathToJavaxJar_noResourceLoader() { try { int x = latestInstalledJavaX(); File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar"); if (!xfile.isFile()) { print("Saving " + f2s(xfile)); String url = x30JarServerURL(); byte[] data = loadBinaryPage(url); if (data.length < 1000000) throw fail("Could not load " + url); saveBinaryFile(xfile.getPath(), data); } return xfile; } catch (Exception __e) { throw rethrow(__e); } } 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 String renderHowLongAgo(Timestamp ts) { return renderHowLongAgo(timestampToLong(ts)); } static public String renderHowLongAgo(long timestamp) { if (timestamp == 0) return "never"; int seconds = howManySecondsAgo(timestamp); if (seconds <= 0) return "just now"; if (seconds < 60) return n2(seconds, "second") + " ago"; int minutes = iround(seconds / 60.0); if (minutes < 60) return n2(minutes, "minute") + " ago"; int hours = iround(minutes / 60.0); if (hours < 24) return n2(hours, "hour") + " ago"; int days = iround(hours / 24.0); return n2(days, "day") + " ago"; } 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 String hrefresh(String target) { return hrefresh(0, target); } static public String hrefresh(double seconds) { return hrefresh(seconds, ""); } static public String hrefresh(double seconds, String target) { return tag("meta", "", "http-equiv", "refresh", "content", iceil(seconds) + (nempty(target) ? "; url=" + target : "")); } 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 boolean fileContentsIs(File f, byte[] data) { try { if (isFile(f) != (data != null)) return false; int l = l(data); if (fileSize(f) != l) return false; BufferedInputStream in = bufferedFileInputStream(f); try { for (int ofs = 0; ofs < l; ofs++) if (data[ofs] != (byte) in.read()) return false; return true; } finally { _close(in); } } catch (Exception __e) { throw rethrow(__e); } } static public List listFilesNotDirs(String dir) { return listFilesOnly(dir); } static public List listFilesNotDirs(File... dirs) { return listFilesOnly(dirs); } static public File fileInSameDir(File f, String newName) { return newFile(parentFile(f), newName); } static public Set synchronizedSet() { return synchroHashSet(); } static public Set synchronizedSet(Set set) { return new SynchronizedSet(set); } static public int countConceptsWhereIC(Concepts cc, Class c, Object... params) { return countConceptsCI(cc, c, params); } static public int countConceptsWhereIC(Class c, Object... params) { return countConceptsCI(c, params); } static public String hsimpletableheader(String... cols) { return tag("tr", join(lambdaMap(__93 -> th(__93), cols))); } static public String beforeVerticalBar(String s) { return trimSubstring(s, 0, smartIndexOf(s, '|')); } static public String hStylesheetSnippet_maxCache(String snippetID) { return tag("link", "", "rel", "stylesheet", "type", "text/css", "href", snippetRawURL_maxCache(snippetID, "text/css")); } static public Set identityHashSet() { return Collections.newSetFromMap(new IdentityHashMap()); } static public boolean isStringOrIntOrLong(Object o) { return o instanceof String || o instanceof Integer || o instanceof Long; } static public String strOr(Object o, String ifNull) { return o == null ? ifNull : str(o); } static public boolean isIdentifier(String s) { return isJavaIdentifier(s); } static public TimeZone getTimeZone(String name) { return TimeZone.getTimeZone(name); } static public String localDateWithMinutes(long time) { SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm"); return format.format(time); } static public String localDateWithMinutes() { return localDateWithMinutes(now()); } static public A _registerIOWrap(A wrapper, Object wrapped) { return wrapper; } static public String dropTrailingSlashIfNemptyAfterwards(String s) { return l(s) > 1 ? dropSuffix("/", s) : s; } static public Integer parseHourAndOptionalMinutesToMinutes(String s) { List l = trimAll(splitAtColon(s)); if (empty(l)) return null; int minute = parseInt(first(l)) * 60; if (l(l) > 1) minute += parseInt(second(l)); return minute; } static public int findEndOfBracketPart2(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 NavigableMap emojiShortNameMap_cache; static public NavigableMap emojiShortNameMap() { if (emojiShortNameMap_cache == null) emojiShortNameMap_cache = emojiShortNameMap_load(); return emojiShortNameMap_cache; } static public NavigableMap emojiShortNameMap_load() { NavigableMap map = ciMap(); for (Map m : rawEmojisList()) { String shortName = (String) (m.get("shortname")); String emoji = (String) (m.get("emoji")); if (startsWith(shortName, ":")) map.put(shortName, emoji); } return map; } static public String stringOptPar(Object[] params, String name) { return (String) optPar(params, name); } 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 int[] subArray(int[] b, int start, int end) { int[] x = new int[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public byte[] subArray(byte[] b, int start, int end) { start = max(start, 0); end = min(end, l(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 long[] subArray(long[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start >= end) return new long[0]; long[] x = new long[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public short[] subArray(short[] b, int start, int end) { if (start <= 0 && end >= l(b)) return b; short[] x = new short[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public float[] subArray(float[] b, int start, int end) { float[] x = new float[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } static public Object[] subArray(Object[] b, int start) { return subArray(b, start, l(b)); } static public Object[] subArray(Object[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start >= end) return new Object[0]; Object[] x = new Object[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } 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 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 codeAnalysis_isSafeIdentifier(String id) { return startsWith(id, "$"); } static public Object[] paramsPlus_inFront(Object[] a1, Object... a2) { return paramsPlus(a2, a1); } 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 boolean hasLettersAllUpperCase(String s) { return hasLetters(s) && !containsLowerCase(s); } static public long recommendedTranspilationDateForStandardFunctions(Collection sfNames) { long date = 0; for (String name : sfNames) { long d = recommendedTranspilationDateForStandardFunction(name); if (d == 0) return 0; date = max(date, d); } return date; } static public Matcher regexpMatcherIC(String pat, String s) { return compileRegexpIC(pat).matcher(unnull(s)); } static public boolean cset_trueIfChanged(Concept c, Object... values) { try { return cset(c, values) != 0; } catch (Exception __e) { throw rethrow(__e); } } static public JTextArea jTextArea() { return jTextArea(""); } static public JTextArea jTextArea(final String text) { return jTextAreaWithUndo(text); } static public Map mapPlus_noOverwrite(Map m, Object... data) { m = cloneMap(m); litmap_impl_noOverwrite(m, data); return m; } static public Object serve500() { return subBot_serve500(); } static public Object serve500(String msg) { return subBot_serve500(msg); } 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 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 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 List collect(Iterable c, String field) { return collectField(c, field); } static public List collect(String field, Iterable c) { return collectField(c, field); } static public void 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 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 defaultJavaXTranslatorID_value = "#759"; static public String defaultJavaXTranslatorID() { return defaultJavaXTranslatorID_value; } 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 boolean isSafeStandardFunction(String name) { return isCodeSafe(formatFunctionCall(name)); } static public List hotwire_libraryIDsFromJar(File jar) { String dehlibs = unnull(loadTextFileFromZip(jar, "libraries")); return regexpExtractAll("\\d+", dehlibs); } static public Map applyFunctionToValue(IF1 f, A key, Map map) { return applyFunctionToMapValue(key, f, map); } static public Map applyFunctionToValue(IF1 f, Map map, A... keys) { for (A key : unnullForIteration(keys)) applyFunctionToValue(f, key, map); return map; } 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 List tok_splitAtComma_unquote(String s) { List tok = javaTok(s); 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 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 SimpleDateFormat simpleDateFormat_timeZone(String format, String timeZone) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(timeZone(timeZone)); return sdf; } static public String angleBracketVarsToStars(String s) { return angleBracketVarsToStars(s, null); } static public String angleBracketVarsToStars(String s, List varNames_out) { List tok = javaTokWithAngleBrackets(s); for (int idx : indicesOfAngleBracketVars(tok)) { { if (varNames_out != null) varNames_out.add(deAngleBracket(tok.get(idx))); } tok.set(idx, "*"); } return join(tok); } 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 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 String dbBotStandardName() { String home = userHome(); String name = dbBotName(getDBProgramID()); if (neq(home, actualUserHome())) name += " " + quote(home); return name + "."; } static public AutoCloseable tempCleaningUp() { AutoCloseable result = null; result = tempSetTL(ping_isCleanUpThread, true); return result; } static public String hjavascript_src_withType(String src, Object... __) { return hfulltag("script", "", paramsPlus_inFront(__, "src", src, "type", "text/javascript")); } static public String joinNempties(String sep, Object... strings) { return joinStrings(sep, strings); } static public String joinNempties(String sep, Iterable strings) { return joinStrings(sep, strings); } static public String html_emojisToUnicode(String s) { return join(mapNonCodeTokens(__94 -> emojisToUnicode(__94), htmlTok(s))); } public static File mkdirsFor(File file) { return mkdirsForFile(file); } 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 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 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 Object defaultDefaultClassFinder() { return new F1() { public Class get(String name) { name = replacePrefix("main$main$", "main$", name); Class c = get2(name); 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); { Class c = findClass_fullName(newName); if (c != null) return c; } } return null; } }; } 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 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 int findEndOfBlock(List tok, int i) { return tok_findEndOfBlock(tok, i); } 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 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 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 TreeMap litCIMap(Object... x) { TreeMap map = caseInsensitiveMap(); litmap_impl(map, x); return map; } static public A proxyFromInvocationHandler(Class intrface, InvocationHandler handler) { return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, handler); } static public String joinNemptiesWithColonSpace(String... strings) { return joinNempties(": ", strings); } static public String joinNemptiesWithColonSpace(Collection strings) { return joinNempties(": ", strings); } static public List dropHTMLTags(List tok) { return dropAllTags(tok); } static public String dropHTMLTags(String html) { return dropAllTags(html); } static public Object callMainBot(String method, Object... args) { return call(mainBot(), method, args); } static public int[] emptyIntArray_a = new int[0]; static public int[] emptyIntArray() { return emptyIntArray_a; } static public void listAdd(Collection c, A a) { if (c != null) c.add(a); } 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 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 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 String hjs_fileUploadBase64Encoder() { return hscript("\r\n var fileConverted = false;\r\n \r\n function submitWithFileConversion(form) {\r\n if (fileConverted) return true;\r\n fileConverted = true;\r\n var file = $('#fileUploader')[0].files[0];\r\n if (file == null) return true;\r\n var reader = new FileReader();\r\n\r\n // delay form submit until reader is done\r\n reader.onloadend = function () {\r\n var b64 = reader.result.replace(/^data:.+;base64,/, '');\r\n $(\"#f_file_base64\").val(b64);\r\n console.log(\"Got base64 data: \" + b64.length);\r\n setTimeout(function() {\r\n $(form).submit();\r\n }, 1000);\r\n };\r\n\r\n reader.readAsDataURL(file);\r\n return false;\r\n }\r\n "); } static public boolean eqGetOneOf(List l, int i, A... options) { return eqOneOf(get(l, i), options); } 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 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 boolean isInstance(Class type, Object arg) { return type.isInstance(arg); } 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 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 File programFile(String name) { return prepareProgramFile(name); } static public File programFile(String progID, String name) { return prepareProgramFile(progID, name); } static public AutoCloseable tempActivity(Object r) { return null; } static public long raf_findEndOfLine(RandomAccessFile raf, long pos, int bufSize) { try { byte[] buf = new byte[bufSize]; long length = raf.length(); while (pos < length) { raf.seek(pos); raf.readFully(buf, 0, (int) Math.min(length - pos, bufSize)); int idx = indexOf_byteArray(buf, (byte) '\n'); if (idx >= 0) return pos + idx + 1; pos += bufSize; } return length; } catch (Exception __e) { throw rethrow(__e); } } static public void setFrameContents(final Component c, final Object contents) { swing(() -> { JFrame frame = getFrame(c); if (frame == null) return; frame.getContentPane().removeAll(); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(wrap(contents)); revalidate(frame); }); } static public Object cloneIfList(Object o) { return o instanceof List ? cloneList((List) o) : o; } 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 String gazelle_postMentionRegexp() { return regexpCaseInsensitivePrefix() + "\\bpost\\s+(\\d+)"; } static public A lookupIgnoreCase(Map map, String key) { for (String s : map.keySet()) if (eqic(s, key)) return map.get(s); return null; } static public List lookupIgnoreCase(MultiMap map, String key) { for (String s : map.keySet()) if (eqic(s, key)) return map.get(s); return litlist(); } 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 String hrefBlank(String link, Object contents, Object... params) { return empty(link) ? strOrEmpty(contents) : tag("a", contents, concatArrays(new Object[] { "href", link, "target", "_blank" }, params)); } 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 void tokPrepend_reTok(List tok, int i, String s) { tokPrepend(tok, i, s); reTok(tok, i, i + 1); } 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 void removeFromMultiPort(long vport) { if (vport == 0) return; for (Object port : getMultiPorts()) call(port, "removePort", vport); } static public void onIndividualConceptChange_notOnAllChanged(Class type, IVF1 r) { onIndividualConceptChange_notOnAllChanged(db_mainConcepts(), type, r); } static public void onIndividualConceptChange_notOnAllChanged(Concepts cc, Class type, IVF1 r) { if (r != null) { if (cc != null) cc.addConceptIndex(new IConceptIndex() { public void update(Concept c) { if (instanceOf(c, type)) r.get((A) c); } public void remove(Concept c) { } }); } } 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 boolean isConceptClassIndexed(Class c) { return isConceptClassIndexed(db_mainConcepts(), c); } static public boolean isConceptClassIndexed(Concepts concepts, Class c) { return concepts.conceptCounterForClass(c) != null; } 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 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 String hinputfield(String name, Object... params) { return htextinput(name, params); } static public MultiSet asCIMultiSet(Iterable l) { MultiSet ms = new MultiSet(); ms.map = ciMap(); ms.addAll(l); return ms; } static public Map mapWithoutKey(Map map, A key) { if (map == null || !map.containsKey(key)) return map; Map m = cloneMap(map); m.remove(key); return m; } static public Map mapWithoutKey(A key, Map map) { return mapWithoutKey(map, key); } static public RuntimeException cancelTo(CancelPoint cp) { if (cp.closed) throw fail("cancel point closed"); throw new CancelToCancelPoint(cp); } 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 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 Map parseDoubleArrowMapCI_tlft(String s) { return parseDoubleArrowMapCI(tlft(s)); } 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 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 String replaceAngleBracketVars(String s, Map map) { return empty(map) ? s : join(replaceAngleBracketVars(javaTokWithAngleBrackets(s), map)); } static public List replaceAngleBracketVars(List tok, Map map) { return replaceAngleBracketVars(tok, map, null); } static public List replaceAngleBracketVars(List tok, Map map, BitSet replacedTokens_out) { if (empty(map)) return tok; tok = cloneList(tok); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (isAngleBracketed(t)) { A t2 = map.get(t); if (t2 == null) t2 = map.get(deAngleBracket(t)); if (t2 != null) { tok.set(i, str(t2)); bitSetSet(replacedTokens_out, i); } } } return tok; } static public String replaceAngleBracketVars(String s, Object... params) { return replaceAngleBracketVars(s, paramsToMap(params)); } 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 Object[] litobjectarray(Object... l) { return litObjectArray(l); } static public Object[] muricaCredentialsPlus(Object... params) { return concatArrays(muricaCredentials(), params); } static public void saveBinaryFileVerbose(File f, byte[] data) { boolean exists = f.exists(); saveBinaryFile(f, data); print((!exists ? "Created" : "Updated") + " file " + f2s(f) + " (" + f.length() + " bytes)"); } static public Object mainBot; static public Object getMainBot() { return mainBot; } static public String shortenEndTime(String endTime, String startTime) { int i = endTime.lastIndexOf(' ') + 1; if (i > 0 && eq(substring(startTime, 0, i), substring(endTime, 0, i))) return trim(substring(endTime, i)); return endTime; } static public File standardLogFile() { return getProgramFile("log"); } static public boolean isCIMap(Map m) { return m instanceof TreeMap && ((TreeMap) m).comparator() == caseInsensitiveComparator(); } static public String ipToCountry2020_dataSnippetID = "#1400400"; static public Map ipToCountry2020_cache = mruCache(100); static public Lock ipToCountry2020_lock = lock(); static public File ipToCountry2020_dataDir() { return javaxCachesDir("ipToCountry2020"); } static public String ipToCountry2020(String ip) { return ipToCountry2020(ipToInt(ip)); } static public String ipToCountry2020(long ipNum) { return mapGetOrCreate(ipToCountry2020_cache, ipNum, () -> ipToCountry2020_uncached(ipNum)); } static public String ipToCountry2020_uncached(long ipNum) { { Lock __0 = ipToCountry2020_lock; lock(__0); try { if (directoryEmpty(ipToCountry2020_dataDir())) unzipSnippet(ipToCountry2020_dataSnippetID, ipToCountry2020_dataDir()); } finally { unlock(__0); } } String line = pairB(binarySearchForLineInTextFile(newFile(ipToCountry2020_dataDir(), "IP2LOCATION-LITE-DB1.CSV"), s -> { List l = tok_splitAtComma_unquote(s); long a = parseLongOpt(first(l)), b = parseLongOpt(second(l)); return ipNum > b ? 1 : ipNum < a ? -1 : 0; })); return get(tok_splitAtComma_unquote(line), 2); } 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 SecretValue aSecretGlobalID() { return secretValueOrNull(aGlobalID()); } 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 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 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 String curly(String s) { return optionalCurlyBrace(s); } static public String dropFirstLine(String text) { if (text == null) return null; int i = text.indexOf('\n'); return i >= 0 ? text.substring(i + 1) : ""; } 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 String angleBracket(String s) { return "<" + s + ">"; } static public List scoredSearch_prepare(String query) { return map(__95 -> replacePlusWithSpace(__95), splitAtSpace(query)); } static public String nMessages(long n) { return n2(n, "message"); } static public String nMessages(Collection l) { return nMessages(l(l)); } 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 Set setMinus(Set set, Object... stuff) { Set s2 = cloneSet(set); for (Object o : stuff) s2.remove(o); return s2; } static public boolean serverMechList_raw_fresh_verbose = false; static public String serverMechList_raw_fresh(String name) { return serverMechList_raw_fresh(name, false); } static public String serverMechList_raw_fresh(String name, boolean opt) { Lock __0 = downloadLock(); lock(__0); try { String text = null; try { text = loadTextFile(remoteMechListMirrorFile(name)); } catch (Throwable __e) { pcallFail(__e); } Object[] params = muricaCredentialsPlus("md5", md5OrNull(text), "l", l(text), "opt", opt ? 1 : 0, "withStatus", 1); String url = "http://butter.botcompany.de:8080/mech/raw/list-text/" + urlencode(name); String page = postPageSilently(url, params); Map map = jsonDecodeMap(page); boolean same = eq(map.get("Same"), true); boolean appended = eq(map.get("Appended"), true); saveTextFile(remoteMechListMirrorMetaFile(name), struct(getMultipleKeys(map, "Name", "Status"))); if (!same) { if (appended) text += (String) map.get("Text"); else text = (String) map.get("Text"); saveTextFile(remoteMechListMirrorFile(name), text); File nameFile = remoteMechListMirrorNameFile(name); if (!fileExists(nameFile)) { String actualName = or((String) map.get("Name"), name); saveTextFile(nameFile, actualName); } } if (serverMechList_raw_fresh_verbose) print("Mech list " + name + ": " + (appended ? "appended" : same ? "same" : "downloaded") + ": " + n2(countLines(text), "line")); if (!same) vmBus_send("remoteMechListMirrorChanged", name); return text; } finally { unlock(__0); } } 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 void unzipSnippet(String snippetID, File toDir) { print("Unzipping snippet " + snippetID + " to " + toDir); zip2dir(loadLibrary(snippetID), toDir); } static public String renderStructs(Object... params) { List l = new ArrayList(); if (odd(l(params))) l.add(addSuffix(str(first(params)), ":")); for (int i = l(params) & 1; i + 1 < l(params); i += 2) l.add(params[i] + "=" + sfu(params[i + 1])); return joinWithSpace(l); } 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 String reversedString(String s) { return reverseString(s); } static public int parseFirstInt(String s) { return parseInt(jextract("", s)); } static public int parseFirstInt(Iterable l) { return parseInt(firstIntegerString(l)); } 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 getQueryFromURL(String url) { return dropAfterSubstring(substring(url, smartIndexOf(url, "?") + 1), "#"); } static public AutoCloseable dm_enter(Object mod) { return (AutoCloseable) callOpt(dm_getModule(mod), "enter"); } 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 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 A uniqCI_returnIfNew(Class c, Object... params) { Pair p = uniqCI2(c, params); return p.b ? p.a : null; } static public A uniqCI_returnIfNew(Concepts cc, Class c, Object... params) { Pair p = uniqCI2(cc, c, params); return p.b ? p.a : null; } 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 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 String digitsOnly(String s) { return filterChars(__96 -> isDigit(__96), s); } 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 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 Map trimValues(Map map) { Map map2 = similarEmptyMap(map); for (A key : keys(map)) map2.put(key, trim(map.get(key))); return map2; } static public String joinLines(List lines) { return fromLines(lines); } static public String joinLines(String glue, String text) { return join(glue, toLines(text)); } 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 List javaTokWithAllBrackets(String s) { return javaTokPlusBrackets2(s); } static public String hhmm() { return hhmm(now()); } static public String hhmm(long time) { return new SimpleDateFormat("HHmm").format(time); } 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 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 void setFieldToIVF1Proxy(Object o, String field, IVF1 target) { setFieldToSingleMethodProxy(o, field, target, "get"); } 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 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 String renderColonProperties(Map map) { return formatColonProperties(map); } static public String renderColonProperties(List> l) { return formatColonProperties(l); } static public String renderColonProperties(Object... params) { return renderColonProperties(litorderedmap(params)); } 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 void failIfOddCount(Object... list) { if (odd(l(list))) throw fail("Odd list size: " + list); } static public void indexConceptFieldDesc(Class c, String field) { indexConceptFieldDesc(db_mainConcepts(), c, field); } static public void indexConceptFieldDesc(Concepts concepts, Class c, String field) { if (!isConceptFieldIndexed(concepts, c, field)) new ConceptFieldIndexDesc(concepts, c, field); } 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 List mapWithIndexStartingAt1(Collection l, IF2 f) { int n = l(l), i = 0; List out = emptyList(n); for (A a : unnullForIteration(l)) out.add(f.get(++i, a)); return out; } 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 getInjectionID() { return (String) call(getJavaX(), "getInjectionID", getMainClass()); } static public RootPaneContainer getPossiblyInternalFrame(Component c) { JInternalFrame f = getInternalFrame(c); if (f != null) return f; return optCast(RootPaneContainer.class, getWindow(c)); } 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 boolean subBot_isHttps() { Object httpd = subBot_httpd(); return eqOneOf(httpd, getOpt(mainBot(), "serveHttps_server"), getOpt(mainBot(), "serveHttpsWithWebsockets_server")) || contains((Collection) getOpt(mainBot(), "serveHttpsWithWebsockets_multiplePorts_servers"), httpd); } static public TreeMap ciMap() { return caseInsensitiveMap(); } static public String spaces(int n) { return rep(' ', n); } static public File actualUserDir() { return new File(actualUserHome()); } static public File actualUserDir(String path) { return new File(actualUserHome(), path); } static public List sortedIgnoreCase(Collection c) { List l = cloneList(c); Collections.sort(l, caseInsensitiveComparator()); return l; } static public String beautifyStructure(String s) { List tok = javaTokForStructure(s); structure_addTokenMarkers(tok); jreplace(tok, "lhm", ""); return join(tok); } 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 boolean flexMatchIC_iterate_debug = false; static public boolean flexMatchIC_iterate_useTokenization = true; static public void flexMatchIC_iterate(String pat, String input, VF1 onMatch, Object... __) { if (flexMatchIC_iterate_debug) print("flexMatchIC_iterate " + pat + " / " + input); IF1> tokenizer = optPar("tokenizer", __, __1 -> javaTokNPunctuation_plusAsterisk(__1)); flexMatchIC_iterate(pat, callTokenizer(tokenizer, pat), callTokenizer(tokenizer, input), onMatch, __); } static public void flexMatchIC_iterate(String pat, List tokPat, List tokInput, VF1 onMatch, Object... __) { List varIndices = flexMatchIC_getVarIndices(tokPat, tokInput); if (varIndices == null) return; if (flexMatchIC_iterate_debug) printStructs("varIndices", varIndices, "tokPat", tokPat, "tokInput", tokInput); IterableIterator> spreadInputs = ai_spreadCertainIndices_2_iterator(tokPat, tokInput, varIndices); for (List tok : spreadInputs) { if (flexMatchIC_iterate_debug) print("Testing spread " + sfu(codeTokens(tokPat)) + " with input: " + sfu(codeTokens(tok))); Matches m = new Matches(); if (flexMatchIC_iterate_useTokenization ? match3(tokPat, tok, m) : match(pat, tok, m)) { if (flexMatchIC_iterate_debug) print("Got match: " + m); callF(onMatch, m); } } } static public String hjs_markRowMagic(Object... __) { String color = optPar("color", __, "#99f"); return hjs(replaceDollarVars("\r\n var rowMagic_hash = window.location.hash.substr(1);\r\n if (rowMagic_hash)\r\n $(\"a[name=\" + rowMagic_hash + \"]\").closest('tr').css({ 'background-color' : '$color'});\r\n ", "color", color)); } static public Set synchroSet() { return synchroHashSet(); } static public Set synchroSet(Set set) { return synchronizedSet(set); } static volatile public boolean muricaPassword_pretendNotAuthed = false; static public String muricaPassword() { if (muricaPassword_pretendNotAuthed) return null; return trim(loadTextFile(muricaPasswordFile())); } 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 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 Object callJavaX(String method, Object... args) { return callOpt(getJavaX(), method, args); } static public HashMap, Class> loadFunctions_cache = new HashMap(); static public Lock loadFunctions_cached_lock = lock(); static public boolean loadFunctions_preferDiskCache = false; static public Class loadFunctions_cached(String... functions) { return loadFunctions_cached(asList(functions)); } static public Class loadFunctions_cached(Collection functions) { TreeSet functionSet = new TreeSet(functions); Lock __0 = loadFunctions_cached_lock; lock(__0); try { Class c = loadFunctions_cache.get(functionSet); if (c != null) return c; String transpilation = null; if (l(functions) == 1 && isSlowMachine()) { String snippetID = stdFunctions_cached().get(first(functions)); if (nempty(snippetID)) { if (!isMD5(getUpToDateSnippetTranspilationMD5(snippetID))) print("Slow machine mode: " + snippetID + " transpilation not up to date"); else { transpilation = getServerTranspiledWithoutLibs(snippetID); print("Loaded server transpilation: " + snippetID); } } } if (transpilation == null) { String cached = getTranspiledStandardFunctionsIfCached(functionSet); if (cached != null && (loadFunctions_preferDiskCache || standardFunctionsCacheUpToDate(functionSet))) transpilation = cached; } if (transpilation != null) { print("Loading " + joinWithPlus(functionSet)); c = veryQuickJava_finish(transpilation, emptyList()); } if (c == null) c = loadFunctions(functionSet); loadFunctions_cache.put(functionSet, c); assertNotNull(loadFunctions_cache.get(functionSet)); return c; } finally { unlock(__0); } } static public void loadFunctions_cached_clearCache() { Lock __1 = loadFunctions_cached_lock; lock(__1); try { loadFunctions_cache.clear(); } finally { unlock(__1); } } static public void _onLoad_loadFunctions_cached() { ownResource(vmBus_onMessage("refreshedTranspiler", new Runnable() { public void run() { try { loadFunctions_clearCache(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "loadFunctions_clearCache();"; } })); } static public String formatDoubleX(double d, int digits) { return formatDoubleFull(d, digits); } static public Boolean not(Boolean b) { return b == null ? null : !b; } static public long now_virtualTime; static public long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } 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 String p_vbar(String... items) { return p_vbar(asList(items)); } static public String p_vbar(Collection items, Object... __) { return pUnlessEmpty(joinNemptiesWithVBar(items), __); } static public boolean setAdd(Collection c, A a) { if (c == null || c.contains(a)) return false; c.add(a); return true; } static public void csetIfUnset(Concept c, String field, Object value) { if (cget(c, field) == null) cset(c, field, value); } 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 String hsubmit(String text, Object... params) { return tag("input", "", concatArrays(new Object[] { "type", "submit", "value", text }, params)); } static public String hsubmit() { return hsubmit("Submit"); } static public List lastTwo(List l) { return takeLast(2, l); } 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 JTextField consoleInputField() { Object console = get(getJavaX(), "console"); return (JTextField) getOpt(console, "tfInput"); } 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 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 List rawEmojisList() { return (List) jsonDecodeMap(loadTextFile(loadLibrary("#1400427"))).get("emojis"); } static public String p_alignRight(String s, Object... params) { return p(s, params_stylePlus(params, "text-align: right")); } static public boolean eqicOneOf(String s, String... l) { for (String x : l) if (eqic(s, x)) return true; return false; } static public int maxLineCount(Collection l) { int n = 0; if (l != null) for (String s : l) n = max(n, countLines(s)); return n; } static public boolean possibleMD5(String s) { return isMD5(s); } static public String htitle(String title) { return hfulltag("title", htmlencode_noQuotes(title)); } static public String intToHex(int i) { return bytesToHex(intToBytes(i)); } static public int countWords(String s) { return numberOfWords2(s); } 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 volatile public PersistableThrowable lastException_lastException; static public PersistableThrowable lastException() { return lastException_lastException; } static public void lastException(Throwable e) { lastException_lastException = persistableThrowable(e); } 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 getComputerID_quick() { return computerID(); } static public String htmlEncode2(String s) { return htmlencode_noQuotes(s); } static public String htmlEncode2(Object o) { return htmlEncode2(strOrEmpty(o)); } static public boolean isStringStartingWith(Object o, String prefix) { return o instanceof String && ((String) o).startsWith(prefix); } static public List getAndClearList(Collection l) { if (l == null) return emptyList(); synchronized (collectionMutex(l)) { List out = cloneList(l); l.clear(); return out; } } static public List pairsAWhereB(Iterable> c, IF1 pred) { return pairsA(filter(c, p -> pred.get(p.b))); } static public String hcss_responstable() { return hcss("\r\n .responstable {\r\n margin: 1em 0;\r\n width: 100%;\r\n overflow: visible;\r\n background: #FFF;\r\n color: #024457;\r\n border-radius: 10px;\r\n border: 1px solid #167F92;\r\n }\r\n \r\n .responstable tr {\r\n border: 1px solid #D9E4E6;\r\n }\r\n .responstable tr:nth-child(odd) {\r\n background-color: #EAF3F3;\r\n }\r\n .responstable th {\r\n display: none;\r\n border: 1px solid #FFF;\r\n background-color: #167F92;\r\n color: #FFF;\r\n padding: 1em;\r\n }\r\n .responstable th:first-child {\r\n display: table-cell;\r\n text-align: center;\r\n }\r\n .responstable th:nth-child(2) {\r\n display: table-cell;\r\n }\r\n .responstable th:nth-child(2) span {\r\n display: none;\r\n }\r\n .responstable th:nth-child(2):after {\r\n content: attr(data-th);\r\n }\r\n @media (min-width: 480px) {\r\n .responstable th:nth-child(2) span {\r\n display: block;\r\n }\r\n .responstable th:nth-child(2):after {\r\n display: none;\r\n }\r\n }\r\n .responstable td {\r\n display: block;\r\n word-wrap: break-word;\r\n max-width: 7em;\r\n }\r\n .responstable td:first-child {\r\n display: table-cell;\r\n text-align: center;\r\n border-right: 1px solid #D9E4E6;\r\n }\r\n @media (min-width: 480px) {\r\n .responstable td {\r\n border: 1px solid #D9E4E6;\r\n }\r\n }\r\n .responstable th, .responstable td {\r\n text-align: left;\r\n margin: .5em 1em;\r\n }\r\n @media (min-width: 480px) {\r\n .responstable th, .responstable td {\r\n display: table-cell;\r\n padding: 1em;\r\n }\r\n }\r\n "); } 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 Map prependEmptyOptionForHSelect(Map map) { Map map2 = litorderedmap("", ""); putAll(map2, map); return map2; } 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 JPanel showFormTitled2(String title, Object... parts) { return showFormTitled_customLayout(formLayouter1(), title, parts); } 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 String hdiv(Object contents, Object... params) { return hfulltag("div", contents, params); } static public String hdiv() { return hdiv(""); } static public float getSwingFontScale() { return or((Float) vm_generalMap_get("swingFontScale_value"), 1f); } static public boolean match3_startOrEndOfLine(String pat, String s, boolean startOfLine, boolean endOfLine) { if (startOfLine) return endOfLine ? match3(pat, s) : matchStart(pat, s); else return endOfLine ? matchEnd(pat, s) : find3(pat, s); } static public File transpiledStandardFunctions_file(TreeSet functionSet) { String name = uniqueFileNameUsingMD5_80_v2(join("+", functionSet)); File dir = javaxCachesDir("Transpiled Standard Functions"); saveTextFileUnlessExists(newFile(dir, name + ".functions"), lines(functionSet)); return newFile(dir, name + ".java"); } static public String addPrefixIfNotEmpty2(String prefix, String s) { return empty(s) ? "" : addPrefix(prefix, s); } static public String dropLeadingSlash(String s) { return dropPrefix("/", s); } static public boolean substanceLookAndFeelEnabled() { return startsWith(getLookAndFeel(), "org.pushingpixels."); } 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 List dropFirstTwoAndLastTwo(List l) { return dropFirstAndLast(2, l); } static public void failIfUnlicensed() { assertTrue("license off", licensed()); } static public String selectedItem(JList l) { return getSelectedItem(l); } static public String selectedItem(JComboBox cb) { return getSelectedItem(cb); } 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"); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", str(l)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); writer.write(urlParameters); writer.flush(); String contents = loadPage_utf8(conn, url, false); writer.close(); return contents; } catch (Exception __e) { throw rethrow(__e); } } static public void saveFileVerbose(File f, byte[] data) { saveBinaryFileVerbose(f, data); } static public List keysSortedByValuesDesc(final Map map) { List l = new ArrayList(map.keySet()); sort(l, mapComparatorDesc(map)); return l; } 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 long fixTimestamp(long timestamp) { return timestamp > now() ? 0 : timestamp; } 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 InputStream urlConnection_getInputStream(URLConnection con) throws IOException { return con.getInputStream(); } static public List allToLong(Collection l) { return lmap(__97 -> toLong(__97), l); } static public float parseFloat(String s) { return Float.parseFloat(s); } static public List allPlus(final int x, List l) { return map(l, new F1() { public Integer get(Integer i) { try { return i + x; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "i+x"; } }); } static public Comparator reverseOrder() { return new Comparator() { public int compare(Object a, Object b) { return cmp(b, a); } }; } 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 boolean fileExists(String path) { return path != null && new File(path).exists(); } static public boolean fileExists(File f) { return f != null && f.exists(); } static public String himgsrc(String src, Object... params) { return tag("img", "", arrayPlus(params, "src", src)); } static public List toLinesFullTrim_java(String text) { return tlft(joinLines(map(__98 -> javaDropComments(__98), tlft(text)))); } static public void tok_statementToBlock(List tok, int i) { if (neqGet(tok, i, "{")) { int iEnd = tok_findEndOfStatement(tok, i) - 1; tokAppend_reTok(tok, iEnd, " }"); tokPrepend_reTok(tok, i, "{ "); } } static public String theAGIBlueDomain() { return "agi.blue"; } 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 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 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 String h1_title(String s) { return htitle_h1(s); } 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 A singleObjectMethodProxy(Class intrface, Object object, String methodName) { return proxyFromInvocationHandler(intrface, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) { String mname = method.getName(); if (mname.equals(methodName)) return call(object, methodName, unnull(args)); if (mname.equals("toString")) return "proxy for " + methodName; return null; } }); } 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 String toLower(String s) { return s == null ? null : s.toLowerCase(); } static public char toLower(char c) { return Character.toLowerCase(c); } 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 WeakReference newWeakReference(A a) { return a == null ? null : new WeakReference(a); } static public List uniquifyAndSortAlphaNum(Collection l) { return sortedAlphaNum(uniquify(l)); } static public void print_setPrefixForThread(final String prefix) { interceptPrintInThisThread(empty(prefix) ? null : new _PrintIndent(prefix)); } static public String hhtml_head_title_body(String title, Object bodyContents, Object... bodyParams) { return hhtml(hhead(htitle(title)) + "\n" + hbody(bodyContents, bodyParams)); } static public MultiMap caseInsensitiveMultiMap() { MultiMap mm = new MultiMap(); mm.data = caseInsensitiveMap(); return mm; } static public int boolToInt(boolean b) { return b ? 1 : 0; } static public String lowestByAlphaNum(Collection c) { String best = null; for (String s : unnullForIteration(c)) if (best == null || alphaNumComparator().compare(s, best) < 0) best = s; return best; } static public boolean sameSnippetID(String a, String b) { if (!isSnippetID(a) || !isSnippetID(b)) return false; return parseSnippetID(a) == parseSnippetID(b); } static public long recommendedTranspilationDateForStandardFunction(String sfName) { return toLong(mechMap("Recommended SF Transpilation Date").get(sfName)); } static public int compareIC(String s1, String s2) { return compareIgnoreCase_jdk(s1, s2); } static public List callFAll(Collection l, Object... args) { return callF_all(l, args); } static public Object[] muricaCredentials() { String pass = muricaPassword(); return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0]; } static public int indexOfIgnoreCase(List a, String b) { return indexOfIgnoreCase(a, b, 0); } static public int indexOfIgnoreCase(List a, String b, int i) { int n = a == null ? 0 : a.size(); for (; i < n; i++) if (eqic(a.get(i), b)) return i; return -1; } static public int indexOfIgnoreCase(String[] a, String b) { return indexOfIgnoreCase(a, b, 0); } static public int indexOfIgnoreCase(String[] a, String b, int i) { int n = a == null ? 0 : a.length; for (; i < n; i++) if (eqic(a[i], b)) return i; return -1; } static public int indexOfIgnoreCase(String a, String b) { return indexOfIgnoreCase_manual(a, b); } static public int indexOfIgnoreCase(String a, String b, int i) { return indexOfIgnoreCase_manual(a, b, i); } static public boolean 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 List listZip(File inZip) { return listZipFile(inZip); } static public List listZip(String inZip) { return listZipFile(inZip); } static public boolean match3_withIntsAndIDs(String pat, String s) { return match3_withIntsAndIDs(pat, s, null); } static public boolean match3_withIntsAndIDs(String pat, String s, Matches m) { List tokPat = javaTokWithAllPlusAngleBrackets(pat); String pat2 = joinMap(tokPat, t -> eqOneOf(t, "", "") ? "*" : t); Matches m2 = m == null ? new Matches() : m; if (!match3(pat2, s, m2)) return false; List vars = filter(codeTokens(tokPat), t -> eqOneOf(t, "", "", "*")); for (int i = 0; i < l(vars); i++) { if (eq(vars.get(i), "") && !isInteger(m2.get(i)) || eq(vars.get(i), "") && !isIdentifier(m2.get(i))) return false; } return true; } 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 A objectWhere(Collection c, Object... data) { return findWhere(c, data); } static public boolean isAbsolutePath(String s) { return s != null && new File(s).isAbsolute(); } static public boolean isAbsolutePath(File f) { return f != null && f.isAbsolute(); } static public 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 A findWhere(Collection c, Object... data) { if (c != null) for (A x : c) if (checkFields(x, data)) return x; return null; } 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 String hbuttonOnClick(String text, String onClick, Object... params) { return hfulltag("button", text, paramsPlus(params, "onClick", onClick)); } static public String stream2string(InputStream in) { return utf8streamToString(in); } static public String urlWithoutQueryAndAnchor(String url) { return takeFirst(url, min(smartIndexOf(url, "?"), smartIndexOf(url, "#"))); } 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 String dm_moduleLibID() { return programID() + "/" + shortClassName(dm_current_mandatory_generic()); } static public String dm_moduleLibID(Object mod) { if (mod == null) return null; mod = dm_getModule(mod); if (hasSuperclassShortNamed(mod, "DynModule")) return programID(mod) + "/" + shortClassName(mod); return null; } static public List allToUpper(Collection l) { List x = new ArrayList(l(l)); if (l != null) for (String s : l) x.add(upper(s)); return x; } static public String hhiddenWithIDAndName(String idAndName) { return hhiddenWithIDAndName(idAndName, null); } static public String hhiddenWithIDAndName(String idAndName, Object value, Object... params) { return tag("input", "", paramsPlus(params, "type", "hidden", "id", idAndName, "name", idAndName, "value", value)); } static public byte[] raf_readFilePart(RandomAccessFile raf, long start, int l) { try { byte[] buf = new byte[l]; raf.seek(start); raf.readFully(buf); return buf; } catch (Exception __e) { throw rethrow(__e); } } static public List myLibraryFiles() { Collection files = (Collection) (getOpt(myClassLoader(), "files")); if (files != null) return asList(files); return ll(getBytecodePathForClass(mc())); } static public boolean neqOneOf(Object o, Object... l) { for (Object x : l) if (eq(o, x)) return false; return true; } 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 TreeMap caseInsensitiveMap() { return new TreeMap(caseInsensitiveComparator()); } static public List filterConcepts(List list, Object... params) { if (empty(params)) return list; List l = new ArrayList(); for (A x : list) if (checkConceptFields(x, params)) l.add(x); return l; } static public String dropTranslators(String src) { return findTranslators2(src, null); } static public List dropTranslators(List tok) { return findTranslators2(tok, null); } static public Set syncIdentityHashSet() { return (Set) synchronizedSet(identityHashSet()); } static public ClassLoader getClassLoaderOrSame(Object o) { return o instanceof ClassLoader ? (ClassLoader) o : getClassLoader(o); } static public Object dm_resolveModule(Object moduleOrStem) { return dm_callOS("resolveModule", moduleOrStem); } static public boolean containsKey(Map map, A key) { return map != null && map.containsKey(key); } static public List dropHTMLComments(List tok) { List l = new ArrayList(); for (int idx = 0; idx < l(tok); idx++) { String t = tok.get(idx); if (even(idx)) { int i; while ((i = t.indexOf("", i + 4); t = substring(t, 0, i) + substring(t, j + 3); } } l.add(t); } return l; } static public Map>> mechHashMap_cache = synchroMap(); static public Map mechHashMap(String listName) { Pair> p = mechHashMap_cache.get(listName); String text = mechList_raw(listName); if (p != null && eq(p.a, text)) return p.b; String parsing = first(mechList_opt(listName + " | Parsing")); p = pair(text, (Map) (parsing != null ? asHashMap((Map) callAndMake(parsing, text)) : parseDoubleArrowMap(new HashMap(), tlft(text)))); mechHashMap_cache.put(listName, p); return p.b; } static public void tok_transpileIfQuoted_dollarVars(List tok) { jreplace_dyn(tok, "if ", new F2, Integer, String>() { public String get(List tok, Integer cIdx) { try { String pat = unquote(tok.get(cIdx + 2)); List vars = new ArrayList(); String pat2 = dollarVarsToStars(pat, vars); int iCurly = cIdx + 4; tok_statementToBlock(tok, iCurly); tokAppend_reTok(tok, iCurly, joinWithSpace(mapWithIndexStartingAt1(vars, (i, var) -> ("S " + var + " = $" + i + ";")))); return ("if (match(" + (quote(pat2)) + ", s, m))"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "S pat = unquote(tok.get(cIdx+2));\r\n new LS vars;\r\n S pat2 = dollarVarsT..."; } }, new TokCondition() { public boolean get(final List tok, final int i) { return containsDollarVars(unquote(tok.get(i + 3))); } }); } static public boolean containsATextArea(Component c) { return childOfType(c, JTextArea.class) != null; } static public boolean vmBus_noObjections(String msg, Object... args) { return !vmBus_anyFalse(msg, args); } static public Object vmGeneralMap_get(Object key) { return vm_generalMap_get(key); } static public boolean isSymLink(File f) { return f != null && Files.isSymbolicLink(toPath(f)); } 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 boolean regexpMatches(String pat, String s) { return pat != null && s != null && regexp(pat, s).matches(); } static public boolean regexpMatches(java.util.regex.Pattern pat, String s) { return pat != null && s != null && regexp(pat, s).matches(); } static public File localSnippetsDir() { return javaxDataDir("Personal Programs"); } static public File localSnippetsDir(String sub) { return newFile(localSnippetsDir(), sub); } 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 A replaceIfEquals(A a, A b, A c) { return replaceIfEqual(a, b, c); } 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 String mechList_opt_raw_fresh(String name) { Object readMode = mechMode().readMode; if (readMode instanceof File) { String md5Name = uniqueFileNameUsingMD5_80_v2(upper(name)); return loadTextFileFromZipFile((File) readMode, md5Name); } boolean useLocal = false, useRemote = true; if (eq(readMode, "mergeLocalAndRemote")) useLocal = true; else if (eq(readMode, "local")) { useLocal = true; useRemote = false; } String s = ""; if (useRemote) { if (eq(mechMode().readMode, "localCopies")) s = unnull(loadTextFile(remoteMechListMirrorFile(name))); else s = serverMechList_raw_fresh(name, true); } if (useLocal) s = appendNewLineIfNempty(s) + localMechList_opt_raw_fresh(name); return s; } 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 String structureOrTextForUser(Object o) { return o == null ? "" : o instanceof String ? (String) o : structureForUser(o); } static public List sortedByField(Collection c, final String field) { List l = new ArrayList(c); sort(l, new Comparator() { public int compare(A a, A b) { return cmp(getOpt(a, field), getOpt(b, field)); } }); return l; } static public List sortedByField(String field, Collection c) { return sortedByField(c, field); } static public Type getRawType(Type t) { if (t instanceof ParameterizedType) return ((ParameterizedType) t).getRawType(); return t; } static public boolean containsNewLine(String s) { return contains(s, '\n'); } static public void retireClassLoader(ClassLoader cl) { try { if (isJavaXClassLoader(cl)) setOptAll(cl, "retired", true, "retiredMarker", new DefunctClassLoader()); } catch (Throwable __e) { pcallFail(__e); } } static public byte[] isGIF_magic = bytesFromHex("47494638"); static public boolean isGIF(byte[] data) { return byteArrayStartsWith(data, isGIF_magic); } static public boolean isGIF(File f) { return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic))); } static public 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 List words2(String s) { List l = new ArrayList(); int n = l(s); for (int i = 0; i < n; ) { int j = i; while (j < n && isLetterOrDigit(s.charAt(j))) ++j; if (j > i) l.add(substring(s, i, j)); while (j < n && !isLetterOrDigit(s.charAt(j))) ++j; i = j; } return l; } static public String joinNemptiesWithVBar(String... strings) { return joinNempties(" | ", strings); } static public String joinNemptiesWithVBar(Collection strings) { return joinNempties(" | ", strings); } 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 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 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 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 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 callAndMake(String functionName, Object... args) { return callAndMake_orDirect(functionName, args); } static public boolean containsNulls(Collection c) { return contains(c, null); } 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 String htextinput(String name, Object... params) { Object value = ""; if (odd(l(params))) { value = params[0]; params = dropFirst(params); } params = html_massageAutofocusParam(params); return tag("input", "", concatArrays(new Object[] { "type", "text", "name", name, "value", value }, params)); } static public String htextinput(String name) { return htextinput(name, ""); } 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 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[] 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 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 Object[] litparams(Object... l) { int n = 0, n1 = l(l); for (int i = 0; i < n1; i += 2) if (l[i] != null && l[i + 1] != null) ++n; if (n == 0) return null; Object[] params = new Object[n * 2]; int j = 0; for (int i = 0; i < n1; i += 2) { Object key = l[i], value = l[i + 1]; if (key != null && value != null) { params[j++] = key; params[j++] = value; } } return params; } static public int lUtf8(String s) { return l(utf8(s)); } 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 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 IF1 swic$(String prefix) { return s -> swic(s, prefix); } static public File localMechListsDir() { return javaxDataDir("Mech Lists"); } static public Object subBot_serveHTML(Object html) { return subBot_serveWithContentType(str(html), "text/html"); } static public String firstToUpper(String s) { if (empty(s)) return s; return Character.toUpperCase(s.charAt(0)) + s.substring(1); } 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 standardCredentialsPass() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass")))); } static public int indexOf_byteArray(byte[] a, byte b) { int n = l(a); for (int i = 0; i < n; i++) if (a[i] == b) return i; return -1; } 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 TreeMap litcimap(Object... x) { return litCIMap(x); } 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 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 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 File programSecretFile(String progID, String fileName) { return secretProgramFile(progID, fileName); } static public File programSecretFile(String fileName) { return secretProgramFile(fileName); } static public String sendOpt(String bot, String text, Object... args) { return sendToLocalBotOpt(bot, text, args); } static public List reverseList(List l) { Collections.reverse(l); return l; } 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 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 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 void saveTextFileUnlessExists(File f, String contents) { if (f != null && !f.exists()) saveTextFile(f, contents); } static public File remoteMechListMirrorFile(String listName) { return newFile(remoteMechListMirrorsDir(), uniqueFileNameUsingMD5_80_v2(upper(listName))); } 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 String neatMechListURL(String listName) { return "http://botcompany.de/mech/raw/list/" + urlencode(listName); } static public String unicode_leftPointingTriangle() { return unicodeFromCodePoint(0x25C2); } static public String joinWithSemicolon(Iterable l) { return join("; ", l); } static public String html_evaluateIfTags(String html, IF1 pred) { List tok = htmlTok(html); boolean anyChange = false; while (true) { ping(); List ifTag = first(findContainerTag(tok, "if")); if (ifTag == null) break; anyChange = true; int iElse = indexOfIC(ifTag, ""); boolean val = pred.get(htmlTagFullParamString(second(ifTag))); if (val) { if (iElse >= 0) clearTokens(ifTag, iElse, l(ifTag) - 2); } else { clearTokens(ifTag, 2, iElse < 0 ? l(ifTag) - 2 : iElse + 1); } clearToken(ifTag, 1); clearToken(ifTag, l(ifTag) - 2); } return anyChange ? join(tok) : html; } static public File parentFile(File f) { return dirOfFile(f); } static public String getServerTranspiledWithoutLibs(String snippetID) { return dropFirstLine(getServerTranspiled2(snippetID)); } 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 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 boolean isProperlyQuoted(String s) { return s.length() >= 2 && s.startsWith("\"") && s.endsWith("\"") && (!s.endsWith("\\\"") || s.endsWith("\\\\\"")) && !containsNewLine(s); } 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 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 JWindow showInTopRightCorner(Component c) { return swing(() -> { JWindow w = new JWindow(); w.add(c); w.pack(); moveToTopRightCorner(w); w.setVisible(true); return w; }); } static public ArrayList cloneListSynchronizingOn(Collection l, Object mutex) { if (l == null) return new ArrayList(); synchronized (mutex) { return new ArrayList(l); } } 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 List padList(List l, int w) { return padList(l, w, null); } static public List padList(List l, int w, A a) { if (l(l) >= w) return l; List x = cloneList(l); while (l(x) < w) x.add(a); return x; } static public String getType(Object o) { return getClassName(o); } static public void mapPut_noOverwrite(Map map, A key, B value) { if (map != null && key != null && value != null && !map.containsKey(key)) map.put(key, value); } 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 postPageSilently(String url, Object... params) { return doPostSilently(litmap(params), url); } static public void ping_okInCleanUp() { if (ping_pauseAll || ping_anyActions) ping_impl(true); } 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 HashMap asHashMap(Map map) { if (map != null && map.getClass() == HashMap.class) return (HashMap) map; HashMap m = new HashMap(l(map)); if (map != null) m.putAll(map); return m; } 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 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 boolean fileNempty(File f) { return fileNotEmpty(f); } static public void cancelTimers(Collection timers) { for (Object timer : timers) cancelTimer(timer); } 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 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 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 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 JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) { return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane"); } 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 String unparseCSSParameter(Map map) { return joinWithSemicolon(map(map, new F2() { public String get(String key, String value) { try { return key + ": " + value; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "key + \": \" + value"; } })); } static public Set mergeSets(Collection... l) { return joinSets(l); } static public Object endMarker() { return iteratorFromFunction_endMarker; } 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 Object serveJSON(Object... data) { return serveJSON_shallowLineBreaks(jsonPrepareData(data)); } 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 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 Collection asCollection(Iterable l) { return l == null ? null : l instanceof Collection ? ((Collection) l) : asList(l); } static public String appendSlash(String s) { return addSlash(s); } static public String hselect_list(String name, Collection entries, Object... params) { return hselect_list(entries, paramsPlus_skipFirst(params, "name", name)); } static public String hselect_list(Collection entries, Object... params) { StringBuilder buf = new StringBuilder(); String selected = null; if (odd(l(params))) { selected = str(first(params)); params = dropFirst(params); } int i = indexOf(params, "allowEmpty"); if (even(i)) { buf.append("\n"); params[i] = params[i + 1] = null; } if (nempty(entries)) for (String k : entries) { String value = k; boolean isSelected = eq(selected, k); buf.append(hfulltag("option", htmlencode(str(or(value, ""))), "value", k, "selected", isSelected ? html_valueLessParam() : null)).append("\n"); } return hfulltag("select", buf, params) + "\n"; } 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 List words(String s) { return codeTokens(dropPunctuation(javaTok(s))); } 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 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 Pair binarySearchForLineInTextFile(File file, IF1 nav) { long length = l(file); int bufSize = 1024; RandomAccessFile raf = randomAccessFileForReading(file); try { long min = 0, max = length; int direction = 0; Pair possibleResult = null; while (min < max) { ping(); long middle = (min + max) / 2; long lineStart = raf_findBeginningOfLine(raf, middle, bufSize); long lineEnd = raf_findEndOfLine(raf, middle, bufSize); String line = fromUtf8(raf_readFilePart(raf, lineStart, (int) (lineEnd - 1 - lineStart))); direction = nav.get(line); possibleResult = pair(new LongRange(lineStart, lineEnd), line); if (direction == 0) return possibleResult; if (direction < 0) max = assertLessThan(max, lineStart); else min = assertBiggerThan(min, lineEnd); } if (direction >= 0) return possibleResult; long lineStart = raf_findBeginningOfLine(raf, min - 1, bufSize); String line = fromUtf8(raf_readFilePart(raf, lineStart, (int) (min - 1 - lineStart))); return pair(new LongRange(lineStart, min), line); } finally { _close(raf); } } 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 String javaDropComments(String s) { return javaDropAllComments(s); } static public String linesPreservingTrailingNewLine(String original, List lines) { String s = lines(lines); return endsWith(original, "\n") ? s : dropSuffix("\n", s); } 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 List sortedByFieldIC(Collection c, final String field) { List l = new ArrayList(c); sort(l, new Comparator() { public int compare(A a, A b) { return compareIC((String) getOpt(a, field), (String) getOpt(b, field)); } }); return l; } static public List sortedByFieldIC(String field, Collection c) { return sortedByFieldIC(c, field); } static public String dropAfterSlash(String s) { if (s == null) return null; int i = s.indexOf('/'); return i < 0 ? s : rtrim(substring(s, 0, i)); } static public String timeInTimeZone(String timeZone) { return timeInTimeZone(timeZone, now()); } static public String timeInTimeZone(String timeZone, long time) { return simpleDateFormat_timeZone("HH:mm", timeZone).format(time); } static public String timeInTimeZone(TimeZone timeZone, long time) { return simpleDateFormat("HH:mm", timeZone).format(time); } 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 String localMechList_opt_raw_fresh(String name) { return unnull(loadTextFile(localMechListFile(name))); } static public List dropAllTags(List tok) { List list = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && t.startsWith("<")) { list.set(list.size() - 1, list.get(list.size() - 1) + tok.get(i + 1)); ++i; } else list.add(t); } return list; } static public String dropAllTags(String html) { if (!contains(html, '<')) return html; return join(dropAllTags(htmlcoarsetok(html))); } 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 String phraseToRegExp(String b) { return (startsWithLetterOrDigit(b) ? "\\b" : "") + regexpQuote(b) + (endsWithLetterOrDigit(b) ? "\\b" : ""); } static public String fieldNameForConceptLink(Concept from, Concept to) { for (Pair p : scanConceptForRefsWithFieldNames(from)) if (derefRef(p.a) == to) return p.b; return null; } 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 Object[] onlyNonNullParams(Object... params) { List out = new ArrayList(); for (int i = 0; i + 1 < l(params); i += 2) if (params[i] != null && params[i + 1] != null) { out.add(params[i]); out.add(params[i + 1]); } return toObjectArray(out); } static public A getAndClearThreadLocal(ThreadLocal tl) { A a = tl.get(); tl.set(null); return 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 Map> multiMapToMap(MultiMap m) { return m == null ? null : m.data; } 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 void addPair(Collection> c, A a, B b) { if (c != null) c.add(pair(a, b)); } 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 Cache> countryDialCodes_rawNumbersTreeMultiMap_cache = new Cache<>(() -> countryDialCodes_rawNumbersTreeMultiMap_load()); static public MultiMap countryDialCodes_rawNumbersTreeMultiMap() { return countryDialCodes_rawNumbersTreeMultiMap_cache.get(); } static public MultiMap countryDialCodes_rawNumbersTreeMultiMap_load() { return mapToMultiMap(mapKeys(__99 -> digitsOnly(__99), multiMapToMap(countryDialCodesMultiMap()))); } static public boolean isQuoted(String s) { if (isNormalQuoted(s)) return true; return isMultilineQuoted(s); } static public String beforeColonOrAll(String s) { return takeFirst(smartIndexOf(s, ':'), s); } 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 Scorer scorerWithSuccessesAndErrors() { Scorer scorer = new Scorer(); scorer.successes = new ArrayList(); scorer.errors = new ArrayList(); return scorer; } static public char[] emptyCharArray = new char[0]; static public char[] emptyCharArray() { return emptyCharArray; } static public String hhiddenMulti(Object... params) { return mapPairsToLines(paramsToPairs(params), (k, v) -> hhidden(str(k), v)); } static public void fixACCInClassLoader(Object o) { } static public String toK_str(long l) { return str_toK(l); } 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 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 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 boolean containsSpaces(String s) { return indexOf(s, ' ') >= 0; } static public boolean conceptsWithFieldGreaterThan_verbose = false; static public Collection conceptsWithFieldGreaterThan(Class c, String field, Object value) { return conceptsWithFieldGreaterThan(db_mainConcepts(), c, field, value); } static public Collection conceptsWithFieldGreaterThan(Concepts concepts, Class c, String field, Object value) { IFieldIndex index = concepts.getFieldIndex(c, field); if (index instanceof ConceptFieldIndexDesc) return ((ConceptFieldIndexDesc) index).objectsWithValueGreaterThan(value); if (conceptsWithFieldGreaterThan_verbose) print("conceptsWithFieldGreaterThan: table scan of " + c + " for field " + field); return objectsWhereFieldGreaterThan(concepts.list(c), field, value); } static public Map parseDoubleLeftArrowMap(Map map, List l) { for (String s : l) { List x = splitAtDoubleLeftArrow(s); if (l(x) == 2) map.put(second(x), first(x)); } return map; } static public boolean eitherIsA(Either e) { return e != null && e.isA(); } static public boolean isDigit(char c) { return Character.isDigit(c); } static public String hinlinepostform(Object contents, Object... __) { return hpostform(contents, params_stylePlus(__, "display: inline")); } static public boolean eitherIsB(Either e) { return e != null && e.isB(); } static public String dropSlashPrefix(String s) { return dropLeadingSlash(s); } 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 dm_callOS(String functionName, Object... args) { return call(dm_os(), functionName, args); } static public List tok_splitAtComma(String s) { return tok_splitAtComma(javaTok(s)); } static public List tok_splitAtComma(List tok) { List out = new ArrayList(); for (int i = 0; i < l(tok); i++) { int j = smartIndexOf(tok, ",", i); out.add(joinSubList(tok, i + 1, j - 1)); i = j; } return out; } 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 String hform(Object contents, Object... params) { return htag("form", contents, params); } static public String loadTextFileFromZip(File inZip, String fileName) { return loadTextFileFromZipFile(inZip, fileName); } static public String pnlToStringWithEmptyLines_rtrim(Iterable l) { return rtrim(pnlToStringWithEmptyLines(l)); } static public String h1(String s, Object... params) { return hfulltag("h1", s, params); } static public String h2(String s, Object... params) { return tag("h2", s, params); } static public String h3(String s, Object... params) { return tag("h3", s, params) + "\n"; } 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 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 Pair random(Map map) { return entryToPair(random(entries(map))); } 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 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 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 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 String md5OrNull(String s) { return s == null ? null : md5(s); } static public Map syncWeakHashMap() { return newWeakHashMap(); } 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 String hmp3upload(Object... params) { return hfileupload(paramsPlus(params, "accept", mp3mimeType())); } static public String insertString(String a, int idx, String b) { return spliceString(a, idx, idx, b); } static public Map synchronizedMRUCache(int maxSize) { return synchroMap(new MRUCache(maxSize)); } 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 Object[] asObjectArray(Collection l) { return toObjectArray(l); } 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 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 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 String rcall_string(String method, Object o, Object... args) { return (String) rcall(method, o, args); } static public String simpleSpaces_javaTok(String s) { return join(simpleSpaces(javaTok(s))); } static public String dbProgramID() { return getDBProgramID(); } static public int getPreferredWidth(Component c) { return preferredWidth(c); } 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 String getString(Map map, Object key) { return map == null ? null : (String) map.get(key); } static public String getString(List l, int idx) { return (String) get(l, idx); } static public String getString(Object o, Object key) { if (o instanceof Map) return getString((Map) o, key); if (key instanceof String) return (String) getOpt(o, (String) key); throw fail("Not a string key: " + getClassName(key)); } static public String getString(String key, Object o) { return getString(o, (Object) key); } static public boolean 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 void sendMailThroughScript(String senderInfo, String from, String to, String subject, String text) { List l = splitAt(senderInfo, "#"); if (l(l) != 2) throw fail("Bad mail sender info"); String url = first(l), pw = second(l); print("Sending mail through " + url); print("From: " + from); print("To: " + to); print("Subject: " + subject); print("Text:"); printIndent("> ", text); assertStartsWith("OK", postPage(url, "pw", pw, "from", from, "to", to, "subject", subject, "text", text)); } static public String loadSnippetSilently(Snippet s) { return loadSnippetQuietly(s); } static public String loadSnippetSilently(String snippetID) { return loadSnippetQuietly(snippetID); } static public List nlTok(String s) { return javaTokPlusPeriod(s); } static public Set vm_busListeners_live_cache; static public Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache; } static public Set vm_busListeners_live_load() { return vm_generalIdentityHashSet("busListeners"); } static public Object[] 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 boolean saveTextFileIfChanged(File f, String contents) { return saveTextFileIfDifferent(f, contents); } static public Map synchroHashMap() { return synchronizedMap(new HashMap()); } static public String defaultBotName() { return getProgramTitle() + "."; } 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 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 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 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 String urlencode(String x) { try { return URLEncoder.encode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } static public String loadTextFileOrCreateWithRandomID(File f) { String id = trim(loadTextFile(f)); if (empty(id)) saveTextFile(f, id = aGlobalID()); return id; } 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 String hr() { return tag("hr"); } static public Object dm_call(Object moduleOrID, String method, Object... args) { Object mod = dm_getModule(moduleOrID); if (mod == null) return null; AutoCloseable __1 = dm_enter(mod); try { return call_withVarargs(mod, method, args); } finally { _close(__1); } } 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 String systemHashCodeHex(Object o) { return intToHex(identityHashCode(o)); } static public String hcrud_imagePreviewStyle() { return "max-width: 200px; max-height: 100px; width: auto; height: auto"; } 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 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 List dm_moduleIDs() { return dm_listModuleIDs(); } 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 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 Set cloneSet(Collection set) { if (set == null) return new HashSet(); synchronized (collectionMutex(set)) { Set s = similarEmptySet(set); s.addAll(set); return s; } } static public String fsI(String id) { return formatSnippetID(id); } static public String fsI(long id) { return formatSnippetID(id); } static public boolean eqic_unnull(String a, String b) { return eqic(unnull(a), unnull(b)); } static public String hcss_linkColorInherit() { return hcss("a { color: inherit; }"); } 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 List splitAtDoubleLeftArrow(String s) { return splitAtDoubleLeftArrow(javaTok(s)); } static public List splitAtDoubleLeftArrow(List tok) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { int j = indexOfSubList(tok, ll("<", "", "="), i); if (i >= l(tok)) break; if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j + 3; } return l; } static public String binaryMimeType() { return "application/octet-stream"; } static public String hTitleClean(String title) { return htmldecode(dropTagsAndHTMLComments(title)); } static public boolean isSubstanceLAF() { return substanceLookAndFeelEnabled(); } static public int calcHeight(int w, int h, int newWidth) { return iround(doubleRatio(h, w) * newWidth); } static public String html_showLineFeedsForPRE(String html) { return replace(html, "\n", unicode_newLineArrow() + "\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 File getSecretProgramDir() { return getSecretProgramDir(actualProgramID()); } static public File getSecretProgramDir(String snippetID) { if (empty(snippetID)) return javaxSecretDir(); return newFile(javaxSecretDir(), formatSnippetID(snippetID)); } 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 Object safeUnstructure(String s) { return unstructure(s, true); } static public Object safeUnstructure(File f) { return safeUnstructureGZFile(f); } static public void moveFile(File a, File b) { if (!renameFile(a, b)) throw fail("File move failed: " + a + " to " + b); } 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 StringTree2 stringTree2_javaTok(Map entries) { StringTree2 tree = new StringTree2(); for (String key : keys(entries)) addToStringTree(tree, javaTokC(key), entries.get(key)); return tree; } 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 Object dm_getService(String serviceName) { return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName))); } 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 String hpasswordfield(String name, Object... params) { Object value = ""; if (odd(l(params))) { value = params[0]; params = dropFirst(params); } params = html_massageAutofocusParam(params); return tag("input", "", concatArrays(new Object[] { "type", "password", "name", name, "value", value }, params)); } static public String hpasswordfield(String name) { return hpasswordfield(name, ""); } static public boolean isInstanceOf(Object o, Class type) { return type.isInstance(o); } static public String orEmptyQuotes(String s) { return or2(s, "\"\""); } 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 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 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 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 cleanKill() { cleanKillVM(); } 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 String htmlTagFullParamString(String tag) { int i = indexOfSpaceEtc(tag); return trimSubstring(i, dropSuffix(">", tag)); } static public List splitAtMinus(String s) { return trimAll(asList(s.split("\\-"))); } static public String ahref_undecorated(String link, Object contents, Object... params) { return ahref_unstyled(link, contents, params); } 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 Map parseDoubleArrowMapCI(List l) { return parseDoubleArrowMap((Map) ciMap(), l); } static public Map parseDoubleArrowMapCI(String s) { return parseDoubleArrowMapCI_tlft(s); } static public void setDefaultVMArgs(String args) { String oldArgs = javaxDefaultVMArgs(); args = trim(args); if (neq(unnull(oldArgs), unnull(args))) { print(); print("Changing default VM arguments from"); print(" " + oldArgs); print("to"); print(" " + args); print(); saveTextFile(javaxDataDir("default-vm-args"), nullIfEmpty(args)); } } 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 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 String gazelle_textURL(long postID) { return gazelle_server() + "text/" + postID; } static public boolean containsSpace(String s) { return containsSpaces(s); } static public List itemPlus(A a, Collection l) { return itemPlusList(a, l); } static public List cloneKeys_noSync(Map map) { return cloneList_noSync(keys(map)); } static public String timeInTimeZoneWithOptionalDate_24(String timezone, long time) { return timeInTimeZoneWithOptionalDate_24(timeZone(timezone), time); } static public String timeInTimeZoneWithOptionalDate_24(TimeZone timezone, long time) { SimpleDateFormat format = simpleDateFormat("yyyy/MM/dd", timezone); String date = format.format(time); boolean needDate = neq(date, format.format(now())); return (needDate ? date + " " : "") + timeInTimeZone(timezone, time); } 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 hcheckboxWithText(String name, String text, boolean checked, Object... params) { String id = randomID(); return hcheckbox(name, checked, paramsPlus(params, "id", id)) + " " + hlabelFor(id, htmlEncode2(text)); } static public String hcheckboxWithText(String name, String text) { return hcheckboxWithText(name, text, false); } static public void change() { callOpt(getOptMC("mainConcepts"), "allChanged"); } 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 String quoteIfNotIdentifierOrInteger(String s) { if (s == null) return null; return isJavaIdentifier(s) || isInteger(s) ? s : quote(s); } static public List cloneAndClearList(Collection l) { List l2 = cloneList(l); l.clear(); return l2; } 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 boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) { return a != null && a.regionMatches(true, offsetA, b, offsetB, len); } 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 long parseLongOpt_pcall(String s) { try { return isInteger(s) ? parseLong(s) : 0; } catch (Throwable __e) { print(exceptionToStringShort(__e)); } return 0; } static public List tlft(String s) { return toLinesFullTrim(s); } static public List tlft(File f) { return toLinesFullTrim(f); } static public String programTitle() { return getProgramName(); } static public List tok_combineRoundOrCurlyBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eqOneOf(t, "{", "(")) { int j = findEndOfBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } static public Path toPath(File f) { return f == null ? null : f.toPath(); } static public AutoCloseable dm_vmBus_onMessage(final String msg, final VF1 onMessage) { return dm_ownResource(vmBus_onMessage(msg, onMessage)); } static public AutoCloseable dm_vmBus_onMessage(final String msg, final IVF1 onMessage) { return dm_ownResource(vmBus_onMessage(msg, ivf1ToVF1(onMessage))); } static public AutoCloseable dm_vmBus_onMessage(final String msg, final IVF2 onMessage) { return dm_ownResource(vmBus_onMessage(msg, ivf2ToVF2(onMessage))); } static public AutoCloseable dm_vmBus_onMessage(String msg, final VF2 onMessage) { return dm_ownResource(vmBus_onMessage(msg, onMessage)); } static public AutoCloseable dm_vmBus_onMessage(String msg, Runnable onMessage) { return dm_ownResource(vmBus_onMessage(msg, onMessage)); } 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 JTextArea jTextAreaWithUndo() { return jTextAreaWithUndo(""); } static public JTextArea jTextAreaWithUndo(final String text) { return jenableUndoRedo(swingNu(JTextArea.class, text)); } 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 Q dm_startQ() { return dm_ownQ(startQ()); } static public Q dm_startQ(String name) { return dm_ownQ(startQ(name)); } static public Object vm_generalMap_get(Object key) { return vm_generalMap().get(key); } static public String dropSpaces(String s) { return unnull(s).replace(" ", ""); } static public String ahref_js(String js, Object contents, Object... params) { return empty(js) ? str(contents) : ahref("#", contents, paramsPlus(params, "onclick", addSuffix(trim(js), ";") + " return false;")); } 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 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 boolean mmo2_match(MMOPattern pattern, String s) { return mmo2_match(pattern, s, false, false); } static public boolean mmo2_match(MMOPattern pattern, String s, boolean startOfLine, boolean endOfLine) { if (pattern == null) return false; String s2 = trim(s); if (pattern instanceof MMOPattern.StartOfLine) return mmo2_match(((MMOPattern.StartOfLine) pattern).p, s2, true, endOfLine); if (pattern instanceof MMOPattern.EndOfLine) return mmo2_match(((MMOPattern.EndOfLine) pattern).p, s2, startOfLine, true); if (pattern instanceof MMOPattern.Phrase) { String p = ((MMOPattern.Phrase) pattern).phrase; if (((MMOPattern.Phrase) pattern).quoted) return cicWithSmartWordBoundary(s2, p); if (startsWith(p, "#")) return eqic(p, s2); return match3_startOrEndOfLine(p, s2, startOfLine, endOfLine); } if (pattern instanceof MMOPattern.And) return all(((MMOPattern.And) pattern).l, pat -> mmo2_match(pat, s2, startOfLine, endOfLine)); if (pattern instanceof MMOPattern.Or) return any(((MMOPattern.Or) pattern).l, pat -> mmo2_match(pat, s2, startOfLine, endOfLine)); if (pattern instanceof MMOPattern.Not) return !mmo2_match(((MMOPattern.Not) pattern).p, s2, startOfLine, endOfLine); throw fail("what. " + pattern); } static public boolean mmo2_match(String pattern, String s) { return mmo2_match(mmo2_parsePattern(pattern), s); } static public void closeAutoCloseables(Collection l) { if (l != null) for (AutoCloseable c : l) { try { c.close(); } catch (Throwable __e) { pcallFail(__e); } } } static public String getLookAndFeel() { return getClassName(UIManager.getLookAndFeel()); } static public String appendNewLineIfNempty(String s) { return empty(s) ? "" : s + "\n"; } static public boolean allUnique(Collection l) { return l(uniquify(l)) == l(l); } 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 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 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 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 Class mc() { return utils.class; } 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 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 Map parseDoubleArrowMap(Map map, List l) { for (String s : l) { List x = splitAtDoubleArrow_bothDirections(s); if (l(x) == 2) map.put(first(x), second(x)); } return map; } static public Map standardCredentialsMap() { String user = standardCredentialsUser(); String pass = standardCredentialsPass(); if (nempty(user) && nempty(pass)) return litmap("_user", user, "_pass", pass); return litmap(); } static public String quoteUnlessIdentifierOrInteger(String s) { return quoteIfNotIdentifierOrInteger(s); } 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 byte[] intToBytes(int i) { return new byte[] { (byte) (i >>> 24), (byte) (i >>> 16), (byte) (i >>> 8), (byte) i }; } static public String hparagraphs(Collection l) { return lines(lambdaMap(__100 -> p(__100), l)); } 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 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 String hreplacetag(String html, String tag, String newTag) { List tok = htmlcoarsetok(html); List> tags = findContainerTag(tok, tag); if (empty(tags)) return html; List theTag = first(tags); List actualTag = subList(theTag, 1, l(theTag) - 1); return join(replaceSubList(cloneList(tok), actualTag, litlist(newTag))); } 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 List syncLambdaMap(IF1 f, Collection l) { if (l == null) return emptyList(); synchronized (collectionMutex(l)) { return map(l, f); } } static public List javaTokWithAllPlusAngleBrackets(String s) { return tok_combineAngleBrackets_keep(javaTokWithAllBrackets(s)); } static public String cleanJavaCompilerOutput(String s) { return dropPrefixTrim("Annotation processing got disabled, since it requires a 1.6 compliant JVM", s); } static public String trimJoin(List s) { return trim(join(s)); } static public boolean saveTextFileIfDifferent(File f, String contents) { if (eq(loadTextFile(f), contents)) return false; { saveTextFile(f, contents); return true; } } static public String jsonEncode_breakAtLevel1(Object o) { StringBuilder buf = new StringBuilder(); jsonEncode_breakAtLevel1(o, buf, 1); return str(buf); } static public void jsonEncode_breakAtLevel1(Object o, StringBuilder buf, int level) { 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(","); if (level == 1) buf.append("\n "); buf.append(quote((String) key)); buf.append(":"); jsonEncode_breakAtLevel1(map.get(key), buf, level + 1); } if (level == 1) buf.append("\n"); 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(","); if (level == 1) buf.append("\n "); jsonEncode_breakAtLevel1(element, buf, level + 1); } if (level == 1) buf.append("\n"); buf.append("]"); } else throw fail("Unknown object for JSON encoding: " + className(o)); } 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 boolean containsDollarVars(String s) { for (String t : javaTokC(s)) if (isDollarVar(t)) return true; return false; } 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 Set keys(Map map) { return map == null ? new HashSet() : map.keySet(); } static public Set keys(Object map) { return keys((Map) map); } static public Set keys(MultiSet ms) { return ms.keySet(); } static public Set keys(IMultiMap mm) { return mm.keySet(); } 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 char stringToChar(String s) { if (l(s) != 1) throw fail("bad stringToChar: " + s); return firstChar(s); } static public String dropPrefix_trim(String prefix, String s) { return dropPrefixTrim(prefix, s); } 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 Pair uniqCI2_sync(Class c, final Object... params) { return uniqCI2_sync(db_mainConcepts(), c, params); } static public Pair uniqCI2_sync(Concepts cc, Class c, final Object... params) { return withDBLock(cc, new F0>() { public Pair get() { try { return uniqCI2(cc, c, params); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return uniqCI2(cc, c, params);"; } }); } static public String hresponstable() { return hcss_responstable(); } 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 String assertIdentifier(String s) { return assertIsIdentifier(s); } static public String assertIdentifier(String msg, String s) { return assertIsIdentifier(msg, s); } 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 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 File remoteMechListMirrorMetaFile(String listName) { return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".meta"); } 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 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 String ok2(String s) { return "ok " + s; } 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 String ol(String... list) { return ol(asList(list)); } static public String ol(List list, Object... params) { StringBuilder buf = new StringBuilder(); int i = indexOf(params, null); if (i == -1) i = l(params); for (String s : withoutNulls(list)) buf.append(tag("li", s, subArray(params, i + 1))).append("\n"); return containerTag("ol", buf, subArray(params, 0, i)) + "\n"; } static public String htableRaw2(List data, List paramsTable, List paramsTR, List paramsTD) { StringBuilder buf = new StringBuilder(); for (List row : data) { buf.append(hopeningTag("tr", toObjectArray(paramsTR))); for (Object cell : row) buf.append(htd(cell, toObjectArray(paramsTD))).append("\n"); buf.append("\n"); } return htag("table", buf, toObjectArray(paramsTable)); } 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 mechList_raw_fresh(String name) { return mechList_opt_raw_fresh(name); } 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 Map allConceptFieldsAsMap(Concept c) { Map map = new HashMap(); for (String field : unnullForIteration(conceptFields(c))) map.put(field, cget(c, field)); return map; } static public A or(A a, A b) { return a != null ? a : b; } static public Map syncMRUCache(int size) { return synchroMap(new MRUCache(size)); } static public String imageSnippetURLOrEmptyGIF(String snippetID) { return empty(snippetID) ? smallestTransparentGIFDataURI() : snippetImageURL(snippetID); } 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 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; } 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 List dropTagsAndHTMLComments(List tok) { return dropHTMLComments(dropTags(tok)); } static public String dropTagsAndHTMLComments(String html) { return join(dropTagsAndHTMLComments(htmlTok(html))); } static public int toMS_int(double seconds) { return toInt_checked((long) (seconds * 1000)); } 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 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 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 AccessControlContext vm_globalACC() { return (AccessControlContext) vm_generalMap_get("Global ACC"); } static public boolean hasConceptIC(Class c, Object... params) { return hasConceptWhereIC(c, params); } static public boolean hasConceptIC(Concepts cc, Class c, Object... params) { return hasConceptWhereIC(cc, c, params); } static public Map guessMimeTypeFromFileName_map = litmap(".css", "text/css", ".js", "text/javascript"); static public String guessMimeTypeFromFileName(String name) { return guessMimeTypeFromFileName(name, binaryMimeType()); } static public String guessMimeTypeFromFileName(String name, String defaultMimeType) { String __1 = guessMimeTypeFromFileName_map.get(fileExtension(name)); if (!empty(__1)) return __1; return or2(URLConnection.guessContentTypeFromName(name), defaultMimeType); } static public double systemLoad() { double load = osMXBean().getSystemLoadAverage(); if (load < 0) return systemCPULoad(); return load; } 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 Map mapPlus_inFront(Map m, Object... data) { LinkedHashMap m2 = new LinkedHashMap(); litmap_impl(m2, data); putAll(m2, m); return m2; } 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 List dm_modulesWithLibID(final String moduleLibID) { return filter(dm_moduleIDs(), new F1() { public Boolean get(String m) { try { return eq(dm_moduleLibID(m), moduleLibID); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "eq(dm_moduleLibID(m), moduleLibID)"; } }); } static public MultiMap treeMultiMap() { return new MultiMap(true); } static public MultiMap treeMultiMap(Comparator comparator) { return new MultiMap(new TreeMap>(comparator)); } static public String getSnippetTitle_safe(String id) { if (isLocalSnippetID(id)) return localSnippetTitle(id); String title = or(loadTextFile(snippetTitle_cacheFile(id)), "?"); try { title = getSnippetTitle(id); } catch (Throwable __e) { pcallFail(__e); } return title; } static public String upper(String s) { return s == null ? null : s.toUpperCase(); } static public char upper(char c) { return Character.toUpperCase(c); } 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 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 Method fastIntern_method; static public String fastIntern(String s) { try { if (s == null) return null; if (fastIntern_method == null) { fastIntern_method = findMethodNamed(javax(), "internPerProgram"); if (fastIntern_method == null) upgradeJavaXAndRestart(); } return (String) fastIntern_method.invoke(null, s); } catch (Exception __e) { throw rethrow(__e); } } static public Iterator iterator(Iterable c) { return c == null ? emptyIterator() : c.iterator(); } static public boolean isSlowMachine() { return eq("1", trimLoadTextFile(javaxDataDir("is-slow-machine.txt"))); } static public void putMultipleKeys(Map map, Collection keys, B value) { if (map == null || keys == null) return; for (A key : keys) map.put(key, value); } 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 boolean hasConceptWhereIC(Class c, Object... params) { return conceptWhereIC(c, params) != null; } static public boolean hasConceptWhereIC(Concepts cc, Class c, Object... params) { return conceptWhereIC(cc, c, params) != null; } 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 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 String hhtml_title_body(String title, Object bodyContents, Object... bodyParams) { return hhtml_head_title_body(title, bodyContents, bodyParams); } static public Object[] filterParams(Object[] params, Object... keys) { Set set = asSet(keys); List l = new ArrayList(); for (int i = 0; i < l(params); i += 2) if (contains(set, params[i])) { l.add(params[i]); l.add(params[i + 1]); } return asObjectArray(l); } static public List parseBusinessHours(String s) { List parts = nempties(tok_splitAtComma(s)); return map(parts, part -> { List l = splitAtMinus(part); IntRange r = intRange(parseHourAndOptionalMinutesToMinutes(first(l)), parseHourAndOptionalMinutesToMinutes(second(l))); if (r.end < r.start && r.start <= 12 * 60 && r.end < 12 * 60) r.end += 12 * 60; return r; }); } 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 Thread currentThread() { return Thread.currentThread(); } static public boolean directoryEmpty(File f) { return directoryIsEmpty(f); } static public boolean regexpContainsIC(String pat, String s) { return regexpFindsIC(pat, s); } static public boolean neqGet(List l, int i, Object o) { return neq(get(l, i), o); } static public List tok_combineRoundBrackets_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 = findEndOfBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } static public Map transformKeys(Map map, Object f) { HashMap m = new HashMap(); for (Object key : keys(map)) m.put(callF(f, key), map.get(key)); return m; } static public String emojisToUnicode(String s) { return regexReplace(s, ":(\\w+):", matcher -> lookupOrKeep(emojiShortNameMap(), matcher.group())); } static public List similarEmptyList(Collection m) { return new ArrayList(); } static public String himageupload(Object... params) { return hfileupload(paramsPlus(params, "accept", "image/png,image/jpeg,image/gif")); } 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 boolean transpileRaw_silent = true; static public boolean transpileRaw_useDiskCache = false; static public String transpileRaw(String mainJava) { return (String) call(dm_transpiler(), "transpileRaw", mainJava, false, transpileRaw_useDiskCache); } 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 String standardCredentials() { String user = standardCredentialsUser(); String pass = standardCredentialsPass(); if (nempty(user) && nempty(pass)) return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass); return ""; } static public double systemCPULoad() { return advancedOSMXBean().getSystemCpuLoad(); } 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 AutoCloseable tempInterceptPrint(F1 f) { return tempSetThreadLocal(print_byThread(), f); } static public String ol_htmlEncode(String... list) { return ol_htmlEncode(asList(list)); } static public String ol_htmlEncode(List list, Object... params) { return ol_htmlEncode((Collection) list, params); } static public String ol_htmlEncode(Collection list, Object... params) { return ol(lmap(__101 -> htmlEncode2(__101), list), params); } 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 String hstylesheetsrc(String src) { return tag("link", "", "rel", "stylesheet", "href", src); } static public Object[] changeParam(Object[] params, String name, Object value) { if (eq(optPar(params, name), value)) return params; Map map = paramsToOrderedMap(params); map.put(name, value); return mapToParams(map); } 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 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 void _initFrame(JFrame f) { myFrames_list.put(f, Boolean.TRUE); standardTitlePopupMenu(f); } 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 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 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 hfullcenter(Object contents, Object... __) { return tag("table", tr(td(contents, "align", "center")), paramsPlus(__, "width", "100%", "height", "100%")); } static public List syncAddOrCreate(List l, A a) { if (l == null) l = syncList(); l.add(a); return l; } static public String unicode_undoArrow() { return unicodeFromCodePoint(0x21B6); } static public boolean strictPutIC(Map map, A key, String value) { if (!(map != null && key != null && value != null)) return true; String old = map.get(key); if (old == null) { map.put(key, value); return true; } return eqic(old, value); } static public boolean strictPutIC(Map map, Symbol key, Symbol value) { if (!(map != null && key != null && value != null)) return true; Symbol old = map.get(key); if (old == null) { map.put(key, value); return true; } return eqic(old, value); } 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 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 List dm_listModuleIDs() { return map(__102 -> dm_moduleID(__102), dm_listStems()); } static public B syncPut(Map map, A key, B value) { if (map == null) return null; synchronized (map) { return map.put(key, value); } } 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 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 IntRange intRange(int start, int end) { return new IntRange(start, end); } static public String intern(String s) { return fastIntern(s); } static public TreeSet asCISet(Iterable c) { return toCaseInsensitiveSet(c); } static public TreeSet asCISet(String... x) { return toCaseInsensitiveSet(x); } static public void internalFrameDefaultPosition(JInternalFrame f) { f.setSize(500, 300); centerInternalFrame(f); } static public int numberOfMethodArguments(Object o, String method) { Class c; boolean mustBeStatic = false; if (o instanceof Class) { c = (Class) o; mustBeStatic = true; } else c = o.getClass(); Class _c = c; int n = -1; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (!m.getName().equals(method)) continue; if (mustBeStatic && !methodIsStatic(m)) continue; int nn = l(m.getParameterTypes()); if (n == -1) n = nn; else if (n != nn) throw fail("Variable number of method arguments: " + _c + "." + method); } c = c.getSuperclass(); } if (n == -1) throw fail("Method not found: " + _c + "." + method); return n; } static public String himg(String src, Object... params) { return tag("img", "", arrayPlus(params, "src", isSnippetID(src) ? snippetImageLink(src) : src)); } static public String himg(BufferedImage img, Object... params) { return himg(dataURL(jpegMimeType(), toJPEG(img)), params); } static public String td(Object contents, Object... params) { return hfulltag("td", contents, params); } static public String td() { return td(""); } static public List splitAtDoubleArrow(String s) { return splitAtDoubleArrow(javaTok(s)); } static public List splitAtDoubleArrow(List tok) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { int j = indexOfSubList(tok, splitAtDoubleArrow_tok(), i); if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j + 3; } return l; } 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 List splitAtAmpersand(String s) { return s == null ? emptyList() : asList(s.split("&")); } static public List splitByJavaToken(String s, String splitToken) { List tok = javaTok(s); List l = new ArrayList(); int i = 1; while (i < l(tok)) { int j = smartIndexOf(tok, splitToken, i); l.add(join(subList(tok, i, j - 1))); i = j + 2; } return l; } static public String th(Object contents, Object... params) { return tag("th", contents, params); } static public List> syncMapToPairs(Map map) { if (map == null) return new ArrayList(); synchronized (collectionMutex(map)) { return mapToPairs(map); } } static public String hjssnippet_maxCache(String snippetID) { return hfulltag("script", "", "src", snippetRawURL_maxCache(snippetID, "text/javascript")); } static public boolean isSubclass(Class a, Class b) { return a != null && b != null && b.isAssignableFrom(a); } 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 A[] arrayOfSameType(A[] a, int n) { return newObjectArrayOfSameType(a, n); } static public String tr(Object contents) { return tag("tr", contents); } static public void tt() { typeWriterConsole(); } static public String tt(Object contents, Object... params) { return tag("tt", contents, params); } static public void flexMatchAngleBracketVarsIC_iterate(String pat, String input, VF1> onMatch) { List vars = new ArrayList(); String starsPat = angleBracketVarsToStars(pat, vars); flexMatchIC_iterate(starsPat, input, new VF1() { public void get(Matches m) { try { Map map = matchesToMapUsingVarList_ciMap(m, vars); if (map != null) callF(onMatch, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "SS map = matchesToMapUsingVarList_ciMap(m, vars);\r\n if (map != null) callF..."; } }); } 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 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 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 File backupConceptsNow() { return backupConceptsNow(db_mainConcepts()); } static public File backupConceptsNow(Concepts cc) { if (cc == null) return null; File f1 = cc.conceptsFile(); File f2 = fileInSameDir(f1, "backups/concepts.structure" + (cc.useGZIP ? ".gz" : "") + ".backup" + ymd_minus_hms()); return copyFile(f1, f2); } static public String hquery(Map params) { return htmlQuery(params); } static public String hquery(Object... data) { return htmlQuery(data); } static public String faviconMimeType() { return "image/x-icon"; } static public IterableIterator navigableMultiSetMapValuesIterator(final MultiSetMap mm) { return iteratorFromFunction(new F0() { public Iterator> it = concurrentlyIterateValues((NavigableMap) mm.data); 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 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 void doublePut(Map map, A key1, A key2, B value) { map.put(key1, value); map.put(key2, value); } static public String squareBracketIfNempty(String s) { return empty(s) ? "" : squareBracket(s); } static public BigInteger parseBigInt(String s) { return new BigInteger(s); } static public JScrollPane jscroll(Component c) { return swing(() -> { return c instanceof JScrollPane ? ((JScrollPane) c) : new JScrollPane(c); }); } 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 void putUnlessZero(Map map, A key, int value) { if (map != null && key != null && value != 0) map.put(key, value); } static public void putUnlessZero(Map map, A key, double value) { if (map != null && key != null && value != 0) map.put(key, value); } static public Long conceptIDOrNull(Concept c) { return c == null ? null : c.id; } static public String ul(String... list) { return ul(asList(list)); } static public String ul(Collection list, Object... params) { StringBuilder buf = new StringBuilder(); int i = indexOf(params, null); if (i == -1) i = l(params); for (Object s : withoutNulls(list)) buf.append(tag("li", s, subArray(params, i + 1))).append("\n"); return containerTag("ul", buf, subArray(params, 0, i)) + "\n"; } 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 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 String hlabelFor(String id, Object contents) { String s = strOrEmpty(contents); return empty(s) ? "" : htag("label", s, "for", id); } static public double elapsedSeconds_timestamp(long time) { return toSeconds(now() - time); } 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(__103 -> wrapForSmartAdd_jComponent(__103), 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(__104 -> wrapForSmartAdd_jComponent(__104), 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 boolean isSafeCodeFragment(String code) { return eq("safe", joinWithComma(getCodeFragmentSafety(code))); } static public Comparator fieldComparator(final String field) { return new Comparator() { public int compare(A a, A b) { return cmp(getOpt(a, field), getOpt(b, field)); } }; } 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 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 String or2(String a, String b) { return nempty(a) ? a : b; } static public String or2(String a, String b, String c) { return or2(or2(a, b), c); } static public String mapPairsToLines(Iterable> l, IF2 f) { return lines(mapPairsToList(l, f)); } static public BufferedImage imageIO_readURL(String url) { try { return ImageIO.read(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } 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 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 Integer mmo2_levenWithSwapsScore(MMOPattern pattern, String s) { return mmo2_levenWithSwapsScore(pattern, s, false, false); } static public Integer mmo2_levenWithSwapsScore(MMOPattern pattern, String s, boolean startOfLine, boolean endOfLine) { String s2 = trim(s); if (pattern == null) return null; if (startsWith(s2, "#")) return null; if (pattern instanceof MMOPattern.StartOfLine) return mmo2_levenWithSwapsScore(((MMOPattern.StartOfLine) pattern).p, s2, true, endOfLine); if (pattern instanceof MMOPattern.EndOfLine) return mmo2_levenWithSwapsScore(((MMOPattern.EndOfLine) pattern).p, s2, startOfLine, true); if (pattern instanceof MMOPattern.Phrase) { if (((MMOPattern.Phrase) pattern).quoted) return mmo2_match(((MMOPattern.Phrase) pattern), s2) ? (Integer) 0 : null; String p = ((MMOPattern.Phrase) pattern).phrase; if (startsWith(p, "#")) return null; if (endsWith(p, "!")) return find3(p, s) ? 0 : null; else return find3_levenWithSwapsDistance(p, s2); } if (pattern instanceof MMOPattern.And) { int score = 0; for (MMOPattern pat : ((MMOPattern.And) pattern).l) { Integer score2 = mmo2_levenWithSwapsScore(pat, s2, startOfLine, endOfLine); if (score2 == null) return null; score += score2; } return score; } if (pattern instanceof MMOPattern.Or) { Integer min = null; for (MMOPattern pat : ((MMOPattern.Or) pattern).l) min = min_withNull(min, mmo2_levenWithSwapsScore(pat, s2, startOfLine, endOfLine)); return min; } if (pattern instanceof MMOPattern.Not) return mmo2_match(pattern, s2) ? 0 : null; throw fail("what. " + pattern); } static public Integer mmo2_levenWithSwapsScore(String pattern, String s) { return mmo2_levenWithSwapsScore(mmo2_parsePattern(pattern), s, false, false); } 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 Runnable asRunnable(Object o) { return toRunnable(o); } 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 void consoleSetInput(final String text) { if (headless()) return; setTextAndSelectAll(consoleInputField(), text); focusConsole(); } 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 String div_alignRight(Object contents, Object... params) { return div(contents, params_stylePlus(params, "text-align: right")); } static public Set gazelle_allSyntacticPatternsFromInput(String input) { Chain tokens = toChain(javaTokC(input)); LinkedHashSet out = new LinkedHashSet(); gazelle_allSyntacticPatternsFromInput_collect(null, tokens, out); return out; } static public void gazelle_allSyntacticPatternsFromInput_collect(ReverseChain prefix, Chain tokens, Set out) { ping(); if (empty(tokens)) { out.add(joinWithSpace(asList(prefix))); return; } gazelle_allSyntacticPatternsFromInput_collect(chainPlus(prefix, first(tokens)), dropFirst(tokens), out); if (!eq(last(prefix), "*")) { ReverseChain prefix2 = chainPlus(prefix, "*"); Chain tokens2 = tokens; while (!empty(tokens2)) { tokens2 = dropFirst(tokens2); gazelle_allSyntacticPatternsFromInput_collect(prefix2, tokens2, out); } } } 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 String applyTranspilationFunction(IVF1> f, String s) { if (f == null) return s; List tok = javaTok(s); f.get(tok); return join(tok); } static public int snippetType_JavaXDesktop() { return 55; } 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 List gazelle_navLinks(String baseLink, String searchQuery, Object... __) { boolean withTeam = optPar("withTeam", __, true); boolean withStats = optPar("withStats", __, true); boolean flat = boolPar("flat", __); List more = ll(ahref(baseLink + "/deletedPosts", "Deleted Posts")); return llNonNulls(flattenStringArray2(ahref(baseLink + "/crud/UserPost?cmd=new", "New Post"), searchQuery != null ? hform(hinputfield("q", searchQuery, "style", "width: 75px") + " " + hsubmit("Search"), "style", "display: inline", "action", baseLink + "/search") : ahref(baseLink + "/search", "Search"), ahref(baseLink + "/rootPosts", "Root Posts"), ahref(baseLink + "/allPosts", "All Posts"), ahref(baseLink + "/latestPosts", "Latest Posts"), ahref(baseLink + "/latestModifiedPosts", "Latest Changes"), ahref(baseLink + "/mainPosts", "Main Posts"), !withTeam ? null : ahref(baseLink + "/team", "Team"), flat ? more : hPopDownButton(flattenStringArray2(!withStats ? null : ahref(baseLink + "/stats", "Stats"), more)))); } 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 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 File newFile(File base, String... names) { for (String name : names) base = new File(base, name); return base; } static public File newFile(String name) { return name == null ? null : new File(name); } static public File newFile(String base, String... names) { return newFile(newFile(base), names); } static public void 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 SnippetTitles getSnippetTitle_cached_cache = new SnippetTitles(); static public String getSnippetTitle_cached(String id) { return getSnippetTitle_cached_cache.get(id); } static public void getSnippetTitle_cached_put(String id, String title) { getSnippetTitle_cached_cache.put(id, title); } static public boolean getSnippetTitle_cached_has(String id) { return getSnippetTitle_cached_cache.has(id); } static public String getSnippetTitle_cached_probe(String id) { return getSnippetTitle_cached_cache.probe(id); } static public List javaTokWithBrackets(String s) { return javaTokPlusBrackets(s); } 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 String ul_htmlEncode(String... list) { return ul_htmlEncode(asList(list)); } static public String ul_htmlEncode(Collection list, Object... params) { return ul(map(__105 -> htmlEncode2(__105), allToString(list)), params); } static public String formatCSVFileForExcel2(List rows) { String sep = "|"; return windowsLineBreaks("sep=" + sep + "\n" + mapToLines_rtrim(rows, row -> join(sep, map(row, col -> replace(newLinesToSpaces(str(col)), sep, " "))))); } static public void indexSingletonConcept(Concepts cc, Class c) { indexConceptField(cc, c, "_dummy"); } static public void indexSingletonConcept(Class c) { indexSingletonConcept(db_mainConcepts(), c); } static public List synchroList() { return synchroList(new ArrayList()); } static public List synchroList(List l) { return new SynchronizedList(l); } static public Object serveInputStream(InputStream in, String mimeType) { return subBot_serveInputStream(in, mimeType); } 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 String formatDoubleArrowPairs_horizontallyAligned(List> l) { return asciiSideBySideWithSeparator(" => ", ll(lines(pairsA(l)), lines(pairsB(l)))); } static public Object subBot_serveFile_maxCache(File file) { return subBot_maxCacheHeaders(subBot_serveFile(file)); } static public Object subBot_serveFile_maxCache(File file, String mimeType) { return subBot_maxCacheHeaders(subBot_serveFile(file, mimeType)); } static public AlphanumComparator alphaNumComparator_instance; static public Comparator alphaNumComparator() { if (alphaNumComparator_instance == null) alphaNumComparator_instance = new AlphanumComparator(); return alphaNumComparator_instance; } static public int matcherInt(Matcher m, int i) { return parseInt(m.group(i)); } static public AutoCloseable tempDisposeWindow(final Window w) { return new AutoCloseable() { public void close() { disposeWindow(w); } }; } 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 boolean loadFunctions_debug = false; static public Object loadFunctions_veryQuickJava; static public Class loadFunctions(String... functions) { return loadFunctions(asList(functions)); } static public Class loadFunctions(Collection functions, Object... __) { print("Compiling " + joinWithPlus(functions)); TreeSet functionSet = new TreeSet(functions); StringBuilder buf = stringBuilder(appendNewLineIfNempty(stringPar("header", __))); for (String s : functionSet) buf.append("please include function " + assertIdentifier(s) + ".\n"); long time = sysNow(); Class c; if (loadFunctions_veryQuickJava != null) c = (Class) callF(loadFunctions_veryQuickJava, str(buf)); else { veryQuickJava_transpiled.set(""); c = veryQuickJava(str(buf)); saveTranspiledStandardFunctions(functionSet, getAndClearThreadLocal(veryQuickJava_transpiled)); } if (loadFunctions_debug) done2_always(time, "loadFunctions: " + join(" ", functions)); return c; } static public int localDayOfMonth(long time) { return parseInt(simpleDateFormat_local("dd").format(time)); } static public int localDayOfMonth() { return localDayOfMonth(now()); } static public String quoteOr(String s, String whenEmpty) { return empty(s) ? whenEmpty : quote(s); } 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 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 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 String hpre_htmlencode(Object contents, Object... params) { return pre_htmlencode(contents, params); } static public String unicode_newLineArrow() { return charToString(0x21b5); } 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 String jreplace_dyn(String s, String in, Object out) { return jreplace_dyn(s, in, out, null); } static public String jreplace_dyn(String s, String in, Object out, Object condition) { List tok = javaTok(s); jreplace_dyn(tok, in, out, condition); return join(tok); } static public boolean jreplace_dyn(List tok, String in, Object out) { return jreplace_dyn(tok, in, out, false, true, null); } static public boolean jreplace_dyn(List tok, String in, IF0 out) { return jreplace_dyn(tok, in, if0ToIF2(out)); } static public boolean jreplace_dyn(List tok, String in, ITokCondition cond, IF0 out) { return jreplace_dyn(tok, in, cond, if0ToIF2(out)); } static public boolean jreplace_dyn(List tok, String in, IF1 out) { return jreplace_dyn(tok, in, (_tok, cIdx) -> out.get(cIdx)); } static public boolean jreplace_dyn(List tok, String in, IF2, Integer, String> out) { return jreplace_dyn(tok, in, (Object) out); } static public boolean jreplace_dyn(List tok, String in, IF2, Integer, String> out, IF2, Integer, Boolean> condition) { return jreplace_dyn(tok, in, (Object) out, (Object) condition); } static public boolean jreplace_dyn(List tok, String in, Object out, Object condition) { return jreplace_dyn(tok, in, out, false, true, condition); } static public boolean jreplace_dyn(List tok, String in, Object out, boolean ignoreCase, boolean reTok, Object condition) { List tokin = javaTok(in); jfind_preprocess(tokin); String[] toks = toStringArray(codeTokensOnly(tokin)); boolean anyChange = false; for (int n = 0; n < 10000; n++) { int i = findCodeTokens(tok, 1, ignoreCase, toks, condition); if (i < 0) return anyChange; String expansion = (String) (callF(out, tok, i)); int end = i + l(tokin) - 2; clearAllTokens(tok, i, end); tok.set(i, expansion); if (reTok) reTok(tok, i, end); anyChange = true; } throw fail("woot? 10000! " + quote(in) + " => " + quote(out)); } static public void consoleClearInput() { consoleSetInput(""); } static public int indexOfIC(List a, String b) { return indexOfIgnoreCase(a, b); } static public int indexOfIC(List a, String b, int i) { return indexOfIgnoreCase(a, b, i); } static public int indexOfIC(String[] a, String b) { return indexOfIC(a, b, 0); } static public int indexOfIC(String[] a, String b, int i) { return indexOfIgnoreCase(a, b, i); } static public int indexOfIC(String a, String b) { return indexOfIgnoreCase(a, b); } static public int indexOfIC(String a, String b, int i) { return indexOfIgnoreCase(a, b, i); } static public int 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 int parseIntOpt(String s) { return parseIntOpt(s, 0); } static public int parseIntOpt(String s, int defValue) { return isInteger(s) ? parseInt(s) : defValue; } 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 dollarVarsToStars(String s) { return dollarVarsToStars(s, null); } static public String dollarVarsToStars(String s, List varNames_out) { List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (isDollarVar(t)) { listAdd(varNames_out, t); tok.set(i, "*"); } else if (eq(t, "*")) listAdd(varNames_out, "*"); } return join(tok); } 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 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 public String longSnippetLink(String id) { return tb_mainServer() + "/tb/show-snippet.php?id=" + parseSnippetID(id); } static public B pairB(Pair p) { return p == null ? null : p.b; } static public String conceptsFileName() { return "concepts.structure.gz"; } 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 htitledSectionWithDiv(String title, Object contents, Object... __) { String backgroundColor = "#fff"; String labelStyle = "width: auto; float: top; position: relative; top: -.6em; left:15px; background-color: " + backgroundColor; String innerDivStyle = stringPar("innerDivStyle", __); String innerDivClass = stringPar("innerDivClass", __); String innerDivID = (String) (optPar("innerDivID", __)); __ = paramsMinus(__, "innerDivStyle", "innerDivID", "innerDivClass"); return div(htag("label", b(" " + title + " "), "style", labelStyle) + div(contents, "style", joinNemptiesWithSemicolon(innerDivStyle, "padding-left: 15px"), "class", joinNemptiesWithSpace("sectionContents", innerDivClass), "id", innerDivID), params_stylePlus("border: 2px solid", __)); } 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 String javaTok_substringC(String s, int i, int j) { return s.substring(i, j); } static public String hscript_clickableRows() { return hscript("\r\n jQuery(document).ready(function($) {\r\n $(\".clickable-row\").click(function() {\r\n window.location = $(this).data(\"href\");\r\n });\r\n });\r\n "); } static public Set tok_allIdentifiers(String s) { return new HashSet(filter(__106 -> isIdentifier(__106), javaTokC(s))); } 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 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 String urldecode(String x) { try { return URLDecoder.decode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } static public String hinput(String name, Object... params) { return htextinput(name, params); } static public List sortedAlphaNum(Collection c) { return sorted(c, new AlphanumComparator()); } static public boolean isLocalSnippet(String snippetID) { return isLocalSnippetID(snippetID); } static public boolean isLocalSnippet(long snippetID) { return isLocalSnippetID(snippetID); } 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 String href(String link, Object contents, Object... params) { if (link == null) return str(contents); return hfulltag("a", contents, arrayPlus(params, "href", link)); } 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 String getStackTrace2(Throwable e) { return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n"); } static public String dropPrefix(String prefix, String s) { return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s; } static public Map>> mechMapCI_cache = synchroMap(); static public Map mechMapCI(String listName) { Pair> p = mechMapCI_cache.get(listName); String text = mechList_raw(listName); if (p != null && eq(p.a, text)) return p.b; String parsing = first(mechList_opt(listName + " | Parsing")); Map map; if (parsing == null) map = parseDoubleArrowMapCI(tlft(text)); else map = asCIMap((Map) callMC(parsing, text)); p = pair(text, map); mechMapCI_cache.put(listName, p); return p.b; } static public MetaTransformer defaultMetaTransformer() { return metaTransformer_transformableAndList(); } static public List> scanConceptForRefsWithFieldNames(Concept c) { List> refs = new ArrayList(); if (c != null) for (Map.Entry __0 : _entrySet(objectToMap(c))) { String field = __0.getKey(); Object o = __0.getValue(); if (o instanceof Concept.Ref) refs.add(pair(((Concept.Ref) o), field)); else if (o instanceof Concept.RefL) for (int i = 0; i < l(((Concept.RefL) o).l); i++) refs.add(pair((Concept.Ref) ((Concept.RefL) o).l.get(i), field + "[" + (i + 1) + "]")); } return refs; } 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 String deAngleBracket(String s) { return isAngleBracketed(s) ? dropFirstAndLast(s) : s; } 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 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 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 byte[] loadBeginningOfBinaryFile(File file, int maxBytes) { return loadBinaryFilePart(file, 0, maxBytes); } static public Set hotwire_classesToShare = synchroSet(); static public Set hotwire_classesToShare() { return hotwire_classesToShare; } static public List> mapPairsB(IF1 f, Iterable> l) { return mapPairB(f, l); } static public List> mapPairsB(Iterable> l, IF1 f) { return mapPairB(l, f); } static public String addSuffix(String s, String suffix) { return s == null || s.endsWith(suffix) ? s : s + suffix; } static public byte[] utf8(String s) { return toUtf8(s); } static public String dummyMainClassName(String progID) { return "m" + psI(progID); } static public List parseList(String s) { return (List) safeUnstructure(s); } static public String hopeningtag(String tag, Map params) { return hopeningTag(tag, params); } static public String hopeningtag(String tag, Object... params) { return hopeningTag(tag, params); } static public List parse3(String s) { return dropPunctuation(javaTokPlusPeriod(s)); } static public Map emptyMap() { return new HashMap(); } static public Component jrigid() { return javax.swing.Box.createRigidArea(new Dimension(0, 0)); } 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 Class primitiveToBoxedTypeOpt(Class type) { return or(primitiveToBoxedType(type), type); } static public long sysTime() { return sysNow(); } 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 List tok_integersInOrder(String s) { return filter(__107 -> isInteger(__107), javaTokC(s)); } 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 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 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 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 void restart() { Object j = getJavaX(); call(j, "cleanRestart", get(j, "fullArgs")); } static public int smartIndexOfSpaceEtc(String s) { int i = indexOfSpaceEtc(s); return i < 0 ? l(s) : i; } static public List secondOfPairs(Collection> l) { return lambdaMap(__108 -> secondOfPair(__108), l); } static public String unicode_crossProduct() { return unicodeFromCodePoint(0x2A2F); } static public Object rcurry(final Object f, final Object arg) { int n = numberOfFunctionArguments(f); if (n == 0) throw fail("function takes no arguments"); if (n == 1) return new F0() { public Object get() { return callF(f, arg); } }; if (n == 2) return new F1() { public Object get(Object a) { return callF(f, a, arg); } }; throw todo("currying a function with " + n + "arguments"); } static public boolean preciseCall_debug = false; static public Object preciseCall(Object o, String method, Object... args) { 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(m, args); if (score < Integer.MAX_VALUE) { if (preciseCall_debug) print("Method score: " + m + " " + score); best.put(m, score); } } Method m = best.get(); if (m != null) return invokeMethod(m, null, args); return call_withVarargs(((Class) o), method, args); } else throw todo(); } catch (Exception __e) { throw rethrow(__e); } } static public Map onlyKeys(Map map, Collection keys) { Set keySet = asSet(keys); return filterKeys(map, a -> contains(keySet, a)); } static public Map onlyKeys(Map map, A... keys) { return onlyKeys(map, litset(keys)); } static public CountryDialCode countryDialCodeByCountryCode(String countryCode) { return objectWhere(countryDialCodes(), "countryCode", upper(countryCode)); } static public int maxStringLength(Collection l) { int n = 0; if (l != null) for (String s : l) n = max(n, l(s)); return n; } 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 double fraction(double d) { return d % 1; } 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 getWeakRef(Reference ref) { return ref == null ? null : ref.get(); } static public void ensureConceptClassIsIndexed(Class c) { ensureConceptClassIsIndexed(db_mainConcepts(), c); } static public void ensureConceptClassIsIndexed(Concepts cc, Class c) { if (cc != null && c != null && !isConceptClassIndexed(cc, c)) indexRandomConceptField(cc, c); } 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 boolean syncEmpty(Collection l) { if (l == null) return true; synchronized (l) { return l.isEmpty(); } } 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 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 String actualProgramID() { return programID(); } 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 boolean isGeneralFileServerSnippet(long id) { return id >= 1400000 && id < 1500000; } static public List nempties(Collection c) { return filterNempty(c); } 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 List sortedAlphanumIC(Collection c) { List l = cloneList(c); Collections.sort(l, alphaNumComparatorIC()); return l; } static public AutoCloseable temp_printPrefix(String prefix) { Object oldValue = print_byThread(); print_setPrefixForThread(prefix); return new AutoCloseable() { public String toString() { return "print_byThread().set(oldValue);"; } public void close() throws Exception { print_byThread().set(oldValue); } }; } 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 String htmlEncode_nlToBR(String s) { return htmlEncode_nlToBr(s); } 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 File imageSnippetCacheFile(String snippetID) { File dir = imageSnippetsCacheDir(); if (!loadBufferedImage_useImageCache) return null; return new File(dir, parseSnippetID(snippetID) + ".png"); } 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 class allSpreads_Data { public int n; public List collecting; } static public class allSpreads_StackEntry { public int remaining, take; public int position; public Object step(List stack, allSpreads_Data d) { if (position == 0) { if (l(d.collecting) >= d.n - 1) { List result = listPlus(d.collecting, remaining); popLast(stack); return result; } position++; } if (position == 1) { if (take <= remaining) { d.collecting.add(take); allSpreads_StackEntry e = new allSpreads_StackEntry(); e.remaining = remaining - take; stack.add(e); position++; } else popLast(stack); } else if (position == 2) { removeLast(d.collecting); take++; position = 1; } return null; } } static public IterableIterator> allSpreads(final int toSpread, final int buckets) { final allSpreads_Data d = new allSpreads_Data(); d.n = buckets; d.collecting = new ArrayList(); final List stack = new ArrayList(); allSpreads_StackEntry e = new allSpreads_StackEntry(); e.remaining = toSpread; stack.add(e); return iff(new F0() { public Object get() { try { while (nempty(stack)) { ping(); { var __1 = last(stack).step(stack, d); if (__1 != null) return __1; } } return endMarker(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "while (nempty(stack)) {\r\n ping();\r\n try object last(stack).step(sta..."; } }); } static public boolean mmo2_matchWithTypos(String pattern, String s) { return mmo2_matchWithTypos(pattern, s, 1); } static public boolean mmo2_matchWithTypos(String pattern, String s, int maxTypos) { return mmo2_matchWithTypos(mmo2_parsePattern(pattern), s, maxTypos); } static public boolean mmo2_matchWithTypos(MMOPattern pattern, String s) { return mmo2_matchWithTypos(pattern, s, 1); } static public boolean mmo2_matchWithTypos(MMOPattern pattern, String s, int maxTypos) { if (maxTypos == 0) return mmo2_match(pattern, s); Integer score = mmo2_levenWithSwapsScore(pattern, s); return score != null && score <= maxTypos; } static public int tok_findEndOfStatement(List tok, int i) { if (eq(get(tok, i), "{")) return findEndOfBlock(tok, i); int j = i; boolean special = false; while (j < l(tok) && neq(tok.get(j), ";")) { String t = get(tok, j); if (eqOneOf(t, "for", "if")) special = true; if (eqOneOf(t, "{", "(")) { j = findEndOfBracketPart(tok, j) + 1; if (special && eq(t, "{")) return j - 1; } else j += 2; } return j + 1; } 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 Pair stringTreeLeafValue2(StringTree2 tree, List items) { int i = 0; while (tree != null && i < l(items)) { if (tree.leafValue != null) return pair(tree.leafValue, i); tree = tree.children.get(items.get(i)); ++i; } return null; } 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 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 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 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 Map safeUnstructureMap(String s) { return (Map) safeUnstructure(s); } static public Map safeUnstructureMap(File f) { return (Map) safeUnstructure(f); } 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 String htextarea(String text, Object... params) { params = html_massageAutofocusParam(params); return hopeningTag("textarea", params) + htmlencode2(text) + ""; } static public String hhead(Object contents) { return tag("head", contents); } static public int hashOfLong(long l) { return Long.hashCode(l); } static public List splitCamelCase(String s) { return ai_splitCamelCase(s); } 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 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 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 String localTimeWithSeconds(long time) { return simpleDateFormat_local("HH:mm:ss").format(time); } static public String localTimeWithSeconds() { return localTimeWithSeconds(now()); } static public void indexRandomConceptField(Class c) { indexRandomConceptField(db_mainConcepts(), c); } static public void indexRandomConceptField(Concepts cc, Class c) { String field = or(first(conceptFields(c)), "_dummy"); print("Indexing " + c + "." + field); indexConceptField(cc, c, field); assertTrue("Concept class indexed", isConceptClassIndexed(cc, c)); { long _startTime_0 = sysNow(); try { print("Got " + nConcepts(countConcepts(cc, c))); } finally { _startTime_0 = sysNow() - _startTime_0; saveTiming(_startTime_0); } } } static public Class hotwireSharingLibraries_silently(String progID) { AutoCloseable __1 = temp_loadPage_silent(); try { return hotwireSharingLibraries(progID); } finally { _close(__1); } } static public String htmlEncode_nlToBr(String s) { return nlToBr(htmlEncode2(s)); } 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 String hjs_selectize() { return "\r\n \r\n \r\n "; } 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 long fileSize(String path) { return getFileSize(path); } static public long fileSize(File f) { return getFileSize(f); } static public Object[] mapToParams(Map map) { return mapToObjectArray(map); } static public Object invokeMethod(Method m, Object o, Object... args) { try { try { return m.invoke(o, args); } catch (InvocationTargetException e) { throw rethrow(getExceptionCause(e)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args))); } } catch (Exception __e) { throw rethrow(__e); } } static public boolean isInQ(Q q) { return q != null && isCurrentThread(q.rst.thread); } static public int countTokens(String s) { return l(javaTokC(s)); } static public int countTokens(List tok) { return l(tok) / 2; } static public int countTokens(IntRange r) { return r == null ? 0 : cncCorrect(r).length() / 2; } static public String h3_htitle(String s) { return htitle(s) + h3(s); } static public boolean isMainProgram() { return creator() == null; } static public Random defaultRandomGenerator() { { Random r = customRandomizerForThisThread(); if (r != null) return r; } return ThreadLocalRandom.current(); } static public Lock downloadLock_lock = fairLock(); static public Lock downloadLock() { return downloadLock_lock; } static public void printConceptIndices() { printConceptIndices(db_mainConcepts()); } static public void printConceptIndices(Concepts cc) { if (cc == null) return; Set> classes = joinSets(keys(cc.fieldIndices), keys(cc.ciFieldIndices)); print(n2(classes, "indexed class", "indexed classes") + "."); for (Class c : classes) { print("Indices on " + c + ":"); for (Map.Entry __1 : _entrySet(cc.fieldIndices.get(c))) { String field = __1.getKey(); IFieldIndex idx = __1.getValue(); print(" " + field + ": " + idx); } for (Map.Entry __0 : _entrySet(cc.ciFieldIndices.get(c))) { String field = __0.getKey(); IFieldIndex idx = __0.getValue(); print(" " + field + " [case-insensitive]: " + idx); } } } 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 String unicode_smallDownPointingTriangle() { return charToString(0x25BE); } static public boolean methodIsStatic(Method m) { return (m.getModifiers() & Modifier.STATIC) != 0; } static public String renderVars(Object... params) { return renderVars_str(params); } static public String ahref_possiblyTargetBlank(String link, Object contents, boolean targetBlank, Object... params) { return ahref(link, contents, targetBlank ? paramsPlus(params, "target", "_blank") : params); } static public String ahref_possiblyTargetBlank(boolean targetBlank, String link, Object contents, Object... params) { return ahref_possiblyTargetBlank(link, contents, targetBlank, params); } static public long sysNow() { ping(); return System.nanoTime() / 1000000; } static public int imageIcon_cacheSize = 10; static public boolean imageIcon_verbose = false; static public Map imageIcon_cache; static public Lock imageIcon_lock = lock(); static public ThreadLocal imageIcon_fixGIF = new ThreadLocal(); static public ImageIcon imageIcon(String imageID) { try { if (imageID == null) return null; Lock __0 = imageIcon_lock; lock(__0); try { if (imageIcon_cache == null) imageIcon_cache = new MRUCache(imageIcon_cacheSize); imageID = fsI(imageID); ImageIcon ii = imageIcon_cache.get(imageID); if (ii == null) { if (imageIcon_verbose) print("Loading image icon: " + imageID); File f = loadBinarySnippet(imageID); Boolean b = imageIcon_fixGIF.get(); if (!isFalse(b)) ii = new ImageIcon(loadBufferedImageFixingGIFs(f)); else ii = new ImageIcon(f.toURI().toURL()); } else imageIcon_cache.remove(imageID); imageIcon_cache.put(imageID, ii); return ii; } finally { unlock(__0); } } catch (Exception __e) { throw rethrow(__e); } } static public ImageIcon imageIcon(File f) { try { return new ImageIcon(f.toURI().toURL()); } catch (Exception __e) { throw rethrow(__e); } } static public ImageIcon imageIcon(Image img) { return 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 hPopDownButtonWithText(String text, String... entries) { return (empty(text) ? "" : text + " ") + hPopDownButton(entries); } static public String hPopDownButtonWithText(String text, Collection entries) { return hPopDownButtonWithText(text, asStringArray(entries)); } 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 String hmsWithColons() { return hmsWithColons(now()); } static public String hmsWithColons(long time) { return new SimpleDateFormat("HH:mm:ss").format(time); } static public void consoleFont(Font font) { callOpt(getConsoleTextArea_gen(), "setFont", font); } static public void printStructs(Object... params) { print(renderStructs(params)); } 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 Map componentID_map = weakHashMap(); static public String componentID(Component c) { return c == null ? null : componentID_map.get(c); } static public Object[] params_stylePlus(Map params, String style) { return paramsPlus(params, "style", joinNemptiesWithSemicolon(stringPar("style", params), style)); } static public Object[] params_stylePlus(Object[] params, String style) { return paramsPlus(params, "style", joinNemptiesWithSemicolon(stringPar("style", params), style)); } static public Object[] params_stylePlus(String style, Object... params) { return params_stylePlus(params, style); } 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 long timestampFromYMDH(int y, int m, int d, int h) { return new GregorianCalendar(y, m - 1, d, h, 0).getTimeInMillis(); } 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 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 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 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 hjavascript_src_snippet(String snippetID, Object... __) { return hfulltag("script", "", paramsPlus(__, "src", snippetRawURL(snippetID, "text/javascript"))); } static public A makeBold(final A c) { if (c != null) { swing(() -> { c.setFont(c.getFont().deriveFont(java.awt.Font.BOLD)); }); } return c; } 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 int countWordsWithoutAngleBracketedAndStars(String s) { int n = 0; for (String t : javaTokWithAllPlusAngleBracketsC(s)) if (!isAngleBracketed(t) && !eq(t, "*")) ++n; return n; } static public File userDir() { return new File(userHome()); } static public File userDir(String path) { return new File(userHome(), path); } 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 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 Map parseEqualsProperties(String text) { return parseEqualsProperties(text, new HashMap()); } static public Map parseEqualsProperties(String text, Map map) { for (String s : tlft(text)) { int i = indexOf(s, '='); if (i > 0) map.put(trimSubstring(s, 0, i), trimSubstring(s, i + 1)); } return map; } static public String nItems(long n) { return n2(n, "item"); } static public String nItems(Collection l) { return nItems(l(l)); } static public String nItems(Map map) { return nItems(l(map)); } static public boolean zipContainsFile(File inZip, String fileName) { try { ZipFile zip = new ZipFile(inZip); try { return zip.getEntry(fileName) != null; } finally { _close(zip); } } catch (Exception __e) { throw rethrow(__e); } } static public void setFieldToSingleMethodProxy(Object o, String field, Object target, String methodName) { if (o == null || target == null) return; Class type = fieldType(o, field); if (type == null) throw fail("Field " + field + " not found in " + className(o)); set(o, field, singleObjectMethodProxy(type, target, methodName)); } static public Object[] prependParamIfOddCount(Object x, Object[] params) { if (odd(l(params))) return itemPlusObjectArray(x, params); return params; } static public List objectsWhereNotIC(Collection c, Object... data) { if (c == null) return null; List l = new ArrayList(); for (A x : c) if (!checkFieldsIC(x, data)) l.add(x); return l; } static public List nonStaticNonTransientFieldObjects(Object o) { if (o == null) return null; List fields = new ArrayList(); Class _c = _getClass(o); do { for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) == 0) fields.add(makeAccessible(f)); _c = _c.getSuperclass(); } while (_c != null); return fields; } static public String _className(Object o) { return className(o); } 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 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 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 String yesNo2(Boolean b) { return eq(b, true) ? "Yes" : eq(b, false) ? "No" : "Unknown"; } static public boolean isInAnonymousClass(Object o) { if (o == null) return false; return isAnonymousClassName(className(o)); } static public boolean isInstanceOfAny(Object o, Collection b) { return any(b, x -> isInstanceOf(o, x)); } static public boolean isInstanceOfAny(Object o, Class... b) { return any(b, x -> isInstanceOf(o, x)); } static public String afterDollar(String s) { return substring(s, smartIndexOf(s, '$') + 1); } static public String shortDynamicClassName(Object o) { if (o instanceof DynamicObject && ((DynamicObject) o).className != null) return ((DynamicObject) o).className; return shortClassName(o); } static public Set collectAngleBracketVars(String s) { return collectAngleBracketVars(javaTokWithAngleBrackets(s)); } static public Set collectAngleBracketVars(List tok) { Set set = ciSet(); for (int i = 0; i < l(tok); i++) if (isAngleBracketVar(tok.get(i))) set.add(deAngleBracket(tok.get(i))); return set; } static public int identityHash(Object o) { return identityHashCode(o); } static public long regexpToLongIC(String regexp, String input) { return parseLong(regexpFirstGroupIC(regexp, input)); } static public int countWhereCI(Collection c, Object... data) { int n = 0; if (c != null) for (Object x : c) if (checkFieldsIC(x, data)) ++n; return n; } static public int toIntOpt(Object o) { return toIntOpt(o, 0); } static public int toIntOpt(Object o, int defaultValue) { if (o == null) return defaultValue; if (o instanceof Number) return ((Number) o).intValue(); if (o instanceof String) return parseIntOpt((String) o); return defaultValue; } static public Object callWithEnter(Object o, String method, String[] arg) { return callWithEnter(o, method, new Object[] { arg }); } static public Object callWithEnter(Object o, String method, Object... args) { if (o == null) return null; AutoCloseable __1 = tempEnter(o); try { return call_withVarargs(o, method, args); } finally { _close(__1); } } static public String regexpReplace_directWithRefs(String s, String pat, String replacement) { Matcher m = regexp(pat, s); return regexpReplace_direct(m, replacement); } static public String regexpReplace_directWithRefs(Matcher m, String replacement) { StringBuffer buf = new StringBuffer(); while (m.find()) m.appendReplacement(buf, replaceDollarVars2_dyn(replacement, v -> !isInteger(v) ? null : matcherGroup(m, parseInt(v)))); m.appendTail(buf); return str(buf); } 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 List regexpExtractGroups(String pat, String s) { return regexpFirstGroups(pat, s); } static public long lastTiming() { return getLastTiming(); } static public List removeAndReturnCollection(List l, int i) { remove(l, i); return l; } static public > B removeAndReturnCollection(B l, A a) { remove(l, a); return l; } static public Map conceptShadow_rawMap(Concept c) { if (c == null) return null; Map map = objectToMap_nonTransient(c); map.remove("refs"); map.remove("backRefs"); map.remove("fieldValues"); map.put(":class", getClassName(c)); return map; } static public Object rcallOpt(String method, Object o, Object... args) { return callOpt_withVarargs(o, method, args); } static public void dm_requireSnippetUpdatesModule() { assertTrue("Update Stefan's OS", dm_subOSConnectorToChannel("snippetUpdates")); } static public String htmlEncode2_str(Object o) { return htmlEncode2_gen(o); } static public String vmClassNameToSubPath(String className) { return empty(className) ? null : replace(className, ".", "/") + ".class"; } static public Map immutableEmptyMap() { return Collections.emptyMap(); } 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 unicode_thumbsUp() { return unicodeFromCodePoint(0x1F44D); } static public A ccopyFields_withConverter(Concept x, A y, String... fields) { if (x == null || y == null) return y; if (empty(fields)) { for (String field : conceptFields(x)) cSmartSetField_withConverter(y, field, cget(x, field)); } else for (String field : fields) { Object o = cget(x, field); if (o != null) cSmartSetField_withConverter(y, field, o); } return y; } 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 String format_quoteAll(String pat, Object... args) { if (args.length == 0) return pat; List tok = javaTok(pat); int argidx = 0; for (int i = 1; i < tok.size(); i += 2) if (tok.get(i).equals("*")) tok.set(i, quote(argidx < args.length ? args[argidx++] : "null")); return join(tok); } static public Map putKeysFirst(Map map, Object... keys) { Map m2 = litorderedmap(); Map remaining = cloneMap(map); for (Object key : keys) { if (remaining.containsKey(key)) { m2.put(key, remaining.get(key)); remaining.remove(key); } } m2.putAll(remaining); return m2; } static public Map putKeysFirst(List keys, Map map) { return putKeysFirst(map, toObjectArray(keys)); } static public String lastTiming_formatted() { return renderElapsedTimePleasantly(lastTiming()); } 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 Class findClassThroughDefaultClassFinder(String shortName) { return shortName == null ? null : (Class) callF(_defaultClassFinder(), "main$" + shortName); } 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 allBackRefObjects(Concept c) { return cloneList(c == null ? null : c.backRefs); } static public List> diffConceptShadows(List l1, List l2) { List> diffs = new ArrayList(); int i1 = 0, i2 = 0; while (i1 < l(l1) && i2 < l(l2)) { ConceptShadow s1 = l1.get(i1), s2 = l2.get(i2); long id1 = s1.id(), id2 = s2.id(); if (id1 < id2) { diffs.add(new CreatedDeletedChanged.Deleted(s1)); ++i1; } else if (id1 > id2) { diffs.add(new CreatedDeletedChanged.Created(s2)); ++i2; } else { if (!eq(s1, s2)) diffs.add(new CreatedDeletedChanged.Changed(s1, s2)); ++i1; ++i2; } } while (i1 < l(l1)) diffs.add(new CreatedDeletedChanged.Deleted(l1.get(i1++))); while (i2 < l(l2)) diffs.add(new CreatedDeletedChanged.Created(l2.get(i2++))); return diffs; } static public boolean addByteCodePathToClassLoader(ClassLoader cl, File bytecode) { return addByteCodePathToClassLoader(cl, bytecode, null); } static public boolean addByteCodePathToClassLoader(ClassLoader cl, File bytecode, String libraryID) { try { Boolean b = (Boolean) (callOpt(cl, "addFile", bytecode, libraryID)); if (b == null) b = isTrue(call(cl, "addFile", bytecode)); if (b) print("Added byte code path " + bytecode + " to " + cl + appendBracketed(libraryID)); return b; } catch (Exception __e) { throw rethrow(__e); } } static public List allConceptShadows() { return allConceptShadows(db_mainConcepts()); } static public List allConceptShadows(Concepts cc) { if (cc == null) return null; List l = asList(cc.allConcepts()); assertTrue("Concepts are sorted by id", isSortedListByCalculatedField(__109 -> conceptID(__109), l)); return lmap(__110 -> conceptShadow(__110), l); } 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 int minUnlessMinus1(int a, int b) { return a == -1 ? b : b == -1 ? a : min(a, b); } static public List replaceKeywordBlock_dyn_any(List tok, Collection keywords, replaceKeywordBlock_dyn_IReplacer func) { for (String keyword : unnullForIteration(keywords)) replaceKeywordBlock_dyn(tok, keyword, func); return tok; } static public void pClose(AutoCloseable c) { close_pcall(c); } 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 String hbuttonOnClick_noSubmit(String text, String onClick, Object... params) { return hfulltag("button", text, paramsPlus(params, "onclick", onClick, "type", "button")); } static public ConceptFieldIndexCI_withTopTen indexConceptFieldCIWithTopTen(Class c, String field) { return indexConceptFieldCIWithTopTen(db_mainConcepts(), c, field); } static public ConceptFieldIndexCI_withTopTen indexConceptFieldCIWithTopTen(Concepts cc, Class c, String field) { var idx = getConceptFieldCIIndex(cc, c, field); if (idx instanceof ConceptFieldIndexCI_withTopTen) return ((ConceptFieldIndexCI_withTopTen) idx); if (idx != null) cc.removeCIFieldIndex(c, field); return new ConceptFieldIndexCI_withTopTen(cc, c, field); } 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 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 IF0 if0_const(final A a) { return () -> a; } 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 String toStringWithClassName(Object o) { return toStringWithClass(o); } 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 Map runnableThreadsWithStackTraces() { Map map = filterMap((__145, __146) -> isThreadRunnable_x(__145, __146), Thread.getAllStackTraces()); map.remove(currentThread()); return map; } static public String renderMultiSet(MultiSet ms) { if (ms == null) return "-"; List l = new ArrayList(); for (Object o : ms.highestFirst()) l.add(str(o) + " (" + ms.get(o) + ")"); return joinWithComma(l); } static public String renderMultiSet(Iterable l) { return renderMultiSet(toMultiSet(l)); } static public A fourth(List l) { return _get(l, 3); } static public A fourth(A[] bla) { return bla == null || bla.length <= 3 ? null : bla[3]; } 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 boolean isTransient(Field f) { return (f.getModifiers() & java.lang.reflect.Modifier.TRANSIENT) != 0; } 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> javaTok_cached_cache = synchronizedMRUCache(100); static public List javaTok_cached(String s) { List tok = javaTok_cached_cache.get(s); if (tok == null) javaTok_cached_cache.put(s, tok = javaTok(s)); return tok; } static public Map toSortedArrayBasedMap(Map map) { if (empty(map)) return null; if (map instanceof SortedArrayBasedMap) return map; return new SortedArrayBasedMap(map); } static public long getLastTiming() { ThreadLocal tl = saveTiming_tl(); if (tl == null) return -1; Long l = tl.get(); return l == null ? -1 : l; } static public boolean isSortedListByComparator(Collection l, Comparator cmp) { Iterator it = iterator(l); if (!it.hasNext()) return true; A a = it.next(); while (it.hasNext()) { A b = it.next(); if (cmp.compare(a, b) > 0) return false; a = b; } return true; } static public String dropPrefixOrNull(String prefix, String s) { return s != null && s.startsWith(prefix) ? s.substring(l(prefix)) : null; } static public String combinePrintParameters(String s, Object o) { return (endsWithLetterOrDigit(s) ? s + ": " : s) + o; } static public String format_quoted(String pat, Object... args) { return format_quoteAll(pat, args); } static public Class loadClassFromClassLoader_orNull(ClassLoader cl, String name) { try { return cl == null ? null : cl.loadClass(name); } catch (ClassNotFoundException e) { return null; } } 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 LinkedHashSet mapToLinkedHashSet(Object f, Collection l) { LinkedHashSet x = new LinkedHashSet(l(l)); if (l != null) for (Object o : l) x.add(callF(f, o)); return x; } static public LinkedHashSet mapToLinkedHashSet(Object f, Iterable l) { LinkedHashSet x = new LinkedHashSet(); if (l != null) for (Object o : l) x.add(callF(f, o)); return x; } static public LinkedHashSet mapToLinkedHashSet(IF1 f, Iterable l) { return mapToLinkedHashSet((Object) f, l); } static public boolean isSortedListByCalculatedField(Collection l, IF1 f) { return isSortedListByComparator(l, (a, b) -> cmp(f.get(a), f.get(b))); } static public boolean isSortedListByCalculatedField(IF1 f, Collection l) { return isSortedListByCalculatedField(l, f); } static public List mcAndUtils() { return llNonNulls(mc(), findClass_fullName("loadableUtils.utils")); } static public String js_redirectAutoScroll2() { return "$(\"input[name=redirect], input[name=redirectAfterSave]\").val(window.location.toString().replace(/(#.+?)$/, \"\") + (window.scrollY == 0 ? \"\" : \"#scrollTo\" + Math.round(window.scrollY)));"; } static public Throwable pcall(Runnable r) { try { r.run(); return null; } catch (Throwable e) { return e; } } static public Object pcall(Object o, String method, Object... args) { try { return call(o, method, args); } catch (Throwable __e) { return null; } } static public A pcall(IF0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { return null; } } static public void dm_mediumRefreshTranspiler() { dm_call(dm_moduleOfType("#1017065/Transpiler"), "mediumRefresh"); } static public java.util.regex.Pattern compileRegexpPossiblyIC_unicodeCase(String pat, boolean ic) { return ic ? compileRegexpIC_unicodeCase(pat) : compileRegexp(pat); } static public boolean getBoolOpt(Object o, String field) { return getBoolOpt(o, field, false); } static public boolean getBoolOpt(Object o, String field, boolean defaultValue) { return getBoolOpt(field, o, defaultValue); } static public boolean getBoolOpt(String field, Object o) { return getBoolOpt(field, o, false); } static public boolean getBoolOpt(String field, Object o, boolean defaultValue) { Object val = getOpt(o, field); return defaultValue ? !eq(Boolean.FALSE, val) : eq(Boolean.TRUE, val); } 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 Collection similarEmptyCollection(Collection c) { if (c instanceof List) return similarEmptyList((List) c); if (c instanceof Set) return similarEmptySet((Set) c); return new ArrayList(); } static public void printVars(Object... params) { printVars_str(params); } 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 String td_top(Object contents, Object... params) { return tdTop(contents, params); } static public Object getStandardFunctionHolder(String functionName) { for (Object o : mcAndUtils()) if (hasMethodNamed(o, functionName)) return o; return loadFunction_cached(functionName); } static public String profileThisThreadToString(Runnable r) { return profileThisThreadToString(poorMansProfiling_defaultInterval(), r); } static public String profileThisThreadToString(int interval, Runnable r) { poorMansProfiling(interval, currentThread()); try { r.run(); } catch (Throwable __e) { pcallFail(__e); } return poorMansProfiling_stopAndRenderResults(); } static public Pair profileThisThreadToString(IF0 f) { return profileThisThreadToString(poorMansProfiling_defaultInterval(), f); } static public Pair profileThisThreadToString(int interval, IF0 f) { Var var = new Var(); String profile = profileThisThreadToString(interval, new Runnable() { public void run() { try { var.set(callF(f)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var.set(callF(f))"; } }); return pair(var.get(), profile); } static public String renderConceptClassesWithCount(Concepts cc) { MultiSet ms = new MultiSet(); for (Concept c : values(cc.concepts)) ms.add(dynamicShortName(c)); return renderMultiSet(ms); } 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 String poorMansProfiling_stopAndRenderResults() { return poorMansProfiling_renderFullResults(poorMansProfiling_stopAndGetResults()); } static public List tok_integers(String s) { return tok_integersInOrder(s); } 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 List dm_modulesOfType(String type) { List l = splitAtSlash(type); if (l(l) == 2) return filterByProgramIDAndShortClassName(dm_listModules(), first(l), second(l)); else return filterByShortClassName(dm_listModules(), type); } static public boolean fileExistsInInDirOrZip(File location, String subPath) { try { if (location.isDirectory()) { File f = new File(location, subPath); return f.exists(); } else if (location.isFile()) { return zipContainsFile(location, subPath); } return false; } catch (Exception __e) { throw rethrow(__e); } } static public String formatGMTWithMilliseconds_24() { return formatGMTWithMilliseconds_24(now()); } static public String formatGMTWithMilliseconds_24(long time) { var sdf = simpleDateFormat("HH:mm:ss''SSSS", TimeZone.getTimeZone("GMT")); return sdf.format(time) + " GMT"; } static public Object dm_moduleOfType(String type) { return first(dm_modulesOfType(type)); } static public Object subBot_serveFileWithName(File file) { return subBot_serveFileWithName(file, file.getName()); } static public Object subBot_serveFileWithName(File file, String name) { return call(getMainBot(), "serveFileWithName", file, name); } static public Object subBot_serveFileWithName(String name, File file) { return subBot_serveFileWithName(file, name); } static public Object subBot_serveFileWithName(File file, String name, String mimeType) { return call(getMainBot(), "serveFileWithName", file, name, mimeType); } static public String joinNemptiesWithEmptyLines(List l) { return joinWithEmptyLines(nempties(l)); } static public String joinNemptiesWithEmptyLines(String... l) { return joinNemptiesWithEmptyLines(asList(l)); } static public List findBackRefsWithField(Concept c, Class type, String field) { return filter(findBackRefs(c, type), o -> cget(o, field) == c); } static public List findBackRefsWithField(Class type, Concept c, String field) { return findBackRefsWithField(c, type, field); } static public List findBackRefsWithField(Class type, String field, Concept c) { return findBackRefsWithField(c, type, field); } static public List filesFromClassLoader(Class c) { return filesFromClassLoader(getClassLoader(c)); } static public List filesFromClassLoader(ClassLoader cl) { Collection l = filesFromClassLoader_new(cl); return l == null ? null : asList(l); } static public String mcName() { return mc().getName(); } static public String renderElapsedTimePleasantly() { return renderElapsedTimePleasantly(lastTiming()); } static public String renderElapsedTimePleasantly(long ms) { double secs = toSeconds(ms); if (secs >= 1) return formatDouble(secs, 3) + " s"; return ms + " ms"; } static public String renderElapsedTimePleasantly(Runnable r) { long time = sysNow(); { if (r != null) r.run(); } return renderElapsedTimePleasantly(sysNow() - time); } static public String renderElapsedTimePleasantly(Duration d) { return d == null ? null : renderElapsedTimePleasantly(d.toMillis()); } static public String leadingAngleBracketStuff(String s) { if (!startsWith(s, ']')) return null; return substring(s, 1, smartIndexOf(s, ']')); } static public List nonStaticFieldObjects(Object o) { List fields = new ArrayList(); Class _c = _getClass(o); do { for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & Modifier.STATIC) == 0) { f.setAccessible(true); fields.add(f); } _c = _c.getSuperclass(); } while (_c != null); return fields; } static public List immutableEmptyList() { return Collections.emptyList(); } static public String jquery_submitFormOnCtrlEnter() { return "if ((event.keyCode == 10 || event.keyCode == 13) && event.ctrlKey) $(this).closest('form').submit();"; } static public Object ccall(Concept.Ref ref, String method, Object... args) { return callWithEnter(cDeref(ref), method, args); } static public Object ccall(Object object, String method, Object... args) { return callWithEnter(object, method, args); } static public String nDiffs(long n) { return n2(n, "diff"); } static public String nDiffs(Collection l) { return nDiffs(l(l)); } static public String nDiffs(Map map) { return nDiffs(l(map)); } static public String loadableUtilsClassNameToMain(String className) { String c = dropPrefixOrNull("loadableUtils.utils$", className); if (c != null) return "main$" + c; return className; } static public String fixHTML(Object contents) { String s = str(contents); return hhtml(hbody(s)); } static public void dm_reloadModule(Object module) { dm_reloadModuleInBackground(module); } static public void dm_reloadModule() { dm_reloadModuleInBackground(); } 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 void stopTimer(java.util.Timer timer) { if (timer != null) timer.cancel(); } static public A findConcept(Class c, Object... params) { return findConceptWhere(c, params); } static public A findConcept(Concepts concepts, Class c, Object... params) { return findConceptWhere(concepts, c, params); } static public String hijackPrintPlusResult_text(IF0 f) { Var var = new Var(); String out = hijackPrint(new Runnable() { public void run() { try { var.set(f.get()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var.set(f!)"; } }); return lines_rtrim(ll(out, str(var))); } static public List regexpFindRangesIC(String pat, String s) { Matcher m = regexpMatcherIC(pat, s); List l = new ArrayList(); while (m.find()) l.add(new IntRange(m.start(), m.end())); return l; } static public void indexConceptClass(Class c) { indexConceptClass(db_mainConcepts(), c); } static public void indexConceptClass(Concepts cc, Class c) { ensureConceptClassIsIndexed(cc, c); } static public Object cCall(Concept.Ref ref, String method, Object... args) { return ccall(ref, method, args); } static public Object cCall(Object object, String method, Object... args) { return ccall(object, method, args); } static public TreeMap toCIMap(Map map) { return asCIMap(map); } static public String nPatterns(long n) { return n2(n, "pattern"); } static public String nPatterns(Collection l) { return nPatterns(l(l)); } static public String nPatterns(Map map) { return nPatterns(l(map)); } static public boolean containsStars(String s) { return containsStars(javaTok_cached(s)); } static public boolean containsStars(List tok) { for (int i = 1; i < l(tok); i += 2) if (eq(tok.get(i), "*")) return true; return false; } 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 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 IF0 call_optional(Object o, String method, String[] arg) { return call_optional(o, method, new Object[] { arg }); } static public IF0 call_optional(Object o, String method, Object... args) { if (!canCallWithVarargs(o, method, args)) return null; return if0_const(call(o, method, args)); } static public boolean cSmartSetField_withConverter(Concept c, String field, Object value) { return cSmartSetField_withConverter(c, field, value, false); } static public boolean cSmartSetField_withConverter(Concept c, String field, Object value, boolean verbose) { return cSmartSetField_withConverter(c, field, value, new DefaultValueConverterForField(), verbose); } static public boolean cSmartSetField_withConverter(Concept c, String field, Object value, ValueConverterForField converter) { return cSmartSetField_withConverter(c, field, value, converter, false); } static public boolean cSmartSetField_withConverter(Concept c, String field, Object value, ValueConverterForField converter, boolean verbose) { try { Field f = setOpt_findField(c.getClass(), field); if (f != null) { if (verbose) print("cSmartSetField_withConverter: setting " + f + " = " + value); if (converter != null && value != null) { OrError result = converter.convertValue(c, f, value); if (result == null) throw fail("Unknown conversion " + className(value) + " => " + f); if (!result.ok()) throw fail("Unknown conversion " + className(value) + " => " + f + ": " + result.error()); value = result.get(); } if (verbose) print("cSmartSetField_withConverter: converted value=" + value); if (value instanceof List && f.getType() == Concept.RefL.class) { Concept.RefL l = (Concept.RefL) (f.get(c)); if (verbose) print("cSmartSetField_withConverter: RefL=" + l); l.replaceWithList((List) value); if (verbose) print("cSmartSetField_withConverter: backrefs=" + c.backRefs); return true; } if (value instanceof Concept && f.getType() == Concept.Ref.class) return ((Concept.Ref) f.get(c)).set((Concept) value); } return _csetField(c, field, value); } catch (Exception __e) { throw rethrow(__e); } } static public MultiSet distinctCIFieldValuesOfConcepts_multiSet(Class c, String field) { return distinctCIFieldValuesOfConcepts_multiSet(db_mainConcepts(), c, field); } static public MultiSet distinctCIFieldValuesOfConcepts_multiSet(Concepts concepts, Class c, String field) { IFieldIndex index = concepts.getCIFieldIndex(c, field); if (index != null) return index.allValues_multiSet(); MultiSet set = ciMultiSet(); for (A x : concepts.list(c)) set.add((String) getOpt(x, field)); return set; } static public Writer outputStreamToWriter(OutputStream out) { try { return new OutputStreamWriter(out, "UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } static public File transpilerErrorSourceFile() { return javaxCachesDir("error-source.java"); } static public SimpleDateFormat simpleDateFormat_GMT(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); return sdf; } 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 int jfind_any(String src, String... patterns) { return jfind_any(javaTok(src), patterns); } static public int jfind_any(List tok, String... patterns) { return jfind_any(tok, 1, patterns); } static public int jfind_any(List tok, int startIdx, String... patterns) { return jfind_any(tok, startIdx, null, patterns); } static public int jfind_any(List tok, TokCondition cond, String... patterns) { return jfind_any(tok, 1, cond, patterns); } static public int jfind_any(List tok, int startIdx, TokCondition cond, String... patterns) { int i = -1; for (String pat : patterns) i = minUnlessMinus1(i, jfind(tok, startIdx, pat, cond)); return i; } static public PrintWriter newPrintWriter(OutputStream out) { return new PrintWriter(outputStreamToWriter(out)); } static public PrintWriter newPrintWriter(Writer out) { return new PrintWriter(out); } static public A cDeref(Concept.Ref ref) { return ref == null ? null : ref.get(); } static public String[] match2x(List pat, List tok) { ArrayList 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); boolean match = false; if (eq(p, "*")) match = true; else if (eq(p, "")) match = isQuoted(t); else if (eq(p, "")) match = isIdentifier(t); else if (eq(p, "")) match = isInteger(t); else { if (!eq(p, t)) return null; continue; } if (!match) return null; result.add(t); } return result.toArray(new String[result.size()]); } static public ConceptShadow conceptShadow(Concept c) { if (c == null) return null; return new ConceptShadow(c); } static public String hjs_handleScrollToAnchor() { return hjs("\r\n $(window).on(\"load\", function() {\r\n var anchor = window.location.hash.substr(1);\r\n var match = anchor.match(/^scrollTo(\\d+)$/);\r\n if (match) {\r\n var y = parseInt(match[1]);\r\n console.log(\"Scrolling to \" + y);\r\n window.scrollTo(0, y);\r\n }\r\n });\r\n "); } static public String unicode_thumbsDown() { return unicodeFromCodePoint(0x1F44E); } static public A id(A a) { return a; } 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 A unlisted_gen(Class c, Object... args) { if (isSubclassOf(c, Concept.class)) return (A) unlisted((Class) c, args); return nuObject(c, args); } static public BufferedOutputStream bufferedFileOutputStream_append(File f) { try { return bufferedOutputStream(newFileOutputStream_append(f)); } catch (Exception __e) { throw rethrow(__e); } } static public Set synchroLinkedHashSet() { return synchronizedSet(new CompactLinkedHashSet()); } 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 A unlistedCopyToClass_withConverter(Class c, Concept a) { if (a == null) return null; A b = unlisted(c); ccopyFields_withConverter(a, b); return b; } static public A evalInVStack(VStack.Computable computation) { return vStackCompute(computation); } 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 boolean isShortNamed(String name, Object o) { return eq(shortClassName(o), name); } 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(__111 -> derefRef(__111), (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 A cgetOpt(Class type, Concept c, String field) { return optCast(type, cget(c, field)); } static public String dropDotSuffix(String s) { return dropTrailingDot(s); } static public int classLoaderPathsCount(Class c) { return classLoaderPathsCount(getClassLoader(c)); } static public int classLoaderPathsCount(ClassLoader cl) { return l(filesFromClassLoader_new(cl)); } static public Set cloneKeySet(Map map) { return cloneSet(keys(map)); } static public A csetAndReturn(A c, Object... values) { cset(c, values); return c; } static public boolean isUnlisted(Concept c) { return c != null && c.concepts() == null; } static public String htmlDecode_dropTags(String html) { return htmldecode_dropAllTags(html); } static public void dm_reloadModuleIn(double seconds) { Object mod = dm_current_generic(); if (mod == null) return; print("Reloading module in " + seconds); doAfter(seconds, new Runnable() { public void run() { try { dm_reloadModule(mod); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "dm_reloadModule(mod)"; } }); } 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 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 void dynamicObject_dropRawField(DynamicObject o, Object key) { if (o == null) return; synchronized (o) { o.fieldValues = (LinkedHashMap) syncMapRemove_deleteMapIfEmpty((Map) o.fieldValues, key); } } static public void truncateListFromStart(List l, int n) { if (l(l) <= n) return; removeSubList(l, 0, l(l) - n); } static public void flexMatchAngleBracketVarsIC_honorPunctuation_noBrackets_iterate(String pat, String input, VF1> onMatch) { List vars = new ArrayList(); String starsPat = angleBracketVarsToStars(pat, vars); flexMatchIC_iterate(starsPat, javaTok(starsPat), javaTok(input), new VF1() { public void get(Matches m) { try { Map map = matchesToMapUsingVarList_ciMap(m, vars); if (map != null) callF(onMatch, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "SS map = matchesToMapUsingVarList_ciMap(m, vars);\r\n if (map != null) callF..."; } }); } 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 B getAny(Map map, A... keys) { for (A a : unnullForIteration(keys)) { B b = map.get(a); if (b != null) return b; } return null; } static public Object[] itemPlusObjectArray(Object a, Object[] l) { Object[] out = new Object[l(l) + 1]; out[0] = a; arraycopy(l, 0, out, 1, l(l)); return out; } static public String joinWithDot(Iterable l) { return join(".", l); } static public String joinWithDot(A... l) { return joinWithDot(asList(l)); } static public LinkedHashMap mapSortedByFunctionOnKey(IF1 f, Map map) { List l = new ArrayList(map.keySet()); sortInPlaceByCalculatedField(l, f); LinkedHashMap map2 = new LinkedHashMap(); for (A a : l) map2.put(a, map.get(a)); return map2; } static public ClassLoader classLoader(Object o) { return classLoaderForObject(o); } 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 String ul_htmlEncode2(String... list) { return ul_htmlEncode(list); } static public String ul_htmlEncode2(Collection list, Object... params) { return ul_htmlEncode(list, params); } static public List wideningListCast(Class c, List l) { return (List) l; } static public Collection wideningListCast(Class c, Collection l) { return (Collection) l; } static public List wideningListCast(List l) { return (List) l; } static public List dm_listModules() { return (List) dm_callOS("listModules"); } static public ClassLoader dm_moduleClassLoader() { return dm_moduleClassLoader(dm_current_mandatory_generic()); } static public ClassLoader dm_moduleClassLoader(Object mod) { return getClassLoader(dm_getModule(mod)); } static public PrintWriter printWriter(OutputStream out) { return newPrintWriter(out); } static public PrintWriter printWriter(Writer out) { return newPrintWriter(out); } 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 Object fieldGet(Field f, Object o) { try { return f == null ? null : f.get(o); } catch (Exception __e) { throw rethrow(__e); } } static public String hSingleRowTable_withSpacing(Object... elements) { return hSingleRowTable_withSpacing(10, elements); } static public String hSingleRowTable_withSpacing(int spacing, Object... elements) { return tag("table", tr(join("", map(new F1() { public String get(Object x) { try { return td_top(x); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "td_top(x)"; } }, nonNulls(elements))))); } static public Object pcallWithEnter(Object o, String method, Object... args) { try { return callWithEnter(o, method, args); } catch (Throwable __e) { return null; } } static public ThreadLocal transpileAndCompileForHotwiring_src = new ThreadLocal(); static public File transpileAndCompileForHotwiring(String src) { return transpileAndCompileForHotwiring(src, null); } static public File transpileAndCompileForHotwiring(String src, List libs) { transpileAndCompileForHotwiring_src.set(null); if (libs == null) libs = new ArrayList(); src = transpileRaw(src); transpileAndCompileForHotwiring_src.set(src); src = findTranslators2(src, libs); String dehlibs = join(" ", libs); File bytecode = javaCompile_overInternalBot(src, dehlibs); print("bytecode", bytecode); print("Files: " + listZip(bytecode)); return bytecode; } static public String toStringWithClass(Object o) { return o == null ? null : className(o) + " - " + o; } static public void printAllConceptChanges() { printAllConceptChanges(db_mainConcepts()); } static public void printAllConceptChanges(Concepts cc) { cc.addConceptIndex(new IConceptIndex() { public void update(Concept c) { print("Updated: " + c); } public void remove(Concept c) { print("Removed: " + c); } }); cc.onAllChanged.add(new Runnable() { public void run() { try { print("General concepts change"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "print(\"General concepts change\");"; } }); } static public String tok_dropCurlyBrackets(String s) { return join(tok_dropCurlyBrackets(javaTok(s))); } static public List tok_dropCurlyBrackets(List tok) { for (int i = 1; i < l(tok); i += 2) { while (eqGetOneOf(tok, i, "{", "}")) { tokAppend(tok, i - 1, tok.get(i + 1)); removeSubList(tok, i, i + 2); } } return tok; } static public List setMinus_inPlace(List l, int i) { return removeAndReturnCollection(l, i); } static public > B setMinus_inPlace(B l, A a) { return removeAndReturnCollection(l, a); } static public Class classLoader_loadClass(Object realm, String name) { try { ClassLoader cl = classLoader(realm); return cl == null ? null : cl.loadClass(name); } catch (Exception __e) { throw rethrow(__e); } } static public int ratioToIntPercent(double x, double y) { return roundToInt(x * 100 / y); } static public long getLong(Object o, String field) { return toLong(getOpt(o, field)); } static public long getLong(String field, Object o) { return getLong(o, field); } static public Concept getConceptOrMarkMissingObject(Class requiredClass, long id) { return getConceptOrMarkMissingObject(db_mainConcepts(), requiredClass, id); } static public Concept getConceptOrMarkMissingObject(Concepts cc, Class requiredClass, long id) { if (cc == null) return null; Concept c = getConcept(cc, id); if (isInstanceOf(c, requiredClass)) return c; if (c instanceof CMissingObject) return c; if (c != null) throw fail("Can't cast: " + toStringWithClassName(c) + "/" + requiredClass); Lock __0 = dbLock(cc); lock(__0); try { if (getConcept(cc, id) == null) return cnew(cc, CMissingObject.class); return null; } finally { unlock(__0); } } static public Map keysAndValuesToString(Map map) { return mapKeysAndValues(__112 -> str(__112), map); } 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 List filterByProgramIDAndShortClassName(Iterable l, String progID, String className) { List out = new ArrayList(); for (Object o : unnull(l)) if (shortClassNameIs(o, className) && sameSnippetID(getProgramID(o), progID)) out.add(o); return out; } static public Map mapKeysAndValues(Object f, Map map) { return mapKeysAndValues(f, f, map); } static public Map mapKeysAndValues(Object fKey, Object fValue, Map map) { if (map == null) return null; Map m = similarEmptyMap(map); for (Map.Entry __1 : _entrySet((Map) map)) { Object key = __1.getKey(); Object val = __1.getValue(); m.put(callF(fKey, key), callF(fValue, val)); } return m; } static public Map mapKeysAndValues(IF1 f, Map map) { return mapKeysAndValues(f, f, map); } static public Map mapKeysAndValues(IF1 fKey, IF1 fValue, Map map) { if (map == null) return null; Map m = similarEmptyMap(map); for (Map.Entry __0 : _entrySet(map)) { A key = __0.getKey(); B val = __0.getValue(); m.put(fKey.get(key), fValue.get(val)); } return m; } static public void dm_addByteCodePathToModuleClassLoader(File bytecode) { try { ClassLoader cl = getClassLoader(dm_current_mandatory_generic()); print("Adding to class loader " + cl + ": " + bytecode); call(cl, "addFile", bytecode); } catch (Exception __e) { throw rethrow(__e); } } static public Collection filesFromClassLoader_new(Class c) { return filesFromClassLoader(getClassLoader(c)); } static public Collection filesFromClassLoader_new(ClassLoader cl) { return (Collection) getOpt(cl, "files"); } static public Map flexMatchAngleBracketVarsIC_honorPunctuation_noBrackets_first(String pat, String input) { return grabValueAndCancel(new VF1>>() { public void get(VF1> onMatch) { try { flexMatchAngleBracketVarsIC_honorPunctuation_noBrackets_iterate(pat, input, onMatch); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "flexMatchAngleBracketVarsIC_honorPunctuation_noBrackets_iterate(pat, input, o..."; } }); } 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 boolean isPersistable(Object o) { return !isInAnonymousClass(o); } static public String dm_requireModule(String moduleLibID) { return dm_makeModule(moduleLibID); } 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 ReliableSingleThread_Multi dm_rstMulti(IVF1 processObject) { return dm_rstMulti(dm_current_mandatory(), processObject); } static public ReliableSingleThread_Multi dm_rstMulti(DynModule mod, IVF1 processObject) { return dm_rstMulti(mod, new ReliableSingleThread_Multi<>(processObject)); } static public ReliableSingleThread_Multi dm_rstMulti(int delay, IVF1 processObject) { return dm_rstMulti(dm_current_mandatory(), delay, processObject); } static public ReliableSingleThread_Multi dm_rstMulti(DynModule mod, int delay, IVF1 processObject) { return dm_rstMulti(mod, new ReliableSingleThread_Multi<>(delay, processObject)); } static public ReliableSingleThread_Multi dm_rstMulti(DynModule mod, ReliableSingleThread_Multi rst) { rst.setEnter(dm_rEnter(mod)); return rst; } static public ConceptID conceptIDObject(Concept c) { return c == null ? null : new ConceptID(c); } static public Set syncLinkedHashSet() { return synchroLinkedHashSet(); } static public String dropTrailingDot(String s) { return dropSuffix(".", s); } static public List splitAtSlash(String s) { return trimAll(asList(s.split("/"))); } static public List listPlusItems_inPlace(List l, A... more) { addAll(l, more); return l; } static public Object cCallOpt(Concept.Ref ref, String method, Object... args) { return ccallOpt(ref, method, args); } static public Object cCallOpt(Object object, String method, Object... args) { return ccallOpt(object, method, args); } static public String matcherGroup(java.util.regex.Matcher m, int n) { return m != null && n >= 1 && n <= m.groupCount() ? m.group(n) : null; } 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 Object subBot_serveText(Object s) { return call(getMainBot(), "serveByteArray", toUtf8(str(s)), "text/plain; charset=utf8"); } static public Object subBot_serveText(InputStream in) { return subBot_serveInputStream(in, "text/plain; charset=utf8"); } static public Object subBot_serveText(File f) { return subBot_serveFile(f, "text/plain; charset=utf8"); } 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 Map mapToValues_ciMap(Iterable l, Object f) { return mapToValues_ciMap(f, l); } static public Map mapToValues_ciMap(Object f, Iterable l) { Map map = ciMap(); if (l != null) for (String o : l) map.put(o, callF(f, o)); return map; } static public Map mapToValues_ciMap(Iterable l, IF1 f) { return mapToValues_ciMap(f, l); } static public List> pairsSortedByA(Collection> l) { return sortedByComparator(l, (a, b) -> cmp(a.a, b.a)); } static public void tokAppend(List tok, int i, String s) { tok.set(i, tok.get(i) + s); } static public MultiSet ciMultiSet() { MultiSet ms = new MultiSet(); ms.map = ciMap(); return ms; } static public MultiSet ciMultiSet(Iterable l) { return asCIMultiSet(l); } static public List tok_identifiers(String s) { return tok_identifiersInOrder(s); } static public List tok_identifiers(List tok) { return tok_identifiersInOrder(tok); } static public Class getClass_vmName_withLoadableUtils(Object realm, String name) { try { ClassLoader cl = getClassLoader(realm); Class c = loadClassFromClassLoader_orNull(cl, name); if (c == null && name.startsWith("main$")) return loadClassFromClassLoader_orNull(cl, "loadableUtils.utils" + substring(name, 4)); return c; } catch (Exception __e) { throw rethrow(__e); } } static public interface replaceKeywordBlock_dyn_IReplacer { public String[] get(List tok, int iOpening, int iClosing); } static public List replaceKeywordBlock_dyn(List tok, String keyword, replaceKeywordBlock_dyn_IReplacer func) { for (int i = 0; i < 1000; i++) { int idx = findCodeTokens(tok, keyword, "{"); if (idx < 0) break; int j = findEndOfBracketPart(tok, idx + 2); String[] be = func == null ? null : func.get(tok, idx + 2, j - 1); tok.set(idx, unnull(first(be))); tok.set(idx + 1, " "); tok.set(idx + 2, ""); tok.set(j - 1, unnull(second(be))); reTok(tok, idx, j); } return tok; } static public Set allConceptIDs() { return allConceptIDs(db_mainConcepts()); } static public Set allConceptIDs(Concepts cc) { return cloneKeySet(cc.concepts); } static public Object get2(Object o, String field1, String field2) { return get(get(o, field1), field2); } static public String joinWithEmptyLines(Iterable l) { return join("\n\n", map(__113 -> rtrim(__113), l)); } static public String joinWithEmptyLines(String... l) { return joinWithEmptyLines(asList(l)); } 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 Object cPcall(Concept.Ref ref, String method, Object... args) { return pcallWithEnter(cDeref(ref), method, args); } static public Object cPcall(Object object, String method, Object... args) { return pcallWithEnter(object, method, args); } static public boolean jMatchStart(String pat, String s) { return jMatchStart(pat, s, null); } static public boolean jMatchStart(String pat, String s, Matches matches) { if (s == null) return false; return jMatchStart(pat, javaTok(s), matches); } static public boolean jMatchStart(String pat, List toks) { return jMatchStart(pat, toks, null); } static public boolean jMatchStart(String pat, List toks, Matches matches) { List tokpat = jfind_preprocess(javaTok(pat)); if (toks.size() < tokpat.size()) return false; String[] m = match2x(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] = join(toks.subList(tokpat.size(), toks.size())); } return true; } static public String dynamicShortName(Object o) { return shortDynamicClassName(o); } static public String replaceDollarVars2_dyn(String s, IF1 f) { if (f == null) return s; return regexpReplace(s, "\\$(\\w+)|\\$\\{(.+?)\\}", matcher -> { String var = or(matcher.group(1), matcher.group(2)); String val = f.get(var); return val == null ? matcher.group() : str(val); }); } static public List llNempties(String... a) { ArrayList l = new ArrayList(a.length); if (a != null) for (String x : a) if (nempty(x)) l.add(x); return l; } static public int getIntOpt(List c, int i) { return toIntOpt(get(c, i)); } static public int getIntOpt(Map map, Object key) { return toIntOpt(mapGet(map, key)); } static public int getIntOpt(Object o, String field) { return getIntOpt(o, field, 0); } static public int getIntOpt(Object o, String field, int defaultValue) { return toIntOpt(getOpt(o, field), defaultValue); } static public int getIntOpt(String field, Object o) { return getIntOpt(field, o, 0); } static public int getIntOpt(String field, Object o, int defaultValue) { return getIntOpt(o, field, defaultValue); } static public MultiSetMapWithTopTen ciMultiSetMapWithTopTen() { MultiSetMapWithTopTen mm = new MultiSetMapWithTopTen(); mm.data = ciMap(); return mm; } static public double toMinutes(long ms) { return ms / 60000.0; } static public String mcDollar() { return mcName() + "$"; } 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 List> bitSetStreaksAndNonStreaks(BitSet bs, int n) { int start = 0; Boolean last = null; List> out = new ArrayList(); for (int i = 0; i < n; i++) { Boolean result = bs.get(i); if (last != null && neq(result, last)) { out.add(pair(intRange(start, i), last)); start = i; } last = result; } if (start < n) out.add(pair(intRange(start, n), last)); return out; } static public boolean classLoaderContainsByteCodePath(ClassLoader cl, File byteCodePath) { return contains(filesFromClassLoader_new(cl), byteCodePath); } static public void quickImportMainConcepts(Object oldConcepts) { quickImportMainConcepts(oldConcepts, null); } static public void quickImportMainConcepts(Object oldConcepts, IF0 enabled) { if (!shortNameIs(oldConcepts, "Concepts")) return; Concepts concepts = db_mainConcepts(); concepts.miscMapPut("dbGrabber", new F0() { public Boolean get() { try { concepts.miscMapRemove("dbGrabber"); try { if (isFalse(callF(enabled))) return false; concepts.idCounter = getLong("idCounter", oldConcepts); printVars_str("idCounter", concepts.idCounter); Map oldMap = (Map) (_get("concepts", oldConcepts)); printVars_str("oldMap", oldMap); RealmCopy rc = new RealmCopy(); rc.nonTransientOnly = true; rc.fullCopy = true; rc.overrideCollectionOrMapCopy = o -> { rc.classMap.put(_getClass(o), _getClass(o)); return false; }; { AutoCloseable __1 = tempSetTL(dynamicObjectIsLoading_threadLocal(), true); try { concepts.concepts.putAll((Map) rc.copy(oldMap)); } finally { _close(__1); } } pnl("quickImportDB", mapSortedByFunctionOnKey(__114 -> str(__114), rc.classMap)); concepts.assignConceptsToUs(); print(nConcepts(countConcepts()) + " quick-imported"); return true; } catch (Throwable __e) { pcallFail(__e); } return false; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "concepts.miscMapRemove(\"dbGrabber\");\r\n pcall {\r\n if (isFalse(callF(en..."; } }); } static public String dotToDollar(String s) { return replace(s, ".", "$"); } static public A vStackCompute(VStack.Computable computation) { if (computation == null) return null; VStack stack = new VStack(computation); stepAll(stack); return (A) stack.result(); } static public void dm_onSnippetTranspiled(VF1 r) { dm_requireSnippetUpdatesModule(); final DynModule m = dm_current_mandatory(); dm_vmBus_onMessage("snippetUpdate", new VF1() { public void get(final List l) { try { m.q().add(new Runnable() { public void run() { try { String uri = getString(l, 1); Matches m = new Matches(); if (swic(uri, "/transpileOK/", m)) { String snippetID = fsI(firstIntAsString(m.rest())); callF(r, snippetID); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String uri = getString(l, 1);\r\n new Matches m;\r\n if (swic(uri, \"/transp..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "switch to m.q();\r\n S uri = getString(l, 1);\r\n new Matches m;\r\n if (s..."; } }); } static public void dm_onSnippetTranspiled(String snippetID, Runnable r) { if (empty(snippetID) || r == null) return; dm_onSnippetTranspiled(new VF1() { public void get(String snippetID2) { try { if (sameSnippetID(snippetID, snippetID2)) r.run(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (sameSnippetID(snippetID, snippetID2))\r\n r.run();"; } }); } static public List assertStringList(Object o) { if (!(o instanceof List)) throw fail("Not a list: " + className(o)); List l = (List) o; for (Object x : l) if (!(x instanceof String)) throw fail("Not a string: " + className(x)); return l; } static public A stepAllAndGet(SteppableAndIF0 s) { stepAll(s); return s.get(); } static public boolean shortNameIs(String name, Object o) { return isShortNamed(name, o); } static public boolean shortNameIs(Object o, String name) { return shortNameIs(name, o); } static public String nObjects(long n) { return n2(n, "object"); } static public String nObjects(Collection l) { return nObjects(l(l)); } static public String nObjects(Map m) { return nObjects(l(m)); } static public boolean isSystemThread(Thread t) { ThreadGroup g = t.getThreadGroup(); return g != null && g.getName().equals("system"); } static public Map compileRegexpIC_unicodeCase_cache = syncMRUCache(10); static public java.util.regex.Pattern compileRegexpIC_unicodeCase(String pat) { java.util.regex.Pattern p = compileRegexpIC_unicodeCase_cache.get(pat); if (p == null) { try { compileRegexpIC_unicodeCase_cache.put(pat, p = java.util.regex.Pattern.compile(pat, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE)); } catch (PatternSyntaxException e) { throw rethrow(wrapPatternSyntaxException(e)); } } return p; } static public int defaultBufferedOutputStreamSize() { return 65536; } static public double elapsedMinutes_timestamp(long time) { return toMinutes(now() - time); } static public void setFieldToIF1Proxy(Object o, String field, IF1 target) { setFieldToSingleMethodProxy(o, field, target, "get"); } static public boolean zipFileContains_falseOnError(File inZip, String fileName) { try { return zipFileContains(inZip, fileName); } catch (Throwable e) { return false; } } static public Map objectToMap_nonTransient(Object o) { if (o == null) return null; if (o instanceof Map) return (Map) o; HashMap map = new HashMap(); for (Field field : nonStaticNonTransientFieldObjects_cachedArray(o)) { Object value = fieldGet(field, o); if (value != null) map.put(field.getName(), value); } if (o instanceof DynamicObject) putAll(map, ((DynamicObject) o).fieldValues); return map; } 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 ClassLoader classLoaderForObject(Object o) { if (o instanceof ClassLoader) return ((ClassLoader) o); if (o == null) return null; return _getClass(o).getClassLoader(); } 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 String aname(String anchor) { return aname(anchor, ""); } static public String aname(String anchor, Object contents, Object... params) { return tag("a", contents, concatArrays(new Object[] { "name", anchor }, params)); } static public FileOutputStream newFileOutputStream_append(File path) { try { return newFileOutputStream(path, true); } catch (Exception __e) { throw rethrow(__e); } } static public FileOutputStream newFileOutputStream_append(String path) { try { return newFileOutputStream(path, true); } catch (Exception __e) { throw rethrow(__e); } } static public IF0 runnableToIF0(Runnable r) { return r == null ? null : () -> { r.run(); return null; }; } static public List regexpGroups(String pat, String s) { return regexpFirstGroups(pat, s); } static public List filterByShortClassName(Iterable l, String name) { List out = new ArrayList(); for (Object o : unnull(l)) if (shortClassNameIs(o, name)) out.add(o); return out; } static public String firstIntAsString(String s) { return jextract("", s); } 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 PrintWriter filePrintWriter_append(File f) { return printWriter(bufferedFileOutputStream_append(f)); } static public void onConceptChangeByClasses_notOnAllChanged(Collection types, Runnable r) { onConceptChangeByClasses_notOnAllChanged(db_mainConcepts(), types, r); } static public void onConceptChangeByClasses_notOnAllChanged(Concepts cc, Collection types, Runnable r) { cc.addConceptIndex(new IConceptIndex() { public void update(Concept c) { if (isInstanceOfAny(c, types)) pcallF(r); } public void remove(Concept c) { if (isInstanceOfAny(c, types)) pcallF(r); } }); } static public long parseDateWithMillisecondsGMT(String s) { try { return simpleDateFormat_GMT("yyyy/MM/dd HH:mm:ss''SSSS").parse(dropSuffix(" GMT", s)).getTime(); } catch (Exception __e) { throw rethrow(__e); } } 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 short[] emptyShortArray = new short[0]; static public short[] emptyShortArray() { return emptyShortArray; } static public long nanos() { return nanoTime(); } static public String hcenter(Object contents, Object... params) { return hfulltag("center", contents, params); } static public String hlinkButton(String url, String text, Object... params) { return hbuttonLink(url, text, params); } 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 Symbol emptySymbol_value; static public Symbol emptySymbol() { if (emptySymbol_value == null) emptySymbol_value = symbol(""); return emptySymbol_value; } static public long parseFirstLong_regexp(String s) { return firstLong_regexp(s); } static public String makeAbsoluteURL(String baseURL, String url) { try { return empty(baseURL) ? url : str(new URL(new URL(baseURL), url)); } catch (Exception __e) { throw rethrow(__e); } } static public boolean dm_subOSConnectorToChannel(String channel) { if (!hasMethodNamed(dm_os(), "subConnectorToChannel")) return false; dm_osCall("subConnectorToChannel", channel); return true; } static public String shortClassName_dropNumberPrefix(Object o) { return dropNumberPrefix(shortClassName(o)); } 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 String pre_htmlEncode(Object contents, Object... params) { return pre_htmlencode(contents, params); } static public List methodsSortedByNameIC(Collection l) { return sortedByCalculatedFieldIC(l, m -> m.getName()); } static public Object addFilenameHeader(Object r, String name) { call(r, "addHeader", "Content-Disposition", "inline; filename=\"" + name + "\""); return r; } static public Object addFilenameHeader(String name, Object r) { return addFilenameHeader(r, name); } static public A unlistedCopyToClass_withConverter_pcall(Class c, Concept a) { if (a == null) return null; A b = unlisted(c); ccopyFields_withConverter_pcall(a, b); return b; } static public boolean isIntegerOrIdentifier(String s) { return isInteger(s) || isIdentifier(s); } static public List splitAtSpace_trim(String s) { return nempties(trimAll(splitAtSpace(s))); } 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 int hashMap_internalHash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } static public boolean userAgentIsBot(String userAgent) { return cic(userAgent, "bot") || cic(userAgent, "crawler"); } static public boolean addLibraryToClassLoader(ClassLoader cl, String libraryID) { try { if (isTrue(callOpt(cl, "hasLibraryID", libraryID))) return false; return addByteCodePathToClassLoader(cl, loadLibraryOrSrcLib(libraryID), libraryID); } catch (Exception __e) { throw rethrow(__e); } } static public List deleteConceptsWhereIC(Class c, Object... params) { return deleteConceptsWhereCI(c, params); } 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 Object dm_osCall(String functionName, Object... args) { return dm_callOS(functionName, args); } static public String nemptyLines(Iterable l) { return lines(nempties(allToStrOrNull(l))); } static public String nemptyLines(Object... l) { return nemptyLinesLL(l); } static public String formatUTCWithSeconds_24() { return formatUTCWithSeconds_24(now()); } static public String formatUTCWithSeconds_24(long time) { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf.format(time) + " UTC"; } static public String linesLL(Object... x) { return lines(ll(x)); } static public String hjs_selectizeClickable() { return hjs("\r\n Selectize.define('clickable', function(options) {\r\n var self = this;\r\n var setup = self.setup;\r\n this.setup = function() {\r\n setup.apply(self, arguments);\r\n \r\n var clicking = false;\r\n \r\n // Detect click on a .clickable\r\n self.$dropdown_content.on('mousedown click', function(e) {\r\n if ($(e.target).hasClass('clickable')) {\r\n if (e.type === 'mousedown') {\r\n clicking = true;\r\n self.isFocused = false; // awful hack to defuse the document mousedown listener\r\n } else {\r\n self.isFocused = true;\r\n setTimeout(function() {\r\n clicking = false; // wait until blur has been preempted\r\n });\r\n }\r\n } else { // cleanup in case user right-clicked or dragged off the element\r\n clicking = false;\r\n self.isFocused = true;\r\n }\r\n });\r\n \r\n // Intercept default handlers\r\n self.$dropdown.off('mousedown click', '[data-selectable]').on('mousedown click', '[data-selectable]', function() {\r\n if (!clicking) {\r\n return self.onOptionSelect.apply(self, arguments);\r\n }\r\n });\r\n self.$control_input.off('blur').on('blur', function() {\r\n if (!clicking) {\r\n return self.onBlur.apply(self, arguments);\r\n }\r\n });\r\n }\r\n });\r\n "); } static public A routeThroughAll(Iterable> processors, A a) { for (var processor : unnullForIteration(cloneList(processors))) { try { a = processor.get(a); } catch (Throwable __e) { pcallFail(__e); } } return a; } static public boolean eqOrEqic(boolean caseInsensitive, String a, String b) { return caseInsensitive ? eqic(a, b) : eq(a, b); } static public Set syncCompactSet() { return new CompactHashSet(); } static public String nemptyLinesLL(Object... l) { return nemptyLines(ll(l)); } static public Object getMigration(Object o) { return applyUntilEqual_goOneBackOnNull(o, x -> deref(getOpt("meta_migratedTo", x))); } static public String ahref_noFollow(String link, Object contents, Object... params) { return tag("a", contents, paramsPlus(params, "href", link, "rel", "nofollow")); } static public int poorMansProfiling_defaultInterval() { return 25; } static public String actualMCDollar() { return actualMC().getName() + "$"; } static public A inlineSwappable(String fieldName, Object host, IF0 defaultCalculation) { if (nempty(fieldName)) { IF0 replacement = (IF0) (getOpt(host, fieldName)); if (replacement != null) return replacement.get(); } return defaultCalculation.get(); } static public MultiSet toMultiSet(Iterable l) { return asMultiSet(l); } static public boolean startsWith_addingSlash(String a, String b) { return startsWith_addingSlash(a, b, null); } static public boolean startsWith_addingSlash(String a, String b, Matches m) { return startsWith(addSlash(a), addSlash(b), m); } static public String stackTraceToString(StackTraceElement[] st) { return lines(st); } static public String stackTraceToString(Throwable e) { return getStackTrace_noRecord(e); } static public void waitForQToEmpty(Q q) { if (q == null || inQ(q)) return; Flag flag = new Flag(); q.add(flag); flag.waitUntilUp(); } 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 List tok_integersAsLongs(String s) { return map(__115 -> parseLong(__115), tok_integers(s)); } static public String snippetURL(String id) { return snippetLink(id); } static public boolean addLibrariesToClassLoader(ClassLoader cl, Collection libIDs) { boolean change = false; for (String libID : unnullForIteration(libIDs)) change |= addLibraryToClassLoader(cl, libID); return change; } static public boolean inQ(Q q) { return isInQ(q); } static public Class actualMC() { return or((Class) realMC(), mc()); } static public long trailingLong_regexp(String s) { return parseLongOr0(regexpExtract("\\d+$", s)); } static public String addSlashSuffix(String s) { return addSlash(s); } 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 SimpleDateFormat simpleDateFormat_UTC(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf; } static public long nanoTime() { return System.nanoTime(); } 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 String regexpExtract(String pat, String s) { if (s == null) return null; Matcher m = regexpMatcher(pat, s); return m.find() ? m.group() : null; } static public String dynShortClassName(Object o) { return shortDynamicClassName(o); } static public String structure_convertTokenMarkersToExplicit(String s) { return join(structure_convertTokenMarkersToExplicit(javaTokForStructure(s))); } static public List structure_convertTokenMarkersToExplicit(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))); tok.set(i, "r" + substring(t, 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 A applyUntilEqual_goOneBackOnNull(IF1 f, A o) { while (true) { ping(); A o2 = f.get(o); if (o2 == null || eq(o, o2)) return o; o = o2; } } static public A applyUntilEqual_goOneBackOnNull(A o, IF1 f) { return applyUntilEqual_goOneBackOnNull(f, o); } static public MultiSet asMultiSet(Iterable l) { return new MultiSet(l); } static public List allToStrOrNull(Iterable c) { return lmap(__116 -> strOrNull(__116), c); } static public List allToStrOrNull(Object... c) { return lmap(__117 -> strOrNull(__117), c); } 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 String shortenStr(Object o) { return shorten_str(o); } static public String shortenStr(Object o, int max) { return shorten_str(o, max); } static public int countCodeTokens(String s) { return countTokens(s); } static public int countCodeTokens(List tok) { return countTokens(tok); } static public void fixConceptIDs() { fixConceptIDs(db_mainConcepts()); } static public void fixConceptIDs(Concepts cc) { if (cc == null) return; for (Map.Entry __0 : _entrySet(cc.concepts)) { long id = __0.getKey(); Concept c = __0.getValue(); if (id == 0) { print("0 concept key: " + c); continue; } if (c.id == id) continue; print("Fixing concept ID: " + c.id + " => " + id + ": " + c); c.id = id; } } static public String dropNumberPrefix(String s) { return dropFirst(s, indexOfNonDigit(s)); } static public int nCodeTokens(String s) { return countCodeTokens(s); } static public int nCodeTokens(List tok) { return countCodeTokens(tok); } static public String targetBlank_noFollow(String link, Object contents, Object... params) { return tag("a", contents, paramsPlus(params, "href", link, "target", "_blank", "rel", "nofollow")); } static public long firstLong_regexp(String s) { return parseLongOr0(regexpExtract("\\d+", s)); } static public List withoutInstancesOf(Iterable i, Class c) { List l = new ArrayList(); if (i == null) return l; c = primitiveToBoxedTypeOpt(c); for (A o : i) if (!isInstance(c, o)) l.add(o); return l; } static public List withoutInstancesOf(Class c, Iterable i) { return withoutInstancesOf(i, c); } static public void assertSameVerbose(Object x, Object y) { assertSameVerbose((String) null, x, y); } static public void assertSameVerbose(String msg, Object x, Object y) { if (x != y) throw fail((msg != null ? msg + ": " : "") + str_shorten(y) + " !== " + str_shorten(x)); else print("OK: " + str_shorten(x)); } static public Class getInnerClass(Class c, String name) { return getInnerClass(c, name, null); } static public Class getInnerClass(Class c, String name, Object classFinder) { return classForName(c.getName() + "$" + name, classFinder); } static public Class getInnerClass(Object o, String name) { return getInnerClass(o, name, null); } static public Class getInnerClass(Object o, String name, Object classFinder) { return getInnerClass(_getClass(o), name, classFinder); } static public Object realMC() { return getThreadLocal(realMC_tl()); } static public List deleteConceptsWhereCI(Class c, Object... params) { List l = cloneList(findConceptsWhereCI(c, params)); deleteConcepts(l); return l; } static public A ccopyFields_withConverter_pcall(Concept x, A y, String... fields) { if (x == null || y == null) return y; if (empty(fields)) { for (String field : conceptFields(x)) pcallF(() -> cSmartSetField_withConverter(y, field, cget(x, field))); } else for (String field : fields) { Object o = cget(x, field); if (o != null) pcallF(() -> cSmartSetField_withConverter(y, field, o)); } return y; } static public String getProgramURL() { return snippetLink(getProgramID()); } static public List allLiveMethodsBelowClass(Object o, Class base) { Class c = _getClass(o); boolean isInstance = c != o; List methods = new ArrayList(); while (c != null && c != base) { for (Method m : c.getDeclaredMethods()) if (isInstance != isStaticMethod(m)) methods.add(m); c = c.getSuperclass(); } return methods; } static public String dateWithSecondsUTC() { return dateWithSecondsUTC(now()); } static public String dateWithSecondsUTC(long time) { SimpleDateFormat format = simpleDateFormat_UTC("yyyy/MM/dd"); return format.format(time) + " " + formatUTCWithSeconds_24(time); } static public long parseLongOr0(String s) { return parseLong(s); } static public long parseLongOr0(Object s) { return parseLong(s); } static public double nsToMS(double nanoseconds) { return nanoseconds / 1e6; } 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 String afterSlash(String s) { return substring(s, smartIndexOf(s, '/') + 1); } 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 ahref_targetBlankIf(String link, Object contents, boolean targetBlank, Object... params) { return ahref_possiblyTargetBlank(link, contents, targetBlank, params); } static public String ahref_targetBlankIf(boolean targetBlank, String link, Object contents, Object... params) { return ahref_possiblyTargetBlank(targetBlank, link, contents, params); } static public Class main() { return getMainClass(); } static public String replaceDollarVars_js(String s, Object... __) { Map vars = paramsToMap_withNulls(__); if (empty(vars)) return s; var vars2 = mapKeys(__118 -> dropDollarPrefix(__118), vars); return replaceDollarVars_dyn(s, var -> { if (!vars2.containsKey(var)) return null; Object value = vars2.get(var); return jsonEncode_extended(value); }); } static public String js_replaceHTML(String html) { return replaceDollarVars_js("\r\n (function() {\r\n var target = document.querySelector(\"html\");\r\n target.innerHTML = $html;\r\n nodeScriptReplace(target);\r\n })(); ", "html", unnull(html)); } 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 Concept options(List l) { return l(l) == 1 ? first(l) : new Options(l); } static public String hjs_escapedDollarVars(String s, Object... __) { return hjs(replaceDollarVars_js(s, __)); } static public String html(Object contents) { return fixHTML(contents); } static public String replaceDollarVars2(String s, Object... params) { if (empty(params)) return s; Map vars = mapKeys(__119 -> dropDollarPrefix(__119), (Map) litcimap(params)); return replaceDollarVars2_dyn(s, var -> strOrNull(vars.get(var))); } static public String repeatString(String s, int n) { StringBuilder buf = new StringBuilder(l(s) * n); for (int i = 0; i < n; i++) buf.append(s); return str(buf); } static public String hreconnectingWebSockets_snippetID() { return "#2000597"; } static public Set syncWeakSet() { return synchroWeakHashSet(); } 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 String html_gazelle_madeByIcon() { return html_gazelle_madeByIcon(""); } static public String html_gazelle_madeByIcon(String link) { return html_gazelle_madeByIcon(link, ""); } static public String html_gazelle_madeByIcon(String link, String description) { return targetBlank(link, himgsnippet("#1103033", "style", "width: .8em; height: .8em", "title", "Object that created this" + (empty(description) ? "" : ": " + description))); } static public String repS(String s, int n) { return repeatString(s, n); } static public String repS(IF0 f, int n) { return join(repF(f, n)); } static public String repS(int n, String s) { return repS(s, n); } static public long lround(double d) { return Math.round(d); } static public long lround(Number n) { return lround(toDouble(n)); } static public void runWithExecutor(Runnable r, Executor e) { if (e == null) r.run(); else e.execute(r); } 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 String js_executeScriptElements() { return "\r\n function executeScriptElements(containerElement) {\r\n const scriptElements = containerElement.querySelectorAll(\"script\");\r\n \r\n Array.from(scriptElements).forEach((scriptElement) => {\r\n const clonedElement = document.createElement(\"script\");\r\n \r\n Array.from(scriptElement.attributes).forEach((attribute) => {\r\n clonedElement.setAttribute(attribute.name, attribute.value);\r\n });\r\n \r\n clonedElement.text = scriptElement.text;\r\n \r\n scriptElement.parentNode.replaceChild(clonedElement, scriptElement);\r\n });\r\n}\r\n "; } static public String jsonEvalMsg(String code, Object... __) { return jsonEncodeMap("eval", jsDollarVars(code, __)); } 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 Runnable runAndReturn(Runnable r) { callF(r); return r; } static public String hnoscript(Object contents) { return hfulltag("noscript", contents); } static public String js_nodeScriptReplace2() { return linesLL(js_executeScriptElements(), "var nodeScriptReplace = executeScriptElements;"); } static public List nonInstancesOf(Iterable i, Class c) { return withoutInstancesOf(i, c); } static public List nonInstancesOf(Class c, Iterable i) { return withoutInstancesOf(c, i); } 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 String hjssnippet(String snippetID, Object... __) { return hjavascript_src_snippet(snippetID, __); } 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 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 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 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 int ubyteToInt(byte b) { return b & 0x0FF; } static public int ubyteToInt(char c) { return c & 0x0FF; } 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 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 int limitToUByte(int i) { return max(0, min(255, i)); } 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 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 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(IntSize o) { return o == null ? 0 : o.size(); } 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 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 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 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 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 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 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 JScrollPane jscroll_copyBackground(Component c) { return setScrollPaneBackground(getBackground(c), jscroll(c)); } static public JFastLogView_noWrap jFastLogView_noWrap() { return jFastLogView_noWrap(""); } static public JFastLogView_noWrap jFastLogView_noWrap(String text) { return withTypeWriterFont(swingNu(JFastLogView_noWrap.class, text)); } static public String getPrintLog() { return str(print_log); } static public void dm_clearModulePrintLog() { clearStringBuffer_gen(dm_current_mandatory()._actualPrintLog()); } 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 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 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 StringBuffer liveLocalPrintLog_realMC(Object o) { Object realMC = getMainClass(o); if (realMC != mc()) return (StringBuffer) getOpt(realMC, "local_log"); return liveLocalPrintLog(); } static public Map humanizeKeys(Map map) { return mapKeys(__120 -> humanizeFormLabel(__120), map); } 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 List addDyn_sync(List l, A a) { if (l == null) l = synchroList(); l.add(a); 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 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 boolean sexyTable_drag = false; static public JTable sexyTable() { final JTable table = sexyTableWithoutDrag(); if (sexyTable_drag) tableEnableTextDrag(table); return table; } 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 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 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 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 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 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 boolean syncRemoveAll(Collection c, Collection b) { if (c == null || b == null) return false; synchronized (collectionMutex(c)) { return c.removeAll(b); } } 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 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 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 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 List syncListGetMulti(final List l, List indices) { synchronized (collectionMutex(l)) { return listGetMulti(l, indices); } } 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 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 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 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 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 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 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 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 void scrollTableDownNow(final JTable table) { if (table != null) { swing(() -> { table.scrollRectToVisible(table.getCellRect(table.getRowCount() - 1, 0, true)); }); } } 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 File printFileInfo(File f) { return printFileInfo("", f); } static public File printFileInfo(String s, File f) { print(s, renderFileInfo(f)); return f; } static public ImageSurface imageSurface(BufferedImage img) { return swingNu(ImageSurface.class, img); } static public ImageSurface imageSurface(MakesBufferedImage img) { return swingNu(ImageSurface.class, img); } static public ImageSurface imageSurface() { return swingNu(ImageSurface.class); } static public void imageSurface_pixelated(ImageSurface imageSurface) { if (imageSurface == null) return; imageSurface.setDoubleBuffered(true); imageSurface.noAlpha = true; imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR; repaint(imageSurface); } static public void imageSurface_pixelated(ImageSurface imageSurface, boolean pixelated) { if (pixelated) imageSurface_pixelated(imageSurface); else imageSurface_unpixelated(imageSurface); } static public JScrollPane jscroll_center(Component c) { return jscroll_centered(c); } 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 BufferedImage loadImage2(String snippetIDOrURL) { return loadBufferedImage(snippetIDOrURL); } static public BufferedImage loadImage2(File file) { return loadBufferedImage(file); } 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 void internalFramePopupMenuItem(Container f, final String name, final Object action) { internalFrameTitlePopupMenuItem(((JInternalFrame) f), name, action); } 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 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 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 Producer gzFileTokenReaderForUnstruct(File f) { return gzFileTokenReaderForUnstruct(f, null); } static public Producer gzFileTokenReaderForUnstruct(File f, CloseablesHolder closeablesHolder) { try { GZIPInputStream gis = newGZIPInputStream(f); BufferedReader bufferedReader = bufferedReader(utf8Reader(gis)); closeablesHolder.add(bufferedReader); return javaTokC_noMLS_onReader(bufferedReader); } catch (Exception __e) { throw rethrow(__e); } } static public Producer moveProducerToNewThread(Producer producer, CloseablesHolder ch) { return moveProducerToNewThread(producer, ch, 65536); } static public Producer moveProducerToNewThread(Producer producer, CloseablesHolder ch, int bufferSize) { if (producer == null) return null; SimpleCircularBuffer buffer = new SimpleCircularBuffer<>(bufferSize); Flag done = new Flag(); Var error = new Var(); ch.add(() -> done.raise()); startThread(new Runnable() { public void run() { try { try { A a; while (!done.isUp() && (a = producer.next()) != null) { ping(); while (buffer.isFull() && !done.isUp()) sleep(1); buffer.add(a); } } catch (Throwable e) { error.set(e); } finally { done.raise(); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n A a;\r\n while (!done.isUp() && (a = producer.next()) != nul..."; } }); return () -> { while (true) { boolean isDone = done.isUp(); A a = buffer.popFirst(); if (a != null) return a; if (isDone) return null; else sleep(1); } }; } 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 Object _onAWTEnter_f; static public AutoCloseable _onAWTEnter() { return (AutoCloseable) callF(_onAWTEnter_f); } static public IterableIterator emptyItIt() { return emptyIterableIterator(); } static public Map dangerousWeakMap() { return newDangerousWeakHashMap(); } static public Map dangerousWeakMap(Object initFunction) { return newDangerousWeakHashMap(initFunction); } static public A[] toArrayOfType(Class type, List l) { return (A[]) unnull(l).toArray(arrayOfType(type, l(l))); } static public A[] toArrayOfType(Class type, Iterable l) { return toArrayOfType(type, asList(l)); } static public RuntimeException asRuntimeException(Throwable t) { if (t instanceof Error) _handleError((Error) t); return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } 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 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 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 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 A withTypeWriterFont(A c) { return setFont(c, typeWriterFont()); } 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; 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 { 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 == 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; 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); } } 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 syncHashMap() { return synchroHashMap(); } 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 String format(String pat, Object... args) { return format3(pat, args); } 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 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 boolean isUnstructuring() { return isTrue(getTL(dynamicObjectIsLoading_threadLocal())); } 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 String fulltag(String tag) { return hfulltag(tag); } static public String fulltag(String tag, Object contents, Object... params) { return hfulltag(tag, contents, params); } static public Random defaultRandomizer() { return defaultRandomGenerator(); } static public JPanel marginPanel() { return jtransparent(borderLayoutPanel()); } 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 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 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 void indexConceptFields(Object... params) { int i = 0; Concepts concepts; if (first(params) instanceof Concepts) { concepts = (Concepts) first(params); ++i; } else concepts = db_mainConcepts(); for (; i < l(params); i += 2) indexConceptField(concepts, (Class) params[i], (String) params[i + 1]); } static public void newPing() { var tl = newPing_actionTL(); Runnable action = tl == null ? null : tl.get(); { if (action != null) action.run(); } } static public List wrapAsList(A[] a) { return wrapArrayAsList(a); } static public DynModule dm_current_mandatory() { return assertNotNull("No module set!", dm_currentModule()); } static public Object leftArrow(String script) { GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser(); parser.allowTheWorld(); return parser.parse(script).get(); } static public Object leftArrow(GazelleV_LeftArrowScriptParser parser, String script) { return parser.parse(script).get(); } 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 int lCharSequence(CharSequence s) { return s == null ? 0 : s.length(); } 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 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 boolean isTrueOrYes(Object o) { return isTrueOpt(o) || o instanceof String && (eqicOneOf(((String) o), "1", "t", "true") || isYes(((String) o))); } 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 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 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 float[] emptyFloatArray = new float[0]; static public float[] emptyFloatArray() { return emptyFloatArray; } static public List ourSubList_noRangeCheck(List l, int startIndex, int endIndex) { if (l instanceof RandomAccess) return new RandomAccessSubList(l, startIndex, endIndex); else return new SubList(l, startIndex, endIndex); } 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 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 Map castMapToMapO(Map map) { return map; } static public List asVirtualList(A[] a) { return wrapArrayAsList(a); } static public Dimension toDimension(WidthAndHeight wh) { return wh == null ? null : new Dimension(wh.getWidth(), wh.getHeight()); } 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 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(__121 -> getClassName(__121), args)); } static public void _onJavaXSet() { } 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 printWithMS(A a) { printWithMS("", a); } static public void printWithMS(String prefix, A a) { printWithMSTime(prefix, a); } 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 str_nullIfEmpty(Object o) { return nullIfEmpty(strOrNull(o)); } static public String hcommentSafe(String text) { return hcomment_unescaped(contains(text, "-->") ? htmlencode(text) : text); } static public String hiddenFields(Map map, Collection keys) { StringBuilder buf = new StringBuilder(); for (String key : keys) { String value = map.get(key); if (!empty(value)) buf.append(htag("input", "", "type", "hidden", "name", key, "value", value) + "\n"); } return str(buf); } static public String hiddenFields(Map map, String... keys) { return hiddenFields(map, asList(keys)); } static public A holdResource(IResourceHolder holder, A a) { { if (holder != null) holder.add(a); } return a; } 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 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 Runnable rPcall(Runnable r) { return r == null ? null : () -> { try { r.run(); } catch (Throwable __e) { pcallFail(__e); } }; } static public PingSource pingSource() { return pingSource_tl().get(); } static public PingSource pingSource(Thread thread) { return pingSource_tl().get(thread); } 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 byte[] md5AsByteArray(byte[] data) { try { return MessageDigest.getInstance("MD5").digest(data); } catch (Exception __e) { throw rethrow(__e); } } 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 A getAndClearTL(ThreadLocal tl) { return getAndClearThreadLocal(tl); } 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 NavigableMap synchroNavigableMap(NavigableMap map) { return new SynchronizedNavigableMap(map); } static public SortedMap synchroSortedMap(SortedMap map) { return new SynchronizedSortedMap(map); } 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 Object newMultiDimensionalOuterArray(Class elementType, int dimensions, int length) { int[] dims = new int[dimensions]; dims[0] = length; return Array.newInstance(elementType, dims); } 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 String dropLeadingDots(String s) { int i = 0; while (charAt(s, i) == '.') ++i; return dropFirst(s, i); } 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 void printStackTrace_inPossiblyCancelledThread(Throwable e) { AutoCloseable __1 = tempUncancelThread(); try { System.out.println(getStackTrace_noRecord(e)); } finally { _close(__1); } } static public String hinputtag(Object contents, Object... params) { return htag("input", contents, params); } 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 String appendColonIfNempty(String s) { return empty(s) ? "" : s + ": "; } static public Pair mapEntryToPair(Map.Entry e) { return e == null ? null : pair(e.getKey(), e.getValue()); } 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 IVF1 runnableToIVF1(Runnable r) { return r == null ? null : a -> r.run(); } static public String mainClassNameForClassLoader(ClassLoader cl) { return or((String) callOpt(cl, "mainClassName"), "main"); } static public String jarBotURL() { return "https://botcompany.de/jar/"; } static public String jarBotURL(String snippetID) { return jarBotURL() + psI(snippetID); } 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 List stdFunctionListSnippetIDs() { return ll("#1006654", "#761"); } static public boolean isRelativeOrAbsoluteURL(String s) { return isAbsoluteURL(s) || isRelativeURL(s); } 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 TreeSet asTreeSet(Collection set) { return set == null ? null : set instanceof TreeSet ? (TreeSet) set : new TreeSet(set); } 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 public A toComponent(A c) { return c; } static public Component toComponent(Swingable c) { return c == null ? null : c.visualize(); } 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 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 ITokCondition tokCondition(IIntPred condition) { return condition == null ? null : (tok, nIdx) -> condition.get(nIdx); } static public long timestampToLong(Timestamp ts) { return ts == null ? 0 : ts.date; } static public String programNameOrNull() { return replaceIfEqual(programName(), "?", null); } 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 Rect preferredScreenBounds() { return screenBounds_safe(preferredScreen()); } static public void bitSetSet(BitSet b, int bit) { setBit(b, bit); } static public Map mruCache(int maxSize) { return synchronizedMRUCache(maxSize); } static public B mapGetOrCreate(Map map, A key, Class c) { return getOrCreate(map, key, c); } static public B mapGetOrCreate(Map map, A key, Object f) { return getOrCreate(map, key, f); } static public B mapGetOrCreate(Map map, A key, IF0 f) { return getOrCreate(map, key, (Object) f); } static public B mapGetOrCreate(Class c, Map map, A key) { return getOrCreate(c, map, key); } static public Integer centerX(Rect r) { return rectCenterX(r); } 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 Integer centerY(Rect r) { return rectCenterY(r); } static public BufferedImage loadBufferedImageFile(File file) { try { if (!isFile(file)) return null; return ImageIO.read(file); } catch (Exception __e) { throw rethrow(__e); } } static public ThreadLocal threadLocalWithDefault(A defaultValue) { return new ThreadLocal() { public A initialValue() { return defaultValue; } }; } static public IterableIterator> ai_spreadCertainIndices_2_iterator(List tokPat, List tokS, List indices) { int extra = (l(tokS) - l(tokPat)) / 2; if (extra < 0 || empty(indices)) return emptyItIt(); return mapI(allSpreads(extra, l(indices)), spread -> { List tok = new ArrayList(); int pos = 0, iSpread = 0, iIndices = 0; for (int i = 0; i < l(tokPat); i++) if (!eq(get(indices, iIndices), i)) tok.add(tokS.get(pos++)); else { ++iIndices; int take = spread.get(iSpread++) * 2; tok.add(joinSubList(tokS, pos, pos + take + 1)); pos += take + 1; } return tok; }); } static public java.awt.Color color(String hex) { return awtColor(hex); } static public JButton basicJButton(String text) { return swing(() -> new JButton(text)); } 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 String localCourierFontName() { return isLinux() ? "Courier" : "Courier New"; } 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 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 DynModule dm_current() { return dm_currentModule(); } static public Number boxedIntOrLong(long l) { return l != (int) l ? boxed(l) : boxed((int) l); } static public Random getRandomizer(Random r) { return r != null ? r : defaultRandomGenerator(); } static public Pair entryToPair(Map.Entry e) { return mapEntryToPair(e); } static public Set> entries(Map map) { return _entrySet(map); } static public Map synchronizedMap() { return synchroMap(); } static public Map synchronizedMap(Map map) { return synchroMap(map); } 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 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 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 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 double floor(double d) { return Math.floor(d); } static public Object dm_transpiler() { return dm_getModule(dm_requireModule("#1017065/Transpiler")); } static public String dataURL(String mimeType, byte[] data) { return "data:" + mimeType + ";base64," + base64(data); } static public String jpegMimeType() { return "image/jpeg"; } static public byte[] toJPEG(BufferedImage img) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ImageIO.write(dropAlphaChannelFromBufferedImage(img), "jpeg", stream); return stream.toByteArray(); } catch (Exception __e) { throw rethrow(__e); } } static public byte[] toJPEG(File f) { return toJPEG(loadImage2(f)); } static public JComponent wrapForSmartAdd_jComponent(Object o) { return componentToJComponent(wrapForSmartAdd(o)); } 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 IF2 if0ToIF2(IF0 f) { return f == null ? null : (a, b) -> f.get(); } static public Object[] paramsMinus(Object[] a1, Object... keys) { return paramsWithout(a1, keys); } 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 IntRange cncCorrect(IntRange r) { return r == null ? null : new IntRange(r.start & ~1, r.end | 1); } static public Random customRandomizerForThisThread() { return customRandomizerForThisThread_tl().get(); } static public > List getVars(Iterable l) { return lambdaMap(__122 -> getVar(__122), l); } static public Producer javaTokC_producer(String s) { return javaTokC_iterator(s); } static public _MethodCache getMethodCache(Class c) { return callOpt_getCache(c); } static public byte[] emptyByteArray_a = new byte[0]; static public byte[] emptyByteArray() { return emptyByteArray_a; } 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 Concepts concepts(Concept c) { return c == null ? null : c._concepts; } 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 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 String jsDollarVars(String s, Object... __) { return replaceDollarVars_js(s, __); } static public void appendToLocalMechLog(String listName, String text) { logMechListAppendLocally(listName, text); } static public List dropSecondIfEmpty(String a, String b) { return empty(b) ? ll(a) : ll(a, b); } 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 setSCPComponent(SingleComponentPanel scp, Component c) { if (scp != null) scp.setComponent(c); } 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 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 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 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 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 A shallowCloneToClass(Class c, Object o) { if (o == null) return null; A a = nuInstance(c); copyFields(o, a); return a; } 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 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 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 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 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 JLabel jimage(Image img) { return jImageLabel(img); } static public JLabel jimage(String imageID) { return jImageLabel(imageID); } 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 JScrollPane setScrollPaneBackground(Color c, JScrollPane sp) { if (sp != null && c != null) { swing(() -> { sp.getViewport().setBackground(c); }); } return sp; } static public Color getBackground(final Component c) { return c == null ? null : swing(new F0() { public Color get() { try { return c.getBackground(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return c.getBackground();"; } }); } static public void clearStringBuffer_gen(Object buf) { if (buf != null) { call(buf, "setLength", 0); call(buf, "trimToSize"); } } 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 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 StringBuffer liveLocalPrintLog() { return local_log; } static public List listWithoutSet(Collection l, Collection stuff) { return listMinusSet(l, stuff); } 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 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 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 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 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 SingleComponentPanel scp() { return singleComponentPanel(); } static public SingleComponentPanel scp(Component c) { return singleComponentPanel(c); } 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 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 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 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 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); } 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 JPanel northAndCenter(Component n, Component c) { return centerAndNorth(c, n); } 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 Pt pt(int x, int y) { return new Pt(x, y); } static public Pt pt(int x) { return new Pt(x, x); } static public Point toPoint(Pt p) { return p == null ? null : new Point(p.x, p.y); } static public int tableRows(JTable table) { return (int) swingCall(table, "getRowCount"); } 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 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 void scrollRowToVisible(JTable t, int rowIndex) { int colIndex = 0; if (!(t.getParent() instanceof JViewport)) return; JViewport viewport = (JViewport) t.getParent(); Rectangle rect = t.getCellRect(rowIndex, colIndex, true); Rectangle viewRect = viewport.getViewRect(); int x = viewRect.x; int y = viewRect.y; if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)) { } else if (rect.x < viewRect.x) { x = rect.x; } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) { x = rect.x - viewRect.width + rect.width; } if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)) { } else if (rect.y < viewRect.y) { y = rect.y; } else if (rect.y > (viewRect.y + viewRect.height - rect.height)) { y = rect.y - viewRect.height + rect.height; } viewport.setViewPosition(new Point(x, y)); } static public int listRowCount(JList list) { return list == null ? 0 : swing(new F0() { public Integer get() { try { return list.getModel().getSize(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return list.getModel().getSize();"; } }); } 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 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 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 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 String hmsWithColonsAndMS() { return hmsWithColonsAndMS(now()); } static public String hmsWithColonsAndMS(long time) { return simpleDateFormat_local("HH:mm:ss:SSS").format(time); } 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 A repaint(A c) { if (c != null) c.repaint(); return c; } static public void imageSurface_unpixelated(ImageSurface imageSurface) { if (imageSurface == null) return; imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_BILINEAR; repaint(imageSurface); } static public JScrollPane jscroll_centered(Component c) { return c instanceof JScrollPane ? ((JScrollPane) c) : jscroll(jFullCenter(c)); } 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 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 String copyTextToClipboardIfNotNull(String text) { if (text != null) copyTextToClipboard(text); return text; } static public BufferedReader utf8Reader(InputStream in) { return utf8BufferedReader(in); } static public BufferedReader utf8Reader(File f) { return utf8BufferedReader(f); } 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 int tableColumnCount(JTable table) { return tableNumColumns(table); } 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 IterableIterator emptyIterableIterator_instance = new IterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; static public IterableIterator emptyIterableIterator() { return emptyIterableIterator_instance; } static public A printException(A e) { printStackTrace(e); return e; } 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 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 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 String commaCombine(Object... l) { return joinNemptiesWithComma(flattenCollectionsAndArrays(l)); } static public boolean isJavaXClassName(String s) { return isJavaXClassName(s, "main$"); } static public boolean isJavaXClassName(String s, String mcDollar) { return startsWithOneOf(s, mcDollar, "loadableUtils."); } 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 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 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 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 A jtransparent(final A a) { { swing(() -> { a.setOpaque(false); }); } return a; } static public JPanel borderLayoutPanel() { return jpanel(new BorderLayout()); } static public Set createOrAddToSyncLinkedHashSet(Set set, A a) { if (set == null) set = syncLinkedHashSet(); set.add(a); return set; } 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 x30_pkg.x30_util.BetterThreadLocal newPing_actionTL; static public x30_pkg.x30_util.BetterThreadLocal newPing_actionTL() { if (newPing_actionTL == null) newPing_actionTL = vm_generalMap_getOrCreate("newPing_actionTL", () -> { Runnable value = (Runnable) (callF_gen(vm_generalMap_get("newPing_valueForNewThread"))); var tl = new x30_pkg.x30_util.BetterThreadLocal(); tl.set(value); return tl; }); return newPing_actionTL; } static public List wrapArrayAsList(A[] a) { return a == null ? null : Arrays.asList(a); } 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 List screenDevices() { return asList(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()); } static public void printWithMSTime(A a) { printWithMSTime("", a); } static public void printWithMSTime(String prefix, A a) { print(hmsWithColonsAndMS() + ": " + combinePrintParameters(prefix, a)); } static public String hcomment_unescaped(String text) { return ""; } 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 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 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 AutoCloseable tempUncancelThread() { return tempRemove(ping_actions, Thread.currentThread()); } static public List standardClassesSnippetIDs() { return ll("#1003674", "#1034167"); } static public boolean isAbsoluteURL(String s) { return isURL(s); } static public boolean isRelativeURL(String s) { return startsWithOneOf(s, "/", "./", "../"); } 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 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 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 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 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 Rect screenBounds_safe(int iScreen) { return screenBounds(min(iScreen, screenCount() - 1)); } 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 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 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 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 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 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 Integer boxed(int i) { return i; } static public Long boxed(long l) { return l; } static public BufferedReader utf8BufferedReader(InputStream in) { return utf8bufferedReader(in); } static public BufferedReader utf8BufferedReader(File f) { return utf8bufferedReader(f); } 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 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 String base64(byte[] a) { return base64encode(a); } static public BufferedImage dropAlphaChannelFromBufferedImage(BufferedImage img) { if (img == null || img.getType() == BufferedImage.TYPE_INT_RGB) return img; int w = img.getWidth(), h = img.getHeight(); BufferedImage newImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); int[] rgb = img.getRGB(0, 0, w, h, null, 0, w); newImage.setRGB(0, 0, w, h, rgb, 0, w); return newImage; } static public ThreadLocal customRandomizerForThisThread_tl = new ThreadLocal(); static public ThreadLocal customRandomizerForThisThread_tl() { return customRandomizerForThisThread_tl; } 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 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 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 String nohup_sanitize(String s) { return empty(s) ? s : takeFirst(50, s.replaceAll("[^.a-zA-Z0-9\\-_]", "")); } 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"); } 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 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 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 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 PCallPolicy defaultPCallPolicy = __1 -> printStackTrace(__1); static public PCallPolicy defaultPCallPolicy() { return defaultPCallPolicy; } static public void defaultPCallPolicy_set(PCallPolicy policy) { defaultPCallPolicy = policy; } static public A nuInstance(Class c) { return nuEmptyObject(c); } 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 IF0 f0ToIF0(F0 f) { return f == null ? null : () -> f.get(); } static public void addMenuItems(JMenu m, Object... x) { fillJMenu(m, x); } static public void addMenuItems(JPopupMenu m, Object... x) { fillJPopupMenu(m, x); } static public File toFile_nullOnEmpty(String s) { return empty(s) ? null : new File(s); } static public void setTrayIconToolTip(TrayIcon trayIcon, String toolTip) { if (trayIcon != null) trayIcon.setToolTip(toolTip); } 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 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 boolean allPaused() { return ping_pauseAll; } 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 String toStringOpt(Object o) { return o instanceof String ? ((String) o) : null; } 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 void setAddAll(Collection a, Collection b) { for (A x : b) setAdd(a, x); } 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 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 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 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 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 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 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 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 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 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 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 File tempFileFor(File f) { return new File(f.getPath() + "_temp"); } 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 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 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 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 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 joinNemptiesWithComma(Object... strings) { return joinNempties(", ", strings); } static public String joinNemptiesWithComma(Iterable strings) { return joinNempties(", ", strings); } 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 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 isArrayType(Class type) { return type != null && type.isArray(); } 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 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 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 A callF_gen(F0 f) { return f == null ? null : f.get(); } static public B callF_gen(F1 f, A a) { return f == null ? null : f.get(a); } static public A callF_gen(IF0 f) { return f == null ? null : f.get(); } static public B callF_gen(IF1 f, A a) { return f == null ? null : f.get(a); } static public B callF_gen(A a, IF1 f) { return f == null ? null : f.get(a); } static public C callF_gen(F2 f, A a, B b) { return f == null ? null : f.get(a, b); } static public C callF_gen(IF2 f, A a, B b) { return f == null ? null : f.get(a, b); } static public void callF_gen(VF1 f, A a) { { if (f != null) f.get(a); } } static public void callF_gen(A a, IVF1 f) { { if (f != null) f.get(a); } } static public void callF_gen(IVF1 f, A a) { { if (f != null) f.get(a); } } static public Object callF_gen(Runnable r) { { if (r != null) r.run(); } return null; } static public Object callF_gen(Object f, Object... args) { return callF(f, args); } static public 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 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 String firstWord2(String s) { s = xltrim(s); if (empty(s)) return ""; if (isLetterOrDigit(first(s))) return takeCharsWhile(__123 -> isLetterOrDigit(__123), s); else return "" + first(s); } 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 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 AutoCloseable tempRemove(Map map, A key) { if (map == null || !map.containsKey(key)) return null; B b = map.get(key); map.remove(key); return new AutoCloseable() { public String toString() { return "map.put(key, b);"; } public void close() throws Exception { map.put(key, b); } }; } 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 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 int screenCount() { return l(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()); } static public Throwable _storeException_value; static public void _storeException(Throwable e) { _storeException_value = e; } static public String base64encode(byte[] a) { int aLen = a.length; int numFullGroups = aLen / 3; int numBytesInPartialGroup = aLen - 3 * numFullGroups; int resultLen = 4 * ((aLen + 2) / 3); StringBuffer result = new StringBuffer(resultLen); char[] intToAlpha = intToBase64; int inCursor = 0; for (int i = 0; i < numFullGroups; i++) { int byte0 = a[inCursor++] & 0xff; int byte1 = a[inCursor++] & 0xff; int byte2 = a[inCursor++] & 0xff; result.append(intToAlpha[byte0 >> 2]); result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]); result.append(intToAlpha[(byte1 << 2) & 0x3f | (byte2 >> 6)]); result.append(intToAlpha[byte2 & 0x3f]); } if (numBytesInPartialGroup != 0) { int byte0 = a[inCursor++] & 0xff; result.append(intToAlpha[byte0 >> 2]); if (numBytesInPartialGroup == 1) { result.append(intToAlpha[(byte0 << 4) & 0x3f]); result.append("=="); } else { int byte1 = a[inCursor++] & 0xff; result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]); result.append(intToAlpha[(byte1 << 2) & 0x3f]); result.append('='); } } return result.toString(); } static final public char[] intToBase64 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; static public 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 String platformQuote(String s) { return isWindows() ? winQuote(s) : bashQuote(s); } static public String platformQuote(File f) { return platformQuote(f2s(f)); } static public boolean isOnPATH(String cmd) { return findCmdOnPATH(cmd) != null; } 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 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 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 void swingNowOrLater(Runnable r) { if (isAWTThread()) r.run(); else swingLater(r); } 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 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 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 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 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 Map weakMap() { return newWeakHashMap(); } 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 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 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 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 long twoIntsToLong(int a, int b) { return (((long) a) << 32) | (((long) b) & 0xFFFFFFFFL); } 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 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 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 int menuItemCount(JMenu menu) { return menu == null ? 0 : swing(() -> menu.getItemCount()); } 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); } 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 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 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); } } static public class DefunctClassLoader { } 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, final 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()"; } }); addMenuItem(menu, "Point: " + point.x + "," + point.y + " (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, "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() { } 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 ConceptClassesDependentValue extends Cache { public Concepts cc = db_mainConcepts(); public ConceptClassesDependentValue(Collection types, IF0 calculate) { super(calculate); onConceptChangeByClasses_notOnAllChanged(cc, types, new Runnable() { public void run() { try { clear(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "clear();"; } }); } } static public class ConceptsRefChecker { public Concepts cc; public List errors = new ArrayList(); public boolean veryVerbose = false; static public class Err { } static public class ErrNoBackRef extends Err implements IFieldsToList { static final public String _fieldOrder = "ref dest"; public Concept.Ref ref; public Concept dest; public ErrNoBackRef() { } public ErrNoBackRef(Concept.Ref ref, Concept dest) { this.dest = dest; this.ref = ref; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + ref + ", " + dest + ")"; } public boolean equals(Object o) { if (!(o instanceof ErrNoBackRef)) return false; ErrNoBackRef __1 = (ErrNoBackRef) o; return eq(ref, __1.ref) && eq(dest, __1.dest); } public int hashCode() { int h = -1351603866; h = boostHashCombine(h, _hashCode(ref)); h = boostHashCombine(h, _hashCode(dest)); return h; } public Object[] _fieldsToList() { return new Object[] { ref, dest }; } } static public class ErrSuperfluousBackRef extends Err implements IFieldsToList { static final public String _fieldOrder = "ref dest"; public Concept.Ref ref; public Concept dest; public ErrSuperfluousBackRef() { } public ErrSuperfluousBackRef(Concept.Ref ref, Concept dest) { this.dest = dest; this.ref = ref; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + ref + ", " + dest + ")"; } public boolean equals(Object o) { if (!(o instanceof ErrSuperfluousBackRef)) return false; ErrSuperfluousBackRef __2 = (ErrSuperfluousBackRef) o; return eq(ref, __2.ref) && eq(dest, __2.dest); } public int hashCode() { int h = 1840777816; h = boostHashCombine(h, _hashCode(ref)); h = boostHashCombine(h, _hashCode(dest)); return h; } public Object[] _fieldsToList() { return new Object[] { ref, dest }; } } static public class ErrDuplicateRef extends Err implements IFieldsToList { public Concept c; public ErrDuplicateRef() { } public ErrDuplicateRef(Concept c) { this.c = c; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + c + ")"; } public boolean equals(Object o) { if (!(o instanceof ErrDuplicateRef)) return false; ErrDuplicateRef __3 = (ErrDuplicateRef) o; return eq(c, __3.c); } public int hashCode() { int h = 1148352877; h = boostHashCombine(h, _hashCode(c)); return h; } public Object[] _fieldsToList() { return new Object[] { c }; } } static public class ErrNullRef extends Err implements IFieldsToList { public Concept c; public ErrNullRef() { } public ErrNullRef(Concept c) { this.c = c; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + c + ")"; } public boolean equals(Object o) { if (!(o instanceof ErrNullRef)) return false; ErrNullRef __4 = (ErrNullRef) o; return eq(c, __4.c); } public int hashCode() { int h = 209467527; h = boostHashCombine(h, _hashCode(c)); return h; } public Object[] _fieldsToList() { return new Object[] { c }; } } static public class ErrMissingRef extends Err implements IFieldsToList { public Concept c; public Concept.Ref ref; public ErrMissingRef() { } public ErrMissingRef(Concept c, Concept.Ref ref) { this.ref = ref; this.c = c; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + c + ", " + ref + ")"; } public boolean equals(Object o) { if (!(o instanceof ErrMissingRef)) return false; ErrMissingRef __5 = (ErrMissingRef) o; return eq(c, __5.c) && eq(ref, __5.ref); } public int hashCode() { int h = 1969969266; h = boostHashCombine(h, _hashCode(c)); h = boostHashCombine(h, _hashCode(ref)); return h; } public Object[] _fieldsToList() { return new Object[] { c, ref }; } } static public class ErrSuperfluousRef extends Err implements IFieldsToList { public Concept c; public Concept.Ref ref; public ErrSuperfluousRef() { } public ErrSuperfluousRef(Concept c, Concept.Ref ref) { this.ref = ref; this.c = c; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + c + ", " + ref + ")"; } public boolean equals(Object o) { if (!(o instanceof ErrSuperfluousRef)) return false; ErrSuperfluousRef __6 = (ErrSuperfluousRef) o; return eq(c, __6.c) && eq(ref, __6.ref); } public int hashCode() { int h = 762378943; h = boostHashCombine(h, _hashCode(c)); h = boostHashCombine(h, _hashCode(ref)); return h; } public Object[] _fieldsToList() { return new Object[] { c, ref }; } } static public class ErrDanglingSource extends Err implements IFieldsToList { static final public String _fieldOrder = "ref dest"; public Concept.Ref ref; public Concept dest; public ErrDanglingSource() { } public ErrDanglingSource(Concept.Ref ref, Concept dest) { this.dest = dest; this.ref = ref; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + ref + ", " + dest + ")"; } public boolean equals(Object o) { if (!(o instanceof ErrDanglingSource)) return false; ErrDanglingSource __7 = (ErrDanglingSource) o; return eq(ref, __7.ref) && eq(dest, __7.dest); } public int hashCode() { int h = 666937292; h = boostHashCombine(h, _hashCode(ref)); h = boostHashCombine(h, _hashCode(dest)); return h; } public Object[] _fieldsToList() { return new Object[] { ref, dest }; } } static public class ErrDanglingDestination extends Err implements IFieldsToList { static final public String _fieldOrder = "ref dest"; public Concept.Ref ref; public Concept dest; public ErrDanglingDestination() { } public ErrDanglingDestination(Concept.Ref ref, Concept dest) { this.dest = dest; this.ref = ref; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + ref + ", " + dest + ")"; } public boolean equals(Object o) { if (!(o instanceof ErrDanglingDestination)) return false; ErrDanglingDestination __8 = (ErrDanglingDestination) o; return eq(ref, __8.ref) && eq(dest, __8.dest); } public int hashCode() { int h = -1158731011; h = boostHashCombine(h, _hashCode(ref)); h = boostHashCombine(h, _hashCode(dest)); return h; } public Object[] _fieldsToList() { return new Object[] { ref, dest }; } } public ConceptsRefChecker() { } public ConceptsRefChecker(Concepts cc) { this.cc = cc; } public List run() { errors.clear(); if (cc == null) return errors; Collection concepts = cc.allConcepts(); if (veryVerbose) print("Checking " + nConcepts(concepts)); for (Concept c : concepts) try { Object badElement = firstElementNotSubclassing(c.backRefs, Concept.Ref.class); if (badElement != null) { print("Bad element in backRefs of " + c + ": " + badElement); continue; } for (Concept.Ref ref : cloneList(c.backRefs)) { if (ref.get() != c) errors.add(new ErrSuperfluousBackRef(ref, c)); if (ref.concept()._concepts != cc) errors.add(new ErrDanglingSource(ref, c)); } Collection refs = c._refs(); badElement = firstElementNotSubclassing(refs, Concept.Ref.class); if (badElement != null) { print("Bad element in backRefs of " + c + ": " + badElement); continue; } if (!allUnique(refs)) errors.add(new ErrDuplicateRef(c)); if (contains(refs, null)) errors.add(new ErrNullRef(c)); refs = nonNulls(refs); Collection actualRefs = scanConceptForRefs(c); for (Concept.Ref ref : listMinusSet(refs, actualRefs)) errors.add(new ErrSuperfluousRef(c, ref)); for (Concept.Ref ref : listMinusSet(actualRefs, refs)) errors.add(new ErrMissingRef(c, ref)); for (Concept.Ref ref : refs) if (ref.has()) { if (!contains(ref.get().backRefs, ref)) errors.add(new ErrNoBackRef(ref, c)); if (ref.get()._concepts != cc) errors.add(new ErrDanglingDestination(ref, c)); } } catch (Throwable e) { printStackTrace(e); print("Error processing concept " + c); } return errors; } public List errors() { return errors; } public String fixAll() { List out = new ArrayList(); for (Err err : reversed(cloneAndClear(errors))) { try { out.add("Processing " + err); if (err instanceof ErrNoBackRef) { ((ErrNoBackRef) err).ref.index(); out.add(" reference added"); } else if (err instanceof ErrSuperfluousRef) { ((ErrSuperfluousRef) err).ref.unindexAndDrop(); out.add(" reference dropped"); } else if (err instanceof ErrDanglingSource) { ((ErrDanglingSource) err).ref.get()._removeBackRef(((ErrDanglingSource) err).ref); out.add(" reference removed from destination"); } else if (err instanceof ErrDanglingDestination) { ((ErrDanglingDestination) err).ref.get()._removeBackRef(((ErrDanglingDestination) err).ref); out.add(" reference removed from destination"); } else if (err instanceof ErrMissingRef) { ((ErrMissingRef) err).ref.registerRef(); out.add(" reference registered"); } else if (err instanceof ErrSuperfluousBackRef) { ((ErrSuperfluousBackRef) err).dest._removeBackRef(((ErrSuperfluousBackRef) err).ref); out.add(" backreference dropped"); } else out.add(" TODO - fix not implemented"); } catch (Throwable __e) { pcallFail(__e); } } return lines(out); } public String runAndFixAll() { run(); return fixAll(); } } 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 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 SortedMap 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; 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; } 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) { print("Concept save failed, will try again"); printStackTrace(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()) 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 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 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(); } } } 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 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 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 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"); } } 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; } } 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 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 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 RiddleWithSolution implements IFieldsToList { public Riddle riddle; public Solution solution; public RiddleWithSolution() { } public RiddleWithSolution(Riddle riddle, Solution solution) { this.solution = solution; this.riddle = riddle; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + riddle + ", " + solution + ")"; } public boolean equals(Object o) { if (!(o instanceof RiddleWithSolution)) return false; RiddleWithSolution __1 = (RiddleWithSolution) o; return eq(riddle, __1.riddle) && eq(solution, __1.solution); } public int hashCode() { int h = -1620977329; h = boostHashCombine(h, _hashCode(riddle)); h = boostHashCombine(h, _hashCode(solution)); return h; } public Object[] _fieldsToList() { return new Object[] { riddle, solution }; } } 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 Hasher { public int hashCode(A a); public boolean equals(A a, A b); } static public class ExpiringMap2 extends AbstractMap { public Map> byKey = new HashMap(); public PriorityBlockingQueue> queue = new PriorityBlockingQueue(); public long standardExpiryTime; public boolean renewOnOverwrite = true, renewOnGet; public Object onChange; public boolean useCountdown = true; public RestartableCountdown countdown = new RestartableCountdown(); public ExpiringMap2() { } public ExpiringMap2(long standardExpiryTime) { this.standardExpiryTime = standardExpiryTime; } public ExpiringMap2(long standardExpiryTime, Object onChange) { this.onChange = onChange; this.standardExpiryTime = standardExpiryTime; } public ExpiringMap2(double standardExpirySeconds) { standardExpiryTime = toMS(standardExpirySeconds); } synchronized public boolean clean() { boolean changes = false; Pair p; long time = sysTime(); while ((p = queue.peek()) != null && time >= p.a) { if (useCountdown) countdown.stop(); p = queue.poll(); Pair v = byKey.get(p.b); if (v != null) { byKey.remove(p.b); changes = true; change(); } } if (useCountdown) countdown.setTargetTime(p != null ? p.a : 0, new Runnable() { public void run() { try { clean(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "clean();"; } }); return changes; } public void change() { callF(onChange); } synchronized public B put(A a, B b) { clean(); long timeout = sysTime() + standardExpiryTime; Pair p = byKey.get(a); if (p != null && renewOnOverwrite) queue.remove(new Pair(p.a, a)); byKey.put(a, pair(timeout, b)); change(); if (p == null || renewOnOverwrite) queue.add(new Pair(timeout, a)); return pairB(p); } synchronized public B remove(Object a) { clean(); Pair p = byKey.get(a); if (p == null) return null; queue.remove(new Pair(p.a, a)); byKey.remove(a); change(); return p.b; } synchronized public B get(Object a) { clean(); Pair p = byKey.get(a); if (renewOnGet && p != null) { queue.remove(new Pair(p.a, a)); long timeout = sysTime() + standardExpiryTime; byKey.put((A) a, pair(timeout, p.b)); queue.add(new Pair(timeout, a)); } return pairB(p); } synchronized public Set> entrySet() { clean(); return synchronizedSet(mapValues(__124 -> pairB(__124), byKey).entrySet()); } synchronized public Set keySet() { clean(); return synchronizedSet(byKey.keySet()); } synchronized public int size() { clean(); return byKey.size(); } public void setStandardExpiryTime(long ms) { standardExpiryTime = ms; } synchronized public ExpiringMap2 setMap(Map innerMap) { byKey = innerMap; return this; } } static abstract public class CloseableIterableIterator extends IterableIterator implements AutoCloseable { public void close() throws Exception { } } static public interface IFieldsToList { public Object[] _fieldsToList(); } 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); } } public interface Enterable { public AutoCloseable enter(); } 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 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 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 HCRUD_Concepts extends HCRUD_Data { public Concepts cc = db_mainConcepts(); public Class cClass; public List> onCreateOrUpdate = new ArrayList(); public List> onCreate = new ArrayList(); public IVF2> afterUpdate; public Map filters; public Map ciFilters; public IF1, Collection> customFilter; public ValueConverterForField valueConverter; public boolean referencesBlockDeletion = false; public boolean trimAllSingleLineValues = false; public Set fieldsToHideInCreationForm; public boolean lockDB = false; public boolean verbose = false; public boolean dropEmptyListValues = true; public boolean lsMagic = false; public boolean convertConceptValuesToRefs = false; public A currentConcept; public boolean useDynamicComboBoxes = false; public IF1 useDynamicComboBoxesForField; public int dynamicComboBoxesThreshold = 1000; public HCRUD_Concepts(Class cClass) { this.cClass = cClass; } public HCRUD_Concepts(Concepts cc, Class cClass) { this.cClass = cClass; this.cc = cc; } transient public IF0 itemName; public String itemName() { return itemName != null ? itemName.get() : itemName_base(); } final public String itemName_fallback(IF0 _f) { return _f != null ? _f.get() : itemName_base(); } public String itemName_base() { return humanizeShortName(cClass); } transient public IF0 itemNamePlural; public String itemNamePlural() { return itemNamePlural != null ? itemNamePlural.get() : itemNamePlural_base(); } final public String itemNamePlural_fallback(IF0 _f) { return _f != null ? _f.get() : itemNamePlural_base(); } public String itemNamePlural_base() { return super.itemNamePlural(); } public List itemsForListing() { return defaultSort(asList(listConcepts())); } @Override public List> list() { return lazyMap(itemsForListing(), a -> new Item(str(a.id)) { public Map calcFullMap() { return itemToMapForList(a); } }); } @Override public List> list(IntRange range) { return lambdaMap(__125 -> itemToMapForList(__125), subListOrFull(itemsForListing(), range)); } public Collection listConcepts() { Collection l = listConcepts_firstStep(); return postProcess(customFilter, l); } transient public IF0> listConcepts_firstStep; public Collection listConcepts_firstStep() { return listConcepts_firstStep != null ? listConcepts_firstStep.get() : listConcepts_firstStep_base(); } final public Collection listConcepts_firstStep_fallback(IF0> _f) { return _f != null ? _f.get() : listConcepts_firstStep_base(); } public Collection listConcepts_firstStep_base() { if (empty(ciFilters)) return conceptsWhere(cc, cClass, mapToParams(filters)); else if (empty(filters)) return conceptsWhereCI(cc, cClass, mapToParams(ciFilters)); else { Collection l = conceptsWhere(cc, cClass, mapToParams(filters)); return filterConceptsIC(l, mapToParams(ciFilters)); } } transient public IF0> defaultSortField; public Pair defaultSortField() { return defaultSortField != null ? defaultSortField.get() : defaultSortField_base(); } final public Pair defaultSortField_fallback(IF0> _f) { return _f != null ? _f.get() : defaultSortField_base(); } public Pair defaultSortField_base() { return pair("id", true); } transient public IF1, List> defaultSort; public List defaultSort(List l) { return defaultSort != null ? defaultSort.get(l) : defaultSort_base(l); } final public List defaultSort_fallback(IF1, List> _f, List l) { return _f != null ? _f.get(l) : defaultSort_base(l); } public List defaultSort_base(List l) { return sortedByConceptIDDesc(l); } transient public IF0 emptyConcept; public A emptyConcept() { return emptyConcept != null ? emptyConcept.get() : emptyConcept_base(); } final public A emptyConcept_fallback(IF0 _f) { return _f != null ? _f.get() : emptyConcept_base(); } public A emptyConcept_base() { return unlisted(cClass); } transient public IF0> emptyObject; public Map emptyObject() { return emptyObject != null ? emptyObject.get() : emptyObject_base(); } final public Map emptyObject_fallback(IF0> _f) { return _f != null ? _f.get() : emptyObject_base(); } public Map emptyObject_base() { A c = emptyConcept(); Map map = itemToMap(c); return mapMinusKeys(fieldsToHideInCreationForm, map); } public Map itemToMap(A c) { if (c == null) return null; return putKeysFirst(getFieldOrder(c), conceptToMap_gen_withNullValues(c)); } public Map itemToMapForList(A c) { if (c == null) return null; Map map = itemToMap(c); massageItemMapForList(c, map); return map; } transient public IVF2> massageItemMapForList; public void massageItemMapForList(A c, Map map) { if (massageItemMapForList != null) massageItemMapForList.get(c, map); else massageItemMapForList_base(c, map); } final public void massageItemMapForList_fallback(IVF2> _f, A c, Map map) { if (_f != null) _f.get(c, map); else massageItemMapForList_base(c, map); } public void massageItemMapForList_base(A c, Map map) { } transient public IVF2> massageItemMapForUpdate; public void massageItemMapForUpdate(A c, Map map) { if (massageItemMapForUpdate != null) massageItemMapForUpdate.get(c, map); else massageItemMapForUpdate_base(c, map); } final public void massageItemMapForUpdate_fallback(IVF2> _f, A c, Map map) { if (_f != null) _f.get(c, map); else massageItemMapForUpdate_base(c, map); } public void massageItemMapForUpdate_base(A c, Map map) { Collection refLFields = nonStaticNonTransientFieldObjectsOfType(Concept.RefL.class, c); printVars_str("refLFields", refLFields, "c", c); for (Field f : refLFields) { TreeMap values = new TreeMap(); Matches m = new Matches(); for (Map.Entry __2 : _entrySet(cloneMap(map))) { String key = __2.getKey(); Object value = __2.getValue(); if (startsWith(key, f.getName() + "_", m) && isInteger(m.rest())) { Concept concept = getConceptFromString((String) value); if (concept != null || !dropEmptyListValues) values.put(parseInt(m.rest()), concept); map.remove(key); } } if (!dropEmptyListValues) while (nempty(values) && lastValue(values) == null) { if (verbose) print("Dropping value " + lastEntry(values)); removeLastKey(values); } map.put(f.getName(), valuesAsList(values)); } for (String name : cloneKeys(map)) { String metaInfo = metaInfoFromForm(name); print("metaInfo for " + name + ": " + metaInfo); if (eqic(metaInfo, "concept")) replaceStringValueWithConcept(map, name); else if (eqic(metaInfo, "bool")) replaceStringValueWithBool(map, name); } for (Field f : nonStaticNonTransientFieldObjectsOfType(Concept.Ref.class, c)) replaceStringValueWithConcept(map, f.getName()); if (trimAllSingleLineValues) for (Map.Entry e : map.entrySet()) { String val = optCastString(e.getValue()); if (val != null && isSingleLine(val) && isUntrimmed(val)) e.setValue(trim(val)); } if (lsMagic) for (Field f : nonStaticNonTransientFieldObjectsOfType(List.class, c)) { if (eqOneOf(f.getName(), "refs", "backRefs")) continue; TreeMap values = new TreeMap(); Matches m = new Matches(); for (Map.Entry __1 : _entrySet(cloneMap(map))) { String key = __1.getKey(); Object value = __1.getValue(); if (startsWith(key, f.getName() + "_", m) && isInteger(m.rest())) { if (!dropEmptyListValues || nempty((String) value)) { if (verbose) print("Adding value " + m.rest() + " / " + value); mapPut(values, parseInt(m.rest()), (String) value); } map.remove(key); } } if (!dropEmptyListValues) while (nempty(values) && empty(lastValue(values))) { if (verbose) print("Dropping value " + lastEntry(values)); removeLastKey(values); } map.put(f.getName(), valuesAsList(values)); } for (Field f : nonStaticNonTransientFieldObjectsOfType(SecretValue.class, c)) map.remove(f.getName()); } public void replaceStringValueWithConcept(Map map, String key) { Object value = map.get(key); if (value instanceof String) { Concept concept = getConceptFromString((String) value); map.put(key, concept); } } public void replaceStringValueWithBool(Map map, String key) { Object value = map.get(key); if (value instanceof String) { map.put(key, englishStringToBool((String) value)); } } transient public IF1> getObject; public Map getObject(Object id) { return getObject != null ? getObject.get(id) : getObject_base(id); } final public Map getObject_fallback(IF1> _f, Object id) { return _f != null ? _f.get(id) : getObject_base(id); } public Map getObject_base(Object id) { return itemToMap(conceptForID(id)); } public Map getObjectForEdit(Object id) { currentConcept = conceptForID(id); return getObject(id); } public Object createObject(Map fullMap, String fieldPrefix) { rawFormValues = fullMap; try { Map map = extractFieldValues(fullMap, fieldPrefix); A c = cnew(cc, cClass); setValues(c, mapMinusKeys(map, filteredFields()), true); cset(c, mapToParams(filters)); cset(c, mapToParams(ciFilters)); pcallFAll(onCreate, c); pcallFAll(onCreateOrUpdate, c); callOpt(c, "_onCreated"); return c.id; } finally { rawFormValues = null; } } public void setValues(A c, Map map, boolean creating) { Lock __3 = lockDB && !creating ? dbLock(cc) : null; lock(__3); try { Map map2 = (Map) cloneMap(map); massageItemMapForUpdate(c, map2); if (verbose) { print("setValues " + map); print("backRefs: " + c.backRefs); } Map oldValues = !creating && afterUpdate != null ? cgetAll_cloneLists(c, keys(map2)) : null; if (convertConceptValuesToRefs) convertAllConceptValuesToRefs(c, map2); if (valueConverter == null) cSmartSet(c, mapToParams(map2)); else cSmartSet_withConverter_pcall(verbose, valueConverter, c, mapToParams(map2)); if (oldValues != null) callF(afterUpdate, c, oldValues); if (verbose) print("backRefs: " + c.backRefs); } finally { unlock(__3); } } public void convertAllConceptValuesToRefs(A c, Map map) { for (Map.Entry __0 : _entrySet(cloneMap(map))) { String key = __0.getKey(); Object value = __0.getValue(); if (value instanceof Concept) if (!hasField(c, key)) { print("Converting value to ref: " + key); map.put(key, c.new Ref((Concept) value)); } } } public A conceptForID(Object id) { return _getConcept(cc, cClass, toLong(id)); } public String updateObject(Object id, Map fullMap, String fieldPrefix) { rawFormValues = fullMap; try { Map map = extractFieldValues(fullMap, fieldPrefix); A c = conceptForID(id); if (c == null) return "Object " + id + " not found"; { String __5 = checkFilters(c); if (!empty(__5)) return __5; } setValues(c, map, false); pcallFAll(onCreateOrUpdate, c); return "Object " + id + " updated"; } finally { rawFormValues = null; } } public String deleteObject(Object id) { A c = conceptForID(id); if (c == null) return "Object " + id + " not found"; { String __6 = checkFilters(c); if (!empty(__6)) return __6; } actuallyDeleteConcept(c); return "Object " + id + " deleted"; } transient public IVF1 actuallyDeleteConcept; public void actuallyDeleteConcept(A c) { if (actuallyDeleteConcept != null) actuallyDeleteConcept.get(c); else actuallyDeleteConcept_base(c); } final public void actuallyDeleteConcept_fallback(IVF1 _f, A c) { if (_f != null) _f.get(c); else actuallyDeleteConcept_base(c); } public void actuallyDeleteConcept_base(A c) { deleteConcept(c); } public String checkFilters(A c) { if (!checkConceptFields(c, mapToParams(filters)) || !checkConceptFieldsIC(c, mapToParams(ciFilters))) return "Object " + c.id + " not in view"; return ""; } public HCRUD_Concepts addFilters(Map map) { for (Map.Entry __7 : _entrySet(unnullForIteration(map))) { String field = __7.getKey(); Object value = __7.getValue(); addFilter(field, value); } return this; } public HCRUD_Concepts addFilter(String field, Object value) { filters = orderedMapPutOrCreate(filters, field, value); return this; } transient public IF1 isEditableValue; public boolean isEditableValue(Object value) { return isEditableValue != null ? isEditableValue.get(value) : isEditableValue_base(value); } final public boolean isEditableValue_fallback(IF1 _f, Object value) { return _f != null ? _f.get(value) : isEditableValue_base(value); } public boolean isEditableValue_base(Object value) { if (value instanceof List) return true; if (value instanceof Collection) return false; return true; } public Renderer getRenderer(String field) { if (!isEditableValue(currentValue)) return new NotEditable(); Class type = fieldType(or(currentConcept, cClass), field); String metaInfo = metaInfoFromForm(field); if (eq(type, boolean.class)) return new CheckBox(); if (eq(type, Boolean.class)) return new ComboBox(ll("", "yes", "no"), b -> trueFalseNull((Boolean) b, "yes", "no", "")); if (isSubtypeOf(type, Concept.Ref.class)) { Class c = fieldTypeArg(field); AbstractComboBox cb = makeConceptsComboBox(field, c); cb.metaInfo = "concept"; return cb; } Object val = deref(currentValue); if (val instanceof Concept) { Class c = ((Concept) val).getClass(); AbstractComboBox cb = makeConceptsComboBox(field, c); cb.metaInfo = "concept"; return cb; } if (eqic(metaInfo, "concept")) { printVars_str("metaInfo value", "field", field, "val", val); AbstractComboBox cb = makeConceptsComboBox(field, Concept.class); cb.metaInfo = "concept"; return cb; } if (eq(type, Concept.RefL.class)) { Class c = fieldTypeArg(field); return new FlexibleLengthList(makeConceptsComboBox(field, c)); } if (eq(type, List.class)) { return new FlexibleLengthList(new TextField(80)); } if (val instanceof Boolean) return new CheckBox(); return super.getRenderer(field); } public DynamicComboBox makeDynamicComboBox(String field, Class c) { DynamicComboBox cb = new DynamicComboBox(field); cb.valueToEntry = value -> { value = deref(value); long id = 0; if (value instanceof Concept) id = conceptID((Concept) value); else if (value instanceof String && isInteger((String) value)) id = parseLong(value); if (id != 0) return comboBoxItem(_getConcept(cc, id)); return null; }; return cb; } public AbstractComboBox makeConceptsComboBox(String field, Class c) { if (c == null) throw fail(("Null type for field " + field + ". currentConcept: ") + currentConcept); if (useDynamicComboBoxes || useDynamicComboBoxesForField != null && useDynamicComboBoxesForField.get(field)) return makeDynamicComboBox(field, c); Collection concepts = listConceptClass(c); if (l(concepts) >= dynamicComboBoxesThreshold) return makeDynamicComboBox(field, c); List entries = comboBoxItems(concepts); ComboBox cb = new ComboBox(entries); cb.valueToEntry = value -> { value = deref(value); long id = 0; if (value instanceof Concept) id = conceptID((Concept) value); else if (value instanceof String && isInteger((String) value)) id = parseLong(value); if (id != 0) { String entry = firstWhereFirstLongIs(entries, id); return entry; } return null; }; return cb; } public Collection listConceptClass(Class c) { return cc.list(c); } public List comboBoxItemsForConceptClass(Class c) { return comboBoxItems(listConceptClass(c)); } public List comboBoxItems(Collection l) { return comboBoxItems_static(l); } static public List comboBoxItems_static(Collection l) { return itemPlus("", lmap(__126 -> comboBoxItem_static(__126), l)); } public String comboBoxItem(Concept val) { return comboBoxItem_static(val); } static public String comboBoxItem_static(Concept val) { return val == null ? null : shorten(val.id + ": " + val); } transient public IF1 objectCanBeDeleted; public boolean objectCanBeDeleted(Object id) { return objectCanBeDeleted != null ? objectCanBeDeleted.get(id) : objectCanBeDeleted_base(id); } final public boolean objectCanBeDeleted_fallback(IF1 _f, Object id) { return _f != null ? _f.get(id) : objectCanBeDeleted_base(id); } public boolean objectCanBeDeleted_base(Object id) { return !referencesBlockDeletion || !hasBackRefs(conceptForID(id)); } public Set filteredFields() { return joinSets(keys(filters), keys(ciFilters)); } public Class fieldTypeArg(String field) { return getTypeArgumentAsClass(genericFieldType(or(currentConcept, cClass), field)); } transient public IF2> conceptClassForComboBoxSearch; public Class conceptClassForComboBoxSearch(String info, String query) { return conceptClassForComboBoxSearch != null ? conceptClassForComboBoxSearch.get(info, query) : conceptClassForComboBoxSearch_base(info, query); } final public Class conceptClassForComboBoxSearch_fallback(IF2> _f, String info, String query) { return _f != null ? _f.get(info, query) : conceptClassForComboBoxSearch_base(info, query); } public Class conceptClassForComboBoxSearch_base(String info, String query) { if (!isIdentifier(info)) return cClass; String field = info; Class c = fieldTypeArg(field); if (c == null) c = cClass; return c; } transient public IF2> comboBoxSearchBaseItems; public List comboBoxSearchBaseItems(String info, String query) { return comboBoxSearchBaseItems != null ? comboBoxSearchBaseItems.get(info, query) : comboBoxSearchBaseItems_base(info, query); } final public List comboBoxSearchBaseItems_fallback(IF2> _f, String info, String query) { return _f != null ? _f.get(info, query) : comboBoxSearchBaseItems_base(info, query); } public List comboBoxSearchBaseItems_base(String info, String query) { var c = conceptClassForComboBoxSearch(info, query); if (c == null) return emptyList(); return comboBoxItemsForConceptClass(c); } public List comboBoxSearch(String info, String query) { List items = comboBoxSearchBaseItems(info, query); return takeFirst(10, scoredSearch(query, items)); } public A conceptForMap(Map map) { if (map == null) return null; long id = toLong(map.get(idField())); return id == 0 ? null : (A) _getConcept(cc, id); } public A getConcept(Map map) { return conceptForMap(map); } public Map extractFieldValues(Map fullMap, String fieldPrefix) { return subMapStartingWith_dropPrefix(fullMap, fieldPrefix); } public Concept getConceptFromString(String s) { long conceptID = parseFirstLong(s); return _getConcept(cc, conceptID); } public String metaInfoFromForm(String field) { return mapGet(rawFormValues, "metaInfo_" + field); } public void addCIFilter(String field, String value) { ciFilters = putOrCreate(ciFilters, field, value); } transient public IF1 titleForObjectID; public String titleForObjectID(Object id) { return titleForObjectID != null ? titleForObjectID.get(id) : titleForObjectID_base(id); } final public String titleForObjectID_fallback(IF1 _f, Object id) { return _f != null ? _f.get(id) : titleForObjectID_base(id); } public String titleForObjectID_base(Object id) { return htmlEncode2(strOrNull(conceptForID(id))); } } static public class HPopDownButton { public String labelHTML; public String buttonHTML = htmlEncode2(unicode_smallDownPointingTriangle()); public List entries = new ArrayList(); public String id = "dropdown-" + aGlobalID(), outerID = "outer-" + id; public String style = "position: relative; display: inline-block; cursor: context-menu"; public String menuStyle = ""; public HPopDownButton() { } public HPopDownButton(String labelHTML, List entries) { this.labelHTML = labelHTML; addAll(this.entries, entries); } public String onclick() { return replaceDollarVars("\r\n var x = document.getElementById($id);\r\n x.style.display = window.getComputedStyle(x).display === \"none\" ? \"block\" : \"none\";\r\n console.log(\"popup \" + id + \" display: \" + x.style.display);\r\n ", "id", jsQuote(id)); } public String html() { return hstyle(replaceDollarVars("\r\n #$id ul {\r\n list-style-type: none;\r\n margin: 0;\r\n padding: 0;\r\n width: 200px;\r\n background-color: #f1f1f1;\r\n }\r\n \r\n #$id {\r\n position: absolute;\r\n display:none;\r\n background-color: #f9f9f9;\r\n width:auto;\r\n height:200px;\r\n overflow: auto;\r\n \r\n min-width: 160px;\r\n box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);\r\n \r\n z-index: 99;\r\n }\r\n \r\n #$id li a {\r\n text-decoration: none;\r\n color: #000;\r\n }\r\n \r\n #$id li { \r\n display: block;\r\n border-bottom: 1px solid #555;\r\n padding: 8px 16px;\r\n color: #000;\r\n }\r\n \r\n #$id li:hover, #$id li:hover > a {\r\n background-color: #3399ff;\r\n color: white;\r\n }\r\n ", "id", id)) + hdiv(buttonHTMLWithOnClick() + hdiv(ul(entries), "id", id, "style", menuStyle), "style", style, "id", outerID) + hscript(replaceDollarVars("\r\n if (typeof $ !== 'undefined')\r\n $('body').click(function(e) {\r\n if (!$(e.target).closest('#$outerID').length) {\r\n $(\"#$id\").hide();\r\n }\r\n });\r\n ", "id", id, "outerID", outerID)); } transient public IF0 buttonHTMLWithOnClick; public String buttonHTMLWithOnClick() { return buttonHTMLWithOnClick != null ? buttonHTMLWithOnClick.get() : buttonHTMLWithOnClick_base(); } final public String buttonHTMLWithOnClick_fallback(IF0 _f) { return _f != null ? _f.get() : buttonHTMLWithOnClick_base(); } public String buttonHTMLWithOnClick_base() { return span(joinNemptiesWithSpace(labelHTML, buttonHTML), "onclick", onclick()); } } 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 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 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 long sysTime() { return clockTimeToSystemTime(date); } public Duration minusAsDuration(Timestamp ts) { return Duration.ofMillis(minus(ts)); } } 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; } } static public class GazelleV_LeftArrowScriptParser extends SimpleLeftToRightParser { final public GazelleV_LeftArrowScriptParser setMagicSwitch(boolean magicSwitch) { return magicSwitch(magicSwitch); } public GazelleV_LeftArrowScriptParser magicSwitch(boolean magicSwitch) { this.magicSwitch = magicSwitch; return this; } final public boolean getMagicSwitch() { return magicSwitch(); } public boolean magicSwitch() { return magicSwitch; } public boolean magicSwitch = true; final public GazelleV_LeftArrowScriptParser setObjectScopesEnabled(boolean objectScopesEnabled) { return objectScopesEnabled(objectScopesEnabled); } public GazelleV_LeftArrowScriptParser objectScopesEnabled(boolean objectScopesEnabled) { this.objectScopesEnabled = objectScopesEnabled; return this; } final public boolean getObjectScopesEnabled() { return objectScopesEnabled(); } public boolean objectScopesEnabled() { return objectScopesEnabled; } public boolean objectScopesEnabled = true; public ClassNameResolver classNameResolver; public List functionContainers = new ArrayList(); final public GazelleV_LeftArrowScriptParser setLasClassLoader(ILASClassLoader lasClassLoader) { return lasClassLoader(lasClassLoader); } public GazelleV_LeftArrowScriptParser lasClassLoader(ILASClassLoader lasClassLoader) { this.lasClassLoader = lasClassLoader; return this; } final public ILASClassLoader getLasClassLoader() { return lasClassLoader(); } public ILASClassLoader lasClassLoader() { return lasClassLoader; } public ILASClassLoader lasClassLoader; final public GazelleV_LeftArrowScriptParser setClassDefPrefix(String classDefPrefix) { return classDefPrefix(classDefPrefix); } public GazelleV_LeftArrowScriptParser classDefPrefix(String classDefPrefix) { this.classDefPrefix = classDefPrefix; return this; } final public String getClassDefPrefix() { return classDefPrefix(); } public String classDefPrefix() { return classDefPrefix; } public String classDefPrefix; final public GazelleV_LeftArrowScriptParser setSourceInfo(Object sourceInfo) { return sourceInfo(sourceInfo); } public GazelleV_LeftArrowScriptParser sourceInfo(Object sourceInfo) { this.sourceInfo = sourceInfo; return this; } final public Object getSourceInfo() { return sourceInfo(); } public Object sourceInfo() { return sourceInfo; } public Object sourceInfo; final public GazelleV_LeftArrowScriptParser setOptimize(boolean optimize) { return optimize(optimize); } public GazelleV_LeftArrowScriptParser optimize(boolean optimize) { this.optimize = optimize; return this; } final public boolean getOptimize() { return optimize(); } public boolean optimize() { return optimize; } public boolean optimize = true; final public GazelleV_LeftArrowScriptParser setUseFixedVarContexts(boolean useFixedVarContexts) { return useFixedVarContexts(useFixedVarContexts); } public GazelleV_LeftArrowScriptParser useFixedVarContexts(boolean useFixedVarContexts) { this.useFixedVarContexts = useFixedVarContexts; return this; } final public boolean getUseFixedVarContexts() { return useFixedVarContexts(); } public boolean useFixedVarContexts() { return useFixedVarContexts; } public boolean useFixedVarContexts = false; public Scope scope; public LinkedHashMap knownVars = new LinkedHashMap(); public Set closerTokens = litset(";", "}", ")"); public BuildingScript currentReturnableScript; public BuildingScript currentLoop; public boolean inParens = false; public int idCounter; public Map classDefs = new HashMap(); final public Map getFunctionDefs() { return functionDefs(); } public Map functionDefs() { return functionDefs; } public Map functionDefs = new HashMap(); public Set flags = ciSet(); transient public Set>> onKnownVarsSnapshot; public GazelleV_LeftArrowScriptParser onKnownVarsSnapshot(IVF1> f) { onKnownVarsSnapshot = createOrAddToSyncLinkedHashSet(onKnownVarsSnapshot, f); return this; } public GazelleV_LeftArrowScriptParser removeKnownVarsSnapshotListener(IVF1> f) { utils.remove(onKnownVarsSnapshot, f); return this; } public void knownVarsSnapshot(Map knownVars) { if (onKnownVarsSnapshot != null) for (var listener : onKnownVarsSnapshot) pcallF_typed(listener, knownVars); } transient public Set> onTypeHook; public GazelleV_LeftArrowScriptParser onTypeHook(IVF1 f) { onTypeHook = createOrAddToSyncLinkedHashSet(onTypeHook, f); return this; } public GazelleV_LeftArrowScriptParser removeTypeHookListener(IVF1 f) { utils.remove(onTypeHook, f); return this; } public void typeHook(LASValueDescriptor type) { if (onTypeHook != null) for (var listener : onTypeHook) pcallF_typed(listener, type); } static public class EvaluableWrapper implements IFieldsToList { public GazelleV_LeftArrowScript.Evaluable expr; public EvaluableWrapper() { } public EvaluableWrapper(GazelleV_LeftArrowScript.Evaluable expr) { this.expr = expr; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + expr + ")"; } public boolean equals(Object o) { if (!(o instanceof EvaluableWrapper)) return false; EvaluableWrapper __21 = (EvaluableWrapper) o; return eq(expr, __21.expr); } public int hashCode() { int h = 700525824; h = boostHashCombine(h, _hashCode(expr)); return h; } public Object[] _fieldsToList() { return new Object[] { expr }; } } public class BuildingScript { public int id = ++idCounter; final public BuildingScript setReturnable(boolean returnable) { return returnable(returnable); } public BuildingScript returnable(boolean returnable) { this.returnable = returnable; return this; } final public boolean getReturnable() { return returnable(); } public boolean returnable() { return returnable; } public boolean returnable = false; final public BuildingScript setIsLoopBody(boolean isLoopBody) { return isLoopBody(isLoopBody); } public BuildingScript isLoopBody(boolean isLoopBody) { this.isLoopBody = isLoopBody; return this; } final public boolean getIsLoopBody() { return isLoopBody(); } public boolean isLoopBody() { return isLoopBody; } public boolean isLoopBody = false; public BuildingScript returnableParent, loopParent; public GazelleV_LeftArrowScript.Script script = new GazelleV_LeftArrowScript.Script(); public List steps = new ArrayList(); public Map functionDefs = new HashMap(); public BuildingScript(boolean returnable) { this(); this.returnable = returnable; } public BuildingScript(boolean returnable, boolean isLoopBody) { this(); this.isLoopBody = isLoopBody; this.returnable = returnable; } public BuildingScript() { } public void add(GazelleV_LeftArrowScript.Evaluable step) { if (step != null) steps.add(step); } public GazelleV_LeftArrowScript.Evaluable get() { var lastStep = last(steps); if (lastStep instanceof GazelleV_LeftArrowScript.ReturnFromScript) if (((GazelleV_LeftArrowScript.ReturnFromScript) lastStep).script == script) replaceLast(steps, ((GazelleV_LeftArrowScript.ReturnFromScript) lastStep).value); if (!returnable && l(steps) == 1 && empty(functionDefs)) return first(steps); if (nempty(functionDefs)) script.functionDefs = functionDefs; script.steps = toTypedArray(GazelleV_LeftArrowScript.Evaluable.class, steps); return script; } public String toStringLong() { return pnlToLines(steps); } public String toString() { return formatRecordVars("BuildingScript", "id", id, "returnable", returnable, "returnableParent", returnableParent, "script", script); } } { tokenize = text -> { List tok = tokenize_base(text); tok = preprocess(tok); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("=== PREPROCESSED\n" + indentx(join(tok)) + "\n==="); return tok; }; } public List preprocess(List tok) { tok = tokenIndexedList3(tok); tok_ifdef(tok, __20 -> getFlag(__20)); tok_pcall_script(tok); tok_script_settable(tok); jreplace(tok, "LS", "L"); return cloneList(tok); } public GazelleV_LeftArrowScript.Script parse(String text) { setText(text); init(); return parse(); } public GazelleV_LeftArrowScript.Script parse() { GazelleV_LeftArrowScript.Script script = parseReturnableScript(); if (optimize) script = script.optimizeScript(); return script; } public GazelleV_LeftArrowScript.Script parseReturnableScript() { return (GazelleV_LeftArrowScript.Script) parseScript(new BuildingScript().returnable(true)); } public GazelleV_LeftArrowScript.Evaluable parseScript(BuildingScript script) { return linkToSrc(() -> { script.returnableParent = currentReturnableScript; script.loopParent = currentLoop; if (script.returnable) currentReturnableScript = script; if (script.isLoopBody) currentLoop = script; return parseBuildingScript(script); }); } public GazelleV_LeftArrowScript.Evaluable parseBuildingScript(BuildingScript script) { try { parseScript_2(script); var builtScript = script.get(); currentReturnableScript = script.returnableParent; currentLoop = script.loopParent; return builtScript; } catch (Throwable e) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Parsed so far:\n" + script); throw rethrowAndAppendToMessage(e, squareBracketed(spaceCombine(sourceInfo, lineAndColumn(-1)))); } } public void parseScript_2(BuildingScript script) { AutoCloseable __10 = tempRestoreMap(knownVars); try { AssureAdvance assure = new AssureAdvance(); while (assure.get()) { knownVarsSnapshot(knownVars); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("parseScript_2: Next token is " + quote(token())); if (is(";")) { next(); continue; } if (isOneOf("}", ")")) break; GazelleV_LeftArrowScript.Evaluable instruction = linkToSrc(() -> parseInstruction(script)); if (instruction != null) script.add(instruction); } if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("parseScript_2 done"); knownVarsSnapshot(knownVars); } finally { _close(__10); } } public GazelleV_LeftArrowScript.Evaluable parseParamDecl(BuildingScript script) { String var = assertIdentifier(tpp()); LASValueDescriptor valueDescriptor = new LASValueDescriptor(); if (is(":")) { var type = parseColonType(); valueDescriptor = LASValueDescriptor.nonExactCanBeNull(type); } knownVars.put(var, valueDescriptor); script.script.params = putOrCreateLinkedHashMap(script.script.params, var, valueDescriptor); return null; } public GazelleV_LeftArrowScript.Evaluable parseInstruction(BuildingScript script) { if (consumeOpt("param")) return parseParamDecl(script); if (is("throw")) { consume(); return new GazelleV_LeftArrowScript.Throw(parseExpr()); } if (isOneOf("return", "ret")) { consume(); GazelleV_LeftArrowScript.Evaluable expr; if (atCmdEnd()) expr = _const(null); else expr = parseAssignmentOrExpr(); return new GazelleV_LeftArrowScript.ReturnFromScript(currentReturnableScript.script, expr); } if (consumeOpt("continue")) { assertCmdEnd(); if (currentLoop == null) throw fail("continue outside of loop"); return new GazelleV_LeftArrowScript.Continue(currentLoop.script); } if (is("temp")) { consume(); GazelleV_LeftArrowScript.Evaluable tempExpr = parseAssignmentOrExpr(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("tempExpr", tempExpr); GazelleV_LeftArrowScript.Evaluable body = parseScript(new BuildingScript()); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("body", body); return new GazelleV_LeftArrowScript.TempBlock(tempExpr, body); } if (is("will") && is(1, "return")) { consume(2); GazelleV_LeftArrowScript.Evaluable exp = parseAssignmentOrExpr(); GazelleV_LeftArrowScript.Evaluable body = parseScript(new BuildingScript()); return new GazelleV_LeftArrowScript.WillReturn(exp, body); } if (is("var") && isIdentifier(token(1))) { consume(); String varName = consume(); var type = parseColonTypeOpt(); if (consumeLeftArrowOpt()) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Found assignment"); GazelleV_LeftArrowScript.Evaluable rhs = parseExpr(); assertNotNull("Expression expected", rhs); knownVars.put(varName, type == null ? or(rhs.returnType(), new LASValueDescriptor()) : LASValueDescriptor.nonExactCanBeNull(type)); return new GazelleV_LeftArrowScript.VarDeclaration(varName, typeToClass(type), rhs); } } return parseAssignmentOrExpr(); } public GazelleV_LeftArrowScript.Evaluable parseAssignmentOrExpr() { { var __2 = parseAssignmentOpt(); if (__2 != null) return __2; } return parseExpr(); } public GazelleV_LeftArrowScript.Evaluable parseAssignmentOpt() { String t = token(); if (isIdentifier(t)) { Type type = null; var ptr = ptr(); if (is(1, ":")) { next(); type = parseColonType(); unconsume(); } if (is(1, "<") && is(2, "-")) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Found assignment"); next(3); GazelleV_LeftArrowScript.Evaluable rhs = parseExpr(); assertNotNull("Expression expected", rhs); boolean newVar = !knownVars.containsKey(t); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("newVar", newVar, "t", t, "knownVars", knownVars); if (newVar && scope != null) { var __3 = scope.completeAssignmentOpt(t, rhs); if (__3 != null) return __3; } knownVars.put(t, type == null ? or(rhs.returnType(), new LASValueDescriptor()) : LASValueDescriptor.nonExactCanBeNull(type)); return newVar ? new GazelleV_LeftArrowScript.VarDeclaration(t, null, rhs) : new GazelleV_LeftArrowScript.Assignment(t, rhs); } ptr(ptr); } return null; } public GazelleV_LeftArrowScript.Evaluable parseOptionalInnerExpression() { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("parseOptionalInnerExpression", "token", token()); if (atCmdEnd() || isOneOf("{", ",", "then")) return null; return parseInnerExpr(); } public GazelleV_LeftArrowScript.Evaluable _const(Object o) { return new GazelleV_LeftArrowScript.Const(o); } public GazelleV_LeftArrowScript.Evaluable parseInnerExpr() { return parseExpr(true); } public GazelleV_LeftArrowScript.Evaluable parseExpr() { if (metaGet("scaffolding") != null) scaffoldCalled(this, "parseExpr"); return parseExpr(false); } public GazelleV_LeftArrowScript.Evaluable parseExpr(boolean inner) { GazelleV_LeftArrowScript.Evaluable e = linkToSrc(() -> inner ? parseExpr_impl(true) : parseFullExpr()); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("parseExpr done:\n" + GazelleV_LeftArrowScript.indentedScriptStruct(e)); return e; } public GazelleV_LeftArrowScript.Evaluable parseFullExpr() { return linkToSrc(() -> parseExprPlusOptionalComma()); } public GazelleV_LeftArrowScript.CallOnTarget parseThenCall(GazelleV_LeftArrowScript.CallOnTarget expr) { consume("then"); GazelleV_LeftArrowScript.CallOnTarget secondCall = (GazelleV_LeftArrowScript.CallOnTarget) (parseCall(null)); return new GazelleV_LeftArrowScript.Then(expr, secondCall); } public GazelleV_LeftArrowScript.Evaluable parseExprPlusOptionalComma() { GazelleV_LeftArrowScript.Evaluable expr = parseExpr_impl(false); while (consumeOpt(",")) { expr = parseCall_noCmdEndCheck(expr); } return expr; } public GazelleV_LeftArrowScript.Evaluable parseExpr_impl(boolean inner) { if (atEnd()) return null; String t = token(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("parseExpr", "token", t); if (is(";")) return null; if (consumeOpt("try")) { GazelleV_LeftArrowScript.Evaluable body = parseCurlyBlock(); while (consumeOpt("catch")) { String var = consumeIdentifierOpt(); AutoCloseable __11 = tempAddKnownVars(var); try { GazelleV_LeftArrowScript.Evaluable catchBlock = parseCurlyBlock(); body = new GazelleV_LeftArrowScript.TryCatch(body, var, catchBlock); } finally { _close(__11); } } if (consumeOpt("finally")) { GazelleV_LeftArrowScript.Evaluable finallyBlock = parseCurlyBlock(); return new GazelleV_LeftArrowScript.TryFinally(body, finallyBlock); } return body; } if (is("def")) { var fd = parseFunctionDefinition(currentReturnableScript.functionDefs); return _const(fd); } if (is("{")) return parseCurlyBlock(); if (is("-") && empty(nextSpace()) && startsWithDigit(token(1)) || startsWithDigit(t)) { var e = parseNumberLiteral(); return parseCall(inner, e); } if (isQuoted(t)) { var e = parseStringLiteral(); return parseCall(inner, e); } if (startsWith(t, '\'')) { consume(); var e = _const(first(unquote(t))); return parseCall(inner, e); } if (isIdentifier(t)) { if (consumeOpt("synchronized")) { var target = parseExpr(); var body = parseCurlyBlock(); return new GazelleV_LeftArrowScript.Synchronized(target, body); } if (is("while")) return parseWhileLoop(); if (is("for")) return parseForEach(); if (is("if")) return parseIfStatement(); if (is("repeat")) return parseRepeatStatement(); if (is("outer")) { consume(); var a = parseAssignmentOpt(); if (!(a instanceof GazelleV_LeftArrowScript.Assignment)) throw fail("Assignment expected"); return new GazelleV_LeftArrowScript.AssignmentToOuterVar(((GazelleV_LeftArrowScript.Assignment) a).var, ((GazelleV_LeftArrowScript.Assignment) a).expression); } consume(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Consumed identifier " + t + ", next token: " + token() + ", inner: " + inner); var e = parseExprStartingWithIdentifier(t, inner); return inner ? parseCall(inner, e) : e; } if (eq(t, "(")) { consume(); GazelleV_LeftArrowScript.Evaluable e = parseExpr_inParens(); consume(")"); return parseCall(inner, e); } if (isOneOf("&", "|") && empty(nextSpace()) && is(1, token())) { return parseBinaryOperator(); } throw fail("Identifier, literal, operator or opening parentheses expected (got: " + quote(t)); } public GazelleV_LeftArrowScript.Evaluable parseExpr_inParens() { boolean inParensOld = inParens; inParens = true; try { return parseExpr(); } finally { inParens = inParensOld; } } public GazelleV_LeftArrowScript.Evaluable parseNumberLiteral() { String t = consumeMultiTokenLiteral(); if (swic(t, "0x")) return _const(parseHexInt(dropFirst(t, 2))); if (swic(t, "0b")) return _const(intFromBinary(dropFirst(t, 2))); if (isInteger(t)) return _const(parseIntOrLong(t)); if (ewic(t, "f")) return _const(parseFloat(t)); if (endsWith(t, "L")) return _const(parseLong(t)); return _const(parseDouble(t)); } public GazelleV_LeftArrowScript.Evaluable parseBinaryOperator() { boolean and = is("&"); next(2); GazelleV_LeftArrowScript.Evaluable a = parseInnerExpr(); GazelleV_LeftArrowScript.Evaluable b = parseInnerExpr(); return and ? new GazelleV_LeftArrowScript.BoolAnd(a, b) : new GazelleV_LeftArrowScript.BoolOr(a, b); } public boolean qualifiedNameContinues() { return empty(prevSpace()) && eq(token(), ".") && empty(nextSpace()) && isIdentifier(token(1)); } public GazelleV_LeftArrowScript.Evaluable parseNewExpr() { String className = assertIdentifier(tpp()); parseTypeArguments(null); LASClassDef cd = classDefs.get(className); if (cd != null) return new GazelleV_LeftArrowScript.NewObject_LASClass(cd.resolvable(lasClassLoader)); var type = knownVars.get(className); if (type != null) return new GazelleV_LeftArrowScript.NewObject_UnknownClass(new GazelleV_LeftArrowScript.GetVar(className), parseArguments()); Object o = findExternalObject(className); if (o instanceof Class) { Class c = (Class) o; if (c == List.class) c = ArrayList.class; else if (c == Map.class) c = HashMap.class; else if (c == Set.class) c = HashSet.class; return new GazelleV_LeftArrowScript.NewObject(c, parseArguments()); } throw new ClassNotFound(className); } public GazelleV_LeftArrowScript.Evaluable parseExprStartingWithIdentifier(String t, boolean inner) { if (eq(t, "true")) return _const(true); if (eq(t, "false")) return _const(false); if (eq(t, "null")) return _const(null); if (eq(t, "new")) return parseNewExpr(); if (eq(t, "class")) { unconsume(); return new GazelleV_LeftArrowScript.ClassDef(parseClassDef().resolvable(lasClassLoader)); } if (eq(t, "list") && is("{")) { GazelleV_LeftArrowScript.Script block = parseReturnableCurlyBlock(); GazelleV_LeftArrowScript.Evaluable e = new GazelleV_LeftArrowScript.ListFromScript(block); return parseCall(inner, e); } var type = knownVars.get(t); if (type != null) { var e = new GazelleV_LeftArrowScript.GetVar(t).returnType(type); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Found var acccess: " + e + ", " + (!inner ? "Checking for call" : "Returning expression")); return parseCall(inner, e); } if (scope != null) { { var __4 = scope.parseExprStartingWithIdentifierOpt(t, inner); if (__4 != null) return __4; } } if (!inner) { var fdef = lookupFunction(t); if (fdef != null) { if (is("~")) return parseTildeCall(new GazelleV_LeftArrowScript.CallFunction(fdef, new GazelleV_LeftArrowScript.Evaluable[0])); return new GazelleV_LeftArrowScript.CallFunction(fdef, parseArguments()); } } if (eq(t, "_context")) return new GazelleV_LeftArrowScript.GetVarContext(); Object o = findExternalObject(t); var start = ptr().minus(2); if (o == null) { throw new UnknownObject(t); } else if (o instanceof EvaluableWrapper) { return parseCall(inner, ((EvaluableWrapper) o).expr); } else if (inner) return linkToSrc(start, _const(o)); else if (o instanceof Class) { return parseExprStartingWithClass(start, ((Class) o)); } else if (o instanceof MethodOnObject) { if (inner) throw fail("Can't call methods in arguments"); return new GazelleV_LeftArrowScript.CallMethod(_const(((MethodOnObject) o).object), ((MethodOnObject) o).method, parseArguments()); } else return parseCall(_const(o)); } public GazelleV_LeftArrowScript.Evaluable parseExprStartingWithClass(ListAndIndex start, Class c) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("parseExprStartingWithClass", "c", c); if (atCmdEnd()) return linkToSrc(start, _const(c)); if (is("(")) return new GazelleV_LeftArrowScript.NewObject(c, parseArguments()); { var __5 = parseLambdaOpt(c); if (__5 != null) return __5; } if (isIdentifier()) { String name = tpp(); if (hasStaticMethodNamed(c, name)) return new GazelleV_LeftArrowScript.CallMethod(_const(c), name, parseArguments()); if (isInterface(c)) return parseLambdaMethodRef(c, name); var field = getField(c, name); if (field == null) field = findFieldInInterfaces(c, name); if (field != null) { if (!isStaticField(field)) throw fail(field + " is not a static field"); if (consumeLeftArrowOpt()) { GazelleV_LeftArrowScript.Evaluable rhs = parseExpr(); return new GazelleV_LeftArrowScript.SetStaticField(field, rhs); } assertCmdEnd(); return new GazelleV_LeftArrowScript.GetStaticField(field); } throw fail(name + " not found in " + c + " (looked for method or field)"); } else throw fail("Method name expected: " + token()); } public GazelleV_LeftArrowScript.Evaluable parseLambdaOpt(Class c) { if (!isInterface(c)) return null; var ptr = ptr(); var parameterized = parseTypeArgumentsOpt(c); if (is("{")) return finishLambdaDef(c, null); if (consumeOpt("_")) { String methodName = consumeIdentifier(); return new GazelleV_LeftArrowScript.LambdaMethodOnArgument(c, methodName, parseArguments()); } int nArgs = 0; while (isIdentifier(token(nArgs))) nArgs++; if (!(is(nArgs, "-") && is(nArgs + 1, ">"))) { ptr(ptr); return null; } String[] argNames = consumeArray(nArgs); skip(2); return finishLambdaDef(c, argNames); } public GazelleV_LeftArrowScript.Evaluable finishLambdaDef(Class c, String[] argNames) { AutoCloseable __12 = tempAddKnownVars(argNames); try { GazelleV_LeftArrowScript.Evaluable body; if (is("{")) body = parseReturnableCurlyBlock(); else body = parseExpr(); var lambda = new GazelleV_LeftArrowScript.LambdaDef(c, argNames, body); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("finishLambdaDef done:\n" + GazelleV_LeftArrowScript.indentedScriptStruct(lambda)); return lambda; } finally { _close(__12); } } public GazelleV_LeftArrowScript.Evaluable parseLambdaMethodRef(Class c, String name) { var fdef = lookupFunction(name); if (fdef != null) { GazelleV_LeftArrowScript.Evaluable[] curriedArguments = parseArguments(); return new GazelleV_LeftArrowScript.CurriedScriptFunctionLambda(c, fdef, curriedArguments); } Object function = findExternalObject(name); if (function == null) throw new UnknownObject(name); if (function instanceof MethodOnObject) { Object target = ((MethodOnObject) function).object; String targetMethod = ((MethodOnObject) function).method; GazelleV_LeftArrowScript.Evaluable[] curriedArguments = parseArguments(); return new GazelleV_LeftArrowScript.CurriedMethodLambda(c, target, targetMethod, curriedArguments); } else if (function instanceof Class) { Class c2 = (Class) function; assertCmdEnd(); var ctors = constructorsWithNumberOfArguments(c2, 1); if (empty(ctors)) throw fail("No single argument constructor found in " + c2); return new GazelleV_LeftArrowScript.CurriedConstructorLambda(c, toArray(Constructor.class, ctors), null); } else throw fail(function + " is not an instantiable class or callable method"); } public GazelleV_LeftArrowScript.FunctionDef lookupFunction(String name) { var script = currentReturnableScript; while (script != null) { var f = script.functionDefs.get(name); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("lookupFunction", "script", script, "name", name, "f", f); if (f != null) return f; script = script.returnableParent; } return functionDefs.get(name); } public GazelleV_LeftArrowScript.Evaluable[] parseArguments() { List l = new ArrayList(); try { while (true) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("parseArgumentsAsList: token is " + quote(t())); if (is("+") && empty(nextSpace()) && isIdentifier(token(1))) { consume(); l.add(_const(token())); continue; } if (consumeOpt("<")) { GazelleV_LeftArrowScript.Evaluable a = parseFullExpr(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("parseArgumentsAsList: token after expr is " + quote(t())); if (a == null) throw fail("expression expected"); l.add(a); break; } GazelleV_LeftArrowScript.Evaluable a = parseOptionalInnerExpression(); if (a == null) break; l.add(a); } return toArrayOrNull(GazelleV_LeftArrowScript.Evaluable.class, l); } catch (Throwable _e) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Arguments parsed so far: " + l); throw rethrow(_e); } } public String consumeMultiTokenLiteral() { return consumeUntilSpaceOr(() -> atCmdEnd() || is(",")); } public boolean atCmdEnd() { return !inParens && atEndOrLineBreak() || closerTokens.contains(token()); } public void assertCmdEnd() { if (!atCmdEnd()) throw fail("Expected end of command, token is: " + quote(token())); } public GazelleV_LeftArrowScript.Evaluable parseCall(GazelleV_LeftArrowScript.Evaluable target) { return parseCall(false, target); } public GazelleV_LeftArrowScript.Evaluable parseCall(boolean inner, GazelleV_LeftArrowScript.Evaluable target) { returnTypeHook(target); if (atCmdEnd()) return target; if (inner) { { var __6 = parseTildeCall(target); if (__6 != null) return __6; } return target; } return parseCall_noCmdEndCheck(target); } public void returnTypeHook(GazelleV_LeftArrowScript.Evaluable e) { if (e != null && e.returnType() != null) typeHook(e.returnType()); } public GazelleV_LeftArrowScript.Evaluable parseCall_noCmdEndCheck(GazelleV_LeftArrowScript.Evaluable target) { var start = ptr(); returnTypeHook(target); if (isIdentifier()) { String name = tpp(); if (consumeLeftArrowOpt()) { GazelleV_LeftArrowScript.Evaluable rhs = parseExpr(); return new GazelleV_LeftArrowScript.SetField(target, name, rhs); } boolean allowNullReference = consumeOpt("?"); var args = parseArguments(); var call = finalizeCall(start, target, name, args); set(call, "allowNullReference", allowNullReference); return call; } { var __7 = parseTildeCall(target); if (__7 != null) return __7; } if (is("!") && is(1, "_getField_")) { next(2); String field = consumeIdentifier(); return new GazelleV_LeftArrowScript.GetField(target, field); } return target; } public boolean consumeLeftArrowOpt() { if (is("<") && eq(token(1), "-")) { next(2); return true; } return false; } public GazelleV_LeftArrowScript.Evaluable parseTildeCall(GazelleV_LeftArrowScript.Evaluable target) { var start = ptr(); if (consumeOpt("~")) { if (isIdentifier()) { String key = consumeIdentifier(); return parseCall(finalizeCall(start, target, "getOpt", _const(key))); } else { int idx = consumeInteger(); return parseCall(finalizeCall(start, target, "listGet", _const(idx))); } } return null; } public GazelleV_LeftArrowScript.Evaluable finalizeCall(ListAndIndex start, GazelleV_LeftArrowScript.Evaluable target, String name, GazelleV_LeftArrowScript.Evaluable... args) { return finalizeCall2(finalizeCall1(start, target, name, args)); } public GazelleV_LeftArrowScript.Evaluable finalizeCall2(GazelleV_LeftArrowScript.CallOnTarget call) { while (is("then")) call = parseThenCall(call); return call; } public GazelleV_LeftArrowScript.CallOnTarget finalizeCall1(ListAndIndex start, GazelleV_LeftArrowScript.Evaluable target, String name, GazelleV_LeftArrowScript.Evaluable... args) { if (magicSwitch) { Object ext = findExternalObject(name); if (ext instanceof MethodOnObject) { if (nempty(args)) return new GazelleV_LeftArrowScript.CallMethodOrGlobalFunction(target, name, ((MethodOnObject) ext), args); else return new GazelleV_LeftArrowScript.CallMethodOrGetFieldOrGlobalFunction(target, name, ((MethodOnObject) ext)); } } if (nempty(args)) return new GazelleV_LeftArrowScript.CallMethod(target, name, args); else return linkToSrc(start, new GazelleV_LeftArrowScript.CallMethodOrGetField(target, name)); } public A linkToSrc(ListAndIndex start, A a) { if (a instanceof IHasTokenRangeWithSrc) if (((IHasTokenRangeWithSrc) a).tokenRangeWithSrc() == null) ((IHasTokenRangeWithSrc) a).setTokenRangeWithSrc(new TokenRangeWithSrc(start, ptr().plus(-1)).sourceInfo(sourceInfo())); return a; } public A linkToSrc(IF0 a) { var start = ptr(); return linkToSrc(start, a.get()); } transient public IF1 findExternalObject; public Object findExternalObject(String name) { return findExternalObject != null ? findExternalObject.get(name) : findExternalObject_base(name); } final public Object findExternalObject_fallback(IF1 _f, String name) { return _f != null ? _f.get(name) : findExternalObject_base(name); } public Object findExternalObject_base(String name) { if (eq(name, "void")) return void.class; { var __8 = parsePrimitiveType(name); if (__8 != null) return __8; } if (qualifiedNameContinues()) { int idx = idx() - 2; do next(2); while (qualifiedNameContinues()); String fqn = joinSubList(tok, idx, idx() - 1); return classForName(fqn); } return findExternalObject2(name); } transient public IF1 findExternalObject2; public Object findExternalObject2(String name) { return findExternalObject2 != null ? findExternalObject2.get(name) : findExternalObject2_base(name); } final public Object findExternalObject2_fallback(IF1 _f, String name) { return _f != null ? _f.get(name) : findExternalObject2_base(name); } public Object findExternalObject2_base(String name) { String fullName = globalClassNames().get(name); if (fullName != null) return classForName(fullName); { var __9 = classForNameOpt_noCache(name); if (__9 != null) return __9; } for (var container : unnullForIteration(functionContainers)) { if (hasMethodNamed(container, name) && !isBlockedFunctionContainerMethod(container, name)) { var moo = new MethodOnObject(container, name); return moo; } var field = getField(container, name); if (field != null && isStaticField(field)) return new EvaluableWrapper(new GazelleV_LeftArrowScript.GetStaticField(field)); } return null; } transient public IF2 isBlockedFunctionContainerMethod; public boolean isBlockedFunctionContainerMethod(Object container, String name) { return isBlockedFunctionContainerMethod != null ? isBlockedFunctionContainerMethod.get(container, name) : isBlockedFunctionContainerMethod_base(container, name); } final public boolean isBlockedFunctionContainerMethod_fallback(IF2 _f, Object container, String name) { return _f != null ? _f.get(container, name) : isBlockedFunctionContainerMethod_base(container, name); } public boolean isBlockedFunctionContainerMethod_base(Object container, String name) { return false; } public GazelleV_LeftArrowScriptParser allowTheWorld() { return allowTheWorld(mc()); } public GazelleV_LeftArrowScriptParser allowTheWorld(Object... functionContainers) { for (Object o : unnullForIteration(reversed(functionContainers))) if (!contains(this.functionContainers, o)) { this.functionContainers.add(0, o); globalClassNames_cache = null; } return this; } public void printFunctionDefs(GazelleV_LeftArrowScript.Script script) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print(values(script.functionDefs)); } public AutoCloseable tempAddKnownVars(String... vars) { return tempAddKnownVars(nonNulls(vars)); } public AutoCloseable tempAddKnownVars(Iterable vars) { var newVars = mapWithSingleValue(vars, new LASValueDescriptor()); return tempAddKnownVars(newVars); } public AutoCloseable tempAddKnownVar(String var, LASValueDescriptor type) { return tempAddKnownVars(litmap(var, type)); } public AutoCloseable tempAddKnownVars(Map newVars) { return tempMapPutAll(knownVars, newVars); } public String parseFunctionDefArg(Map argsOut) { if (consumeOpt("(")) { String result = parseFunctionDefArg(argsOut); consume(")"); return result; } if (isIdentifier()) { String arg = tpp(); var type = typeToValueDescriptor(parseColonTypeOpt()); argsOut.put(arg, type); return arg; } return null; } public GazelleV_LeftArrowScript.FunctionDef parseFunctionDefinition(Map functionDefsToAddTo) { var start = ptr(); consume("def"); boolean synthetic = consumeOpt("!"); if (synthetic) consume("synthetic"); String functionName = assertIdentifier(tpp()); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("parseFunctionDefinition " + functionName); return parseFunctionDefinition_step2(functionDefsToAddTo, start, functionName).synthetic(synthetic); } public GazelleV_LeftArrowScript.FunctionDef parseFunctionDefinition_step2(Map functionDefsToAddTo, ListAndIndex start, String functionName) { LinkedHashMap args = new LinkedHashMap(); while (parseFunctionDefArg(args) != null) { } var returnType = parseColonTypeOpt(); var fd = new GazelleV_LeftArrowScript.FunctionDef(functionName, keysList(args), null); fd.argTypes(valuesArray(LASValueDescriptor.class, args)); { if (functionDefsToAddTo != null) functionDefsToAddTo.put(functionName, fd); } AutoCloseable __13 = tempAddKnownVars(args); try { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Parsing function body"); fd.body = parseReturnableCurlyBlock(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Defined function " + functionName + ", added to " + functionDefsToAddTo); if (returnType != null) fd.returnType(returnType); return linkToSrc(start, fd); } finally { _close(__13); } } public Scope currentScope() { return scope; } public AutoCloseable tempScope(Scope scope) { var oldScope = currentScope(); this.scope = scope; return () -> { this.scope = oldScope; }; } public GazelleV_LeftArrowScript.Script parseReturnableCurlyBlock() { return (GazelleV_LeftArrowScript.Script) parseCurlyBlock(new BuildingScript().returnable(true)); } public GazelleV_LeftArrowScript.Evaluable parseCurlyBlock() { return parseCurlyBlock(new BuildingScript()); } public GazelleV_LeftArrowScript.Evaluable parseCurlyBlock(BuildingScript script) { consume("{"); boolean inParensOld = inParens; inParens = false; var body = parseScript(script); consume("}"); inParens = inParensOld; return body; } public GazelleV_LeftArrowScript.Evaluable parseWhileLoop() { consume("while"); var condition = parseExpr(); var body = parseCurlyBlock(new BuildingScript().isLoopBody(true)); return new GazelleV_LeftArrowScript.While(condition, body); } public GazelleV_LeftArrowScript.Evaluable parseForEach() { return new ParseForEach().get(); } public class ParseForEach { public GazelleV_LeftArrowScript.Evaluable collection, body; public IF0 finish; public Set vars = new HashSet(); public String addVar(String var) { return addAndReturn(vars, var); } public String consumeVar() { return addVar(consumeIdentifier()); } public void parseBody() { AutoCloseable __14 = tempAddKnownVars(vars); try { body = parseCurlyBlock(new BuildingScript().isLoopBody(true)); } finally { _close(__14); } } public GazelleV_LeftArrowScript.Evaluable get() { consume("for"); if (is(1, "to")) { String var = consumeVar(); consume("to"); GazelleV_LeftArrowScript.Evaluable endValue = parseExpr(); parseBody(); return new GazelleV_LeftArrowScript.ForIntTo(endValue, var, body); } int iIn = relativeIndexOf("in"); if (iIn < 0) throw fail("for without in"); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("iIn", iIn); if (iIn == 1) { String var = consumeVar(); finish = () -> new GazelleV_LeftArrowScript.ForEach(collection, var, body); } else if (iIn == 2) { if (consumeOpt("iterator")) { String var = consumeVar(); finish = () -> new GazelleV_LeftArrowScript.ForIterator(collection, var, body); } else if (consumeOpt("nested")) { String var = consumeVar(); finish = () -> new GazelleV_LeftArrowScript.ForNested(collection, var, body); } else throw fail("Unknown pattern for 'for' loop"); } else if (iIn == 3) { if (isOneOf("pair", "Pair")) { consume(); String varA = consumeVar(); String varB = consumeVar(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("varA", varA, "varB", varB); finish = () -> new GazelleV_LeftArrowScript.ForPairs(collection, body, varA, varB); } else { String varA = consumeVar(); consume(","); String varB = consumeVar(); finish = () -> new GazelleV_LeftArrowScript.ForKeyValue(collection, body, varA, varB); } } else if (iIn == 4) { consume("index"); String varIndex = consumeVar(); consume(","); String varElement = consumeVar(); finish = () -> new GazelleV_LeftArrowScript.ForIndex(collection, body, varIndex, varElement); } else throw fail("Unknown pattern for 'for' loop"); consume("in"); collection = parseExpr_inParens(); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("collection", collection); parseBody(); return finish.get(); } } public GazelleV_LeftArrowScript.Evaluable parseIfStatement() { consume("if"); GazelleV_LeftArrowScript.Evaluable condition, body, elseBranch = null; { AutoCloseable __15 = tempAdd(closerTokens, "then"); try { condition = parseExpr(); } finally { _close(__15); } } if (consumeOpt("then")) { AutoCloseable __16 = tempAdd(closerTokens, "else"); try { body = parseExpr(); if (consumeOpt("else")) elseBranch = parseExpr(); } finally { _close(__16); } } else { body = parseCurlyBlock(); if (consumeOpt("else")) { if (is("if")) elseBranch = parseIfStatement(); else elseBranch = parseCurlyBlock(); } } return new GazelleV_LeftArrowScript.IfThen(condition, body, elseBranch); } public GazelleV_LeftArrowScript.Evaluable parseRepeatStatement() { consume("repeat"); var n = parseExpr(); var body = parseCurlyBlock(); return new GazelleV_LeftArrowScript.RepeatN(n, body); } public void addVar(String var) { addVar(var, new LASValueDescriptor()); } public void addVar(String var, LASValueDescriptor type) { knownVars.put(var, type); } public void addVar(String var, Class type, boolean canBeNull) { addVar(var, typeToValueDescriptor(type, canBeNull)); } public LASValueDescriptor typeToValueDescriptor(Type type) { return typeToValueDescriptor(type, true); } public LASValueDescriptor typeToValueDescriptor(Type type, boolean canBeNull) { return type == null ? new LASValueDescriptor() : new LASValueDescriptor.NonExact(typeToClass(type), canBeNull); } public Map globalClassNames_cache; public Map globalClassNames() { if (globalClassNames_cache == null) globalClassNames_cache = globalClassNames_load(); return globalClassNames_cache; } public Map globalClassNames_load() { var packages = mapToTreeSet(importedPackages(), pkg -> pkg + "."); Map out = new HashMap(); for (var name : unnullForIteration(importedClasses())) out.put(shortenClassName(name), name); for (var fc : functionContainers) if (fc instanceof Class) { if (isAnonymousClass((Class) fc)) continue; out.put(shortClassName((Class) fc), className((Class) fc)); } var classContainers = classContainerPrefixes(); TreeSet classContainerSet = asTreeSet(classContainers); for (var className : classNameResolver().allFullyQualifiedClassNames()) { if (isAnonymousClassName(className)) continue; if (!contains(className, '$')) { String pkg = longestPrefixInTreeSet(className, packages); if (pkg != null) { String shortName = dropPrefix(pkg, className); if (!shortName.contains(".") && !out.containsKey(shortName)) out.put(shortName, className); } } String container = longestPrefixInTreeSet(className, classContainerSet); if (container != null) { String shortName = dropPrefix(container, className); String existing = out.get(shortName); if (existing != null) { int priority = indexOf(classContainers, container); String oldContainer = longestPrefixInTreeSet(existing, classContainerSet); int oldPriority = indexOf(classContainers, oldContainer); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("className", className, "shortName", shortName, "container", container, "priority", priority, "existing", existing, "oldPriority", oldPriority); if (priority > oldPriority) continue; } out.put(shortName, className); } } for (var __22 : _entrySet(unnullForIteration(classShortcuts()))) { var key = __22.getKey(); var val = __22.getValue(); String fullName = out.get(val); if (fullName != null) out.put(key, fullName); } return out; } transient public IF0> classShortcuts; public Map classShortcuts() { return classShortcuts != null ? classShortcuts.get() : classShortcuts_base(); } final public Map classShortcuts_fallback(IF0> _f) { return _f != null ? _f.get() : classShortcuts_base(); } public Map classShortcuts_base() { return javaxClassShortcuts(); } transient public IF0> importedPackages; public Collection importedPackages() { return importedPackages != null ? importedPackages.get() : importedPackages_base(); } final public Collection importedPackages_fallback(IF0> _f) { return _f != null ? _f.get() : importedPackages_base(); } public Collection importedPackages_base() { return itemPlus("java.lang", standardImports_fullyImportedPackages()); } transient public IF0> importedClasses; public Collection importedClasses() { return importedClasses != null ? importedClasses.get() : importedClasses_base(); } final public Collection importedClasses_fallback(IF0> _f) { return _f != null ? _f.get() : importedClasses_base(); } public Collection importedClasses_base() { return standardImports_singleClasses(); } public void addClassAlias(String alias, String longName) { String fullName = globalClassNames().get(longName); if (fullName != null) globalClassNames().put(alias, fullName); } public List classContainerPrefixes() { return map(functionContainers, fc -> className(fc) + "$"); } static public class UnknownObject extends RuntimeException implements IFieldsToList { public String name; public UnknownObject() { } public UnknownObject(String name) { this.name = name; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + name + ")"; } public Object[] _fieldsToList() { return new Object[] { name }; } public String getMessage() { return "Unknown object: " + name; } } static public class ClassNotFound extends UnknownObject { public ClassNotFound(String className) { super(className); } public String getMessage() { return "Class not found: " + name; } } abstract static public class Scope { public GazelleV_LeftArrowScript.Evaluable parseExprStartingWithIdentifierOpt(String t, boolean inner) { return null; } public GazelleV_LeftArrowScript.Evaluable completeAssignmentOpt(String lhs, GazelleV_LeftArrowScript.Evaluable rhs) { return null; } } public class ClassDefScope extends Scope implements IFieldsToList { public LASClassDef classDef; public ClassDefScope() { } public ClassDefScope(LASClassDef classDef) { this.classDef = classDef; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + classDef + ")"; } public boolean equals(Object o) { if (!(o instanceof ClassDefScope)) return false; ClassDefScope __0 = (ClassDefScope) o; return eq(classDef, __0.classDef); } public int hashCode() { int h = -1760310585; h = boostHashCombine(h, _hashCode(classDef)); return h; } public Object[] _fieldsToList() { return new Object[] { classDef }; } public GazelleV_LeftArrowScript.Evaluable getThis() { return new GazelleV_LeftArrowScript.GetVar("this"); } public GazelleV_LeftArrowScript.Evaluable parseExprStartingWithIdentifierOpt(String t, boolean inner) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("ClassDefScope.parseExprStartingWithIdentifierOpt", "t", t); return linkToSrc(() -> { var field = classDef.fieldsByName.get(t); if (field != null) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Found field " + field); var e = inner ? new GazelleV_LeftArrowScript.GetField(getThis(), field.name) : new GazelleV_LeftArrowScript.CallMethodOrGetField(getThis(), field.name); return parseCall(inner, e); } Class superClass = typeToClass(classDef.superClass); var field2 = findFieldOfClass(superClass, t); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("field2", field2, "superClass", superClass, "t", t); if (field2 != null) { if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) print("Found field " + field2); var e = inner ? new GazelleV_LeftArrowScript.GetField(getThis(), field2.getName()) : new GazelleV_LeftArrowScript.CallMethodOrGetField(getThis(), field2.getName()); return parseCall(inner, e); } if (!inner && (classDef.methodsByName.containsKey(t) || classHasMethodNamed(typeToClass(classDef.superClass), t))) { return new GazelleV_LeftArrowScript.CallMethod(getThis(), t, parseArguments()); } return null; }); } public GazelleV_LeftArrowScript.Evaluable completeAssignmentOpt(String lhs, GazelleV_LeftArrowScript.Evaluable rhs) { var field = classDef.fieldsByName.get(lhs); if (field != null) return new GazelleV_LeftArrowScript.SetField(getThis(), lhs, rhs); Class superClass = typeToClass(classDef.superClass); var field2 = findFieldOfClass(superClass, lhs); if (field2 != null) return new GazelleV_LeftArrowScript.SetField(getThis(), lhs, rhs); return null; } } public LASClassDef parseClassDef() { return linkToSrc(() -> { consume("class"); LASClassDef classDef = new LASClassDef(); classDef.verbose(scaffoldingEnabled()); if (nempty(classDefPrefix)) classDef.classDefPrefix(classDefPrefix); String name = consumeIdentifier(); classDef.userGivenName(name); classDefs.put(name, classDef); AutoCloseable __17 = tempMapPut(classDefs, "selfType", classDef); try { if (consumeOpt("extends")) { classDef.superClass(parseType()); } if (consumeOpt("is")) classDef.interfaces.add(parseType()); consume("{"); AutoCloseable __18 = tempAddKnownVar("this", new LASValueDescriptor.NonExactType(classDef.resolvable(lasClassLoader), false)); try { AutoCloseable __19 = !objectScopesEnabled ? null : tempScope(new ClassDefScope(classDef)); try { while (!is("}")) { if (is(";")) { next(); continue; } if (is("def")) { GazelleV_LeftArrowScript.FunctionDef fd = parseFunctionDefinition(null); if (GazelleV_LeftArrowScriptParser.this.scaffoldingEnabled()) printVars("knownVarsAfterFunctionDef", knownVars); classDef.addMethod(fd); continue; } var start = ptr(); if (consumeOpt("ctor")) { var fd = parseFunctionDefinition_step2(null, start, ""); fd.returnType(void.class); classDef.addMethod(fd); continue; } if (consumeOpt("initializer")) { classDef.initializers.add(parseCurlyBlock()); continue; } LASClassDef.FieldDef fd = new LASClassDef.FieldDef(); if (is("transient")) { fd.addModifier(tpp()); } fd.name(consumeIdentifier()); var type = parseColonType(); fd.type(type); if (consumeLeftArrowOpt()) fd.initializer(parseExpr()); classDef.addField(fd); } consume("}"); return classDef; } finally { _close(__19); } } finally { _close(__18); } } finally { _close(__17); } }); } public Type parseColonTypeOpt() { if (is(":")) return parseColonType(); return null; } public Type parseColonType() { consume(":"); return parseType(); } public Type findType(String typeName) { LASClassDef cd = classDefs.get(typeName); if (cd != null) return cd.resolvable(lasClassLoader); Object o = findExternalObject(typeName); if (o instanceof Class) return ((Class) o); throw new ClassNotFound(typeName); } public Type parseType() { String typeName = consumeIdentifier(); Type type = findType(typeName); return parseArrayType(parseTypeArguments(type)); } public Type parseArrayType(Type type) { while (is("[") && is(1, "]")) { consume(2); type = new GenericArrayTypeImpl(type); } return type; } final public Type parseTypeArgumentsOpt(Type type) { return parseTypeArguments(type); } public Type parseTypeArguments(Type type) { if (is("<") && empty(nextSpace()) && isIdentifier(token(1))) { next(); List args = new ArrayList(); while (true) { args.add(parseType()); if (is(">")) break; consume(","); } consume(">"); if (type != null) type = new ParameterizedTypeImpl(null, type, toTypedArray(Type.class, args)); } return type; } transient public IF1 classForName; public Class classForName(String name) { return classForName != null ? classForName.get(name) : classForName_base(name); } final public Class classForName_fallback(IF1 _f, String name) { return _f != null ? _f.get(name) : classForName_base(name); } public Class classForName_base(String name) { try { return Class.forName(name); } catch (Exception __e) { throw rethrow(__e); } } public void copyFunctionContainersFrom(GazelleV_LeftArrowScriptParser parser) { functionContainers = cloneList(parser.functionContainers); globalClassNames_cache = parser.globalClassNames(); isBlockedFunctionContainerMethod = parser.isBlockedFunctionContainerMethod; } public ClassNameResolver classNameResolver() { if (classNameResolver == null) classNameResolver = new ClassNameResolver().byteCodePath(assertNotNull(getBytecodePathForClass(this))).init(); return classNameResolver; } public GazelleV_LeftArrowScriptParser classNameResolver(ClassNameResolver classNameResolver) { this.classNameResolver = classNameResolver; return this; } public GazelleV_LeftArrowScript.Evaluable parseStringLiteral() { return _const(unquote_relaxedMLS(consume())); } public void addFunctionDefs(Map map) { putAll(functionDefs, map); } public GazelleV_LeftArrowScriptParser setFlag(String flag) { flags.add(flag); return this; } public boolean getFlag(String flag) { return flags.contains(flag); } public void noImports() { importedPackages = () -> null; importedClasses = () -> null; classShortcuts = () -> null; } } 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(); { cleanUp(sleeper); sleeper = null; } } } 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 FlexThreadLocal extends BetterThreadLocal { static public Map motherThreads = weakMap(); public A get() { return get(grandMotherThread()); } public void set(A a) { map.put(grandMotherThread(), a); } static public Thread grandMotherThread() { return grandMotherThread(currentThread()); } static public Thread grandMotherThread(Thread t) { return applyWhileNotNull(__197 -> motherThread(__197), t); } static public void setMotherThread(Thread t) { mapPutOrRemove(motherThreads, currentThread(), grandMotherThread(t)); } static public Thread motherThread() { return motherThread(currentThread()); } static public Thread motherThread(Thread t) { return mapGet(motherThreads, t); } } static public class OrError extends Var { public Object error; public OrError() { } public OrError(A value) { super(value); } public OrError(boolean dummy, Object error) { this.error = error; assertNotNull(error); } public boolean ok() { return error == null; } public Object error() { return error; } static public OrError ok(B a) { return new OrError(a); } static public OrError error(Object error) { return new OrError(true, error); } public String toString() { return ok() ? super.toString() : str(error); } } 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 SnippetTitles { public Map titles = synchroHashMap(); public String get(String snippetID) { if (snippetID == null) return null; long id = parseSnippetID(snippetID); if (titles.containsKey(id)) return titles.get(id); else { String title = getSnippetTitle_safe(snippetID); titles.put(id, title); return title; } } public String probe(String id) { return titles.get(parseSnippetID(id)); } public void put(String id, String title) { titles.put(parseSnippetID(id), title); } public boolean has(String id) { return titles.containsKey(parseSnippetID(id)); } public void clear() { titles.clear(); } } static public class RandomAccessSubList extends SubList implements RandomAccess { public RandomAccessSubList(List root, int fromIndex, int toIndex) { super(root, fromIndex, toIndex); } } static public class BreadthFirstPathFinder_withLinkType implements Steppable { public LinkedList queue = new LinkedList(); public MultiMap> links = new MultiMap(); public IF1>> getChildren; public BreadthFirstPathFinder_withLinkType() { } public BreadthFirstPathFinder_withLinkType(IF1>> getChildren) { this.getChildren = getChildren; } public BreadthFirstPathFinder_withLinkType(IF1>> getChildren, A startNode) { this.getChildren = getChildren; add(startNode); } public void add(A a) { add(a, null, null); } public void add(A a, A prev, B linkType) { if (!links.containsKey(a)) { links.put(a, prev == null ? null : pair(prev, linkType)); queue.add(a); } } public boolean step() { ping(); if (empty(queue)) return false; A a = popFirst(queue); for (Pair link : unnullForIteration(getChildren.get(a))) add(link.a, a, link.b); return true; } public boolean nodeReached(A a) { return links.containsKey(a); } public Collection getBackLinks(A a) { return pairsA(links.get(a)); } public Collection> getBackLinksWithTypes(A a) { return links.get(a); } public List> examplePathWithTypes(A start, A dest) { List> path = new ArrayList(); A node = dest; path.add(pair(node, null)); while (node != start) { ping(); Pair link = first(getBackLinksWithTypes(node)); if (link == null) return null; path.add(link); node = link.a; } return reversed(path); } } 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); } } static public class ReliableSingleThread_Multi { public IVF1 processObject; public int delay; public ReliableSingleThread_Multi(IVF1 processObject) { this.processObject = processObject; } public ReliableSingleThread_Multi(int delay, IVF1 processObject) { this.processObject = processObject; this.delay = delay; } public ReliableSingleThread_Multi(int delay, IVF1 processObject, F0 enter) { this.processObject = processObject; this.delay = delay; setEnter(enter); } public Set changedObjects = synchroSet(); public ReliableSingleThread rst = new ReliableSingleThread(new Runnable() { public void run() { try { process(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "process();"; } }); public void add(A a) { if (changedObjects.add(a)) rst.trigger(); } public void addAll(Iterable l) { for (A a : unnullForIteration(l)) { ping(); add(a); } } private void process() { sleep(delay); for (A object : syncCloneAndClearList(changedObjects)) { ping(); pcallF(processObject, object); } } public void setEnter(F0 enter) { rst.enter = enter; } } public interface TransientObject { } 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 CompactHashSet extends java.util.AbstractSet { final static public int INITIAL_SIZE = 0; final static public int FIRST_INCREMENT = 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 CompactHashSet() { this(INITIAL_SIZE); } public CompactHashSet(int size) { objects = (A[]) (size == 0 ? emptyObjectArray() : new Object[size]); elements = 0; freecells = objects.length; modCount = 0; } public CompactHashSet(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; } synchronized public A find(Object o) { if (objects.length == 0) return null; 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 synchronized public boolean add(Object o) { if (objects.length == 0) rehash(FIRST_INCREMENT); 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 synchronized public boolean remove(Object o) { if (objects.length == 0) return false; 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 synchronized public void clear() { elements = 0; for (int ix = 0; ix < objects.length; ix++) objects[ix] = null; freecells = objects.length; modCount++; } @Override synchronized 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 synchronized 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() { synchronized (CompactHashSet.this) { for (index = 0; index < objects.length && (objects[index] == null || objects[index] == deletedObject); index++) ; expectedModCount = modCount; } } @Override public boolean hasNext() { synchronized (CompactHashSet.this) { return index < objects.length; } } @SuppressWarnings("empty-statement") @Override public T next() { synchronized (CompactHashSet.this) { 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() { synchronized (CompactHashSet.this) { 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; } } } } synchronized public int capacity() { return objects.length; } synchronized 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 MultiSetMapWithTopTen extends MultiSetMap { public MultiSetMap byCount = multiSetMap_innerLinkedHashSet_outerRevTreeMap(); public MultiSetMapWithTopTen() { } public MultiSetMapWithTopTen(boolean useTreeMap) { super(useTreeMap); } public MultiSetMapWithTopTen(MultiSetMap map) { super(map); } public MultiSetMapWithTopTen(Map> data) { super(data); } private void unindex(A key, Set values) { if (nempty(values)) byCount.remove(l(values), key); } private void index(A key, Set values) { if (nempty(values)) byCount.add(l(values), key); } public boolean put(A key, B value) { synchronized (data) { Set set = data.get(key); unindex(key, set); if (set == null) data.put(key, set = _makeEmptySet()); boolean changed = set.add(value); index(key, set); if (!changed) return false; { ++size; return true; } } } public void remove(A key) { synchronized (data) { Set set = data.get(key); if (set == null) return; size -= l(set); unindex(key, set); data.remove(key); } } public void remove(A key, B value) { synchronized (data) { Set set = data.get(key); if (set == null) return; unindex(key, set); boolean changed = set.remove(value); index(key, set); if (changed) { --size; if (set.isEmpty()) data.remove(key); } } } public void clear() { synchronized (data) { data.clear(); byCount.clear(); size = 0; } } public IterableIterator keysByPopularityIterator() { return multiSetMapValuesIterator(byCount); } } 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 StringTree2 { public A leafValue; public HashMap> children = new HashMap(); public A get() { return leafValue; } public StringTree2 get(String s) { return children.get(s); } public StringTree2 getOrAdd(String s) { StringTree2 t = children.get(s); if (t == null) children.put(s, t = new StringTree2()); return t; } } static public interface SteppableAndIF0 extends Steppable, IF0 { } 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 + "]"; } } 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 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 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 InternationalPhoneValidator { public String rawInput; public String filtered; public List dialCodes; public String countryPart, localPart; public boolean valid = false; public String error; public InternationalPhoneValidator() { } public InternationalPhoneValidator(String rawInput) { this.rawInput = rawInput; } public void run() { try { filtered = dropPrefix("+", dropSpecialChars(rawInput)); if (!isAllDigits(filtered)) { error = "Bad characters"; return; } splitLocal(); } catch (Exception __e) { throw rethrow(__e); } } public String dropSpecialChars(String s) { return replaceAll(s, "[\\s\\(\\)\\-]", ""); } public void splitLocal() { String countryPart = longestPrefixInNavigableSet(filtered, navigableKeys(countryDialCodes_rawNumbersTreeMultiMap())); if (countryPart == null) { error = "Invalid country code"; return; } dialCodes = countryDialCodes_rawNumbersTreeMultiMap().get(countryPart); localPart = dropPrefix(countryPart, filtered); if (l(filtered) < 7) { error = "Phone number too short"; return; } else if (l(filtered) > 15) { error = "Phone number too long"; return; } valid = true; } } 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 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 ConceptFieldIndexCI_withTopTen extends ConceptFieldIndexCI { public ConceptFieldIndexCI_withTopTen(Class cc, String field) { super(cc, field); } public ConceptFieldIndexCI_withTopTen(Concepts concepts, Class cc, String field) { super(concepts, cc, field); } public void init() { valueToObject = generalizedCIMultiSetMapWithTopTen(); } } static public interface ValueConverterForField { public OrError convertValue(Object object, Field field, Object value); } static public interface Visitable { public void visitUsing(IVF1 f); } static public class MultiSleeper extends RestartableCountdown implements ISleeper_v2 { public MultiSetMap entries = treeMultiSetMap(); public void check() { var time = nextWakeUpTime(); var action = firstValue(entries); 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..."; } }); } synchronized public 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); } } }; } } 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 WithPollValue extends LazyVar { public Object pollValue = noPoll; static public Object noPoll = new Object(); public WithPollValue() { } public WithPollValue(Object pollValue, IF0 makeValue) { super(makeValue); this.pollValue = pollValue; } public WithPollValue(Object pollValue, A value) { super(value); this.pollValue = pollValue; } public Object pollValue() { return pollValue; } public String toString() { return "WithPollValue " + pollValue + " " + super.toString(); } } 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 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 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 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 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 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 abstract public class F3 { abstract public D get(A a, B b, C c); } static public class Not implements IFieldsToList, Transformable, Visitable { public A a; public Not() { } public Not(A a) { this.a = a; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + a + ")"; } public boolean equals(Object o) { if (!(o instanceof Not)) return false; Not __0 = (Not) o; return eq(a, __0.a); } public int hashCode() { int h = 78515; h = boostHashCombine(h, _hashCode(a)); return h; } public Object[] _fieldsToList() { return new Object[] { a }; } public Object transformUsing(IF1 f) { return new Not((A) f.get(a)); } public void visitUsing(IVF1 f) { f.get(a); } public Boolean get(Object o) { return not((Boolean) callF(a, o)); } } public static interface IF0 { public A get(); } static public interface IHasGlobalID { public GlobalID globalID(); } static public class DefaultValueConverterForField implements ValueConverterForField { public OrError convertValue(Object object, Field field, Object value) { Class actualType = field.getType(); Class type = primitiveToBoxedTypeOpt(actualType); if (isInstance(type, value)) return new OrError(value); if (type == Integer.class && !(value instanceof Integer)) return new OrError(toInt(trimIfString(value))); if (type == Double.class && !(value instanceof Double)) return new OrError(toDouble(trimIfString(value))); if (type == Boolean.class && value instanceof String) if (actualType == Boolean.class && eq(value, "")) return new OrError(null); else return new OrError(eqicOneOf((String) value, "1", "true", "yes")); if (type == GlobalID.class && value instanceof String) return new OrError(new GlobalID((String) value)); return new OrError(value); } } static public class StringBufferWithMaxSize implements Appendable { public int maxSize; public StringBuilder buf = new StringBuilder(); public StringBufferWithMaxSize(int maxSize) { this.maxSize = maxSize; } public Appendable append(char c) { return append(str(c)); } public Appendable append(CharSequence csq, int start, int end) { return append(csq.subSequence(start, end)); } public int size() { return l(buf); } public synchronized Appendable append(CharSequence csq) { if (full()) return this; int n = l(csq); if (size() + n > maxSize) buf.append(subCharSequence(csq, maxSize - size())); else buf.append(csq); return this; } public boolean full() { return size() >= maxSize; } synchronized public String toString() { return str(buf); } } 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 interface IF2 { public C get(A a, B b); } static public interface IF1 { public B get(A a); } static public interface IVF1 { public void get(A a); } static public interface IVF2 { public void get(A a, B b); } 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 public class Options extends ConceptL { public Options() { } public Options(List l) { super(l); } public Options(Concept... l) { super(asList(l)); } } static public class HDivWithVerticalExpandButton { public int initialHeight; public String expandButtonText = "MORE"; public Object contents; public String btnID = aGlobalID(); public HDivWithVerticalExpandButton(int initialHeight, Object contents) { this.contents = contents; this.initialHeight = initialHeight; } public HDivWithVerticalExpandButton(int initialHeight, Object contents, String expandButtonText) { this.expandButtonText = expandButtonText; this.contents = contents; this.initialHeight = initialHeight; } public String html() { return hjs(expandVars("var pressed_$btnID = false;")) + div(contents, "class", "expandable", "style", "max-height: " + initialHeight + "px; overflow: hidden;") + "\n" + hbuttonOnClick_noSubmit(expandButtonText, expandVars("\r\n pressed_$btnID = true;\r\n $(this).prev('.expandable').css('max-height', 'none');\r\n $(this).hide();\r\n "), "style", "display: none", "id", btnID) + "\n" + hjs(expandVars("\r\n {\r\n let btn = $('#$btnID');\r\n window.check_$btnID = function() {\r\n if (pressed_$btnID) return;\r\n $(btn).toggle($(btn).prev('.expandable').outerHeight() >= $initialHeight);\r\n setTimeout(check_$btnID, 5000);\r\n };\r\n check_$btnID(); setTimeout(check_$btnID, 1000);\r\n }\r\n ")); } public String expandVars(String js) { return replaceDollarVars(js, "btnID", btnID, "initialHeight", initialHeight); } public boolean needsJQuery() { return true; } } 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 abstract public class LiveValue implements IF0WithChangeListeners { abstract public Class getType(); public abstract A get(); } 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 _PrintIndent extends F1 { public String prefix; public boolean beginningOfLine = true; public _PrintIndent() { } public _PrintIndent(String prefix) { this.prefix = prefix; } public Boolean get(String s) { if (empty(s)) return false; boolean nl = s.endsWith("\n"); if (nl) s = dropLast(s); s = s.replace("\n", "\n" + prefix); print_raw(beginningOfLine ? prefix + s : s); if (nl) print_raw("\n"); beginningOfLine = nl; return false; } } static public class JavaScript extends Var { public JavaScript() { } public JavaScript(String src) { super(src); } public String javaScriptSource() { return get(); } public String toString() { return hjs(get()); } } static public interface Steppable { public boolean step(); } static public class MMOPattern { static public class Phrase extends MMOPattern implements IFieldsToList { public String phrase; public boolean quoted = false; public Phrase() { } public Phrase(String phrase, boolean quoted) { this.quoted = quoted; this.phrase = phrase; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + phrase + ", " + quoted + ")"; } public boolean equals(Object o) { if (!(o instanceof Phrase)) return false; Phrase __1 = (Phrase) o; return eq(phrase, __1.phrase) && eq(quoted, __1.quoted); } public int hashCode() { int h = -1905095975; h = boostHashCombine(h, _hashCode(phrase)); h = boostHashCombine(h, _hashCode(quoted)); return h; } public Object[] _fieldsToList() { return new Object[] { phrase, quoted }; } } static public class And extends MMOPattern implements IFieldsToList { public List l; public And() { } public And(List l) { this.l = l; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + l + ")"; } public boolean equals(Object o) { if (!(o instanceof And)) return false; And __2 = (And) o; return eq(l, __2.l); } public int hashCode() { int h = 65975; h = boostHashCombine(h, _hashCode(l)); return h; } public Object[] _fieldsToList() { return new Object[] { l }; } } static public class Or extends MMOPattern implements IFieldsToList { public List l; public Or() { } public Or(List l) { this.l = l; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + l + ")"; } public boolean equals(Object o) { if (!(o instanceof Or)) return false; Or __3 = (Or) o; return eq(l, __3.l); } public int hashCode() { int h = 2563; h = boostHashCombine(h, _hashCode(l)); return h; } public Object[] _fieldsToList() { return new Object[] { l }; } } static public class Not extends MMOPattern implements IFieldsToList { public MMOPattern p; public Not() { } public Not(MMOPattern p) { this.p = p; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + p + ")"; } public boolean equals(Object o) { if (!(o instanceof Not)) return false; Not __4 = (Not) o; return eq(p, __4.p); } public int hashCode() { int h = 78515; h = boostHashCombine(h, _hashCode(p)); return h; } public Object[] _fieldsToList() { return new Object[] { p }; } } static public class Weighted extends MMOPattern implements IFieldsToList { static final public String _fieldOrder = "weight p"; public double weight; public MMOPattern p; public Weighted() { } public Weighted(double weight, MMOPattern p) { this.p = p; this.weight = weight; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + weight + ", " + p + ")"; } public boolean equals(Object o) { if (!(o instanceof Weighted)) return false; Weighted __5 = (Weighted) o; return weight == __5.weight && eq(p, __5.p); } public int hashCode() { int h = -446368457; h = boostHashCombine(h, _hashCode(weight)); h = boostHashCombine(h, _hashCode(p)); return h; } public Object[] _fieldsToList() { return new Object[] { weight, p }; } } static public class StartOfLine extends MMOPattern implements IFieldsToList { public MMOPattern p; public StartOfLine() { } public StartOfLine(MMOPattern p) { this.p = p; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + p + ")"; } public boolean equals(Object o) { if (!(o instanceof StartOfLine)) return false; StartOfLine __6 = (StartOfLine) o; return eq(p, __6.p); } public int hashCode() { int h = -326863539; h = boostHashCombine(h, _hashCode(p)); return h; } public Object[] _fieldsToList() { return new Object[] { p }; } } static public class EndOfLine extends MMOPattern implements IFieldsToList { public MMOPattern p; public EndOfLine() { } public EndOfLine(MMOPattern p) { this.p = p; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + p + ")"; } public boolean equals(Object o) { if (!(o instanceof EndOfLine)) return false; EndOfLine __7 = (EndOfLine) o; return eq(p, __7.p); } public int hashCode() { int h = -810372346; h = boostHashCombine(h, _hashCode(p)); return h; } public Object[] _fieldsToList() { return new Object[] { p }; } } } 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 MetaTransformer { static public interface StructureHandler { default public Object transform(Object o, IF1 recurse) { return null; } public void visit(Object o, IVF1 recurse); } public List structureHandlers; public Set seen; public MetaTransformer() { } public MetaTransformer(StructureHandler... handlers) { structureHandlers = asList(handlers); } final public void add(StructureHandler sh) { addStructureHandler(sh); } public void addStructureHandler(StructureHandler sh) { structureHandlers.add(sh); } public Object transform(IF1 f, Object o) { ping(); Object x = f.get(o); if (x != null) return x; IF1 recurse = liftFunction(f); for (StructureHandler h : unnullForIteration(structureHandlers)) { ping(); { var __2 = h.transform(o, recurse); if (__2 != null) return __2; } } return o; } public void visit(IVF1 f, Object o) { ping(); if (o == null) return; if (seen != null && !seen.add(o)) return; f.get(o); for (StructureHandler h : unnullForIteration(structureHandlers)) { ping(); IVF1 recurse = x -> { markPointer(o, x); visit(f, x); }; h.visit(o, recurse); } } public void visit_vstack(IVF1 f, Object o) { vstackCompute(new visit_vstackComputable(f, o)); } public class visit_vstackComputable extends VStackComputableWithStep implements IFieldsToList { public IVF1 f; public Object o; public visit_vstackComputable() { } public visit_vstackComputable(IVF1 f, Object o) { this.o = o; this.f = f; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + f + ", " + o + ")"; } public boolean equals(Object _o) { if (!(_o instanceof visit_vstackComputable)) return false; visit_vstackComputable __0 = (visit_vstackComputable) _o; return eq(f, __0.f) && eq(o, __0.o); } public int hashCode() { int h = 1091269166; h = boostHashCombine(h, _hashCode(f)); h = boostHashCombine(h, _hashCode(o)); return h; } public Object[] _fieldsToList() { return new Object[] { f, o }; } public void step(VStack stack) { if (step == 0) { ping(); if (o == null) { stack._return(); return; } step++; } if (step == 1) { if (seen != null && !seen.add(o)) { stack._return(); return; } ++step; } if (step == 2) { f.get(o); ++step; } stack.replace(new ForEach_vstack<>(structureHandlers, h -> { IVF1 recurse = x -> { markPointer(o, x); stack.call(new visit_vstackComputable(f, x)); }; h.visit(o, recurse); })); } } public IF1 liftFunction(IF1 f) { return o -> transform(f, o); } public boolean any(IF1 pred, Object o) { Flag flag = new Flag(); withCancelPoint(cp -> visit(x -> { if (pred.get(x)) { flag.raise(); cancelTo(cp); } }, o)); return flag.isUp(); } public void addVisitor(IVF1 visitor) { if (visitor == null) return; addStructureHandler(new StructureHandler() { public void visit(Object o, IVF1 recurse) { visitor.get(o); } }); } public void avoidCycles() { seen = identityHashSet(); } transient public IVF2 markPointer; public void markPointer(Object a, Object b) { if (markPointer != null) markPointer.get(a, b); else markPointer_base(a, b); } final public void markPointer_fallback(IVF2 _f, Object a, Object b) { if (_f != null) _f.get(a, b); else markPointer_base(a, b); } public void markPointer_base(Object a, Object b) { } } 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 HTMLFramer1 { public String title; public boolean titleIsHTML = false; public List navItems = new ArrayList(); public List contents = new ArrayList(); public LinkedHashSet headElements = new LinkedHashSet(); public boolean navBeforeTitle = false; public List willRender = new ArrayList(); static public class NavItem implements IFieldsToList { static final public String _fieldOrder = "link html targetBlank"; public String link; public String html; public NavItem() { } public NavItem(String link, String html) { this.html = html; this.link = link; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + link + ", " + html + ")"; } public boolean equals(Object o) { if (!(o instanceof NavItem)) return false; NavItem __1 = (NavItem) o; return eq(link, __1.link) && eq(html, __1.html); } public int hashCode() { int h = -900864330; h = boostHashCombine(h, _hashCode(link)); h = boostHashCombine(h, _hashCode(html)); return h; } public Object[] _fieldsToList() { return new Object[] { link, html }; } public boolean targetBlank = false; } public String get() { return render(); } transient public IF0 render; public String render() { return render != null ? render.get() : render_base(); } final public String render_fallback(IF0 _f) { return _f != null ? _f.get() : render_base(); } public String render_base() { callFAll(willRender); return hhtml(hhead(htitle(titleIsHTML ? hTitleClean(title) : title) + lines(headElements)) + hbody((navBeforeTitle ? renderNav() + renderTitle() : renderTitle() + renderNav()) + nemptyLines(contents))); } transient public IF0 renderTitle; public String renderTitle() { return renderTitle != null ? renderTitle.get() : renderTitle_base(); } final public String renderTitle_fallback(IF0 _f) { return _f != null ? _f.get() : renderTitle_base(); } public String renderTitle_base() { return h1(encodedTitle()); } public String encodedTitle() { return titleIsHTML ? title : htmlEncode2(title); } transient public IF0 renderNav; public String renderNav() { return renderNav != null ? renderNav.get() : renderNav_base(); } final public String renderNav_fallback(IF0 _f) { return _f != null ? _f.get() : renderNav_base(); } public String renderNav_base() { if (empty(navItems)) return ""; return div_vbar(map(__127 -> renderNavItem(__127), navItems), "style", "margin-bottom: 0.5em"); } public String renderNavItem(NavItem ni) { return ahref_possiblyTargetBlank(ni.link, ni.html, ni.targetBlank); } public void addNavItem(String html) { navItems.add(new NavItem(null, html)); } public void addNavItems(Iterable htmls) { forEach(__128 -> addNavItem(__128), htmls); } public void addNavItem(String link, String html, Object... __) { navItems.add(setAll(new NavItem(link, html), filterParams(__, "targetBlank"))); } final public void addInHEAD(Object html) { addInHead(html); } public void addInHead(Object html) { headElements.add(str(html)); } public void add(String html) { add((Object) html); } public void add(IF0 html) { add(lambdaToToString(html)); } public void add(Object html) { if (notNullOrEmptyString(html)) contents.add(html); } public void addAll(Collection l) { forEach(__129 -> add(__129), l); } public void clearNavItems() { navItems.clear(); } public HTMLFramer1 setTitle(String title) { this.title = title; return this; } public String htmlTitle(String title) { this.title = title; titleIsHTML = true; return title; } public Collection headElements() { return headElements; } } 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(__130 -> f2s(__130), 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); } } 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 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 ChangeTriggerable { public void change(); } static public class TransferableImage implements Transferable { public Image i; public TransferableImage(Image i) { this.i = i; } public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (flavor.equals(DataFlavor.imageFlavor) && i != null) { return i; } else { throw new UnsupportedFlavorException(flavor); } } public DataFlavor[] getTransferDataFlavors() { DataFlavor[] flavors = new DataFlavor[1]; flavors[0] = DataFlavor.imageFlavor; return flavors; } public boolean isDataFlavorSupported(DataFlavor flavor) { DataFlavor[] flavors = getTransferDataFlavors(); for (int i = 0; i < flavors.length; i++) { if (flavor.equals(flavors[i])) { return true; } } return false; } } static public class SimpleCircularBuffer implements Iterable, IntSize { public SimpleCircularBuffer() { } public A[] buffer; public long base; public int size; public SimpleCircularBuffer(int capacity) { buffer = (A[]) new Object[capacity]; } synchronized public void add(A a) { if (size == buffer.length) { --size; ++base; } buffer[(int) ((base + size) % buffer.length)] = a; ++size; } synchronized public A get(long pos) { if (pos < base || pos >= base + size) return null; return buffer[(int) (pos % buffer.length)]; } synchronized public A getFromBase(long pos) { return get(pos + base); } public synchronized int size() { return size; } public Iterator iterator() { return new IterableIterator() { public long i; public boolean hasNext() { return i < size(); } public A next() { return get(base + (i++)); } }; } synchronized public int capacity() { return buffer.length; } synchronized public boolean isFull() { return size() == capacity(); } public boolean isEmpty() { return size() == 0; } final public long base() { return getBase(); } synchronized public long getBase() { return base; } final public A remove() { return popFirst(); } synchronized public A popFirst() { if (isEmpty()) return null; A a = get(base); --size; ++base; return a; } synchronized public A nextToLast() { return get(base + size - 2); } synchronized public A last() { return get(base + size - 1); } synchronized public A first() { return get(base); } public List asList() { return utils.asList(this); } } 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()); } } 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(); } } public interface Updateable { public void update(); } 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 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 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 __187 -> set(__187); } public String toString() { return str(this.get()); } } 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 class MRUAndAllTimeTop_optimized { public MRUAndAllTimeTop_optimized() { } public Map mru = syncMRUCache(10); public OptimizedMultiSet allTimeTop = new OptimizedMultiSet(); public int allTimeMaxSize = 100; synchronized public void add(A a) { mru.remove(a); mru.put(a, true); allTimeTop.add(a); allTimeTop.truncate(allTimeMaxSize); } synchronized public void addAll(Iterable l) { for (A a : unnullForIteration(l)) add(a); } synchronized public int size() { return l(mru) + allTimeTop.uniqueSize(); } synchronized public IterableIterator mixedIterator() { return uniqueIterator(roundRobinCombinedIterator(reversedIterator(keysList(mru)), iterator(allTimeTop.highestFirst()))); } public String toString() { return shortClassName(this) + " (" + n2(size()) + ")"; } public Collection recent() { return reversedKeysList(mru); } public A mostRecent() { return last(keys(mru)); } } static public interface ITokCondition { public boolean get(List tok, int i); } 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 class SecretValue extends Var { public SecretValue() { } public SecretValue(A a) { super(a); } public String toString() { return "Secret value"; } } 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; } } static public class CancelToCancelPoint extends QuickException { public CancelPoint cp; public CancelToCancelPoint(CancelPoint cp) { this.cp = cp; } } 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(); } } 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 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 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 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 CMissingObject extends Concept { } static public class HTMLPopDownButton { public Collection entries = new ArrayList(); public int width = 200, height = 200; public String id = "dropdown-" + aGlobalID(), outerID = "outer-" + id; public String onclick = replaceDollarVars("\r\n var x = document.getElementById($id);\r\n x.style.display = window.getComputedStyle(x).display === \"none\" ? \"block\" : \"none\";\r\n console.log(\"popup \" + id + \" display: \" + x.style.display);\r\n ", "$id", jsQuote(id)); public HTMLPopDownButton(String... entries) { this.entries = asList(entries); } public HTMLPopDownButton(Collection entries) { this.entries = entries; } public void add(String entry) { utils.add(this.entries, entry); } public void addAll(String... entries) { utils.addAll(this.entries, entries); } public String html() { return hstyle(replaceDollarVars("\r\n #$id ul {\r\n list-style-type: none;\r\n margin: 0;\r\n padding: 0;\r\n width: " + width + "px;\r\n background-color: #f1f1f1;\r\n }\r\n \r\n #$id {\r\n position: absolute;\r\n display:none;\r\n background-color: #f9f9f9;\r\n width:auto;\r\n height: " + height + "px;\r\n overflow: auto;\r\n \r\n min-width: 160px;\r\n box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);\r\n \r\n z-index: 99;\r\n }\r\n \r\n #$id li a {\r\n text-decoration: none;\r\n color: #000;\r\n }\r\n \r\n #$id li { \r\n display: block;\r\n border-bottom: 1px solid #555;\r\n padding: 8px 16px;\r\n color: #000;\r\n }\r\n " + "\r\n #$id li:hover, #$id li:hover > a {\r\n background-color: #3399ff;\r\n color: white;\r\n }\r\n ", "$id", id)) + hdiv(span(htmlEncode2(unicode_smallDownPointingTriangle()), "onclick", onclick) + hdiv(ul(entries), "id", id), "style", "position: relative; display: inline-block; cursor: context-menu", "id", outerID) + hscript(replaceDollarVars("\r\n if (typeof $ !== 'undefined')\r\n $('body').click(function(e) {\r\n //console.log(\"target=\" + e.target + \", outerID=$outerID\");\r\n if (!$(e.target).closest('#$outerID').length) {\r\n //console.log(\"hiding $id\");\r\n $(\"#$id\").hide();\r\n }\r\n });\r\n ", "id", id, "outerID", outerID)); } public HTMLPopDownButton width(int width) { this.width = width; return this; } public HTMLPopDownButton height(int height) { this.height = height; return this; } } 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 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 public interface IIntPred { public boolean get(int a); } 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 CountryDialCode implements IFieldsToList { public String country; public String countryCode; public String dialCode; public CountryDialCode() { } public CountryDialCode(String country, String countryCode, String dialCode) { this.dialCode = dialCode; this.countryCode = countryCode; this.country = country; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + country + ", " + countryCode + ", " + dialCode + ")"; } public boolean equals(Object o) { if (!(o instanceof CountryDialCode)) return false; CountryDialCode __1 = (CountryDialCode) o; return eq(country, __1.country) && eq(countryCode, __1.countryCode) && eq(dialCode, __1.dialCode); } public int hashCode() { int h = 240284435; h = boostHashCombine(h, _hashCode(country)); h = boostHashCombine(h, _hashCode(countryCode)); h = boostHashCombine(h, _hashCode(dialCode)); return h; } public Object[] _fieldsToList() { return new Object[] { country, countryCode, dialCode }; } } static public class MechListDependentCache extends Cache { public String listName, lastListContents; public MechListDependentCache() { } public MechListDependentCache(String listName, Object maker) { this.maker = maker; this.listName = listName; } public A make() { return (A) callF(maker, lastListContents); } public A get() { if (hasLock(lock)) return value; { String listContents = mL_raw(listName); Lock __0 = lock; lock(__0); try { if (!eqOrSame(listContents, lastListContents)) clear(); lastListContents = listContents; } finally { unlock(__0); } } return super.get(); } } 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 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 ConceptID implements IFieldsToList { public long id; public ConceptID() { } public ConceptID(long id) { this.id = id; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + id + ")"; } public boolean equals(Object o) { if (!(o instanceof ConceptID)) return false; ConceptID __1 = (ConceptID) o; return id == __1.id; } public int hashCode() { int h = 1110223203; h = boostHashCombine(h, _hashCode(id)); return h; } public Object[] _fieldsToList() { return new Object[] { id }; } public ConceptID(Concept concept) { id = concept.id; } } 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 HTMLTabs { public String id = "tabs_" + aGlobalID(); public List tabs = new ArrayList(); public class Tab { public String id = aGlobalID(); public String label; public String contents; public Tab(String label, String contents) { this.contents = contents; this.label = label; } } public String css() { return "\r\n .tab-selectors {\r\n display: flex;\r\n }\r\n \r\n .tab-selector {\r\n flex: 1;\r\n cursor: pointer;\r\n margin: 2px 2px;\r\n }\r\n \r\n .tab-selectors .selected {\r\n font-weight: bold;\r\n background: #add8e6;\r\n }\r\n \r\n .tabs-container {\r\n border-radius: 25px;\r\n border: 2px solid #73AD21;\r\n padding: 20px;\r\n }\r\n "; } public String html() { return hcss(css()) + div(div(mapToLines(tabs, tab -> div(tab.label, "class", "tab-selector" + stringIf(tab == first(tabs), " selected"), "onclick", "$(" + jsQuote("#" + id + " .tab-selector") + ").removeClass('selected'); " + "$(this).addClass('selected'); " + "$(" + jsQuote("#" + id + " .tab-page") + ").hide(); " + "$(" + jsQuote("#" + tab.id) + ").show();")), "class", "tab-selectors") + mapToLines(tabs, tab -> div(tab.contents, "class", "tab-page", "style", tab == first(tabs) ? "" : "display: none", "id", tab.id)), "id", id, "class", "tabs-container"); } public void add(String label, Object contents) { tabs.add(new Tab(label, strOrNull(contents))); } } 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; } } static public class CreatedDeletedChanged { static public class Created extends CreatedDeletedChanged implements IFieldsToList { public A a; public Created() { } public Created(A a) { this.a = a; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + a + ")"; } public boolean equals(Object o) { if (!(o instanceof Created)) return false; Created __1 = (Created) o; return eq(a, __1.a); } public int hashCode() { int h = -1601759544; h = boostHashCombine(h, _hashCode(a)); return h; } public Object[] _fieldsToList() { return new Object[] { a }; } } static public class Deleted extends CreatedDeletedChanged implements IFieldsToList { public A a; public Deleted() { } public Deleted(A a) { this.a = a; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + a + ")"; } public boolean equals(Object o) { if (!(o instanceof Deleted)) return false; Deleted __2 = (Deleted) o; return eq(a, __2.a); } public int hashCode() { int h = -1079851015; h = boostHashCombine(h, _hashCode(a)); return h; } public Object[] _fieldsToList() { return new Object[] { a }; } } static public class Changed extends CreatedDeletedChanged implements IFieldsToList { public A a; public A b; public Changed() { } public Changed(A a, A b) { this.b = b; this.a = a; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + a + ", " + b + ")"; } public boolean equals(Object o) { if (!(o instanceof Changed)) return false; Changed __3 = (Changed) o; return eq(a, __3.a) && eq(b, __3.b); } public int hashCode() { int h = -1891370348; h = boostHashCombine(h, _hashCode(a)); h = boostHashCombine(h, _hashCode(b)); return h; } public Object[] _fieldsToList() { return new Object[] { a, b }; } } } 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 SortedArrayBasedMap extends CompactAbstractMap { public Object[] entries; public SortedArrayBasedMap() { } public SortedArrayBasedMap(Map map) { List> l = pairsSortedByA(mapToPairs(map)); int n = l(l); entries = new Object[n * 2]; for (int i = 0; i < n; i++) { Pair p = l.get(i); entries[i * 2] = p.a; entries[i * 2 + 1] = p.b; } } public int size() { return l(entries) / 2; } public Set> entrySet() { return new AbstractSet>() { public int size() { return SortedArrayBasedMap.this.size(); } public Iterator> iterator() { return new Iterator>() { public int idx; public boolean hasNext() { return idx < l(entries); } public Map.Entry next() { SimpleEntry e = new SimpleEntry((A) entries[idx], (B) entries[idx + 1]); idx += 2; return e; } }; } }; } public int find(Object key) { return find(0, size(), key); } public int find(int fromIndex, int toIndex, Object key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; Object midVal = entries[mid * 2]; int c = cmp(midVal, key); if (c < 0) low = mid + 1; else if (c > 0) high = mid - 1; else return mid; } return -(low + 1); } public boolean containsKey(Object o) { return find(o) >= 0; } @Override public B get(Object o) { int i = find(o) * 2; return i >= 0 ? (B) entries[i + 1] : null; } } static public class ScoredSearcher { public int maxResults = 1000; public List preparedTerms; public Map scores = new HashMap(); public ScoredSearcher() { } public ScoredSearcher(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) { putUnlessZero(scores, object, scoredSearch_score(s, preparedTerms)); } 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 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) { putUnlessZero(scores, object, score); } public List get() { return takeFirst(maxResults, keysSortedByValuesDesc(scores)); } public List> withScores() { return map(get(), a -> scoredWithMapValue(scores, a)); } public A best() { return keyWithHighestValue(scores); } } 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 boolean SimpleCRUD_searcher = true; static public class SimpleCRUD { public Concepts concepts; public Class cc; public JTable table; public JPanel buttons, panel; public Object renderer; public Object sorter; public String hID = "ID"; public Set unshownFields; public Set excludeFieldsFromEditing; public String modifiedField; public TableSearcher tableSearcher; public Set multiLineFields; public Set dontDuplicateFields; public boolean latestFirst = false; public int formFixer = 12; public boolean editOnDoubleClick = true; public boolean ensureIndexed = false; public boolean showValuesAsStruct = false; public SimpleCRUD(Class cc) { this(db_mainConcepts(), cc); } public SimpleCRUD(Concepts concepts, Class cc) { this.cc = cc; this.concepts = concepts; } public SimpleCRUD show(String frameTitle) { make(); showFrame(frameTitle, panel); return this; } public SimpleCRUD show() { return show(plural(shortClassName(cc))); } public SimpleCRUD showMaximized() { show(); maximizeFrame(panel); return this; } public JPanel makePanel() { return make(); } public JPanel make() { db(); framesBot(); return make_dontStartBots(); } public JPanel make_dontStartBots() { printVars("SimpleCRUD.make_dontStartBots", "concepts", concepts, "cc", cc, "count", countConcepts(cc)); if (ensureIndexed) indexConceptClass(concepts, cc); AutoCloseable __1 = tempSetTL(showConceptsTable_concepts, concepts); try { AutoCloseable __2 = tempSetTL(showConceptsTable_latestFirst, latestFirst); try { AutoCloseable __3 = tempSetTL(showConceptsTable_sorter, sorter); try { AutoCloseable __4 = tempSetTL(showConceptsTable_dropFields, asList(unshownFields)); try { AutoCloseable __5 = tempSetTL(dataToTable_useStruct, showValuesAsStruct); try { table = makeConceptsTable(cc, wrapRenderer(renderer)); { swing(() -> { buttons = jRightAlignedLine(jbutton("Add...", new Runnable() { public void run() { try { newConcept(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "newConcept()"; } }), tableDependButton(table, jbutton("Edit", new Runnable() { public void run() { try { editConcept(selectedConcept()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "editConcept(selectedConcept())"; } })), tableDependButton(table, jbutton("Delete", new Runnable() { public void run() { try { final List l = selectedConcepts(); startThread("Delete concepts", new Runnable() { public void run() { try { 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 "withDBLock(concepts, new Runnable() { public void run() { try { for (A c : ..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final List l = selectedConcepts();\r\n thread \"Delete concepts\" {\r\n..."; } })), tableDependButton(table, jbutton("Duplicate...", new Runnable() { public void run() { try { duplicateConcept(selectedConcept()); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "duplicateConcept(selectedConcept())"; } }))); if (SimpleCRUD_searcher) { tableSearcher = tableWithSearcher2(table, "withMargin", true); panel = centerAndSouthWithMargin(tableSearcher.panel, withBottomMargin(buttons)); } else panel = centerAndSouthWithMargin(table, withBottomMargin(buttons)); Object fEdit = new VF1() { public void get(Integer row) { try { editConcept(conceptForRow(row)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "editConcept(conceptForRow(row))"; } }; tablePopupMenuItem(table, "Edit...", fEdit); if (editOnDoubleClick) onDoubleClick(table, fEdit); }); } return panel; } finally { _close(__5); } } finally { _close(__4); } } finally { _close(__3); } } finally { _close(__2); } } finally { _close(__1); } } public Object wrapRenderer(final Object renderer) { return renderer == null ? null : new F1() { public Object get(A a) { try { return putAll(litorderedmap(hID, str(a.id)), (Map) callF(renderer, a)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "putAll(litorderedmap(hID, str(a.id)), (Map) callF(renderer, a))"; } }; } public void newConcept() { duplicateConcept(null); } public void duplicateConcept(A oldConcept) { final A c = unlisted(cc); ccopyFieldsExcept(oldConcept, c, dontDuplicateFields); final Map map = makeComponents(c); Runnable r = new Runnable() { public void run() { try { concepts.register(c); saveData(c, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "concepts.register(c);\r\n saveData(c, map);"; } }; AutoCloseable __6 = tempSetMCOpt("formLayouter1_fixer2", formFixer); try { showFormTitled2("New " + shortClassName(cc), arrayPlus(mapToObjectArray(map), r)); } finally { _close(__6); } } public void editConcept(final A c) { if (c == null) return; final Map map = makeComponents(c); Runnable r = new Runnable() { public void run() { try { saveData(c, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "saveData(c, map)"; } }; AutoCloseable __7 = tempSetMCOpt("formLayouter1_fixer2", formFixer); try { showFormTitled2("Edit " + shortClassName(cc) + " #" + c.id, arrayPlus(mapToObjectArray(map), r)); } finally { _close(__7); } } final public A selectedConcept() { return selected(); } public A selected() { return conceptForRow(selectedRow(table)); } public A conceptForRow(int row) { return (A) concepts.getConcept(toLong(getTableCell(table, row, 0))); } public int indexOfConcept(final A c) { if (c == null) return -1; return swing(new F0() { public Integer get() { try { int n = tableRowCount(table); 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 = tableRowCount(table);\r\n for row to n:\r\n if (toLong(getTab..."; } }); } public List selectedConcepts() { return swing(() -> { int[] rows = table == null ? null : table.getSelectedRows(); List l = new ArrayList(); for (int row : unnullForIteration(rows)) l.add(conceptForRow(row)); return l; }); } public Map makeComponents(A c) { Map map = litorderedmap(); makeComponents(c, map); return map; } public JComponent fieldComponent(A c, String field) { Class type = getFieldType(cc, field); Object value = getOpt(c, field); if (type == boolean.class) return jCenteredCheckBox(isTrue(value)); else if (contains(multiLineFields, field) || containsNewLines(optCast(String.class, value))) return typeWriterTextArea((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 try { return autoComboBox(valueToString(value), new TreeSet(map(__131 -> valueToString(__131), collect(list(concepts, cc), field)))); } catch (Throwable e) { printException(e); return jTextField(valueToString(value)); } } public void saveComponent(A c, String field, JComponent comp) { comp = unwrap(comp); Class type = fieldType(c, field); if (type == SecretValue.class) { String text = getTextTrim((JPasswordField) comp); cset(c, field, empty(text) ? null : new SecretValue(text)); } else if (comp instanceof JTextComponent) cset(c, field, convertToField(trimIf(!(comp instanceof JTextArea), getText((JTextComponent) comp)), cc, field)); else if (comp instanceof JComboBox) { String text = getTextTrim((JComboBox) comp); if (isSubtype(type, Concept.class)) cset(c, field, getConcept(concepts, parseFirstLong(text))); else cset(c, field, convertToField(text, cc, field)); } else if (comp instanceof JCheckBox) cset(c, field, isChecked((JCheckBox) comp)); } public List fields() { if (excludeFieldsFromEditing != null && modifiedField != null) excludeFieldsFromEditing.add(modifiedField); return listWithoutSet(filter(conceptFieldsInOrder(cc), new F1() { public Boolean get(String field) { try { return fieldType(cc, field) != Concept.Ref.class; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "fieldType(cc, field) != Concept.Ref.class"; } }), joinSets(excludeFieldsFromEditing, unshownFields)); } public void excludeFieldsFromEditing(String... fields) { excludeFieldsFromEditing = setPlus(excludeFieldsFromEditing, fields); } public void makeComponents(A c, Map map) { for (String field : fields()) map.put(field, fieldComponent(c, field)); } public void saveData(A c, Map components) { for (String field : keys(components)) saveComponent(c, field, components.get(field)); if (modifiedField != null) cset(c, modifiedField, now()); } public JTable table() { return table; } transient public IF1 valueToString; public String valueToString(Object o) { return valueToString != null ? valueToString.get(o) : valueToString_base(o); } final public String valueToString_fallback(IF1 _f, Object o) { return _f != null ? _f.get(o) : valueToString_base(o); } public String valueToString_base(Object o) { return showValuesAsStruct ? structureOrText_crud(o) : strOrNull(o); } } 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 TransitiveHull implements SteppableAndIF0> { public IF1> f; public LinkedHashSet seen = new LinkedHashSet(); public LinkedList> pool = new LinkedList(); public Integer max; public TransitiveHull(IF1> f, A starter) { this.f = f; add(starter); } public void add(A a) { pool.add(singletonIterator(a)); } public boolean step() { if (max != null && l(seen) >= max) return false; if (empty(pool)) return false; Iterator it = first(pool); if (!it.hasNext()) { removeFirst(pool); return true; } process(it.next()); return true; } public void process(A entry) { if (!seen.add(entry)) return; Iterable newStuff = f.get(entry); onGotCollection(entry, newStuff); if (nempty(newStuff)) pool.add(iterator(newStuff)); } transient public IVF2> onGotCollection; public void onGotCollection(A entry, Iterable newStuff) { if (onGotCollection != null) onGotCollection.get(entry, newStuff); else onGotCollection_base(entry, newStuff); } final public void onGotCollection_fallback(IVF2> _f, A entry, Iterable newStuff) { if (_f != null) _f.get(entry, newStuff); else onGotCollection_base(entry, newStuff); } public void onGotCollection_base(A entry, Iterable newStuff) { } public Set get() { return seen; } } 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 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); } } 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 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 abstract public class VF2 { abstract public void get(A a, B b); } static public class JavaXHyperlinker { public boolean targetBlank = false; abstract static public class PeepHole { public List tok; public int cIdx; public String prevPrev, prev, token, next; public void explain(String text) { explain(cIdx, text); } abstract public void explain(int i, String text); public void link(String url) { link(cIdx, url); } abstract public void link(int i, String url); } public Map shortFor = litmap("BigInt", "BigInteger", "$1", "m.unq(0)", "$2", "m.unq(1)", "$3", "m.unq(2)", "LS", "List", "sclass", "static class", "asclass", "abstract static class", "svoid", "static void", "SS", "Map", "S", "String", "ret", "return", "L", "List", "Cl", "Collection", "O", "Object", "sO", "static Object", "sS", "static String", "fO", "final Object", "fS", "final String", "sS", "static String", "sbool", "static boolean", "fbool", "final boolean", "bool", "boolean", "Int", "Integer", "cast", "casting to the type required on the left-hand side", "°", "()", "ItIt", "IterableIterator", "ES", "Ext (string plus extended information)", "CloseableItIt", "CloseableIterableIterator", "LPairS", "List>", "ISegmenter", "IF1>", "dbl", "double"); public String explFunc = "anonymous function declaration (similar to Java 8 lambdas)"; public String explPNoconsole = "Main program including Substance L&F, started in non-AWT thread, hiding the console"; public Map tokenExplanations = litmap("cm", "cm summons the last version of a module in Stefan's OS (cm originally stood for 'compact module')", "~.", "short for accessing a field or calling a method by reflection", "beaConcept", "a BEA concept is just a concept (database-enabled Java class) derived from BEAObject (the AGI base class)", "== null ?:", "short for: == null ? null :", "p-exp {", "main program with automatic upgrade", "mapLike", "a function that takes a global function name as first argument and can be called like this: (...)", "mapMethodLike", "a function that takes a method or field name as first argument and can be called like this: (...)", "func(", explFunc, "func{", explFunc, "voidfunc", "anonymous function declaration without return value (similar to Java 8 lambdas)", "ctex", "ctex rethrows exceptions as RuntimeExceptions so you don't have to declare them", "p {", "short for: public static void main(String[] args)", "p-experiment {", "Main program with a nice big console & auto-restart", "p-substance {", "Main program including Substance L&F, started in AWT thread", "p-subst {", "Main program including Substance L&F, started in non-AWT thread", "p-noconsole {", explPNoconsole, "pn {", explPNoconsole, "answer {", "Answer function - static S answer(S s) { new Matches m; ...; null; }", "time {", "Run the code block and print how long it took", "cprint {", "A module with default class name derived from DynPrintLog", "semiauto {", "In a semiauto block, JavaX automatically adds a ; to (almost) every line", "autosemi {", "In an autosemi block, JavaX automatically adds a ; to (almost) every line", "Clusters", "Clusters is short for Map>", "temp", "temp is like try (...) extending to the end of the current block", "pcall {", "protected call - try { ... } catch { print exception }", "r {", "r { ... } is short for: new Runnable() { public void run() { ... } }", "runnable {", "runnable { ... } is short for: new Runnable() { public void run() { ... } }", "pcall-short {", "protected call, shorter output - try { ... } catch { printShortException }", "LPair<", "LPair<...> is short for: L>", "visualize {", "Visualisation method for an OS module; returns a Swing component", "visualize as", "define a visualization for the module", "enhanceFrame {", "Method that changes properties of an OS module's frame", "run {", "short for: public void run()", "start {", "Method that is run when an OS module is loaded", "enter {", "Methods in a module should be marked 'enter' for bookkeeping", "vf<", "reference to function as voidfunc", "compact module", "try to save memory by reusing code between modules", "cmodule", "cmodule = compact module for Stefan's OS. compact = try to save memory by reusing code between modules", "cmodule2", "cmodule2 = compact module for Stefan's OS (newer version). compact = try to save memory by reusing code between modules", "rThread {", "Runnable in a new thread", "shit(", "short for: return with print", "shit:", "short for: return with print", ":=", "the := operator translates to a simple comma, but converts an identifier on its left-hand side into a string", "noeq", "don't auto-generate equals+hashCode methods", "for single (", "for single is for ping + singletonUnlessNull", "selfType", "selfType is replaced with the enclosing class's name", "runnable class", "short for: class X implementing Runnable { run { ... }}", "aka", "In JavaX, methods can have multiple names"); public Map sc, sf; public StringTree2 tokenExplanationsTree; public List> explainers = new ArrayList(); public NotTooOften ntoClearCaches = nto_mins(5); public JavaXHyperlinker() { maybeClearCaches(); tokenExplanationsTree = stringTree2_javaTok(tokenExplanations); } public void maybeClearCaches() { ntoClearCaches.dO(() -> clearCaches()); } public String codeToHTML(String code) { return codeToHTML(code, true); } public String codeToHTML(String code, boolean real) { maybeClearCaches(); List tok = javaTok(code); Map links = new HashMap(); Map explanations = new HashMap(); putMultipleKeys(explanations, allPlus(4, jfindAll(tok, "void q {")), "Function will execute in module's queue"); Map styles = new HashMap(); tokensToColors(tok, styles); Matches m = new Matches(); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); String prev = get(tok, i - 2), prevPrev = get(tok, i - 4); String next = get(tok, i + 2); String sfID = sf.get(t); PeepHole ph = new PeepHole() { public void explain(int i, String text) { explanations.put(i, text); } public void link(int i, String url) { links.put(i, url); } }; ph.tok = tok; ph.cIdx = i; ph.prevPrev = prevPrev; ph.prev = prev; ph.token = t; ph.next = next; pcallFAll(explainers, ph); if (eq(t, "include") && eq(next, "functions")) { i += 4; String name; while (i < l(tok) && isIdentifier(name = get(tok, i))) { mapPut(links, i, sf.get(name)); i += 2; } continue; } if (startsWith(t, "lambda", m) && isInteger(m.rest()) && isIdentifier(next)) explanations.put(i, ("lambda reference to a " + (m.rest()) + "-argument function")); if (eq(t, "is") && isIdentifier(next)) explanations.put(i, "synonym of 'implements'"); if (eq(t, "methodLambda0") && isIdentifier(next)) explanations.put(i, ("short for: x -> x." + next + "() (with a fresh variable instead of x)")); if (eqOneOf(t, "lambda0", "l0") && isIdentifier(next)) explanations.put(i, ("short for: -> " + next + "()")); if (eq(t, "swappable") && isIdentifier(next)) explanations.put(i, "swappable functions can be exchanged per object instance"); if (eq(t, "main") && isIdentifier(next)) explanations.put(i, "reference to the current 'main' class (where all the standard functions are held, not always called 'main')"); if (eq(t, "autoDispose") && isIdentifier(next)) explanations.put(i, "autoDispose adds a cleanMeUp method that properly disposes of this variable"); if (eq(t, "optional") && isIdentifier(next)) explanations.put(i, "optional parameter (null if omitted)"); if (eq(t, "macro") && isIdentifier(next)) explanations.put(i, "define a macro called '" + next + "', visible until the end of the enclosing block (or until redefined)"); if (eq(t, "virtual") && isIdentifier(next)) explanations.put(i, "\"virtual\" represents a type that is not visible in this realm, so it is transpiled to just Object"); if (eq(t, "concept") && isIdentifier(next)) explanations.put(i, "A concept is like a Java class, but persistable"); if (eq(t, "flexeq") && isIdentifier(next)) explanations.put(i, "flexeq is a fix for records inside parameterized classes"); if (eq(t, "switchable") && isIdentifier(next)) explanations.put(i, "A field that can be changed through the module's popup menu"); if (eq(t, "embedded") && isIdentifier(next)) explanations.put(i, "\"embedded\" allows you to put a function where they would not normally be allowed"); if (eq(t, "visual") && isIdentifier(next)) explanations.put(i, "short definition of the visualize() function"); if (eq(t, "dm_q") && isIdentifier(next)) explanations.put(i, "Function reference delegating to module queue"); if (eq(t, "!") && isIdentifier(prev) && neq(next, "=")) explanations.put(i, "! is short for .get()"); if (eq(t, "#") && isIdentifier(next)) explanations.put(i, "# makes an identifier local to the scope"); if (eq(t, "f") && isIdentifier(next)) explanations.put(i, "f references a static function in the main class"); if (eq(t, "r") && isIdentifier(next)) explanations.put(i, "short for: r { " + next + "() }"); if (eqOneOf(t, "rThread", "rThreadEnter") && isIdentifier(next)) explanations.put(i, "short for: " + t + " { " + next + "() }"); if (eq(t, "dispose") && isIdentifier(next)) explanations.put(i, "short for: cleanUp(" + next + "); " + next + " = null;"); if (eq(t, "*") && eq(next, "(")) explanations.put(i, "Short syntax for a constructor declaration"); if (eq(t, "thread") && eq(next, "{")) explanations.put(i, "Start a new thread with the following code"); if (eq(t, "module") && isIdentifier(next)) explanations.put(i, "A module is a class that can be loaded in Stefan's OS"); if (eq(t, "record") && isIdentifier(next)) explanations.put(i, "A record is a value-based class"); if (eq(t, "srecord") && isIdentifier(next)) explanations.put(i, "An srecord is a static value-based class"); if (eqOneOf(t, "cached", "simplyCached") && isIdentifier(next)) explanations.put(i, "A function that caches its return value"); if (eq(t, "thread") && isQuoted(next)) explanations.put(i, "Start a new thread with the following name & code"); if (eq(t, "if") && isQuoted(next)) { try { List tok2 = tok_subListWithoutBorderNTokens(tok, i, i + 3); tok_expandIfQuoted(tok2); explanations.put(i, "short for: " + join(tok2)); } catch (Throwable __e) { pcallFail(__e); } } if (eq(t, "html") && eq(next, "{")) explanations.put(i, "short for: static Object html(String uri, final Map params) ctex {"); if (eq(t, "try") && eq(next, "answer")) doublePut(explanations, i, i + 2, "\"try answer\" returns the expression if it isn't null or empty"); if (isSingleQuoteIdentifier(t)) explanations.put(i, "string constant, " + quote(fromSingleQuoteIdentifier(t))); if (eq(t, "event") && isIdentifier(next)) explanations.put(i, "declare a function called " + next + "() plus helpers for adding listeners"); if (eqOneOf(t, "null", "false", "true", "this") && eq(next, ";") && tok_tokenBeforeLonelyReturnValue(tok, i - 2)) doublePut(explanations, i, i + 2, "short for: return " + t + ";"); String e = shortFor.get(t); if (e != null) mapPut(explanations, i, "short for: " + e); if (!explanations.containsKey(i) && sfID != null) { if (eqOneOf(prev, "f", "r", "rThread", "function") || startsWith(prev, "lambda") || isIdentifier(next) && eqGet(tok, i + 4, "(") || eqOneOf(next, "(", "°") && (neq(prev, ".") || eq(prevPrev, "main") && neq(get(tok, i - 6), ".")) || eq(prev, "{") && eq(next, "}") && eq(prevPrev, "postProcess") || eq(prev, ":") && eq(prevPrev, ":")) links.put(i, sfID); } List fewTokens = codeTokens(subList(tok, i - 1, i + 2 * 5)); Pair p = stringTreeLeafValue2(tokenExplanationsTree, fewTokens); if (p != null) { int lastCodeToken = i + p.b * 2 - 2; if (eq(get(tok, lastCodeToken), "{")) lastCodeToken -= 2; mapPutInRange(explanations, i, lastCodeToken + 1, p.a); } if (isQuoted(t) && eq(prev, "(") && isIdentifier(prevPrev) && isMechFunction(prevPrev)) mapPut(links, i, neatMechListURL(unquote(t))); mapPut(links, i, sc.get(t)); } StringBuilder out = new StringBuilder(); Map titles = getSnippetTitles(filter(__132 -> isSnippetID(__132), values(links))); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (empty(t)) continue; String id = links.get(i), ex = explanations.get(i); String style = styles.get(i); if (t.startsWith("[[") && t.endsWith("]]")) { String explanation = "[[...]] denotes a multi-line string constant (as in Lua)"; out.append(dottedSpan("[[", explanation)); String inner = htmlencode(dropPrefix("[[", dropSuffix("]]", t))); out.append(span(inner, "style", "background-color: #77FF77")); out.append(dottedSpan("]]", explanation)); continue; } if (t.startsWith("[=[") && t.endsWith("]=]")) { String explanation = "[=[...]=] denotes a multi-line string constant (as in Lua)"; out.append(dottedSpan("[=[", explanation)); String inner = htmlencode(dropPrefix("[=[", dropSuffix("]=]", t))); out.append(span(inner, "style", "background-color: #77FF77")); out.append(dottedSpan("]=]", explanation)); continue; } String enc = htmlencode(t); out.append(id != null ? ahref(makeLink(real, id), enc, "title", isSnippetID(id) ? titles.get(fsI(id)) : ex, "style", "text-decoration: none; color: black; border-bottom: dotted 1px", "target", targetBlank ? "_blank" : null) : ex != null ? dottedSpan(enc, ex) : style != null ? span(enc, "style", style) : enc); } String html = str(out); html = dynamize_noEncode(html); return html; } public String makeLink(boolean real, String id) { if (isRelativeOrAbsoluteURL(id)) return id; if (real) return longSnippetLink(id); return "/" + psI(id); } public void clearCaches() { stdFunctions_clearCache(); sc = standardClassesMap(); sf = stdFunctions_cached(); } public boolean isMechFunction(String s) { return startsWithOneOf(s, "mech", "mL"); } public void tokensToColors(List tok, Map styles) { for (int i = 0; i < l(tok); i += 2) if (tok_whitespaceContainsJavaComments(tok.get(i))) styles.put(i, "color: #666666"); } public void addExplainer(IVF1 explainer) { explainers.add(explainer); } } static abstract public class TokCondition implements ITokCondition { public abstract boolean get(List tok, int i); } 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 HCRUD extends HAbstractRenderable { public HCRUD_Data data; public boolean mutationRights = true; public boolean allowCreateOrDelete = true; public boolean allowCreate = true; public boolean allowEdit = true; public boolean singleton = false; public boolean cmdsLeft = false; public boolean showEntryCountInTitle = false; public boolean allowFieldRenaming = false; public int defaultTextFieldCols = 80; public int valueDisplayLength = 1000; public String tableClass; public String formTableClass; public String checkBoxClass = "crud_chkbox"; public String customTitle; public boolean showTextFieldsAsAutoExpandingTextAreas = false; public Set unshownFields; public Set uneditableFields; public Set unlistedFields; public boolean showCheckBoxes = false; public boolean cleanItemIDs = false; public boolean haveJQuery, haveSelectizeJS, haveSelectizeClickable; public boolean needsJQuery = false; public boolean paginate = false; public boolean sortable = false; public boolean buttonsOnTop, buttonsOnBottom = true; public boolean duplicateInNewTab = false; public String formID = "crudForm"; public boolean showQuickSaveButton = false; public boolean enableMultiSelect = true; public boolean cellColumnToolTips = false; public boolean showSearchField = false; public String searchQuery; public Map params; public HTMLPaginator paginator = new HTMLPaginator(); public String sortByField = "id"; public String sortParameter = "sort"; public boolean descending = false; public int flexibleLengthListLeeway = 5; public Object objectIDToHighlight; public boolean showOnlySelected = false; public String fieldPrefix = "f_"; public int entryCount; public HCRUD() { } public HCRUD(HCRUD_Data data) { this.data = data; } public HCRUD(String baseLink, HCRUD_Data data) { this.data = data; this.baseLink = baseLink; } public String newLink() { return appendQueryToURL(baseLink, "cmd", "new"); } public String deleteLink(Object id) { return appendQueryToURL(baseLink, "delete_" + id, 1); } public String editLink(Object id) { return appendQueryToURL(baseLink, "edit", id); } public String duplicateLink(Object id) { return appendQueryToURL(baseLink, "duplicate", id); } public void setParams(Map params) { this.params = params; if (objectIDToHighlight == null) objectIDToHighlight = params.get("selectObj"); if (eq("1", params.get("showOnlySelected"))) showOnlySelected = true; } public String render(boolean withCmds, Map params) { setParams(params); if (!withCmds) return renderTable(false); { String __3 = handleCommands(params); if (!empty(__3)) return __3; } return renderMsgs(params) + divUnlessEmpty(nav()) + renderTable(withCmds); } transient public IF0 nav; public String nav() { return nav != null ? nav.get() : nav_base(); } final public String nav_fallback(IF0 _f) { return _f != null ? _f.get() : nav_base(); } public String nav_base() { List l = new ArrayList(); if (actuallyAllowCreate()) l.add(ahref(newLink(), "New " + itemName())); if (showSearchField) l.add(hInlineSearchForm("search", searchQuery, "")); return joinWithVBar(l); } public String handleCommands(Map params) { List msgs = new ArrayList(); if (eqGet(params, "action", "create")) { if (!actuallyAllowCreate()) throw fail("Creating objects not allowed"); processRenames(params); Object id = data.createObject(preprocessUpdateParams(params), fieldPrefix); msgs.add(itemName() + " created (ID: " + id + ")"); objectIDToHighlight = id; } if (eqGet(params, "action", "update")) { if (!actuallyAllowEdit()) throw fail("Editing objects not allowed"); String id = params.get("id"); processRenames(params); msgs.add(data.updateObject(id, preprocessUpdateParams(params), fieldPrefix)); objectIDToHighlight = id; } List toDeleteList = keysDeprefixNemptyValue(params, "delete_"); if (eq(params.get("bulkAction"), "deleteSelected")) toDeleteList.addAll(keysDeprefixNemptyValue(params, "obj_")); for (String toDelete : toDeleteList) { if (!actuallyAllowDelete()) throw fail("Deleting objects not allowed"); msgs.add(data.deleteObject(toDelete)); } return empty(msgs) ? "" : refreshAfterCommand(params, msgs); } transient public IF2, List, String> refreshAfterCommand; public String refreshAfterCommand(Map params, List msgs) { return refreshAfterCommand != null ? refreshAfterCommand.get(params, msgs) : refreshAfterCommand_base(params, msgs); } final public String refreshAfterCommand_fallback(IF2, List, String> _f, Map params, List msgs) { return _f != null ? _f.get(params, msgs) : refreshAfterCommand_base(params, msgs); } public String refreshAfterCommand_base(Map params, List msgs) { String redirectAfterSave = mapGet(params, "redirectAfterSave"); if (nempty(redirectAfterSave)) return hrefresh(redirectAfterSave); return refreshWithMsgs(msgs, "anchor", objectIDToHighlight == null ? null : "obj" + objectIDToHighlight, "params", objectIDToHighlight == null ? null : litmap("selectObj", objectIDToHighlight)); } public String encodeField(String s) { return or(data.fieldNameToHTML(s), s); } transient public IF2 renderValue; public String renderValue(String field, Object value) { return renderValue != null ? renderValue.get(field, value) : renderValue_base(field, value); } final public String renderValue_fallback(IF2 _f, String field, Object value) { return _f != null ? _f.get(field, value) : renderValue_base(field, value); } public String renderValue_base(String field, Object value) { if (value instanceof HTML) return ((HTML) value).html; value = deref(value); if (value instanceof SecretValue) return hhiddenStuff(renderValue_inner(((SecretValue) value).get())); return renderValue_inner(value); } transient public IF1 renderValue_inner; public String renderValue_inner(Object value) { return renderValue_inner != null ? renderValue_inner.get(value) : renderValue_inner_base(value); } final public String renderValue_inner_fallback(IF1 _f, Object value) { return _f != null ? _f.get(value) : renderValue_inner_base(value); } public String renderValue_inner_base(Object value) { if (value instanceof Boolean) return yesNo_short((Boolean) value); return htmlEncode_nlToBr_withIndents(shorten(valueDisplayLength, strOrEmpty(value))); } public String renderTable(boolean withCmds) { return renderTable(withCmds, data.list()); } public String valueToSortable(Object value) { if (value instanceof HTML) return ((HTML) value).get(); return strOrNull(value); } public String renderTable(boolean withCmds, List> l) { entryCount = l(l); if (empty(l)) return p("No entries"); if (!eq(data.defaultSortField(), pair(sortByField, descending))) { if (nempty(sortByField)) { print("Sorting " + nEntries(l) + " by " + sortByField); l = sortByTransformedMapKey_alphaNum(__198 -> valueToSortable(__198), l, sortByField); } if (descending) l = reversed(l); } Map keyEncoding = new HashMap(); List> l2 = lazyMap(l, _map -> { Object id = itemID(_map); return data.new Item(id) { public Map calcFullMap() { Map map = _map; map = mapMinusKeys(map, joinSets(unshownFields, unlistedFields)); Map map2 = postProcessTableRow(map, mapToMap((key, value) -> pair(mapPut_returnValue(keyEncoding, key, encodeField(key)), renderValue(key, value)), map)); if (singleton) map2.remove(encodeField(data.idField())); if (withCmds) map2 = addCmdsToTableRow(map, map2); map2.put(firstKey(map2), aname("obj" + id, firstValue(map2))); return map2; } }; }); List out = new ArrayList(); if (paginate) { paginator.processParams(params); paginator.baseLink = addParamsToURL(baseLink, filterKeys(__133 -> keepParamInPagination(__133), params)); paginator.max = l(l2); out.add(divUnlessEmpty(paginator.renderNav())); List> l3 = subListOrFull(l2, paginator.visibleRange()); if (objectIDToHighlight != null && (showOnlySelected || !any(__134 -> isHighlighted(__134), l3))) { l3 = llNonNulls(firstThat(__135 -> isHighlighted(__135), l2)); } l2 = l3; } Map replaceHeaders = new HashMap(); if (sortable && !singleton) for (Map.Entry __1 : _entrySet(keyEncoding)) { String key = __1.getKey(); String html = __1.getValue(); boolean sortedByField = eq(sortByField, key); boolean showDescendingLink = sortedByField && !descending; String htmlOld = html; if (sortedByField) { String title = showDescendingLink ? "Click here to sort descending" : "Click here to sort ascending"; String titleSorted = "Sorted by this field (" + (descending ? "descending" : "ascending") + ")"; title = titleSorted + ". " + title; html = span_title(title, unicode_downOrUpPointingTriangle(descending)) + " " + html; } String sortLink = appendQueryToURL(baseLink, sortParameter, showDescendingLink ? "-" + key : key); replaceHeaders.put(htmlOld, ahref(sortLink, html)); } Map paramsByColName = null; if (cellColumnToolTips) { paramsByColName = new HashMap(); for (Map map : l2) for (String key : keys(map)) if (!paramsByColName.containsKey(key)) paramsByColName.put(key, litobjectarray("title", nullIfEmpty(htmldecode_dropTagsAndComments(key)))); } out.add(hpostform(htmlTable2_noHtmlEncode(l2, paramsPlus(tableParams(), "replaceHeaders", replaceHeaders, "paramsByColName", paramsByColName)) + (!withCmds || !showCheckBoxes ? "" : "\n" + divUnlessEmpty(renderBulkCmds())), "action", baseLink)); if (showCheckBoxes && haveJQuery && enableMultiSelect) out.add(hCheckBoxMultiSelect_v2()); return lines_rtrim(out); } public Object mapToID(Map item) { return item == null ? null : dropAllTags(strOrNull(item.get(encodeField(idField())))); } public boolean isHighlighted(Map item) { Object id = mapToID(item); return eq(id, objectIDToHighlight); } transient public IF0 renderBulkCmds; public String renderBulkCmds() { return renderBulkCmds != null ? renderBulkCmds.get() : renderBulkCmds_base(); } final public String renderBulkCmds_fallback(IF0 _f) { return _f != null ? _f.get() : renderBulkCmds_base(); } public String renderBulkCmds_base() { return "Bulk action: " + hselect("bulkAction", litorderedmap("", "", "deleteSelected", "Delete selected")) + " " + hsubmit("OK", "onclick", "return confirm('Are you sure?')"); } public Map addCmdsToTableRow(Map map, Map map2) { if (showCheckBoxes) { Object id = itemID(map); map2.put(checkBoxKey(), hcheckbox("obj_" + id, false, "title", "Select this object for a bulk action", "class", checkBoxClass)); map2 = putKeysFirst(map2, checkBoxKey()); } map2.put(cmdsKey(), renderCmds(map)); if (cmdsLeft) map2 = putKeysFirst(map2, cmdsKey()); return map2; } public Object[] tableParams() { return litparams("tdParams", litparams("valign", "top"), "tableParams", litparams("class", tableClass)); } public String renderForm(Map map) { AutoCloseable __5 = tempSetTL(htmlencode_forParams_useV2, true); try { map = mapMinusKeys(map, joinSets(unshownFields, uneditableFields, data.filteredFields())); Map mapWithoutID = mapWithoutKey(map, data.idField()); List> matrix = map(mapWithoutID, (field, value) -> { String help = data.fieldHelp(field); return ll(allowFieldRenaming ? hinputfield("rename_" + field, field, "class", "field-rename", "style", "border: none; text-align: right", "title", "Edit this to rename field " + quote(field) + " or clear to delete field") : encodeField(field), addHelpText(help, renderInput(field, value))); }); massageFormMatrix(map, matrix); return htableRaw_valignTop(matrix, empty(formTableClass) ? litparams("border", 1, "cellpadding", 4) : litparams("class", formTableClass)); } finally { _close(__5); } } public String renderInput(String field, Object value) { String name = fieldPrefix + field; return renderInput(name, data.getRenderer(field, value), value); } public String renderInput(String name, HCRUD_Data.Renderer r, Object value) { if (r != null) value = r.preprocessValue(value); String meta = r == null ? "" : renderMetaInfo(r.metaInfo, name); if (r instanceof HCRUD_Data.AceEditor) { HTMLAceEditor ace = new HTMLAceEditor(strOrEmpty(value)); ace.name = name; ace.divParams.put("style", "width: " + ((HCRUD_Data.AceEditor) r).cols + "ch; height: " + ((HCRUD_Data.AceEditor) r).rows + "em"); customizeACEEditor(ace); return meta + ace.headStuff() + ace.html(); } if (r instanceof HCRUD_Data.TextArea) return meta + htextarea(strOrEmpty(value), "name", name, "cols", ((HCRUD_Data.TextArea) r).cols, "rows", ((HCRUD_Data.TextArea) r).rows); if (r instanceof HCRUD_Data.TextField) return meta + renderTextField(name, strOrEmpty(value), ((HCRUD_Data.TextField) r).cols); if (r instanceof HCRUD_Data.ComboBox) return meta + renderComboBox(name, ((HCRUD_Data.ComboBox) r).valueToEntry(value), ((HCRUD_Data.ComboBox) r).entries, ((HCRUD_Data.ComboBox) r).editable); if (r instanceof HCRUD_Data.DynamicComboBox) return meta + renderDynamicComboBox(name, ((HCRUD_Data.DynamicComboBox) r).valueToEntry(value), ((HCRUD_Data.DynamicComboBox) r).info, ((HCRUD_Data.DynamicComboBox) r).editable, ((HCRUD_Data.DynamicComboBox) r).url); if (r instanceof HCRUD_Data.CheckBox) return meta + htrickcheckboxWithText(name, "", isTrue(value)); if (r instanceof HCRUD_Data.FlexibleLengthList) { List list = (List) value; List rows = new ArrayList(); int n = l(list) + flexibleLengthListLeeway; for (int i = 0; i < n; i++) { Object item = _get(list, i); rows.add(tr(td(i + 1 + ".", "align", "right") + td(renderInput(name + "_" + i, ((HCRUD_Data.FlexibleLengthList) r).itemRenderer, item)))); } return meta + htag("table", lines(rows)); } if (r instanceof HCRUD_Data.NotEditable) return "Not editable"; return renderInput_default(name, value); } transient public IVF1 customizeACEEditor; public void customizeACEEditor(HTMLAceEditor ace) { if (customizeACEEditor != null) customizeACEEditor.get(ace); else customizeACEEditor_base(ace); } final public void customizeACEEditor_fallback(IVF1 _f, HTMLAceEditor ace) { if (_f != null) _f.get(ace); else customizeACEEditor_base(ace); } public void customizeACEEditor_base(HTMLAceEditor ace) { } public String renderMetaInfo(String metaInfo, String name) { if (empty(metaInfo)) return ""; return hhidden("metaInfo_" + dropPrefix(fieldPrefix, name), metaInfo); } public String renderInput_default(String name, Object value) { return renderTextField(name, strOrEmpty(value), defaultTextFieldCols); } public String renderTextField(String name, String value, int cols) { if (showTextFieldsAsAutoExpandingTextAreas) { return htextarea(value, "name", name, "class", "auto-expand", "style", "width: " + cols + "ch", "autofocus", eq(mapGet(params, "autofocus"), name) ? html_valueLessParam() : null, "onkeydown", jquery_submitFormOnCtrlEnter()); } return htextfield(name, value, "size", cols, "style", "font-family: monospace"); } public String renderNewForm() { return renderNewForm(data.emptyObject()); } public String renderNewFormWithParams(Map params) { Map filteredMap = subMapStartingWith_dropPrefix(params, fieldPrefix); Map map = joinMaps(data.emptyObject(), (Map) filteredMap); data.rawFormValues = params; for (Map.Entry __0 : _entrySet(filteredMap)) { String key = __0.getKey(); String value = __0.getValue(); List l = splitAt(key, "_"); if (l(l) == 2) { String field = first(l); int idx = parseInt(second(l)); List list = (List) (map.get(field)); if (!(list instanceof ArrayList)) map.put(field, list = new ArrayList()); listPut(list, idx, value); } } return renderNewForm(map); } public String renderNewForm(Map map) { String buttons = p(hsubmit("Create")); return hpostform(hhidden("action", "create") + formExtraHiddens() + stringIf(buttonsOnTop, buttons) + renderForm(map) + stringIf(buttonsOnBottom, buttons), paramsPlus(formParameters(), "action", baseLink)); } transient public IF0 formParameters; public Object[] formParameters() { return formParameters != null ? formParameters.get() : formParameters_base(); } final public Object[] formParameters_fallback(IF0 _f) { return _f != null ? _f.get() : formParameters_base(); } public Object[] formParameters_base() { return litparams("id", formID); } public String idField() { return data.idField(); } public String renderEditForm(String id) { if (!actuallyAllowEdit()) return "Can't edit objects in this table"; if (!data.objectCanBeEdited(id)) return htmlEncode2("Object " + id + " can't be edited"); Map map = data.getObjectForEdit(id); if (map == null) return htmlEncode2("Entry " + id + " not found"); String onlyFields = mapGet(params, "onlyFields"); if (nempty(onlyFields)) map = onlyKeys(map, itemPlus(idField(), tok_identifiersOnly(onlyFields))); String buttons = p_vbar(hsubmit("Save changes"), !showQuickSaveButton ? "" : hbuttonOnClick_noSubmit("Save & keep editing", "\r\n $.ajax({\r\n type: 'POST',\r\n url: $('#crudForm').attr('action'),\r\n data: $('#crudForm').serialize(), \r\n success: function(response) { successNotification(\"Saved\"); },\r\n }).error(function() { errorNotification(\"Couldn't save\"); });\r\n "), deleteObjectHTML(id)); return hpostform(hhidden("action", "update") + formExtraHiddens() + hhidden("id", id) + p("Object ID: " + htmlEncode2(id)) + stringIf(buttonsOnTop, buttons) + renderForm(map) + stringIf(buttonsOnBottom, buttons), paramsPlus(formParameters(), "action", baseLink + "#obj" + id)); } public String renderPage(Map params) { setParams(params); { String __4 = handleComboSearch(params); if (!empty(__4)) return __4; } if (eqGet(params, "cmd", "new")) { if (!actuallyAllowCreate()) return "Can't create objects in ths table"; return frame(customTitleOr("New " + itemName()), renderNewFormWithParams(params)); } if (nempty(params.get("edit"))) return frame("Edit " + itemName(), renderEditForm(params.get("edit"))); if (nempty(params.get("duplicate"))) return frame("New " + itemName(), renderNewForm(data.getObjectForDuplication(params.get("duplicate")))); String rendered = render(mutationRights, params); String title = null; if (singleton) title = ahref(baseLink, firstToUpper(data.itemName())); else { if (objectIDToHighlight != null) title = data.titleForObjectID(objectIDToHighlight); if (empty(title)) title = (showEntryCountInTitle ? n2(entryCount) + " " : "") + ahref(baseLink, firstToUpper(data.itemNamePlural())); } return frame(customTitleOr(title), rendered); } public HCRUD makeFrame(MakeFrame makeFrame) { super.makeFrame(makeFrame); return this; } public String cmdsKey() { return ""; } public String checkBoxKey() { return ""; } public String itemName() { return data.itemName(); } transient public IF2, Map, Map> postProcessTableRow; public Map postProcessTableRow(Map data, Map rendered) { return postProcessTableRow != null ? postProcessTableRow.get(data, rendered) : postProcessTableRow_base(data, rendered); } final public Map postProcessTableRow_fallback(IF2, Map, Map> _f, Map data, Map rendered) { return _f != null ? _f.get(data, rendered) : postProcessTableRow_base(data, rendered); } public Map postProcessTableRow_base(Map data, Map rendered) { return rendered; } public Object itemID(Map item) { Object id = mapGet(item, data.idField()); if (cleanItemIDs) id = htmlDecode_dropTags(strOrNull(getVarOpt(id))); return id; } public long itemIDAsLong(Map item) { return parseLong(itemID(item)); } transient public IF1, List> additionalCmds; public List additionalCmds(Map item) { return additionalCmds != null ? additionalCmds.get(item) : additionalCmds_base(item); } final public List additionalCmds_fallback(IF1, List> _f, Map item) { return _f != null ? _f.get(item) : additionalCmds_base(item); } public List additionalCmds_base(Map item) { return null; } transient public IF1, String> renderCmds; public String renderCmds(Map item) { return renderCmds != null ? renderCmds.get(item) : renderCmds_base(item); } final public String renderCmds_fallback(IF1, String> _f, Map item) { return _f != null ? _f.get(item) : renderCmds_base(item); } public String renderCmds_base(Map item) { Object id = itemID(item); List additionalCmds = additionalCmds(item); return joinNemptiesWithVBar(!actuallyAllowEdit() || !data.objectCanBeEdited(id) ? null : ahref(editLink(id), "EDIT"), deleteObjectHTML(id), !actuallyAllowCreate() ? null : targetBlankIf(duplicateInNewTab, duplicateLink(id), "dup", "title", "duplicate"), empty(additionalCmds) ? null : hPopDownButton(additionalCmds)); } public boolean actuallyAllowCreate() { return !singleton && allowCreateOrDelete && allowCreate; } public boolean actuallyAllowEdit() { return allowCreateOrDelete && allowEdit; } public boolean actuallyAllowDelete() { return !singleton && allowCreateOrDelete; } transient public IVF2, List>> massageFormMatrix; public void massageFormMatrix(Map map, List> matrix) { if (massageFormMatrix != null) massageFormMatrix.get(map, matrix); else massageFormMatrix_base(map, matrix); } final public void massageFormMatrix_fallback(IVF2, List>> _f, Map map, List> matrix) { if (_f != null) _f.get(map, matrix); else massageFormMatrix_base(map, matrix); } public void massageFormMatrix_base(Map map, List> matrix) { } public String renderComboBox(String name, String value, List entries, boolean editable) { if (haveSelectizeJS) { String id = aGlobalID(); return hselect_list(entries, value, "name", name, "id", id) + hjs("$('#" + id + "').selectize" + "\r\n ({\r\n searchField: 'text',\r\n openOnFocus: true,\r\n dropdownParent: 'body',\r\n create: " + jsBool(editable) + "\r\n /*allowEmptyOption: true*/\r\n " + unnull(moreSelectizeOptions2(name)) + "\r\n });\r\n ") + selectizeLayoutFix(); } if (haveJQuery) { String id = aGlobalID(); return tag("datalist", mapToLines(__136 -> hoption(__136), entries), "id", id) + tag("input", "", "name", name, "list", id); } if (editable) return hinputfield(name, value); return hselect_list(entries, value, "name", name); } public String renderDynamicComboBox(String name, String value, String info, boolean editable) { return renderDynamicComboBox(name, value, info, editable, null); } public String renderDynamicComboBox(String name, String value, String info, boolean editable, String url) { assertTrue("haveSelectizeJS", haveSelectizeJS); String id = aGlobalID(); String ajaxURL = or2(url, baseLink); return hselect_list(llNempties(value), value, "name", name, "id", id) + hjs("$('#" + id + "').selectize" + "\r\n ({\r\n searchField: 'text',\r\n valueField: 'text',\r\n labelField: 'text',\r\n openOnFocus: true,\r\n dropdownParent: 'body',\r\n create: " + jsBool(editable) + ",\r\n load: function(query, callback) {\r\n if (!query.length) return callback();\r\n var data = {\r\n comboSearchInfo: " + jsQuote(info) + ",\r\n comboSearchQuery: query\r\n };\r\n console.log(\"Loading \" + " + jsQuote(baseLink) + " + \" with \" + JSON.stringify(data));\r\n $.ajax({\r\n url: " + jsQuote(ajaxURL) + ",\r\n type: 'GET',\r\n dataType: 'json',\r\n data: data,\r\n error: function() {\r\n console.log(\"Got error\");\r\n callback();\r\n },\r\n success: function(res) {\r\n //console.log(\"Got data: \" + res);\r\n var converted = res.map(x => { return {text: x}; });\r\n //console.log(\"Converted: \" + converted);\r\n callback(converted);\r\n }\r\n });\r\n }\r\n /*allowEmptyOption: true*/\r\n " + moreSelectizeOptions2(name) + "\r\n });\r\n ") + selectizeLayoutFix(); } public void processSortParameter(Map params) { String sort = mapGet(params, sortParameter); if (nempty(sort)) if (startsWith(sort, "-")) { descending = true; sortByField = substring(sort, 1); } else { descending = false; sortByField = sort; } } public String deleteObjectHTML(Object id) { return !actuallyAllowDelete() ? null : !data.objectCanBeDeleted(id) ? span_title("Object can't be deleted, either there are references to it or you are not authorized", htmlEncode2(unicode_DEL())) : ahrefWithConfirm("Really delete item " + id + "?", deleteLink(id), htmlEncode2(unicode_DEL()), "title", "delete"); } public String addHelpText(String helpText, String html) { return empty(helpText) ? html : html + p(small(helpText), "style", "text-align: right"); } public String moreSelectizeOptions2(String name) { return unnull(moreSelectizeOptions(name)) + (!haveSelectizeClickable ? "" : "\r\n , plugins: ['clickable']\r\n , render: {\r\n option: function(item) {\r\n var id = item.text.match(/\\d+/)[0];\r\n return '';\r\n }\r\n }\r\n "); } transient public IF1 moreSelectizeOptions; public String moreSelectizeOptions(String name) { return moreSelectizeOptions != null ? moreSelectizeOptions.get(name) : moreSelectizeOptions_base(name); } final public String moreSelectizeOptions_fallback(IF1 _f, String name) { return _f != null ? _f.get(name) : moreSelectizeOptions_base(name); } public String moreSelectizeOptions_base(String name) { return ""; } public String handleComboSearch(Map params) { String query = params.get("comboSearchQuery"); if (nempty(query)) { String info = params.get("comboSearchInfo"); return jsonEncode_shallowLineBreaks(data.comboBoxSearch(info, query)); } return null; } transient public IF1, Map> preprocessUpdateParams; public Map preprocessUpdateParams(Map params) { return preprocessUpdateParams != null ? preprocessUpdateParams.get(params) : preprocessUpdateParams_base(params); } final public Map preprocessUpdateParams_fallback(IF1, Map> _f, Map params) { return _f != null ? _f.get(params) : preprocessUpdateParams_base(params); } public Map preprocessUpdateParams_base(Map params) { return params; } public void disableAllMutationRights() { mutationRights = allowCreateOrDelete = allowCreate = allowEdit = false; } transient public IF1 keepParamInPagination; public boolean keepParamInPagination(String name) { return keepParamInPagination != null ? keepParamInPagination.get(name) : keepParamInPagination_base(name); } final public boolean keepParamInPagination_fallback(IF1 _f, String name) { return _f != null ? _f.get(name) : keepParamInPagination_base(name); } public boolean keepParamInPagination_base(String name) { return eq(name, "search"); } public String customTitleOr(String title) { return or2(customTitle, or2(mapGet(params, "title"), title)); } transient public IF0 selectizeLayoutFix; public String selectizeLayoutFix() { return selectizeLayoutFix != null ? selectizeLayoutFix.get() : selectizeLayoutFix_base(); } final public String selectizeLayoutFix_fallback(IF0 _f) { return _f != null ? _f.get() : selectizeLayoutFix_base(); } public String selectizeLayoutFix_base() { return hcss(".selectize-input, .selectize-control { min-width: 300px }"); } public String formExtraHiddens() { String redirectAfterSave = mapGet(params, "redirectAfterSave"); return empty(redirectAfterSave) ? "" : hhidden("redirectAfterSave", redirectAfterSave); } public void processRenames(Map params) { if (!allowFieldRenaming) return; for (String key1 : keysList(params)) { String field = dropPrefixOrNull("rename_", key1); if (field == null) continue; String newName = trim(params.get(key1)); if (newName == null || eq(field, newName)) continue; print("Renaming " + field + " to " + or2(newName, "")); params.remove("rename_" + field); String re = "^([^_]+_)" + regexpQuote(field) + "(_[^_]+)?$"; for (String key : keysList(params)) { List groups = regexpGroups(re, key); if (groups != null) { String newKey = empty(newName) ? null : first(groups) + newName + unnull(second(groups)); mapPut(params, newKey, params.get(key)); params.put(key, ""); print("Renaming key: " + key + " => " + newKey); } } } } } abstract static public class ConceptFieldIndexCI_certainValues extends ConceptFieldIndexBase_certainValues { public ConceptFieldIndexCI_certainValues(Class cc, String field) { super(cc, field); } public ConceptFieldIndexCI_certainValues(Concepts concepts, Class cc, String field) { super(concepts, cc, field); } public void init() { valueToObject = generalizedCIMultiSetMap(); } public void register() { } } public interface IntSize { public int size(); default public boolean isEmpty() { return size() == 0; } } 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 HTMLForm { public HTMLForm() { } public List rows = new ArrayList(); public String tableClass = "responstableForForms"; public Map hiddenValues = new HashMap(); public boolean renderForm = true; public String formAction; abstract static public class Row { public Row() { } public String label; abstract public Object contents(); } static public class LiteralRow extends Row { public LiteralRow() { } public String contents; public LiteralRow(String label, String contents) { this.contents = contents; this.label = label; } public Object contents() { return contents; } } public String css() { return eq(tableClass, "responstableForForms") ? hcss_responstableForForms() : ""; } public String get() { return hcss(css()) + html(); } public String html() { List> matrix = map(rows, row -> ll(row.label, strOrEmpty(row.contents()))); String table = htableRaw_valignTop(matrix, empty(tableClass) ? litparams("border", 1, "cellpadding", 4) : litparams("class", tableClass)); table += hhiddenMulti(hiddenValues); return renderForm ? hpostform(table, "action", formAction) : table; } public void add(String label, Object contents) { rows.add(new LiteralRow(label, strOrEmpty(contents))); } public void addButton(String text) { add("", hsubmit(text)); } public void addHidden(String name, String value) { hiddenValues.put(name, value); } } static public interface IRef extends IF0 { public default void replaceValue(A oldValue, A newValue) { } } 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 ConceptsShadowLogger implements AutoCloseable { public Concepts cc; public int delay = 500; public boolean verbose = false; public List shadows; public HashSet changedIDs = new HashSet(); public boolean fullChange = false; public PrintWriter writer; public Lock lock = lock(); transient public Q q = startQ("ConceptsShadowLogger"); public IVF1 changeHandler = change -> { Lock __0 = lock; lock(__0); try { if (change instanceof ConceptChange) changedIDs.add(((ConceptChange) change).c.id); else if (change instanceof ConceptCreate) changedIDs.add(((ConceptCreate) change).c.id); else if (change instanceof ConceptDelete) changedIDs.add(((ConceptDelete) change).id); else if (change instanceof FullChange) fullChange = true; } finally { unlock(__0); } }; public ConceptsShadowLogger() { } public ConceptsShadowLogger(Concepts cc) { this.cc = cc; } public void install() { makeShadows(); cc.onChange(changeHandler); } public void uninstall() { cc.removeChangeListener(changeHandler); } public void makeShadows() { shadows = allConceptShadows(cc); } public void flush() { q.add(new Runnable() { public void run() { try { flush_impl(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "flush_impl();"; } }); } public void flush_impl() { sleep(delay); Set changedIDs; { Lock __1 = lock; lock(__1); try { if (fullChange) { changedIDs = allConceptIDs(cc); fullChange = false; } else { changedIDs = this.changedIDs; this.changedIDs = new HashSet(); } } finally { unlock(__1); } } List> newShadows = map(sorted(changedIDs), id -> pair(id, conceptShadow(cc.getConcept(id)))); List> diffs = new ArrayList(); List updatedShadows = new ArrayList(); int i1 = 0, i2 = 0; List> l1 = newShadows; List l2 = shadows; while (i1 < l(l1) && i2 < l(l2)) { long id1; ConceptShadow s1; Pair __3 = newShadows.get(i1); id1 = __3.a; s1 = __3.b; ConceptShadow s2 = shadows.get(i2); long id2 = s2.id(); if (id1 < id2) { diffs.add(new CreatedDeletedChanged.Created(s1)); updatedShadows.add(s1); ++i1; } else if (id1 > id2) { updatedShadows.add(s2); ++i2; } else { if (s1 == null) diffs.add(new CreatedDeletedChanged.Deleted(s2)); else { if (eq(s1, s2)) print("Unchanged concept: " + id1); else diffs.add(new CreatedDeletedChanged.Changed(s2, s1)); updatedShadows.add(s1); } ++i1; ++i2; } } while (i1 < l(l1)) { long id; ConceptShadow s; Pair __4 = l1.get(i1++); id = __4.a; s = __4.b; if (s != null) { diffs.add(new CreatedDeletedChanged.Created(s)); updatedShadows.add(s); } else print("Concept already gone again: " + id); } updatedShadows.addAll(subList(l2, i2)); shadows = updatedShadows; if (verbose) pnl("SHADOW DIFF", diffs); if (writer != null && nempty(diffs)) { writer.println(structure(diffs)); writer.flush(); } } public void close() { runInQAndWait(q, new Runnable() { public void run() { try { { cleanUp(writer); writer = null; } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "dispose writer"; } }); } } 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"; } } 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; } } static public interface IContentsIndexedList2 extends List { public TreeSet indicesOf_treeSetOfHasIndex(A o); } 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 Worker extends Concept { public String loginName, displayName; public boolean available = false; public long lastOnline; public Ref image = new Ref(); static public String _fieldOrder = "loginName displayName"; public String renderAsHTML() { return htmlEncode2(loginName + " (display name: " + displayName + ")"); } } abstract static public class DynNewBot2 extends DynPrintLogAndEnabled { public void setEleu(Object eleu) { mainBot = eleu; } public int maxRefsToShow = 5; volatile public long requestsServed; transient public String templateID = "#1029809"; static public String cssID = "#1029808"; transient public String botName = "DynNewBot2"; transient public String heading = "DynNewBot2"; transient public String adminName = "DynNewBot2 Admin"; transient public String botImageID = "#1102935"; transient public String userImageID = "#1102803"; transient public String chatHeaderImageID = "#1102802"; transient public String timeZone = ukTimeZone_string(); transient public String baseLink = ""; transient public boolean newDesign = true; transient public boolean ariaLiveTrick = false; transient public boolean ariaLiveTrick2 = true; public class WorkerChat { public int workerLongPollTick = 200; public int workerLongPollMaxWait = 1000 * 30; public long lastWorkerRequested; public String mainAdminLink = "/"; public Object html(DynNewBot2.Req req) { Map params = req.params; String uri = req.uri, uri2 = appendSlash(uri); boolean requestAuthed = req.auth != null; Conversation conv = req.conv; if (startsWith(uri2, "/worker/")) { if (!req.webRequest.isHttps()) return subBot_serveRedirect("https://" + req.webRequest.domain() + req.uri + htmlQuery(req.params)); if (!requestAuthed) return serveAuthForm(params.get("uri")); if (nempty(params.get("turnBotOn"))) conv.turnBotOn(); return serveWorkerPage(req); } return null; } public String serveWorkerPage(DynNewBot2.Req req) { AuthedDialogID auth = req.auth; Conversation conv = req.conv; String uri = req.uri; Map params = req.params; String cookie = conv.cookie; String uri2 = afterLastSlash(uri); if (eq(uri2, "availableWorkers")) return "Available workers: " + or2(joinWithComma(map(workersAvailable(), w -> w.renderAsHTML())), "-"); if (nempty(params.get("workerLogOut"))) cset(auth, "loggedIn", null); if (auth.loggedIn != null && nempty(params.get("workerAvailableBox"))) if (cset_trueIfChanged(auth.loggedIn, "available", nempty(params.get("workerAvailable")))) noteConversationChange(); if (nempty(params.get("acceptConversation"))) { if (conv.worker == null) { cset(conv, "worker", auth.loggedIn); conv.turnBotOff(); } } String loginID = params.get("workerLogIn"); if (nempty(loginID)) cset(auth, "loggedIn", getConcept(Worker.class, parseLong(loginID))); Map map = prependEmptyOptionForHSelect(mapToOrderedMap(conceptsSortedByFieldCI(Worker.class, "loginName"), w -> pair(w.id, w.loginName))); if (auth.loggedIn == null) return hsansserif() + p("You are not logged in as a worker") + hpostform("Log in as: " + hselect("workerLogIn", map, conceptID(auth.loggedIn)) + " " + hsubmit("OK"), "action", botMod().baseLink + "/worker"); if (eq(uri2, "conversation")) { if (conv == null) return "Conversation not found"; String onOffURL = botMod().baseLink + "/worker/botOnOff" + hquery("cookie", cookie) + "&on="; return hsansserif() + loadJQuery() + hhidden("cookie", cookie) + hpostform(hhidden("cookie", cookie) + p(renderBotStatus(conv)) + p(conv.botOn ? hsubmit("Accept conversation", "name", "acceptConversation") : hsubmit("Turn bot back on", "name", "turnBotOn")), "action", botMod().baseLink + "/worker/innerFrameSet", "target", "innerFrameSet") + hscriptsrc(botMod().baseLink + "/script" + hquery("workerMode", 1, "cookie", conv.cookie)); } if (eq(uri2, "conversations")) { cset(auth.loggedIn, "lastOnline", now()); boolean poll = eq("1", params.get("poll")); String content = ""; if (poll) { long seenChange = parseLong(params.get("lastChange")); vmBus_send("chatBot_startingWorkerPoll", mc(), conv); long start = sysNow(); List msgs; boolean first = true; while (licensed() && sysNow() < start + workerLongPollMaxWait && lastConversationChange == seenChange) sleep(workerLongPollTick); printVars_str("lastWorkerRequested", lastWorkerRequested, "seenChange", seenChange); if (lastWorkerRequested > seenChange) content = hscript("\r\n window.parent.parent.frames[0].sendDesktopNotification(\"A worker is requested!\", { action: function() { window.focus(); } });\r\n window.parent.parent.frames[0].playWorkerRequestedSound();\r\n "); } long pingThreshold = now() - activeConversationTimeout(); List convos = sortByCalculatedFieldDesc(c -> c.lastMsgTime(), conceptsWithFieldGreaterThan(Conversation.class, "lastPing", pingThreshold)); content += hhiddenWithID("lastConversationChange", lastConversationChange) + tag("table", hsimpletableheader("IP", "Country", "Bot/worker status", "Last change", "Last messages") + mapToLines(convos, c -> { List lastMsgs = lastTwo(c.msgs); String style = c == conv ? "background: #90EE90" : null; String convLink = botMod().baseLink + "/worker/innerFrameSet" + hquery("cookie", c.cookie); return tag("tr", td(ahref(convLink, c.ip, "target", "innerFrameSet")) + td(getCountry(c)) + td(renderBotStatus(c)) + td(renderHowLongAgo(c.lastMsgTime())) + td(ahref(convLink, hparagraphs(lambdaMap(__199 -> renderMsgForWorkerChat(__199), lastMsgs)), "target", "innerFrameSet", "style", "text-decoration: none")), "style", style); }), "class", "responstable"); if (poll) return content; String incrementalURL = botMod().baseLink + "/worker/conversations?poll=1&lastChange="; return hhtml(hhead(hsansserif() + loadJQuery() + hscript_clickableRows()) + hbody(h3(botName) + hpostform("Logged in as " + htmlEncode2(auth.loggedIn.loginName) + " (display name: " + htmlEncode2(auth.loggedIn.displayName) + ")" + hhidden("workerAvailableBox", 1) + "   " + hcheckboxWithText("workerAvailable", "I am available", auth.loggedIn.available, "onclick", "form.submit()") + "   " + hsubmit("Log out", "name", "workerLogOut"), "target", "innerFrameSet", "action", botMod().baseLink + "/worker/innerFrameSet") + p("Available workers: " + b(or2(joinWithComma(map(workersAvailable(), w -> w.displayName)), "none"))) + h3("Active conversations") + hcss_responstable() + hdivWithID("contentArea", content) + hscript("\r\n function poll_start() {\r\n var lastChange = $(\"#lastConversationChange\").val();\r\n if (!lastChange)\r\n setTimeout(poll_start, 1000);\r\n else {\r\n var url = \"#INCREMENTALURL#\" + lastChange;\r\n console.log(\"Loading \" + url);\r\n $.get(url, function(src) {\r\n if (src.match(/^ERROR/)) console.log(src);\r\n else {\r\n console.log(\"Loaded \" + src.length + \" chars\");\r\n $(\"#contentArea\").html(src);\r\n }\r\n setTimeout(poll_start, 1000);\r\n }, 'text')\r\n .fail(function() {\r\n console.log(\"Rescheduling after fail\");\r\n setTimeout(poll_start, 1000);\r\n });\r\n }\r\n }\r\n poll_start();\r\n ".replace("#INCREMENTALURL#", incrementalURL)))); } if (eq(uri2, "notificationArea")) return hhtml(hhead(hsansserif() + loadJQuery()) + hbody(hdesktopNotifications() + div(small(span(hbutton("CLICK HERE to enable notification sounds!"), "id", "enableSoundsBtn") + " | " + span("", "id", "notiStatus")), "style", "float: right") + hscript("\r\n function enableSounds() {\r\n document.removeEventListener('click', enableSounds);\r\n $(\"#enableSoundsBtn\").html(\"Notification sounds enabled\");\r\n }\r\n document.addEventListener('click', enableSounds);\r\n \r\n if (window.workerRequestedSound == null) {\r\n console.log(\"Loading worker requested sound\");\r\n window.workerRequestedSound = new Audio(\"https://botcompany.de/files/1400404/worker-requested.mp3\");\r\n }\r\n \r\n function playWorkerRequestedSound() {\r\n console.log(\"Playing worker requested sound\");\r\n window.workerRequestedSound.play();\r\n }\r\n window.playWorkerRequestedSound = playWorkerRequestedSound;\r\n\r\n "))); if (eq(uri2, "innerFrameSet")) return hhtml(hhead_title("Worker Chat [" + auth.loggedIn.loginName + "]") + hframeset_cols("*,*", tag("frame", "", "name", "conversations", "src", botMod().baseLink + "/worker/conversations" + hquery("cookie", cookie)) + tag("frame", "", "name", "conversation", "src", conv == null ? null : botMod().baseLink + "/worker/conversation" + hquery("cookie", cookie)))); return hhtml(hhead_title("Worker Chat [" + auth.loggedIn.loginName + "]") + hframeset_rows("50,*", tag("frame", "", "name", "notificationArea", "src", botMod().baseLink + "/worker/notificationArea") + tag("frame", "", "name", "innerFrameSet", "src", conv == null ? null : botMod().baseLink + "/worker/innerFrameSet" + hquery("cookie", cookie)))); } public String renderMsgForWorkerChat(Msg msg) { return (msg.fromWorker != null ? htmlEncode2(msg.fromWorker.displayName) : msg.fromUser ? "User" : "Bot") + ": " + b(htmlEncode2If(shouldHtmlEncodeMsg(msg), msg.text)); } public Collection workersAvailable() { long timestamp = now() - workerLongPollMaxWait - 10000; return filter(list(Worker.class), w -> w.available && w.lastOnline >= timestamp); } public boolean anyWorkersAvailable() { return nempty(workersAvailable()); } public String renderBotStatus(Conversation conv) { return "Bot is " + b(conv.botOn ? "on" : "off") + "
" + "Assigned worker: " + b(conv.worker == null ? "none" : conv.worker.displayName); } } transient public WorkerChat workerChat = new WorkerChat(); transient public ReliableSingleThread rstBotActions = dm_rst(this, new Runnable() { public void run() { try { botActions(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "botActions();"; } }); transient public String defaultHeaderColorLeft = "#2a27da"; transient public String defaultHeaderColorRight = "#00ccff"; transient public boolean enableUsers = false; transient public boolean useWebSockets = false; transient public boolean showRegisterLink = false; transient public boolean showTalkToBotLink = false; transient public boolean alwaysRedirectToHttps = false; transient public boolean redirectOnLogout = false; transient public boolean showFullErrors = false; transient public boolean lockWhileDoingBotActions = false; transient public boolean standardButtonsAsSymbols = false; transient public boolean enableVars = false; transient public boolean enableAvatars = false; transient public boolean enableRandomActions = false; transient public boolean recordExecutionsAndInputs = true; transient public boolean phoneNumberSpecialInputField = true; transient public boolean enableRadioButtons = false; transient public boolean newDialogAfterWindowClosed = false; transient public boolean showJoiningConversation = false; transient public boolean quickRadioButtons = false; transient public boolean useDynamicComboBoxes = false; transient public boolean prefixPrintsWithConvID = true; transient public boolean enableUndoStates = false; transient public boolean showCRUDToEveryone = false; transient public boolean showCRUDToNonMasterUsers = true; transient public boolean showOnlySelectedObject = false; transient public boolean storeBaseClassesInStructure = false; transient public boolean botDisabled = false; transient public boolean useBotNameAsModuleName = true; transient public boolean showMailSenderInfo = true; transient public boolean authedDialogIDForEveryCookie = false; transient public boolean showDeliveredDomains = true; public String mailSenderInfo; transient public int typingTimeshift = 2000; transient public ThreadLocal currentReq = new ThreadLocal(); transient volatile public Scorer consistencyCheckResults; transient public Lock statsLock = lock(); transient public Map specialPurposes = litcimap("bad email address", "Please enter a valid e-mail address", "bad phone number", "Please enter a valid phone number"); transient public String nameOfReferencesColumn = "Referenced by"; transient public Set requestsInFlight = syncWeakSet(); public void start() { super.start(); if (useBotNameAsModuleName) dm_setModuleName(botName); dm_assertFirstSibling(); concepts_setUnlistedByDefault(true); standardTimeZone(); standardTimeZone_name = timeZone; print("DB program ID: " + dbProgramID()); realPW(); pWebChatBot(); dm_doEvery(60.0, new Runnable() { public void run() { try { cleanConversations(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cleanConversations();"; } }); rstBotActions.trigger(); } public void indexAllLinkableClasses() { ensureConceptClassesAreIndexed(allLinkableClasses()); } public JComponent visualize() { JComponent _c = super.visualize(); addToControlArea(jPopDownButton_noText(popDownButtonEntries())); return _c; } public Object[] popDownButtonEntries() { return litobjectarray("Show/edit master password...", runnableThread(new Runnable() { public void run() { try { AutoCloseable __24 = enter(); try { editMasterPassword(); } finally { _close(__24); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter(); editMasterPassword();"; } }), !showMailSenderInfo ? null : "Show/edit mail sender info...", runnableThread(new Runnable() { public void run() { try { AutoCloseable __25 = enter(); try { editMailSenderInfo(); } finally { _close(__25); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter(); editMailSenderInfo();"; } })); } static public class Req implements IWebRequest { public IWebRequest webRequest; public String uri; public Map params; public AuthedDialogID auth; public Domain authDomainObj; public String authDomain; public HTMLFramer1 framer; public boolean masterAuthed = false; public Conversation conv; public String subURI; public WeakReference handlingThread; public String uri() { return uri; } final public String subUri() { return subURI(); } public String subURI() { return subURI; } public Map params() { return params; } public Map headers() { return webRequest.headers(); } public Map files() { return webRequest.files(); } public boolean isHttps() { return webRequest.isHttps(); } public String cookie() { return webRequest.cookie(); } public boolean requestAuthed() { return auth != null; } public String get(String param) { return mapGet(params, param); } public boolean isPost() { return webRequest.isPost(); } public void markNoSpam() { webRequest.noSpam(); } public void noSpam() { markNoSpam(); } public String uriWithParams() { return appendParamsToURL(uri, params); } public HTMLFramer1 framer() { return framer; } } public boolean calcMasterAuthed(Req req) { return req != null && req.auth != null && req.auth.master; } public Object html(IWebRequest request) { AutoCloseable __19 = enter(); try { vmBus_logMethodCall("html", "this", this, "request", request); try { return html2(request); } catch (Throwable e) { printStackTrace(e); return subBot_serve500(showFullErrors || calcMasterAuthed(currentReq()) ? getStackTrace(e) : "Error."); } finally { currentReq.set(null); } } finally { _close(__19); } } public Req currentReq() { return currentReq.get(); } public void requestServed() { } public Object html2(IWebRequest request) { htmlencode_forParams_useV2(); { Lock __2 = statsLock; lock(__2); try { requestsServed++; change(); requestServed(); vmBus_logMethodCall("html", "this", this, "requestsServed", requestsServed); } finally { unlock(__2); } } Req req = webRequestToReq(request); AutoCloseable __20 = tempAdd(requestsInFlight, req); try { if (alwaysRedirectToHttps) { var __10 = redirectToHttps(req); if (__10 != null) return __10; } vmBus_logMethodCall("html", "Calling html3"); return html3(req); } finally { _close(__20); } } public Req newReq() { return new Req(); } public Req webRequestToReq(IWebRequest request) { Req req = newReq(); req.webRequest = request; req.uri = request.uri(); req.params = request.params(); req.handlingThread = weakRef(currentThread()); return req; } public Object html3(Req req) { IWebRequest request = req.webRequest; String uri = req.uri; Map params = req.params; if (eq(params.get("_newConvCookie"), "1")) return hrefresh(appendQueryToURL(req.uri, mapPlus(mapMinus(req.params, "_newConvCookie"), "cookie", "test_" + aGlobalID()))); String cookie = request.cookie(); boolean workerMode = nempty(params.get("workerMode")) || startsWith(uri, "/worker"); String domain = request.domain(), _domain = domain; saveDeliveredDomain(domain); Domain domainObj = findDomainObj(domain); String convCookie = params.get("cookie"); Conversation conv = botDisabled ? null : isRequestFromBot(req) ? null : nempty(convCookie) ? getConv(convCookie) : nempty(cookie) ? getConv(cookie) : null; req.conv = conv; AutoCloseable tempThing = conv == null || !prefixPrintsWithConvID ? null : temp_printPrefix("Conv " + conv.cookie + ": "); AutoCloseable __21 = tempThing; try { currentReq.set(req); String botConfig = params.get("_botConfig"); Map botConfigParams = decodeURIParams(botConfig); String simulatedDomain = botConfigParams.get("domain"); Domain domainObj2 = nempty(simulatedDomain) ? findDomainObj(simulatedDomain) : domainObj; if (nempty(botConfigParams)) cset(conv, "botConfig", botConfigParams); if (conv != null && !workerMode) if (cset_trueIfChanged(conv, "ip", request.clientIP(), "domain", domain, "domainObj", domainObj2)) { calcCountry(conv); initAvatar(conv); } { var __11 = handleAuth(req, cookie); if (__11 != null) return __11; } Matches m = new Matches(); if (startsWith(uri, "/worker-image/", m)) { long id = parseLong(m.rest()); return subBot_serveFile_maxCache(workerImageFile(id), "image/jpeg"); } if (startsWith(uri, "/uploaded-image/", m)) { long id = parseLong(m.rest()); UploadedImage img = getConcept(UploadedImage.class, id); return img == null ? serve404() : subBot_serveFile_maxCache(img.imageFile(), "image/jpeg"); } if (startsWith(uri, "/uploaded-sound/", m)) { long id = parseLong(m.rest()); UploadedSound sound = getConcept(UploadedSound.class, id); return sound == null ? serve404() : subBot_serveFile_maxCache(sound.soundFile(), sound.mimeType); } if (startsWith(uri, "/uploaded-file/", m)) { long id = parseLong(dropAfterSlash(m.rest())); UploadedFile f = getConcept(UploadedFile.class, id); return f == null ? serve404() : subBot_serveFile_maxCache(f.theFile(), or2(params.get("ct"), or2(trim(f.mimeType), binaryMimeType()))); } AuthedDialogID auth = authObject(cookie); fillReqAuthFromCookie(req, cookie, auth); if (eq(params.get("logout"), "1")) { { var __12 = handleLogout(req); if (__12 != null) return __12; } auth = authObject(cookie); } boolean requestAuthed = req.auth != null; boolean masterAuthed = req.masterAuthed; Domain authDomainObj = req.authDomainObj; String authDomain = req.authDomain; if (requestAuthed) req.markNoSpam(); { var __13 = serve2(req); if (__13 != null) return __13; } makeFramer(req); HTMLFramer1 framer = req.framer; if (showCRUDToEveryone || showCRUDToNonMasterUsers && requestAuthed || req.masterAuthed) { var __14 = serveCRUD(req); if (__14 != null) return __14; } if (!requestAuthed && settings().talkToBotOnlyWithAuth) return serveAuthForm(params.get("uri")); if (eq(uri, "/emoji-picker/index.js")) return withHeader(subBot_maxCacheHeaders(serveInputStream(bufferedFileInputStream(loadLibrary("#1400436")), "text/javascript"))); if (eq(uri, "/emoji-picker-test")) return loadSnippet("#1029870"); if (eq(uri, "/logs")) { if (!masterAuthed) return serveAuthForm(rawLink(uri)); return webChatBotLogsHTML2(rawLink(uri), params); } if (eq(uri, "/refchecker")) { if (!masterAuthed) return serveAuthForm(rawLink(uri)); ConceptsRefChecker refChecker = new ConceptsRefChecker(db_mainConcepts()); List errors = refChecker.run(); if (eq(params.get("fix"), "1")) return serveText(refChecker.fixAll()); else return serveText(jsonEncode_breakAtLevels(2, litorderedmap("errors", allToString(errors)))); } if (eq(uri, "/backupDBNow")) { if (!masterAuthed) return serveAuthForm(rawLink(uri)); return serveText("Backed up DB as " + fileInfo(backupConceptsNow())); } if (eq(uri, "/auth-only")) { if (!requestAuthed) return serveAuthForm(params.get("uri")); return ""; } if (eq(uri, "/leads-api")) return serveLeadsAPI(request); if (workerChat != null) { var __15 = workerChat.html(req); if (__15 != null) return __15; } String message = trim(params.get("btn")); if (empty(message)) message = trim(params.get("message")); if (match("new dialog", message)) { Lock __3 = dbLock(); lock(__3); try { conv.newDialog(); message = null; } finally { unlock(__3); } } if (eqic(message, "!toggle notifications")) { cset(conv, "notificationsOn", !conv.notificationsOn); message = null; } if (eqic(message, "!undo states")) { conv.add(new Msg(false, n2(conv.undoStates, "undo state"))); message = null; } this.conv.set(conv); if (nempty(message) && !lastUserMessageWas(conv, message)) { Lock __4 = dbLock(); lock(__4); try { print("Adding message: " + message); possiblyTriggerNewDialog(conv); if (workerMode) { Msg msg = new Msg(false, message); msg.fromWorker = auth.loggedIn; conv.add(msg); } else { conv.add(new Msg(true, message)); addScheduledAction(new OnUserMessage(conv)); } } finally { unlock(__4); } } String testMode = params.get("testMode"); if (nempty(testMode)) { print("Setting testMode", testMode); cset(conv, "testMode", eq("1", testMode)); } if (eq(uri, "/msg")) return withHeader("OK"); if (eq(uri, "/typing")) { if (workerMode) { conv.botTyping = now(); print(conv.botTyping + " Bot typing in: " + conv.cookie); } else { conv.userTyping = now(); print(conv.userTyping + " User typing in: " + conv.cookie); } return withHeader("OK"); } if (eq(uri, "/renderMessages")) { long msgTime = parseLong(params.get("msgTime")); List msgs = conv.allMsgs(); if (msgTime != 0) msgs = filter(msgs, msg -> msg.time == msgTime); StringBuilder buf = new StringBuilder(); renderMessages(conv, buf, msgs, msg -> false); return hhtml_title_body(nMessages(msgs), hstylesheetsrc(cssURL()) + p(nMessages(msgs) + " found") + buf); } if (eq(uri, "/incremental")) { if (newDialogAfterWindowClosed && !conv.isActive()) { print("Clearing conversation, timed out"); Lock __5 = dbLock(); lock(__5); try { conv.newDialog(); } finally { unlock(__5); } } long start = sysNow(), start2 = now(); print("start2", start2); cset(conv, "lastPing", now()); possiblyTriggerNewDialog(conv); int a = parseInt(params.get("a")); int reloadCounter = conv.reloadCounter; List msgs; boolean first = true; int timeout = toInt(req.params.get("timeout")); long endTime = start + (timeout <= 0 || timeout > longPollMaxWait / 1000 ? longPollMaxWait : timeout * 1000L); while (licensed() && sysNow() < endTime) { int as = conv.archiveSize(); msgs = cloneSubList(conv.msgs, a - as); boolean reloadTriggered = conv.reloadCounter > reloadCounter; boolean actuallyNewDialog = a < as; boolean newDialog = actuallyNewDialog || reloadTriggered; if (newDialog) msgs = cloneList(conv.msgs); long typing = workerMode ? conv.userTyping : conv.botTyping; boolean otherPartyTyping = typing >= start2 - typingTimeshift; boolean anyEvent = nempty(msgs) || newDialog || otherPartyTyping; if (!anyEvent) { if (first) { first = false; } sleep(longPollTick); } else { if (eq(req.params.get("json"), "1")) return serveJSON_breakAtLevels(2, litorderedmap("n", conv.allCount(), "newDialog", trueOrNull(newDialog), "otherPartyTyping", trueOrNull(otherPartyTyping), "msgs", map(msgs, msg -> litorderedmap("time", msg.time, "fromUser", msg.fromUser, "fromWorker", msg.fromWorker == null ? null : msg.fromWorker.displayName, "text", msg.text, "labels", msg.labels)))); StringBuilder buf = new StringBuilder(); if (newDialog) { String l = or2_trim(domainObj2.headerColorLeft, defaultDomain().headerColorLeft, defaultHeaderColorLeft), r = or2_trim(domainObj2.headerColorRight, defaultDomain().headerColorRight, defaultHeaderColorRight); buf.append(hcss(".chat_header { background: linear-gradient(135deg, " + hexColorToCSSRGB(l) + " 0%, " + hexColorToCSSRGB(r) + " 100%); }")); buf.append(hscript("$('#chatBot_notiToggleText').text(" + jsQuote("Turn " + (conv.notificationsOn ? "off" : "on") + " notifications") + ");")); if (showJoiningConversation) { buf.append(hscript("$('#otherSideTyping .joining').html(" + jsQuote(nameOfBotSide(conv) + " now joining conversation...") + ");" + "setTimeout(function() { $('#otherSideTyping .joining').html(''); }, 5000);")); } } if (otherPartyTyping) { buf.append(hscript("showTyping(" + jsQuote(conv.botImg()) + ");")); } renderMessages(conv, buf, msgs); if (ariaLiveTrick2 && !workerMode) { Msg msg = lastBotMsg(msgs); if (msg != null) { String author = msg.fromWorker != null ? htmlEncode2(msg.fromWorker.displayName) : botName; buf.append(hscript("$(\"#screenreadertrick\").html(" + jsQuote(author + " says: " + msg.text) + ");")); } } if (a != 0 && anyInterestingMessages(msgs, workerMode)) buf.append(hscript(stringIf(conv.notificationsOn, "window.playChatNotification();\n") + "window.setTitleStatus(" + jsQuote((workerMode ? "User" : botName) + " says…") + ");")); String html = str(buf); return withHeader("\n" + html); } } return withHeader(""); } if (eqOneOf(uri, "/script", "/demo")) { Lock __6 = dbLock(); lock(__6); try { String myTemplateID = templateID; String templateIDParam = req.params.get("templateID"); if (nempty(templateIDParam) && allowedTemplateID(templateIDParam)) myTemplateID = templateIDParam; String html = loadSnippet_cached(myTemplateID); String botLayout = req.params.get("botLayout"); String layout = or2(botLayout, defaultBotLayout()); html = modifyTemplateBeforeDelivery(html, req); String heading = or2(headingForReq(req), or2(trim(domainObj2.botName), this.heading)); String botImg = botImageForDomain(domainObj); UploadedSound sound = settings().notificationSound.get(); String notificationSound = sound != null ? sound.soundURL() : defaultNotificationSound(); String miscParam = workerMode ? "workerMode=1&" : ""; if (nempty(botLayout)) miscParam += "botLayout=" + urlencode(botLayout) + "&"; String incrementalURL = baseLink + "/incremental?" + miscParam + "a="; String typingURL = baseLink + "/typing?" + miscParam; String msgURL = baseLink + "/msg?" + miscParam + "message="; if (eqic(layout, "sahil")) { html = replaceDollarVars(html, "incrementalURL", incrementalURL, "typingURL", typingURL, "msgURL", msgURL, "n", 0, "notificationSound", notificationSound, "workerMode", workerMode, "heading", heading, "botImg", botImg); } else { String langlinks = ""; if (html.contains(langlinks)) html = html.replace(langlinks, ahref(rawLink("eng"), "English") + " | " + ahref(rawLink("deu"), "German")); html = html.replace("#COUNTRY#", lower(conv.country)); html = html.replace("#BOTIMG#", botImg); html = html.replace("#N#", "0"); html = html.replace("#INCREMENTALURL#", incrementalURL); html = html.replace("#MSGURL#", msgURL); html = html.replace("#TYPINGURL#", typingURL); html = html.replace("#CSS_ID#", psI_str(cssID)); if (ariaLiveTrick || ariaLiveTrick2) html = html.replace("aria-live=\"polite\">", ">"); html = html.replace("#OTHERSIDE#", workerMode ? "User" : "Representative"); if (nempty(params.get("debug"))) html = html.replace("var showActions = false;", "var showActions = true;"); html = html.replace("#AUTOOPEN#", jsBool(workerMode || eq(params.get("_autoOpenBot"), "1") || botAutoOpen(domainObj2))); html = html.replace("#BOT_ON#", jsBool(botOn() || eq(uri, "/demo"))); html = html.replace("$HEADING", heading); html = html.replace("#WORKERMODE", jsBool(workerMode)); html = html.replace("#NOTIFICATIONSOUND#", notificationSound); html = html.replace("", ""); html = hreplaceTitle(html, heading); } if (eq(uri, "/demo")) return serveBotDemo(req, html); else return withHeader(subBot_serveJavaScript(html)); } finally { unlock(__6); } } { var __16 = serveOtherPage(req); if (__16 != null) return __16; } if (eq(uri, "/")) { var __17 = serveHomePage(); if (__17 != null) return __17; } if (eq(uri, "/login")) return serveAuthForm(); String uri2 = dropSlashPrefix(uri); if (!startsWith(uri, "/crud/") && nempty(uri2)) { UploadedFile fileToServe = conceptWhere(UploadedFile.class, "liveURI", urldecode(uri2)); if (fileToServe != null) return subBot_serveFile(fileToServe.theFile(), nempty(fileToServe.mimeType) ? fileToServe.mimeType : guessMimeTypeFromFileName(afterLastSlash(fileToServe.liveURI))); } if (requestAuthed) { if (masterAuthed && eq(uri, "/dialogTree")) { BotStep step = getConcept(BotStep.class, toLong(params.get("stepID"))); if (step == null) return serve404("Step not found"); return hhtml_head_title_body("Dialog Tree for " + step, hmobilefix() + hsansserif() + h2("Dialog Tree") + hcss_linkColorInherit() + hcss("\r\n .dialogTree li { margin-top: 0.8em; }\r\n ") + renderDialogTree(step)); } if (eq(uri, "/thoughts")) return serveThoughts(req); if (masterAuthed && eq(uri, "/search")) return serveSearch(req); if (eq(uri, "/leads-csv")) { String text = leadsToCSV(conceptsWhere(Lead.class, mapToParams(filtersForClass(Lead.class, req)))); String name = "bot-leads" + (authDomainObj == null ? "" : "-" + replace(str(authDomainObj), "/", "-")) + "-" + ymd_minus_hm() + ".csv"; return serveCSVWithFileName(name, text); } if (eq(uri, "/cleanConversations") && masterAuthed) { cleanConversations(); return hrefresh(baseLink + "/crud/Conversation"); } if (eq(uri, "/deleteDeliveredDomains") && masterAuthed) { deleteDeliveredDomains(); return hrefresh(baseLink + "/crud/DeliveredDomain"); } if (eq(uri, "/emojis")) { framer.title = "Emoji List"; framer.contents.add(htmlTable2(map(emojiShortNameMap(), (code, emoji) -> litorderedmap("Shortcode", code, "Emoji", emoji)))); } if (eq(uri, "/embedCode")) { String goDaddyEmbedCode = ""; framer.title = "Embed Code"; framer.contents.add(h2("Chat bot embed code") + (empty(goDaddyEmbedCode) ? "" : h3("GoDaddy Site Builder") + p("Add an HTML box with this code:") + pre(htmlEncode2(goDaddyEmbedCode)) + h3("Other")) + p("Add this code in front of your " + tt(htmlEncode2("")) + " tag:") + pre(htmlEncode2(hjavascript_src_withType("https://" + request.domain() + baseLink + "/script")))); } if (eq(uri, "/stats")) { framer.add(htableRaw2(nonNulls(renderStats()), ll("class", "responstable"), null, null)); return completeFrame(req); } if (eq(uri, "/unpackToWeb") & req.masterAuthed) { UploadedFile file = getConcept(UploadedFile.class, parseLong(req.params.get("fileID"))); if (file == null) return serve404("File not found"); String path = unnull(req.params.get("path")); File zipFile = file.theFile(); int changes = 0; for (String filePath : listZIP(zipFile)) { String liveURI = appendSlash(path) + filePath; UploadedFile entry = uniq(UploadedFile.class, "liveURI", liveURI); byte[] data = loadBinaryFromZip(zipFile, filePath); if (!fileContentsIs(entry.theFile(), data)) { ++changes; saveBinaryFile(entry.theFile(), data); touchConcept(entry); } } return "Unpacked, " + nChanges(changes); } } { var __18 = serveDefaultPage(req); if (__18 != null) return __18; } return completeFrame(req); } finally { _close(__21); } } public Object serveDefaultPage(Req req) { return null; } public Object completeFrame() { return completeFrame(currentReq()); } transient public IF1 completeFrame; public Object completeFrame(Req req) { return completeFrame != null ? completeFrame.get(req) : completeFrame_base(req); } final public Object completeFrame_fallback(IF1 _f, Req req) { return _f != null ? _f.get(req) : completeFrame_base(req); } public Object completeFrame_base(Req req) { HTMLFramer1 framer = req.framer; boolean authed = req.requestAuthed(); if (authed) { if (settings().enableWorkerChat) framer.addNavItem(baseLink + "/worker", "Worker chat"); framer.addNavItem(baseLink + "?logout=1", "Log out"); } if (!authed || alwaysShowLogInLink()) framer.addNavItem(logInLink(), "Log in"); return framer.render(); } public boolean alwaysShowLogInLink() { return false; } public String logInLink() { return baseLink + "/"; } public Object serve2(Req req) { vmBus_send("html_serve2", this, req); return null; } public Object serveOtherPage(Req req) { return null; } public
A getDomainValue(Domain domainObj, IF1 getter, A defaultValue) { if (domainObj != null) { A val = getter.get(domainObj); if (val != null) return val; } { A val = getter.get(defaultDomain()); if (val != null) return val; } return defaultValue; } public String makeBaseTitle(Req req) { return ahref(baseLink + "/", adminName) + " " + squareBracket(loggedInUserDesc_html(req)); } public HTMLFramer1 newFramerInstance() { return new HTMLFramer1(); } public void makeFramer(Req req) { HTMLFramer1 framer = newFramerInstance(); req.framer = framer; framer.titleIsHTML = true; framer.title = makeBaseTitle(req); framer.addInHead(hsansserif() + hmobilefix() + hresponstable() + hcss_responstableForForms()); framer.addInHead(loadJQuery2()); framer.addInHead(hjs_selectize()); framer.addInHead(hjs_copyToClipboard()); framer.addInHead(hNotificationPopups()); framer.addInHead(hcss_linkColorInherit()); if (useWebSockets) framer.addInHead(webSocketHeadStuff(req)); makeNavItems(req, framer); List cmdClasses = botCmdClasses(req); if (nempty(cmdClasses)) framer.contents.add(p("Bot actions: " + joinWithVBar(map(cmdClasses, c -> makeClassNavItem(c, req))))); } public void makeNavItems(Req req, HTMLFramer1 framer) { if (showTalkToBotLink) framer.addNavItem(simulateDomainLink(req.authDomain), "Talk to bot", "targetBlank", true); for (Class c : navItemClasses(req)) framer.addNavItem(makeClassNavItem(c, req)); } public List navItemClasses(Req req) { return crudClasses(req); } public HCRUD makeCRUD(Class c, Req req) { return makeCRUD(c, req, req.framer); } public HCRUD makeCRUD(Class c, Req req, HTMLFramer1 framer) { HCRUD_Concepts data = crudData(c, req); data.referencesBlockDeletion = true; String searchQuery = trim(req.get("search")); data.customFilter = crudSearchFilter(req, data, searchQuery); HCRUD crud = new HCRUD(crudLink(c), data); crud.searchQuery = searchQuery; crud.params = req.params; crud.buttonsOnTop = neqOneOf(c, UploadedFile.class, UploadedSound.class, UploadedImage.class); crud.haveJQuery = crud.haveSelectizeJS = true; crud.sortable = true; crud.paginate = true; crud.paginator.step = 25; crud.cmdsLeft = true; crud.showCheckBoxes = true; crud.tableClass = "responstable"; crud.formTableClass = "responstableForForms"; if (!req.requestAuthed()) crud.disableAllMutationRights(); crud.renderValue_inner = value -> { if (isConceptList(value)) { List l = (List) value; return joinMap(l, ref -> p(ahref(conceptLink(ref), htmlEncode_nlToBr_withIndents(str(ref))))); } String html = crud.renderValue_inner_base(value); if (value instanceof Concept) return ahref(conceptLink((Concept) value), html); return html; }; if (c == Conversation.class) { crud.nav = () -> joinNemptiesWithVBar(crud.nav_base(), ahref(baseLink + "/cleanConversations", "Clean list")); crud.unshownFields = litset("oldDialogs", "worker", "botOn", "lastPing", "cookie", "form", "testMode", "userMessageProcessed", "newDialogTriggered"); } if (c == DeliveredDomain.class || c == Conversation.class || c == Lead.class || c == ConversationFeedback.class) crud.allowCreate = crud.allowEdit = false; if (c == Settings.class) { crud.singleton = countConcepts(Settings.class) == 1; if (!settings().multiLanguageMode) crud.unshownFields = litset("defaultLanguage"); { if (framer != null) framer.add(p(joinNemptiesWithVBar(ahref(baseLink + "/emojis", "Emojis"), ahref(baseLink + "/stats", "Stats"), ahref(baseLink + "/embedCode", "Embed Code")))); } } if (c == Lead.class) { if (framer != null) framer.add(p(ahref(baseLink + "/leads-csv", "Export as CSV"))); } if (c == BotOutgoingQuestion.class) { crud.unlistedFields = litset("multipleChoiceSeparator", "placeholder"); if (!enableRadioButtons) crud.unlistedFields.add("radioButtons"); crud.massageFormMatrix = (map, matrix) -> { int idx = indexOfPred(matrix, row -> cic(first(row), "Actions")); BotOutgoingQuestion item = getConcept(BotOutgoingQuestion.class, toLong(map.get(crud.idField()))); if (item == null) return; if (idx < 0) return; List row = matrix.get(idx); row.set(1, hcrud_mergeTables(row.get(1), tag("table", map(s -> tr(td() + td(htmlEncode2(s))), item.buttons)), "for:")); }; } data.addFilters(filtersForClass(c, req)); if (c == Domain.class) { crud.renderCmds = map -> { Domain dom = getConcept(Domain.class, toLong(crud.itemID(map))); return joinNemptiesWithVBar(crud.renderCmds_base(map), targetBlank(simulateDomainLink(dom.domainAndPath), "Talk to bot")); }; if (showDeliveredDomains) { if (framer != null) framer.add(p("See also the " + ahref(crudLink(DeliveredDomain.class), "list of domains the bot was delivered on"))); } } if (c == DeliveredDomain.class) { crud.nav = () -> joinNemptiesWithVBar(crud.nav_base(), ahref("/deleteDeliveredDomains", "Delete all")); crud.renderCmds = map -> { DeliveredDomain dom = getConcept(DeliveredDomain.class, toLong(crud.itemID(map))); return joinNemptiesWithVBar(crud.renderCmds_base(map), targetBlank(simulateDomainLink(dom.domain), "Talk to bot")); }; } if (c == UploadedImage.class) { crud.massageFormMatrix = (map, matrix) -> { UploadedImage item = getConcept(UploadedImage.class, toLong(crud.itemID(map))); addInFront(matrix, ll("Upload image", hjs_imgUploadBase64Encoder() + himageupload("id", "imgUploader") + hhiddenWithIDAndName("f_img_base64"))); }; crud.formParameters = () -> paramsPlus(crud.formParameters_base(), "onsubmit", "return submitWithImageConversion(this)"); } if (c == UploadedSound.class) { crud.massageFormMatrix = (map, matrix) -> { UploadedSound item = getConcept(UploadedSound.class, toLong(crud.itemID(map))); matrix.add(ll("Upload MP3/OGG/WAV/M4A", hjs_fileUploadBase64Encoder() + haudioUpload("id", "fileUploader") + hhiddenWithIDAndName("f_file_base64"))); }; crud.formParameters = () -> litparams("onsubmit", "return submitWithFileConversion(this)"); } if (c == UploadedFile.class) { crud.massageFormMatrix = (map, matrix) -> { UploadedFile item = getConcept(UploadedFile.class, toLong(crud.itemID(map))); matrix.add(ll("Upload File", hjs_fileUploadBase64Encoder() + hfileupload("id", "fileUploader") + hhiddenWithIDAndName("f_file_base64") + hjs("\r\n $(\"input[name=thefile]\").change(function(e) {\r\n var name = e.target.files[0].name;\r\n if (name)\r\n $(\"input[name=f_name]\").val(name); \r\n });\r\n "))); }; crud.formParameters = () -> litparams("onsubmit", "return submitWithFileConversion(this)"); } if (isSubclassOf(c, BotStep.class)) { crud.renderCmds = map -> { BotStep step = getConcept(BotStep.class, toLong(crud.itemID(map))); return joinNemptiesWithVBar(crud.renderCmds_base(map), targetBlank(simulateScriptLink(step), "Test in bot"), hPopDownButton(targetBlank(baseLink + "/dialogTree?stepID=" + step.id, "Show Dialog Tree"))); }; if (showDeliveredDomains) { if (framer != null) framer.add(p("See also the " + ahref(crudLink(DeliveredDomain.class), "list of domains the bot was delivered on"))); } } if (c == Worker.class) { crud.unshownFields = litset("lastOnline"); crud.uneditableFields = litset("available", "lastOnline"); } crud.postProcessTableRow = (item, rendered) -> { long id = crud.itemIDAsLong(item); Concept concept = getConcept(id); if (concept == null) return rendered; Collection refs = allBackRefs(concept); if (empty(refs)) return rendered; refs = sortedByConceptID(refs); String rts = req.get("refsToShow"); int refsToShow = empty(rts) ? maxRefsToShow : parseInt(rts); int more = l(refs) - refsToShow; return mapPlus(rendered, span_title("Where is this object used", nameOfReferencesColumn), joinMap(takeFirst(refsToShow, refs), ref -> p(ahref(conceptLink(ref), htmlEncode_nlToBr_withIndents(str(ref))))) + (more <= 0 ? "" : "
" + ahref(addParamsToURL(crudLink(concept), "refsToShow", 10000), "+" + n2(more) + " more"))); }; return crud; } public Class isLinkableConcept(Concept c, Req req) { if (req == null || c == null) return null; Class theClass = _getClass(c); return firstThat(allLinkableClasses(req), base -> isSubclassOf(theClass, base)); } public String crudLink(Concept c) { return conceptLink(c, currentReq()); } public String conceptLink(Concept c) { return conceptLink(c, currentReq()); } public String conceptLink(Concept c, Req req) { Class theClass = c.getClass(); if (req != null) { theClass = isLinkableConcept(c, req); if (theClass == null) return null; } return c == null ? null : appendQueryToURL(crudLink(theClass), "selectObj", c.id, "showOnlySelected", showOnlySelectedObject ? "1" : null) + "#obj" + c.id; } public String conceptEditLink(Concept c, Object... __) { return c == null ? null : appendQueryToURL(crudLink(c.getClass()), paramsPlus(__, "edit", c.id)); } public String conceptDuplicateLink(Concept c) { return c == null ? null : appendQueryToURL(crudLink(c.getClass()), "duplicate", c.id); } public
String makeClassNavItem(Class c, Req req) { HCRUD_Concepts data = crudData(c, req); HCRUD crud = makeCRUD(c, req, null); Map filters = filtersForClass(c, req); int count = countConcepts(c, mapToParams(filters)); return (crud.singleton ? "" : span(n2(count), "data-isCountOf", shortClassName(c)) + " ") + ahref(crudLink(c), count == 1 ? data.itemName() : data.itemNamePlural()) + (!crud.actuallyAllowCreate() ? "" : " " + targetBlankIf(newLinkTargetBlank(c), newLinkForCRUD(crud, c), "+", "title", "Create New " + data.itemName())); } transient public IF1 newLinkTargetBlank; public boolean newLinkTargetBlank(Class c) { return newLinkTargetBlank != null ? newLinkTargetBlank.get(c) : newLinkTargetBlank_base(c); } final public boolean newLinkTargetBlank_fallback(IF1 _f, Class c) { return _f != null ? _f.get(c) : newLinkTargetBlank_base(c); } public boolean newLinkTargetBlank_base(Class c) { return false; } public String newLinkForCRUD(HCRUD crud, Class c) { return crud.newLink(); } public Collection allLinkableClasses() { Req req = newReq(); req.masterAuthed = true; return allLinkableClasses(req); } public Collection allLinkableClasses(Req req) { return joinSets(crudClasses(req), botCmdClasses()); } public List botCmdClasses() { return dynNewBot2_botCmdClasses(); } public List dynNewBot2_botCmdClasses() { List l = ll(BotMessage.class, UploadedImage.class, BotImage.class, BotOutgoingQuestion.class, BotPause.class, Sequence.class); if (enableRandomActions) l.add(BotRandomAction.class); if (settings().multiLanguageMode) l.add(BotSwitchLanguage.class); return l; } public List crudClasses(Req req) { return dynNewBot2_crudClasses(req); } public List dynNewBot2_crudClasses(Req req) { if (req == null ? null : req.masterAuthed) { List l = ll(Conversation.class, Lead.class, ConversationFeedback.class, Domain.class, UserKeyword.class, UploadedSound.class, UploadedFile.class); if (enableAvatars) l.add(Avatar.class); l.add(Settings.class); if (settings().multiLanguageMode) l.add(Language.class); if (settings().enableWorkerChat) l.add(Worker.class); if (recordExecutionsAndInputs) addAll(l, ExecutedStep.class, InputHandled.class); return l; } else return ll(Conversation.class, Lead.class, ConversationFeedback.class); } public Map filtersForClass(Class c, Req req) { if (c == Conversation.class && req.authDomainObj != null) return litmap("domainObj", req.authDomainObj); if (eqOneOf(c, Lead.class, ConversationFeedback.class) && req.authDomainObj != null) return litmap("domain", req.authDomainObj); return null; } public String crudBase() { return baseLink + "/crud"; } public String crudLink(Class c) { return crudBase() + "/" + shortName(c); } public HCRUD_Concepts crudData(Class c, Req req) { HCRUD_Concepts cc = new HCRUD_Concepts<>(c); if (useDynamicComboBoxes) cc.useDynamicComboBoxes = true; if (eq(req.get("dynamicComboBoxes"), "1")) cc.useDynamicComboBoxes = true; cc.trimAllSingleLineValues = true; cc.fieldHelp("comment", "Put any comment about this object here"); cc.itemName = () -> replaceIfEquals(dropPrefix("Bot ", cc.itemName_base()), "Jump Button", "Button"); cc.valueConverter = new DefaultValueConverterForField() { public OrError convertValue(Object object, Field field, Object value) { print("convertValue " + field + " " + className(value)); if (value instanceof String && eq(field.getGenericType(), type_LS())) { print("tlft"); return new OrError(tlft((String) value)); } return super.convertValue(object, field, value); } }; if (c == InputHandled.class) { cc.itemNamePlural = () -> "Inputs Handled"; } if (c == Domain.class) { cc.fieldHelp("domainAndPath", "without http:// or https://", "botName", "Bot name for this domain (optional)", "headerColorLeft", "Hex color for left end of header gradient (optional)", "headerColorRight", "Hex color for right end of header gradient (optional)", "autoOpenBot", "Open the bot when page is loaded", "password", "A separate password for people who can see only this domain", "pageRegexp", "A Java-style regular expression that filters which page the bot is shown on"); cc.massageItemMapForList = (item, map) -> { map.put("domainAndPath", new HTML(b(htmlEncode2(((Domain) item).domainAndPath)))); map.put("password", new SecretValue(map.get("password"))); }; } if (c == BotOutgoingQuestion.class) { cc.dropEmptyListValues = false; cc.addRenderer("displayText", new HCRUD_Data.TextArea(80, 10)); cc.addRenderer("buttons", new HCRUD_Data.TextArea(80, 10, o -> lines_rtrim((List) o))); cc.fieldHelp("displayText", displayTextHelp(), "key", "Internal key for question (any format, can be empty, put \"-\" to disable storing answer)", "defaultValue", "What the input field is prefilled with", "placeholder", "A text the empty input field shows as a hint", "buttons", "Buttons to offer as standard answers (one per line, use | to add a shortened version submitted as user input)", "allowFreeText", "Can user enter free text in addition to clicking a button?", "multipleChoice", "Can user select multiple buttons?", "optional", "Can user skip the question by entering nothing?", "multipleChoiceSeparator", "Internal field, just leave as it is", "answerCheck", "Select this to validate user's answer against a pattern", "buttonActions", "Optional actions (one for each button in the list above)", "radioButtons", "Show buttons as radio buttons"); cc.addRenderer("answerCheck", new HCRUD_Data.ComboBox("", "email address", "phone number")); cc.massageItemMapForList = (item, map) -> { map.put("buttons", new HTML(ol_htmlEncode(((BotOutgoingQuestion) item).buttons))); map.put("buttonActions", new HTML(ul(map(((BotOutgoingQuestion) item).buttonActions, action -> ahref(conceptLink(action), htmlEncode2_nlToBr(str(action))))))); }; } if (c == UserKeyword.class) { cc.fieldHelp("language", "Language that this keyword matches in (optional)", "pattern", targetBlank("http://code.botcompany.de:8081/getraw.php?id=1030319", "'PhraseCache'") + " matching pattern (most important field)", "examples", "Example inputs that should be matched (one per line, optional)", "counterexamples", "Example inputs that should be NOT matched (one per line, optional)", "action", "What bot does when input is matched", "enabled", "Uncheck to disable this keyword", "priority", "If set, this keyword overrides other input handlers (e.g. from outgoing questions)", "precedence", "Precedence over other keywords (higher value = match first)"); for (String field : ll("examples", "counterexamples")) cc.addRenderer(field, new HCRUD_Data.TextArea(80, 5, o -> lines_rtrim((List) o))); cc.massageItemMapForList = (item, map) -> { map.put("examples", lines_rtrim(((UserKeyword) item).examples)); map.put("counterexamples", lines_rtrim(((UserKeyword) item).counterexamples)); }; } if (c == Settings.class) { cc.fieldHelp("mainDomainName", "Domain where bot is hosted (to correctly send image and sound links)", "botTypingDelay", "Delay in seconds before bot sends message, base value", "botTypingDelayPerWord", "Delay in seconds before bot sends message, per word", "botTypingMaxDelay", "Delay in seconds before bot sends message, max value", "preferredCountryCodes", "Country codes to display first in list (e.g. \"+1, +91\")", "notificationSound", "Bot message notification sound (can leave empty, then we use the " + ahref(defaultNotificationSound(), "default sound"), "talkToBotOnlyWithAuth", "Show bot only to authorized persons", "mailLeadsTo", "Where to send a mail when a new lead occurs (addresses separated by comma)", "leadMailSubject", "Subject for lead notification mails"); } if (c == Conversation.class) cc.massageItemMapForList = (item, map) -> { replaceMap(map, litorderedmap("id", map.get("id"), "IP", map.get("ip"), "started", formatLocalDateWithMinutes(((Conversation) item).created), "country", map.get("country"), "msgs", lines_rtrim(((Conversation) item).msgs), "avatar", map.get("avatar"), "answers", htmlEncode2(renderColonProperties(((Conversation) item).answers)), "stack", new HTML(ol(cloneMap(((Conversation) item).stack, activeSeq -> htmlEncode2(str(activeSeq))))))); }; if (c == BotMessage.class) { cc.addRenderer("text", new HCRUD_Data.TextArea(80, 10)); cc.addRenderer("specialPurpose", new HCRUD_Data.ComboBox(itemPlus("", keys(specialPurposes)))); cc.fieldHelp("text", displayTextHelp(), "specialPurpose", "Special occasion when to display this message", "disableInput", "Check to disable user input while this message is showing"); } if (c == Form.class) cc.massageItemMapForList = (item, map) -> { map.put("steps", pnlToStringWithEmptyLines_rtrim(((Form) item).steps)); }; if (c == Sequence.class) cc.massageItemMapForList = (item, map) -> { map.put("steps", new HTML(ol(map(((Sequence) item).steps, step -> ahref(conceptLink(step), htmlEncode2_nlToBr(str(step))))))); }; if (c == BotImage.class) cc.massageItemMapForList = (item, map) -> { String url = ((BotImage) item).imageURL(); if (isURL(url)) map.put("Image Preview", new HTML(himg(url, "style", hcrud_imagePreviewStyle()))); map.put(cc.fieldNameToHTML("imageURL"), new HTML(htmlEncode2(url) + " " + himgsnippet("#1101381", "onclick", "copyToClipboard(" + jsQuote(url) + "); " + "window.createNotification({ theme: 'success', showDuration: 3000 })({ message: " + jsQuote("Image URL copied to clipboard") + "});"))); }; if (c == UploadedImage.class) { cc.massageItemMapForList = (item, map) -> { String url = ((UploadedImage) item).imageURL(); File f = ((UploadedImage) item).imageFile(); map.put("Image Size", toK_str(fileSize(f))); if (fileSize(f) > 0) map.put("Image Preview (click for full-scale)", new HTML(targetBlank(url, himg(url, "style", hcrud_imagePreviewStyle())))); }; IVF2 massageItemMapForUpdate_old = cc.massageItemMapForUpdate; cc.massageItemMapForUpdate = (item, map) -> { cc.massageItemMapForUpdate_fallback(massageItemMapForUpdate_old, item, map); String base64 = (String) map.get("img_base64"); print("Got base64 data: " + l(base64)); if (nempty(base64)) { File f = ((UploadedImage) item).imageFile(); saveFileVerbose(f, base64decode(base64)); } map.remove("img_base64"); }; } if (c == UploadedSound.class) { cc.massageItemMapForList = (item, map) -> { String url = ((UploadedSound) item).soundURL(); File f = ((UploadedSound) item).soundFile(); map.put("Sound Size", toK_str(fileSize(f))); if (fileSize(f) > 0) map.put("Test Sound", new HTML(ahref(url, "Test Sound"))); }; IVF2 massageItemMapForUpdate_old = cc.massageItemMapForUpdate; cc.massageItemMapForUpdate = (item, map) -> { cc.massageItemMapForUpdate_fallback(massageItemMapForUpdate_old, item, map); String base64 = (String) map.get("file_base64"); print("Got base64 data: " + l(base64)); if (nempty(base64)) { File f = ((UploadedSound) item).soundFile(); saveFileVerbose(f, base64decode(base64)); } map.remove("file_base64"); }; } if (c == UploadedFile.class) { cc.fieldHelp("name", "Also used as file name when downloading", "mimeType", "Content type (MIME type) for this file (optional)", "liveURI", "URI to serve file under. No leading slash."); cc.massageItemMapForList = (item, map) -> { String url = ((UploadedFile) item).downloadURL(); File f = ((UploadedFile) item).theFile(); map.put("File Size", toK_str(fileSize(f))); if (fileSize(f) > 0) map.put("Download", new HTML(ahref(url, "Download"))); }; IVF2 massageItemMapForUpdate_old = cc.massageItemMapForUpdate; cc.massageItemMapForUpdate = (item, map) -> { cc.massageItemMapForUpdate_fallback(massageItemMapForUpdate_old, item, map); String base64 = (String) map.get("file_base64"); print("Got base64 data: " + l(base64)); if (nempty(base64)) { File f = ((UploadedFile) item).theFile(); saveFileVerbose(f, base64decode(base64)); } map.remove("file_base64"); }; } if (c == Worker.class) { cc.massageItemMapForList = (item, map) -> { AbstractBotImage image = ((Worker) item).image.get(); if (image != null) map.put("Image Preview", new HTML(himg(image.imageURL(), "style", hcrud_imagePreviewStyle()))); }; } if (c == Avatar.class) { cc.fieldHelp("shift", "hours when avatar is active, e.g. 8-18 (leave empty if always on shift, put 0-0 if never on shift)"); cc.massageItemMapForList = (item, map) -> { map.put("On Shift Now", ((Avatar) item).onShift()); }; } return cc; } public Map crudHelp() { return litmap(DeliveredDomain.class, "This list is filled by the bot with the domains it was delivered on. " + "Some may be bogus, we write down whatever the browser sends."); } public void saveDeliveredDomain(String domain) { if (empty(domain)) return; uniqCI(DeliveredDomain.class, "domain", beforeColonOrAll(domain)); } public void cleanConversations() { withDBLock(new Runnable() { public void run() { try { cdelete(filter(list(Conversation.class), c -> l(c.msgs) <= 1 && elapsedSeconds_timestamp(c.created) >= 60 && c.lastPing == 0)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cdelete(filter(list(Conversation), c -> l(c.msgs) <= 1\r\n && elapsedSec..."; } }); } public void deleteDeliveredDomains() { cdelete(DeliveredDomain.class); } public Object serveThoughts(Req req) { HTMLFramer1 framer = new HTMLFramer1(); framer.addInHead(hsansserif() + hmobilefix()); framer.add(div_floatRight(hbutton("Reload", "onclick", "location.reload()"))); framer.add(h2("Bot Thoughts")); if (req.conv == null) framer.add("No conversation"); else { framer.add(p("Conversation cookie: " + req.conv.cookie)); Conversation conv = req.conv; framer.add(h3("Stack")); framer.add(empty(conv.stack) ? p("empty") : ol(lmap(__137 -> htmlEncode2_gen(__137), reversed(conv.stack)))); } return framer.render(); } public Object serveSearch(Req req) { makeFramer(req); HTMLFramer1 framer = req.framer; framer.add("Search here"); return framer.render(); } transient public boolean debug = false; public Domain findDomainObj(String domain) { Domain domainObj = conceptWhereCI(Domain.class, "domainAndPath", domain); if (domainObj == null) domainObj = defaultDomain(); return domainObj; } public Domain defaultDomain() { return uniqCI(Domain.class, "domainAndPath", ""); } transient public int longPollTick = 200; transient public int longPollMaxWait = 1000 * 30; transient public int activeConversationSafetyMargin = 30000; transient public Set specialButtons = litciset("Cancel", "Back", "Abbrechen", "Zurück"); public String dbStats() { Collection all = list(Conversation.class); int nRealConvos = countPred(all, c -> l(c.msgs) > 1); return nConversations(nRealConvos); } public String realPW() { return loadTextFileOrCreateWithRandomID(realPWFile()); } public File realPWFile() { return secretProgramFile("password.txt"); } public String defaultRedirectAfterLogin() { return baseLink + "/"; } public String serveAuthForm() { return serveAuthForm(null); } public String serveAuthForm(String redirect) { redirect = dropParamFromURL(redirect, "logout"); if (empty(redirect)) redirect = defaultRedirectAfterLogin(); return hhtml(hhead(htitle(botName + ": Log-In") + hsansserif() + hmobilefix() + (useWebSockets ? webSocketHeadStuff() : "")) + hbody(hfullcenter(authFormHeading() + hpostform(hhidden("redirect", redirect) + tag("table", (enableUsers ? tr(td("User:") + td(hinputfield("user")) + td()) : "") + tr(td("Password:") + td(hpassword("pw")) + td(hsubmit("Log in")))), "action", baseLink + "/login") + (!showTalkToBotLink ? "" : p(ahref(baseLink + "/demo", "Talk to bot"))) + pUnlessEmpty(joinNemptiesWithSpace(!showRegisterLink ? "" : hbuttonLink(baseLink + "/register", "Register as new user"), !requestAuthed() ? "" : hbuttonLink(baseLink + "?logout=1", "Log out"))) + authFormMoreContent()))); } public String authFormHeading() { return h3_htmlEncode(adminName); } public String authFormMoreContent() { return ""; } public String leadsToCSV(Collection leads) { List fields = ciContentsIndexedList(); List rows = new ArrayList(); for (Lead lead : unnullForIteration(leads)) { List row = new ArrayList(); for (Map.Entry __22 : _entrySet(unnullForIteration(mapPlus_inFront((Map) (Map) lead.answers, "Date", formatLocalDateWithMinutes(lead.date.date), "Domain", lead.domain.get(), "Conversation ID", conceptID(lead.conversation.get()))))) { String key = __22.getKey(); Object val = __22.getValue(); int idx = fields.indexOf(key); if (idx < 0) idx = addAndReturnIndex(fields, key); listSet(row, idx, val, ""); } rows.add(row); } return formatCSVFileForExcel2(itemPlusList(fields, rows)); } public String countryCodeOptions(Conversation conv) { Collection countryCodes = putSetElementsFirst(keys(countryDialCodesMultiMap()), splitAtComma_trim(settings().preferredCountryCodes)); String selected = dialCodeStringForCountryCode(conv.country); return mapToLines(c -> { List cdc = countryDialCodesMultiMap().get(c); String text = nempty(cdc) ? c + " [" + joinWithComma(collectSorted("countryCode", cdc)) + "]" : c; return tag("option", text, "value", c, "selected", eq(c, selected) ? html_valueLessParam() : null); }, itemPlus("", countryCodes)); } public List addTypingDelays(List steps) { return concatMap(steps, step -> { double delay = step.preTypingDelay(); if (delay <= 0) return ll(step); return ll(new BotSendTyping(), new BotPause(delay), step); }); } public BotMessage messageForPurpose(String specialPurpose) { return conceptWhere(BotMessage.class, "specialPurpose", specialPurpose); } public Object serveLeadsAPI(Object req) { Map headers = (Map) (rcall("headers", req)); Map params = (Map) (get("params", req)); String tenantID = params.get("tenantID"); if (empty(tenantID)) return serveJSONError("Empty tenantID"); String pw = params.get("pw"); if (empty(pw)) pw = dropPrefix_trim("Bearer ", headers.get("Authorization")); if (empty(pw)) return serveJSONError("Empty password"); Domain domain = conceptWhere(Domain.class, "tenantID", tenantID); if (domain == null) return serveJSONError("Tenant ID not found"); if (neq(domain.password, pw)) return serveJSONError("Bad passsword"); Collection leads = conceptsWhere(Lead.class, "domain", domain); return serveJSON(map(leads, lead -> { Map map = litorderedmap("tenantID", tenantID, "leadID", lead.id, "domain", str(lead.domain), "date", formatLocalDateWithSeconds(lead.created), "data", lead.answers); return map; })); } public Object serveJSONError(String error) { return serveJSON(litorderedmap("error", error)); } public String botImageForDomain(Domain domainObj) { String botImg = imageSnippetURLOrEmptyGIF(chatHeaderImageID); if (domainObj != null && domainObj.botImage.has()) botImg = domainObj.botImage.get().imageURL(); else if (defaultDomain().botImage.has()) botImg = defaultDomain().botImage.get().imageURL(); return botImg; } public String simulateDomainLink(String domain) { return appendQueryToURL(baseLink + "/demo", "_botConfig", makePostData("domain", domain), "_newConvCookie", 1, "_autoOpenBot", 1); } public String simulateScriptLink(BotStep script) { return appendQueryToURL(baseLink + "/demo", "_botConfig", makePostData("mainScript", script.id), "_newConvCookie", 1, "_autoOpenBot", 1); } public Scorer consistencyCheckResults() { if (consistencyCheckResults == null) consistencyCheckResults = doConsistencyChecks(); return consistencyCheckResults; } public Scorer doConsistencyChecks() { Scorer scorer = scorerWithSuccessesAndErrors(); for (UserKeyword uk : list(UserKeyword.class)) try { localConsistencyCheck(uk, scorer); } catch (Throwable e) { scorer.addError(htmlEncode2(str(e))); } try { globalConsistencyCheck(scorer); } catch (Throwable e) { scorer.addError(htmlEncode2(str(e))); } return scorer; } public void localConsistencyCheck(UserKeyword uk, Scorer scorer) { String patHTML = span_title(str(uk.parsedPattern()), htmlEncode2(uk.pattern)); String item = "[Entry " + ahref(conceptLink(uk), uk.id) + "] "; for (String input : unnullForIteration(uk.examples)) { boolean ok = uk.matchWithTypos(input); scorer.add(ok, ok ? item + "Example OK: " + patHTML + " => " + htmlEncode2(quote(input)) : item + "Example doesn't match pattern: " + patHTML + " => " + htmlEncode2(quote(input))); } for (String input : unnullForIteration(uk.counterexamples)) { boolean ok = !uk.matchWithTypos(input); scorer.add(ok, ok ? item + "Counterexample OK: " + patHTML + " => " + htmlEncode2(quote(input)) : item + "Counterexample matches pattern: " + patHTML + " => " + htmlEncode2(quote(input))); } } public void globalConsistencyCheck(Scorer scorer) { List list = concatLists(enabledUserKeywordsForPriority(true), enabledUserKeywordsForPriority(false)); for (UserKeyword uk : list) for (String example : unnullForIteration(uk.examples)) { String item1 = ahref(conceptLink(uk), uk.id); UserKeyword found = firstThat(list, uk2 -> uk2.matchWithTypos(example)); if (found == null) continue; if (found == uk) scorer.addOK("[Entry " + item1 + "] Global check OK for input " + htmlEncode2(quote(example))); else { String item2 = ahref(conceptLink(found), found.id); String items = "[Entries " + item1 + " and " + item2 + "] "; scorer.addError(items + "Input " + htmlEncode2(quote(example)) + " shadowed by pattern: " + htmlEncode2(quote(found.pattern)) + ". Try reducing precedence value of entry " + item2 + " or increasing precedence value of entry " + item1); } } } static public Collection enabledUserKeywordsForPriority(boolean priority) { return sortByFieldDesc("precedence", conceptsWhere(UserKeyword.class, onlyNonNullParams("priority", priority))); } public boolean handleGeneralUserInput(Conversation conv, Msg msg, Boolean priority) { for (UserKeyword qa : enabledUserKeywordsForPriority(priority)) { if (qa.enabled && qa.matchWithTypos(msg.text)) { print("Matched pattern: " + qa.pattern + " / " + msg.text); conv.noteEvent(new EvtMatchedUserKeyword(qa, msg)); conv.callSubroutine(qa.action.get()); conv.scheduleNextStep(); return true; } } return false; } public void didntUnderstandUserInput(Conversation conv, Msg msg) { } transient public Settings settings_cache; public Settings settings() { if (settings_cache == null) settings_cache = settings_load(); return settings_cache; } public Settings settings_load() { Settings settings = conceptWhere(Settings.class); print("Got settings: " + settings); return settings; } public String displayTextHelp() { return "Text to show to user (can include HTML and " + targetBlank(baseLink + "/emojis", "emojis") + ")"; } public void botActions() { Lock __7 = lockWhileDoingBotActions ? dbLock() : null; lock(__7); try { while (licensed()) { ScheduledAction action = lowestConceptByField(ScheduledAction.class, "time"); if (action == null) break; if (action.time > now()) { doAfter(100, rstBotActions); break; } cdelete(action); print("Executing action " + action); try { action.run(); } catch (Throwable __e) { pcallFail(__e); } } } finally { unlock(__7); } } public void addScheduledAction(ScheduledAction action) { addScheduledAction(action, 0); } public void addScheduledAction(ScheduledAction action, long delay) { action.time = now() + delay; registerConcept(action); rstBotActions.trigger(); } transient public ThreadLocal out = new ThreadLocal(); transient public ThreadLocal conv = new ThreadLocal(); transient public long lastConversationChange = now(); public void makeIndices() { indexConceptFieldDesc(ScheduledAction.class, "time"); indexConceptFieldCI(Domain.class, "domainAndPath"); indexConceptFieldCI(DeliveredDomain.class, "domain"); indexConceptFieldCI(CannedAnswer.class, "hashTag"); indexConceptFieldCI(Language.class, "languageName"); indexConceptField(Lead.class, "domain"); indexConceptField(ConversationFeedback.class, "domain"); indexConceptField(UploadedFile.class, "liveURI"); } public void startDB() { db(); } public void pWebChatBot() { db_mainConcepts().storeBaseClassesInStructure = storeBaseClassesInStructure || storeBaseClassesInStructure; startDB(); indexConceptFields(Conversation.class, "cookie", Conversation.class, "worker", Conversation.class, "lastPing", Worker.class, "loginName", AuthedDialogID.class, "cookie"); db_mainConcepts().miscMapPut(DynNewBot2.class, this); assertNotNull("settings 1", uniq(Settings.class)); indexSingletonConcept(Settings.class); assertNotNull("settings 2", uniq(Settings.class)); makeIndices(); indexAllLinkableClasses(); assertNotNull("settings 3", uniq(Settings.class)); uniq(BotSaveLead.class); uniq(BotSaveFeedback.class); uniq(BotClearStack.class); uniq(BotEndConversation.class); uniq(BotDoNothing.class); uniq(BotIdleMode.class); uniq(BotNewDialog.class); if (enableUndoStates) uniq(BotGoBack.class); if (enableAvatars) uniq(RandomAvatar.class); } public void addReplyToConvo(Conversation conv, IF0 think) { out.set(new Out()); String reply = ""; try { reply = think.get(); } catch (Throwable __e) { pcallFail(__e); } Msg msg = new Msg(false, reply); msg.out = out.get(); conv.add(msg); } public Msg msgFromThinkFunction(IF0 think) { out.set(new Out()); String reply = ""; try { reply = think.get(); } catch (Throwable __e) { pcallFail(__e); } Msg msg = new Msg(false, reply); msg.out = out.get(); return msg; } public Object withHeader(String html) { return withHeader(subBot_noCacheHeaders(subBot_serveHTML(html))); } public Object withHeader(Object response) { call(response, "addHeader", "Access-Control-Allow-Origin", "*"); return response; } public String renderMessageText(String text, boolean htmlEncode) { text = trim(text); if (eqic(text, "!rate conversation")) text = "Rate this conversation"; if (htmlEncode) text = htmlEncode2(text); text = nlToBr(text); return html_emojisToUnicode(text); } public void renderMessages(Conversation conv, StringBuilder buf, List msgs) { renderMessages(conv, buf, msgs, msg -> msg == last(msgs)); } public void renderMessages(Conversation conv, StringBuilder buf, List msgs, IF1 showButtons) { if (empty(msgs)) return; ChatRenderer renderer = makeChatRenderer(currentReq()); for (Msg m : msgs) { boolean showTheButtons = showButtons.get(m); if (m.fromUser || neqOneOf(m.text, "-", "") || showTheButtons && m.out != null && nempty(m.out.buttons)) renderer.appendMsg(conv, buf, m, showTheButtons); if (showTheButtons) { buf.append(hscript(botMod().phoneNumberSpecialInputField ? "$(\"#chat_telephone, .iti\").hide(); $(\"#chat_message\").show().prop('disabled', false).focus();" : "$(\"#chat_message\").prop('disabled', false).focus();")); if (m.out != null && nempty(m.out.javaScript)) buf.append(hscript(m.out.javaScript)); } } } abstract public class ChatRenderer { abstract public void appendMsg(Conversation conv, StringBuilder buf, Msg m, boolean showButtons); public Conversation conv; public String id; public Msg m; public String html; public String name; public String time; public String text; public boolean bot = false; public Worker fromWorker; public Out out; public List labels; public boolean useTrick = false; public String author; public String imgURL; public void prepare(Conversation conv, Msg m) { this.conv = conv; this.m = m; html = renderMessageText(m.text, shouldHtmlEncodeMsg(m)); name = m.fromUser ? defaultUserName() : botName; time = formatTime(m.time); text = html; modifyTextForRendering(); bot = !m.fromUser; fromWorker = m.fromWorker; out = m.out; labels = m.labels; useTrick = ariaLiveTrick; id = randomID(); author = fromWorker != null ? htmlEncode2(fromWorker.displayName) : botName; if (bot) { if (fromWorker != null && fileExists(workerImageFile(fromWorker.id))) imgURL = fullRawLink("worker-image/" + fromWorker.id); else imgURL = conv.botImg(); } } public void modifyTextForRendering() { if (eqic(text, "!back")) text = unicode_undoArrow(); } abstract public String renderMultipleChoice(List buttons, Collection selections, String multipleChoiceSeparator); public String renderSingleChoice(List buttons) { List out = new ArrayList(); for (int i = 0; i < l(buttons); i++) { String code = buttons.get(i); String text = replaceButtonText(code); String userInput = htmldecode_dropAllTags(text); List split = splitAtVerticalBar(text); if (l(split) == 2) { userInput = second(split); text = code = first(split); } out.add(hbuttonOnClick_returnFalse(text, "submitAMsg(" + jsQuote(userInput) + ")", "class", "chatbot-choice-button automated-message", "title", eq(code, text) ? null : code)); if (!specialButtons.contains(code) && i + 1 < l(buttons) && specialButtons.contains(buttons.get(i + 1))) out.add("  "); } return lines(out); } } public class ChatRendererSahilStyle extends ChatRenderer { public void appendMsg(Conversation conv, StringBuilder buf, Msg m, boolean showButtons) { prepare(conv, m); List div = new ArrayList(); List inMessage = new ArrayList(); List afterMessage = new ArrayList(); if (!bot) imgURL = "/pays5/imgs/icons/avatar.svg"; if (nempty(imgURL)) { div.add(div("", "class", "bg-img", "role", "img", "aria-labelledby", m.fromUser ? "Avatar" : "Bot", "style", "background-image: url('" + imgURL + "')")); } if (showButtons) appendButtons(inMessage, afterMessage, m.out); div.add(span(text + lines(inMessage), "class", "message")); div.add(span(time, "class", "message-timestamp")); buf.append(div(lines(div) + lines(afterMessage), "class", "message-wrapper" + stringUnless(bot, " user"))).append("\n"); } public void appendButtons(List inMessage, List afterMessage, Out out) { String placeholder = out == null ? "" : unnull(out.placeholder); String defaultInput = out == null ? "" : unnull(out.defaultInput); inMessage.add(hscript("chatBot_setInput(" + jsQuote(defaultInput) + ", " + jsQuote(placeholder) + ");")); if (out == null) return; List buttons = out.buttons; if (empty(buttons)) return; String buttonsHtml; if (out.multipleChoice) inMessage.add(span(renderMultipleChoice(buttons, text_multipleChoiceSplit(out.defaultInput, out.multipleChoiceSeparator), out.multipleChoiceSeparator), "class", "select-options")); else if (out.radioButtons) inMessage.add(span(renderRadioButtons(buttons, out.defaultInput), "class", "select-options")); else afterMessage.add(div(renderSingleChoice(buttons), "class", "automated-messages")); } public String renderMultipleChoice(List buttons, Collection selections, String multipleChoiceSeparator) { Set selectionSet = asCISet(selections); String rand = randomID(); String className = "chat_multiplechoice_" + rand; String allCheckboxes = "$(\"." + className + "\")"; if (eq(multipleChoiceSeparator, ",")) multipleChoiceSeparator += " "; return joinWithBR(map(buttons, name -> span(span("", "class", "square-box") + " " + name, "class", className + " option" + stringIf(contains(selectionSet, name), " selected"), "data-value", name))) + "
" + hbuttonOnClick_returnFalse("OK", "submitMsg()", "class", "btn btn-ok") + hscript(replaceDollarVars("\r\n $(\".$className *, .$className\").click(function(e) {\r\n e.stopImmediatePropagation(); // prevent double firing\r\n\r\n // toggle check box\r\n console.log(\"Target: \" + e.target);\r\n $(e.target).closest(\".option\").toggleClass(\"selected\");\r\n\r\n // update message\r\n var theList = $('.$className.selected').map(function() { return this.dataset.value; }).get();\r\n console.log('theList: ' + theList);\r\n $('#chat_message').val(theList.join($sep));\r\n });\r\n //$(\".$className *\").click(function(e) { e.stopPropagation(); });\r\n ", "className", className, "sep", jsQuote(multipleChoiceSeparator))); } public String renderRadioButtons(List buttons, String selection) { String rand = randomID(); String className = "chat_radio_" + rand; String allRadioButtons = "$(\"." + className + "\")"; return joinWithBR(map(buttons, name -> span(span("", "class", "square-box round") + " " + name, "class", className + " option" + stringIf(eqic(selection, name), " selected"), "data-value", name))) + (quickRadioButtons ? "" : "
" + hbuttonOnClick_returnFalse("OK", "submitMsg()", "class", "btn btn-ok")) + hscript(replaceDollarVars("\r\n $(\".$className *, .$className\").click(function(e) {\r\n e.stopImmediatePropagation(); // prevent double firing\r\n var option = $(e.target).closest(\".option\");\r\n \r\n // clear other radio buttons\r\n $(\".$className\").removeClass(\"selected\");\r\n\r\n // activate radio button\r\n option.addClass(\"selected\");\r\n\r\n // update message\r\n $('#chat_message').val(option[0].dataset.value);\r\n\r\n if ($quickRadioButtons)\r\n submitMsg();\r\n });\r\n //$(\".$className *\").click(function(e) { e.stopPropagation(); });\r\n ", "className", className, "quickRadioButtons", quickRadioButtons)); } } public class ChatRendererHusainStyle extends ChatRenderer { public void appendMsg(Conversation conv, StringBuilder buf, Msg m, boolean showButtons) { prepare(conv, m); String tag = useTrick ? "div" : "span"; if (bot) { if (nempty(m.text)) { if (fromWorker != null) buf.append("

" + author + "

"); buf.append("<" + tag + " class=\"chat_msg_item chat_msg_item_admin\"" + (useTrick ? " id=\"" + id + "\" aria-live=\"polite\" tabindex=\"-1\"" : "") + ">"); if (nempty(imgURL)) buf.append("\r\n
\r\n \r\n
".replace("$IMG", imgURL)); buf.append("" + (fromWorker != null ? "" : botName + " ") + "says"); buf.append(text); buf.append(""); if (fromWorker != null) buf.append("
"); if (useTrick) buf.append(hscript("$('#" + id + "').focus();")); } } else buf.append(("\r\n You say\r\n <" + tag + " class=\"chat_msg_item chat_msg_item_user\"" + (useTrick ? " aria-live=\"polite\"" : "") + ">$TEXT\r\n ").replace("$TEXT", text)); if (nempty(labels)) buf.append(span(join("   ", map(labels, lbl -> span("  " + lbl + "  "))), "class", "labels chat_msg_item chat_msg_item_user")).append("\n"); if (showButtons) appendButtons(buf, out, null); } public void appendButtons(StringBuilder buf, Out out, Set buttonsToSkip) { String placeholder = out == null ? "" : unnull(out.placeholder); String defaultInput = out == null ? "" : unnull(out.defaultInput); if (out != null && out.disableInput) buf.append(hscript(jsDisableInputField())); else buf.append(hscript("chatBot_setInput(" + jsQuote(defaultInput) + ", " + jsQuote(placeholder) + ");")); if (out == null) return; List buttons = listMinusSet(out.buttons, buttonsToSkip); if (empty(buttons)) return; String buttonsHtml; if (out.multipleChoice) buttonsHtml = renderMultipleChoice(buttons, text_multipleChoiceSplit(out.defaultInput, out.multipleChoiceSeparator), out.multipleChoiceSeparator); else buttonsHtml = renderSingleChoice(buttons); buf.append(span(buttonsHtml, "class", "chat_msg_item chat_msg_item_admin chat_buttons" + stringIf(!out.multipleChoice, " single-choice"))); } public String renderMultipleChoice(List buttons, Collection selections, String multipleChoiceSeparator) { Set selectionSet = asCISet(selections); String rand = randomID(); String className = "chat_multiplechoice_" + rand; String allCheckboxes = "$(\"." + className + "\")"; return joinWithBR(map(buttons, name -> hcheckbox("", contains(selectionSet, name), "value", name, "class", className) + " " + name)) + "
" + hbuttonOnClick_returnFalse("OK", "submitMsg()", "class", "btn btn-ok") + hscript(allCheckboxes + ".change(function() {" + " var theList = $('." + className + ":checkbox:checked').map(function() { return this.value; }).get();" + " console.log('theList: ' + theList);" + " $('#chat_message').val(theList.join(" + jsQuote(multipleChoiceSeparator) + "));" + "});"); } } public String replaceButtonText(String s) { if (standardButtonsAsSymbols) { if (eqicOneOf(s, "back", "zurück")) return unicode_undoArrow(); if (eqicOneOf(s, "cancel", "Abbrechen")) return unicode_crossProduct(); } return s; } public void appendDate(StringBuilder buf, String date) { buf.append("\r\n
\r\n DATE\r\n
".replace("DATE", date)); } public boolean lastUserMessageWas(Conversation conv, String message) { Msg m = last(conv.msgs); return m != null && m.fromUser && eq(m.text, message); } public String formatTime(long time) { return timeInTimeZoneWithOptionalDate_24(timeZone, time); } public String formatDialog(String id, List msgs) { List lc = new ArrayList(); for (Msg m : msgs) lc.add(htmlencode((m.fromUser ? "> " : "< ") + m.text)); return id + ul(lc); } public Conversation getConv(final String cookie) { return uniq(Conversation.class, "cookie", cookie); } public String errorMsg(String msg) { return hhtml(hhead_title("Error") + hbody(hfullcenter(span(msg, "class", "error_msg") + "

" + ahref(jsBackLink(), "Back")))); } public String defaultUserName() { return "You"; } public boolean botOn() { return true; } public boolean botAutoOpen(Domain domain) { return getDomainValue(domain, d -> d.autoOpenBot, false); } public File workerImageFile(long id) { return id == 0 ? null : javaxDataDir("adaptive-bot/images/" + id + ".jpg"); } public long activeConversationTimeout() { return longPollMaxWait + activeConversationSafetyMargin; } public AuthedDialogID authObject(String cookie) { AuthedDialogID auth = null; if (nempty(cookie)) auth = authedDialogIDForEveryCookie ? uniq(AuthedDialogID.class, "cookie", cookie) : conceptWhere(AuthedDialogID.class, "cookie", cookie); return auth; } public boolean anyInterestingMessages(List msgs, boolean workerMode) { return any(msgs, m -> m.fromUser == workerMode); } public boolean shouldHtmlEncodeMsg(Msg msg) { return msg.fromUser; } public void calcCountry(Conversation c) { cset(c, "country", ""); getCountry(c); } public String getCountry(Conversation c) { if (empty(c.country) && nempty(c.ip)) cset(c, "country", ipToCountry2020_safe(c.ip)); return or2(c.country, "?"); } public void initAvatar(Conversation c) { if (enableAvatars && !c.avatar.has() && c.domainObj.has()) { AbstractAvatar a = c.domainObj.get().avatar.get(); Avatar avatar = a == null ? null : a.getActualAvatar(); cset(c, "avatar", avatar); } } public void noteConversationChange() { lastConversationChange = now(); } public String template(String hashtag, Object... params) { return replaceSquareBracketVars(getCannedAnswer(hashtag), params); } public String getCannedAnswer(String hashTag) { return getCannedAnswer(hashTag, null); } public String getCannedAnswer(String hashTag, Conversation conv) { return hashTag; } public List text_multipleChoiceSplit(String input, String multipleChoiceSeparator) { return trimAll(splitAt(input, dropSpaces(multipleChoiceSeparator))); } public Msg lastBotMsg(List l) { return lastThat(l, msg -> !msg.fromUser); } public File uploadedImagesDir() { return programDir("uploadedImages"); } public File uploadsBaseDir() { return programDir(); } public File uploadedSoundsDir() { return newFile(uploadsBaseDir(), "uploadedSounds"); } public File uploadedFilesDir() { return programDir("uploadedFiles"); } public String defaultNotificationSound() { return "https://botcompany.de/files/1400403/notification.mp3"; } public String convertToAbsoluteURL(String url) { if (isURL(url)) return url; String domain = settings().mainDomainName; return empty(domain) ? url : "https://" + domain + addSlashPrefix(url); } public String absoluteAdminURL() { return convertToAbsoluteURL(baseLink); } public void editMasterPassword() { if (!confirmOKCancel("Are you sure? This will reveal the password.")) return; JTextField tf = jtextfield(realPW()); showFormTitled2(botName + " master password", "Password", tf, new Runnable() { public void run() { try { String pw = gtt(tf); if (empty(pw)) infoBox("Empty password, won't save"); else { saveTextFile(realPWFile(), pw); infoBox("Saved new password for " + adminName); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String pw = gtt(tf);\r\n if (empty(pw)) infoBox(\"Empty password, won't s..."; } }); } public void editMailSenderInfo() { JTextField tf = jtextfield(realPW()); inputText("Mail sender info", mailSenderInfo, new VF1() { public void get(String mailSenderInfo) { try { setField("mailSenderInfo", mailSenderInfo); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setField(+mailSenderInfo);"; } }); } public Object handleAuth(Req req, String cookie) { String pw = trim(req.params.get("pw")); if (nempty(pw) && nempty(cookie)) { Domain authDomain; if (eq(pw, realPW())) cset(uniq(AuthedDialogID.class, "cookie", cookie), "restrictedToDomain", null, "master", true); else if ((authDomain = conceptWhere(Domain.class, "password", pw)) != null) cset(uniq(AuthedDialogID.class, "cookie", cookie), "restrictedToDomain", authDomain, "master", false); else return errorMsg("Bad password, please try again"); String redirect = req.params.get("redirect"); if (nempty(redirect)) return hrefresh(redirect); } return null; } public String loggedInUserDesc_html(Req req) { return htmlEncode2(loggedInUserDesc(req)); } public String loggedInUserDesc(Req req) { return req.masterAuthed ? "super user" : req.authDomain; } public Object redirectToHttps(Req req) { if (!req.webRequest.isHttps()) return subBot_serveRedirect("https://" + req.webRequest.domain() + req.uri + htmlQuery(req.params)); return null; } public void startMainScript(Conversation conv) { initAvatar(conv); Domain domain = conv.domainObj.get(); if (domain == null) { botMod().addReplyToConvo(conv, () -> "Error: No domain set"); return; } BotStep seq = getConcept(BotStep.class, parseLong(mapGet(conv.botConfig, "mainScript"))); if (seq == null) seq = domain.mainScript.get(); if (seq == null) { botMod().addReplyToConvo(conv, () -> "Error: No main script set for " + htmlEncode2(str(domain))); return; } conv.callSubroutine(seq); if (enableUndoStates) conv.addUndoState(); conv.scheduleNextStep(); } public boolean isRequestFromBot(Req req) { return false; } public String modifyTemplateBeforeDelivery(String html, Req req) { return html; } public String headingForReq(Req req) { return null; } public Object serveHomePage() { return null; } public void possiblyTriggerNewDialog(Conversation conv) { if (empty(conv.msgs) && conv.newDialogTriggered < conv.archiveSize()) { cset(conv, "newDialogTriggered", conv.archiveSize()); addScheduledAction(new OnNewDialog(conv)); } } public String rewriteBotMessage(Conversation conv, String text) { if (!enableVars || conv == null) return text; text = html_evaluateIfTags(text, var -> eqic("true", print("if " + var + ": ", calcVar(conv, dropDollarPrefix(var))))); print("text", text); text = replaceDollarVars_dyn(text, var -> print("calcVar " + var, calcVar(conv, var))); return text; } public String calcVar(Conversation conv, String var) { if (conv == null) return null; { String val = syncGet(conv.answers, var); if (val != null) return val; } if (eqic(var, "botName") && conv.avatar.has()) return conv.avatar.get().name; return null; } public String cssURL() { return serveSnippetURL(cssID); } public class RenderDialogTree { public Set seen = new HashSet(); public String render(BotStep step) { if (!seen.add(step)) return "[see above] " + htmlEncode2(str(step)); List children = new ArrayList(); if (step instanceof Sequence) for (Pair __0 : iterateWithIndex1(((Sequence) step).steps)) { int i = pairA(__0); BotStep step2 = pairB(__0); children.add("Step " + i + ": " + renderDialogTree(step2)); } if (step instanceof BotOutgoingQuestion) for (Pair __1 : ((BotOutgoingQuestion) step).buttonsWithActions()) { String input = pairA(__1); BotStep step2 = pairB(__1); children.add("If user says " + b(htmlEncode2(quote(last(splitAtVerticalBar(input))))) + "

=> " + (step2 == null ? "no action defined" : renderDialogTree(step2))); } return stepToHTMLFull(step) + ulIfNempty(children, "class", "dialogTree"); } } public String stepToHTMLFull(BotStep step) { if (step == null) return "-"; String link = conceptLink(step, currentReq()); return ahref_unstyled(link, prependSquareBracketed(step.id)) + ahref(link, htmlEncode2_nlToBr(step.fullToString())); } public String renderDialogTree(BotStep step) { return new RenderDialogTree().render(step); } public ChatRenderer makeChatRenderer(Req req) { String botLayout = req.params.get("botLayout"); String layout = or2(botLayout, defaultBotLayout()); return eqic(layout, "sahil") ? new ChatRendererSahilStyle() : new ChatRendererHusainStyle(); } public String defaultBotLayout() { return "husain"; } public boolean allowedTemplateID(String id) { return false; } public double typingDelayForText(String text) { double perWord = settings().botTypingDelayPerWord; double x = settings().botTypingDelay; if (perWord != 0) x += countWords(dropHTMLTags(text)) * settings().botTypingDelayPerWord; double max = settings().botTypingMaxDelay; if (max != 0) x = min(x, max); return x; } public String nameOfBotSide(Conversation conv) { String __9 = calcVar(conv, "botName"); if (!empty(__9)) return __9; return "Representative"; } public void addThingsAboveCRUDTable(Req req, Class c, List aboveTable) { } public boolean checkPhoneNumber(String s) { return isValidInternationalPhoneNumber(s); } public void onNewLead(Lead lead) { for (String address : splitAtComma_trim(settings().mailLeadsTo)) try { String text = formatColonProperties(lead.answers); sendMailThroughScript(mailSenderInfo, "auto@botcompany.de", address, settings().leadMailSubject, text); } catch (Throwable e) { printStackTrace(e); appendToFile(programFile("mail-errors"), getStackTrace(e)); } } public void doUndo(Conversation conv) { UndoState undoState = syncNextToLast(conv.undoStates); print("Undo state: " + undoState); if (undoState != null) { syncRemoveLast(2, conv.undoStates); conv.dropScheduledActions(); syncReplaceCollection(conv.stack, undoState.stack); print("Stack after undo: " + conv.stack); conv.scheduleNextStep(); } } public Collection cruddableClasses(Req req) { List classes = crudClasses(req); List cmdClasses = botCmdClasses(req); return flattenList2(classes, DeliveredDomain.class, cmdClasses); } public List botCmdClasses(Req req) { return req.masterAuthed ? botCmdClasses() : null; } public Object serveCRUD(Req req) { String uri = req.uri(); if (!uri.startsWith(crudBase())) return null; for (Class c : (Set) asSet(cruddableClasses(req))) if (eq(uri, dropUriPrefix(baseLink, crudLink(c)))) { HCRUD crud = makeCRUD(c, req); return serveCRUD(req, c, crud); } return null; } public Object serveCRUD(Req req, Class c, HCRUD crud) { HTMLFramer1 framer = req.framer; Map params = req.params(); String help = mapGet(crudHelp(), c); if (nempty(help)) framer.add(p(help)); String json = crud.handleComboSearch(params); if (nempty(json)) return serveText(json); List aboveTable = new ArrayList(); if (c == UserKeyword.class) { Scorer scorer = consistencyCheckResults(); framer.add(p("Consistency check results: " + nTests(scorer.successes) + " OK, " + nErrors(scorer.errors))); if (nempty(scorer.errors)) framer.add(ul(map(scorer.errors, e -> "Error: " + e))); } addThingsAboveCRUDTable(req, c, aboveTable); String baseTitle = framer.title; crud.makeFrame = (title, contents) -> { framer.title = joinNemptiesWithVBar(title, baseTitle); return h2(title) + lines(aboveTable) + contents; }; crud.processSortParameter(params); String crudHTML = crud.renderPage(params); if (containsHTMLRedirect(crudHTML)) return crudHTML; framer.add(crudHTML); framer.add(hjs_markRowMagic()); return completeFrame(req); } public IF1, Collection> crudSearchFilter(Req req, HCRUD_Concepts data, String searchQuery) { if (empty(searchQuery)) return null; boolean debug = eq(req.get("searchDebug"), "1"); HTMLFramer1 framer = req.framer; return objects -> { ScoredSearcher searcher = new ScoredSearcher<>(searchQuery); if (debug) { if (framer != null) framer.add(hcomment(renderVars_struct("searcher", searcher))); } for (A a : unnullForIteration(objects)) { Map map = allConceptFieldsAsMap(a); List fields = allToString(values(map)); fields.add(str(a.id)); if (debug) { if (framer != null) framer.add(hcomment(renderVars_str("a", a, "fields", fields))); } double score = searcher.scoreFields(fields) + searcher.scoreFields(keys(map)) * 0.2; searcher.put(a, score); } return searcher.get(); }; } public boolean requestAuthed() { return currentReq() != null && currentReq().requestAuthed(); } public String webSocketHeadStuff() { return webSocketHeadStuff(currentReq()); } transient public IF1 webSocketHeadStuff; public String webSocketHeadStuff(Req req) { return webSocketHeadStuff != null ? webSocketHeadStuff.get(req) : webSocketHeadStuff_base(req); } final public String webSocketHeadStuff_fallback(IF1 _f, Req req) { return _f != null ? _f.get(req) : webSocketHeadStuff_base(req); } public String webSocketHeadStuff_base(Req req) { return hreconnectingWebSockets() + hjs("\r\n var webSocketQuery = window.location.search;\r\n var ws;\r\n var wsVerbose = true;\r\n var wsReady = false;\r\n \r\n function wsOnOpen(onOpen) {\r\n if (wsReady) onOpen();\r\n else {\r\n var old = ws.onopen;\r\n ws.onopen = function() {\r\n if (old) old();\r\n onOpen();\r\n };\r\n };\r\n }\r\n \r\n //$(document).ready(function() {\r\n var url = ((window.location.protocol === \"https:\") ? \"wss://\" : \"ws://\") + window.location.host + " + jsQuote(baseLink + req.uri()) + " + webSocketQuery;\r\n console.log(\"Opening WebSocket: \" + url);\r\n ws = new ReconnectingWebSocket(url);\r\n ws.onopen = function(event) {\r\n wsReady = true;\r\n console.log(\"WebSocket ready!\");\r\n ws.onmessage = " + js_evalOnWebSocketMessage() + ";\r\n };\r\n //});\r\n "); } public void fillReqAuthFromCookie(Req req, String cookie, AuthedDialogID auth) { req.auth = auth; boolean requestAuthed = auth != null; if (requestAuthed) cset(auth, "lastSeen", now()); req.masterAuthed = calcMasterAuthed(req); req.authDomainObj = !requestAuthed ? null : auth.restrictedToDomain.get(); req.authDomain = !requestAuthed ? null : auth.domain(); } transient public IF0>> renderStats; public List> renderStats() { return renderStats != null ? renderStats.get() : renderStats_base(); } final public List> renderStats_fallback(IF0>> _f) { return _f != null ? _f.get() : renderStats_base(); } public List> renderStats_base() { long us = db_mainConcepts().uncompressedSize; return ll(ll("Concepts", n2(conceptCount())), ll("DB size on disk", htmlEncode2(toK_str(fileSize(conceptsFile())))), us == 0 ? null : ll("DB size uncompressed", htmlEncode2(toK_str(us))), ll("DB load time", htmlEncode2(renderDBLoadTime())), ll("DB save time", htmlEncode2(renderDBSaveTime())), ll("Last saved", htmlEncode2(renderHowLongAgo(db_mainConcepts().lastSaveWas)))); } public Object serveBotDemo(Req req, String js) { return hhtml(hhead(htitle(heading) + loadJQuery2() + botDemoHeadStuff()) + hbody(hjavascript(js))); } public String botDemoHeadStuff() { return ""; } public Object handleLogout(Req req) { cdelete(req.auth); if (redirectOnLogout) return hrefresh(req.uri); return null; } } static public class ExecutedStep extends Concept { static final public String _fieldOrder = "step conversation msg"; public Ref step = new Ref(); public Ref conversation = new Ref(); public Msg msg; } static public class InputHandled extends Concept { static final public String _fieldOrder = "input conversation msg inputHandler handled"; public String input; public Ref conversation = new Ref(); public Msg msg; public Ref inputHandler = new Ref(); public boolean handled = false; } abstract static public class BotStep extends Concept { public String comment; public boolean run(Conversation conv) { return false; } public ScheduledAction nextStepAction(Conversation conv) { return new Action_NextStep(conv, conv.executedSteps); } public String fullToString() { return toString(); } public double preTypingDelay() { return 0; } public boolean isUndoBoundary() { return false; } } static public class Sequence extends BotStep { public RefL steps = new RefL(); public String toString() { return "Sequence " + quoteOr(comment, "(unnamed)") + spaceRoundBracketed(nSteps(steps)); } public boolean run(Conversation conv) { syncAdd(conv.stack, new ActiveSequence(this)); conv.change(); return true; } } static public class BotRandomAction extends BotStep { public RefL actions = new RefL(); public String toString() { return "Random Action " + appendBracketed(comment) + (empty(actions) ? " [empty]" : ": " + first(actions) + (l(actions) == 1 ? "" : " + " + n2(l(actions) - 1) + " more")); } public boolean run(Conversation conv) { BotStep step = random(actions); if (step == null) return true; return step.run(conv); } } static public class BotMessage extends BotStep { public String text; public String specialPurpose; public boolean disableInput = false; static public String _fieldOrder = "text specialPurpose"; public String toString() { return toString(40); } public String toString(int shorten) { return "Message" + spacePlusRoundBracketedIfNempty(comment) + ": " + newLinesToSpaces2(shorten(text, shorten)); } public String fullToString() { return toString(Integer.MAX_VALUE); } public boolean run(Conversation conv) { Msg msg = new Msg(false, text); msg.out = new Out(); msg.out.disableInput = disableInput; conv.add(msg); return true; } public double preTypingDelay() { return botMod().typingDelayForText(text); } } abstract static public class AbstractBotImage extends BotStep { public String altText; public boolean run(Conversation conv) { botMod().addReplyToConvo(conv, () -> himgsrc(imageURL(), "title", altText, "alt", altText, "class", "chat_contentImage")); return true; } abstract public String imageURL(); public double preTypingDelay() { return botMod().settings().botTypingDelay; } } static public class BotImage extends AbstractBotImage { public String imageURL, altText; static public String _fieldOrder = "imageURL"; public String imageURL() { return imageURL; } public String toString() { return "Image" + spacePlusRoundBracketedIfNempty(comment) + ": " + imageURL; } } static public class UploadedImage extends AbstractBotImage { public String imageURL() { return botMod().convertToAbsoluteURL(botMod().baseLink + "/uploaded-image/" + id); } public File imageFile() { return newFile(botMod().uploadedImagesDir(), id + ".png"); } public String toString() { return "Image" + spacePlusRoundBracketedIfNempty(altText) + spacePlusRoundBracketedIfNempty(comment); } public void delete() { if (concepts() == db_mainConcepts()) deleteFile(imageFile()); super.delete(); } public BufferedImage getImage() { return loadImage2(imageFile()); } } static public class UploadedSound extends Concept { public String comment; public String mimeType = mp3mimeType(); public String soundURL() { return botMod().convertToAbsoluteURL(botMod().baseLink + "/uploaded-sound/" + id); } public File soundFile() { return newFile(botMod().uploadedSoundsDir(), id + ".mp3"); } public String toString() { return "Sound" + spacePlusRoundBracketedIfNempty(comment); } public void delete() { if (concepts() == db_mainConcepts()) deleteFile(soundFile()); super.delete(); } public boolean isPublic = false; } static public class UploadedFile extends Concept { static final public String _fieldOrder = "name comment mimeType liveURI"; public String name, comment, mimeType, liveURI; public String downloadURL() { return downloadURL(null); } public String downloadURL(String contentType) { return botMod().convertToAbsoluteURL(appendQueryToURL(botMod().baseLink + "/uploaded-file/" + id + (empty(name) ? "" : "/" + urlencode(name)), "ct", contentType)); } final public File getFile() { return theFile(); } public File theFile() { return newFile(botMod().uploadedFilesDir(), id + ".png"); } public String toString() { return "File " + spacePlusRoundBracketedIfNempty(name) + spacePlusRoundBracketedIfNempty(comment); } public void delete() { if (concepts() == db_mainConcepts()) deleteFile(theFile()); super.delete(); } } static public class BotDoNothing extends BotStep { public boolean run(Conversation conv) { return false; } public String toString() { return "Do nothing"; } } static public class BotSendTyping extends BotStep { public boolean run(Conversation conv) { conv.botTyping = print("Bot typing", now()); return true; } } static public class BotGoBack extends BotStep { public boolean run(Conversation conv) { botMod().doUndo(conv); return false; } public String toString() { return "Go back one step"; } } static public class BotNewDialog extends BotStep { public boolean run(Conversation conv) { conv.newDialog(); return false; } public String toString() { return "New dialog"; } } static public class BotPause extends BotStep { public double seconds; public BotPause() { } public BotPause(double seconds) { this.seconds = seconds; } public boolean run(Conversation conv) { botMod().addScheduledAction(nextStepAction(conv), toMS(seconds)); return false; } public String toString() { return "Pause for " + (seconds == 1 ? "1 second" : formatDouble(seconds, 1) + " seconds"); } } static public class BotOutgoingQuestion extends BotStep implements IInputHandler { public String displayText; public String key; public String defaultValue; public String placeholder; public List buttons; public boolean allowFreeText = true; public boolean multipleChoice = false; public boolean radioButtons = false; public String multipleChoiceSeparator = ", "; public boolean optional = false; public String answerCheck; public RefL buttonActions = new RefL(); static public String _fieldOrder = "displayText key defaultValue placeholder buttons buttonActions allowFreeText multipleChoice optional answerCheck"; public String toString() { return "Question: " + orEmptyQuotes(displayText); } public List> buttonsWithActions() { return zipTwoListsToPairs_longer(buttons, buttonActions); } public boolean run(Conversation conv) { String text = botMod().rewriteBotMessage(conv, displayText); Msg msg = new Msg(false, text); msg.out = makeMsgOut(); conv.add(msg); cset(conv, "inputHandler", this); return false; } public Out makeMsgOut() { Out out = new Out(); out.placeholder = or(placeholder, displayText); out.defaultInput = defaultValue; out.buttons = cloneList(buttons); out.multipleChoice = multipleChoice; out.multipleChoiceSeparator = multipleChoiceSeparator; out.radioButtons = radioButtons; if (eqic(answerCheck, "phone number") && botMod().phoneNumberSpecialInputField) out.javaScript = "$(\"#chat_message\").hide(); $(\"#chat_telephone, .iti\").show(); $(\"#chat_telephone\").val(\"\").focus();"; else if (!allowFreeText) { out.javaScript = jsDisableInputField(); if (empty(out.placeholder)) out.placeholder = " "; } return out; } public boolean handleInput(String s, Conversation conv) { print("BotOutgoingQuestion handleInput " + s); s = trim(s); String theKey = or2(key, htmldecode_dropAllTags(trim(displayText))); if (nempty(theKey) && !eq(theKey, "-")) syncPut(conv.answers, theKey, s); conv.change(); if (eqic(answerCheck, "email address") && !isValidEmailAddress_simple(s)) { handleValidationFail(conv, "bad email address"); return true; } if (eqic(answerCheck, "phone number") && !botMod().checkPhoneNumber(s)) { handleValidationFail(conv, "bad phone number"); return true; } conv.removeInputHandler(this); int idx = indexOfIC(trimAll(lmap(__138 -> dropStuffBeforeVerticalBar(__138), buttons)), s); print("Button index of " + quote(s) + " in " + sfu(buttons) + " => " + idx); BotStep target = get(buttonActions, idx); print("Button action: " + target); if (target != null) conv.callSubroutine(target); print("Scheduling next step in " + conv); conv.scheduleNextStep(); return true; } public double preTypingDelay() { return empty(displayText) ? 0 : botMod().typingDelayForText(displayText); } public void handleValidationFail(Conversation conv, String purpose) { BotMessage msg = botMod().messageForPurpose(purpose); String text = or2(or2(msg == null ? null : msg.text, getOrKeep(botMod().specialPurposes, purpose)), "Invalid input, please try again"); printVars_str("handleValidationFail", "purpose", purpose, "msg", msg, "text", text); Msg m = new Msg(); m.text = text; m.out = makeMsgOut(); conv.add(m); cset(conv, "inputHandler", this); return; } public boolean isUndoBoundary() { return true; } } static public class BotIdleMode extends BotStep { public String toString() { return "Idle Mode (wait indefinitely)"; } public boolean run(Conversation conv) { return false; } } static public class BotEndConversation extends BotStep { public String toString() { return "End Conversation (disable user input)"; } public boolean run(Conversation conv) { Msg msg = new Msg(false, ""); msg.out = new Out(); msg.out.javaScript = jsDisableInputField(); msg.out.placeholder = " "; conv.add(msg); return true; } } static public String jsDisableInputField() { return "$(\"#chat_message\").prop('disabled', true).attr('placeholder', '');"; } static public class BotSaveLead extends BotStep { public String toString() { return "Save Lead"; } public boolean run(Conversation conv) { Lead lead = cnew(Lead.class, "conversation", conv, "domain", conv.domainObj, "date", new Timestamp(now()), "answers", cloneMap(conv.answers)); botMod().onNewLead(lead); return true; } } static public class BotSaveFeedback extends BotStep { public String toString() { return "Save Conversation Feedback"; } public boolean run(Conversation conv) { cnew(ConversationFeedback.class, "conversation", conv, "domain", conv.domainObj, "date", new Timestamp(now()), "answers", filterKeys(conv.answers, swic$("Conversation Feedback:"))); return true; } } static public class BotClearStack extends BotStep { public boolean run(Conversation conv) { syncRemoveAllExceptLast(conv.stack); conv.change(); return true; } public String toString() { return "Clear Stack [forget all running procedures in conversation]"; } } static public class BotSwitchLanguage extends BotStep { public Ref language = new Ref(); public boolean run(Conversation conv) { cset(conv, "language", language); return true; } public String toString() { return "Switch to " + language; } } static public class UserKeyword extends Concept { static final public String _fieldOrder = "language pattern examples counterexamples action enabled priority precedence parsedPattern"; public Ref language = new Ref(); public String pattern; public List examples, counterexamples; public Ref action = new Ref(); public boolean enabled = true; public boolean priority = false; public int precedence; transient public MMOPattern parsedPattern; public void change() { parsedPattern = null; botMod().consistencyCheckResults = null; super.change(); } public MMOPattern parsedPattern() { if (parsedPattern == null) return parsedPattern = mmo2_parsePattern(pattern); return parsedPattern; } public String toString() { return "User Keyword: " + pattern; } public boolean matchWithTypos(String s) { return mmo2_matchWithTypos(parsedPattern(), s); } } static public class Language extends Concept { static final public String _fieldOrder = "languageName comment"; public String languageName; public String comment; public String toString() { return languageName + spaceRoundBracketed(comment); } } static public class Evt extends Concept { } static public class EvtMatchedUserKeyword extends Evt { static final public String _fieldOrder = "userKeyword msg"; public Ref userKeyword = new Ref(); public Msg msg; public EvtMatchedUserKeyword() { } public EvtMatchedUserKeyword(UserKeyword userKeyword, Msg msg) { this.userKeyword.set(userKeyword); this.msg = msg; } } static public class EvtJumpTo extends Evt { public Ref target = new Ref(); public EvtJumpTo() { } public EvtJumpTo(BotStep target) { this.target.set(target); } } static public class EvtCallSubroutine extends Evt { public Ref target = new Ref(); public EvtCallSubroutine() { } public EvtCallSubroutine(BotStep target) { this.target.set(target); } } abstract static public class AbstractAvatar extends Concept { abstract public Avatar getActualAvatar(); } static public class RandomAvatar extends AbstractAvatar { public Avatar getActualAvatar() { return random(filter(list(Avatar.class), a -> a.onShift())); } public String toString() { return "Choose a random avatar that is on shift"; } } static public class Avatar extends AbstractAvatar { static final public String _fieldOrder = "name comment shift image"; public String name, comment; public String shift; public Ref image = new Ref(); public Avatar getActualAvatar() { return this; } public boolean onShift() { List shifts = parseBusinessHours_pcall(shift); if (empty(shifts)) return true; shifts = splitBusinessHoursAtMidnight(shifts); int minute = minuteInDay(timeZone(botMod().timeZone)); return anyIntRangeContains(shifts, minute); } public String toString() { return empty(name) ? super.toString() : "Avatar " + name + appendBracketed(comment); } } static public class Out extends DynamicObject { public List buttons; public boolean multipleChoice, radioButtons; public String multipleChoiceSeparator; public String placeholder; public String defaultInput; public String javaScript; public boolean disableInput = false; } static public class Msg extends DynamicObject { public long time; public boolean fromUser = false; public Worker fromWorker; public String text; public Out out; public List labels; public Msg() { } public Msg(boolean fromUser, String text) { this.text = text; this.fromUser = fromUser; time = now(); } public Msg(String text, boolean fromUser) { this.fromUser = fromUser; this.text = text; time = now(); } public String toString() { return (fromUser ? "User" : "Bot") + ": " + text; } } static public class AuthedDialogID extends Concept { static final public String _fieldOrder = "cookie master restrictedToDomain loggedIn lastSeen"; public String cookie; public boolean master = false; public Ref restrictedToDomain = new Ref(); public Worker loggedIn; public long lastSeen; public String domain() { return !restrictedToDomain.has() ? null : restrictedToDomain.get().domainAndPath; } public Ref user = new Ref(); public boolean userMode = false; public User user() { return user.get(); } } static public class ActiveSequence { public Sequence originalSequence; public List steps; public int stepIndex; public ActiveSequence() { } public ActiveSequence(BotStep step) { if (step instanceof Sequence) { steps = cloneList(((Sequence) step).steps); originalSequence = (Sequence) step; } else steps = ll(step); steps = botMod().addTypingDelays(steps); } public boolean done() { return stepIndex >= l(steps); } public BotStep currentStep() { return get(steps, stepIndex); } public void nextStep() { ++stepIndex; } public String toString() { return (stepIndex >= l(steps) ? "DONE " : "Step " + (stepIndex + 1) + "/" + l(steps) + " of ") + (originalSequence != null ? str(originalSequence) : squareBracket(joinWithComma(steps))); } } static public class UndoState { public List stack; public UndoState() { } public UndoState(List stack) { this.stack = stack; } public String toString() { return "UndoState " + stack; } } static public class Conversation extends Concept { static final public String _fieldOrder = "cookie ip country domain domainObj oldDialogs msgs lastPing botOn notificationsOn worker userTyping botTyping testMode nextActionTime userMessageProcessed newDialogTriggered dryRun avatar stack undoStates executedSteps inputHandler language answers botConfig events reloadCounter"; public String cookie, ip, country, domain; public Ref domainObj = new Ref(); public List> oldDialogs = new ArrayList(); public List msgs = new ArrayList(); public long lastPing; public boolean botOn = true; public boolean notificationsOn = true; public Worker worker; transient volatile public long userTyping, botTyping; public boolean testMode = false; public long nextActionTime = Long.MAX_VALUE; public long userMessageProcessed; public int newDialogTriggered = -1; transient public boolean dryRun = false; public Ref avatar = new Ref(); public List stack = new ArrayList(); public List undoStates; public int executedSteps; public IInputHandler inputHandler; public Ref language = new Ref(); public Map answers = litcimap(); public Map botConfig; public RefL events = new RefL(); public int reloadCounter; public void add(Msg m) { m.text = trim(m.text); syncAdd(msgs, m); botMod().noteConversationChange(); change(); vmBus_send("chatBot_messageAdded", mc(), this, m); } public int allCount() { return archiveSize() + syncL(msgs); } public int archiveSize() { return syncLengthLevel2(oldDialogs) + syncL(oldDialogs); } public List allMsgs() { return concatLists_syncIndividual(syncListPlus(oldDialogs, msgs)); } public long lastMsgTime() { Msg m = last(msgs); return m == null ? 0 : m.time; } public void incReloadCounter() { cset(this, "reloadCounter", reloadCounter + 1); } public void turnBotOff() { cset(this, "botOn", false); botMod().noteConversationChange(); } public void turnBotOn() { cset(this, "botOn", true, "worker", null); String backMsg = botMod().getCannedAnswer("#botBack", this); if (empty(msgs) || lastMessageIsFromUser() || !eq(last(msgs).text, backMsg)) add(new Msg(backMsg, false)); botMod().noteConversationChange(); } public boolean lastMessageIsFromUser() { return nempty(msgs) && last(msgs).fromUser; } public void newDialog() { if (syncNempty(msgs)) syncAdd(oldDialogs, msgs); cset(this, "msgs", new ArrayList()); syncClear(answers); syncClear(stack); syncClear(undoStates); dropScheduledActions(); change(); print("newDialog " + archiveSize() + "/" + allCount()); vmBus_send("chatBot_clearedSession", mc(), this); } public void dropScheduledActions() { deleteConcepts(ScheduledActionOnConversation.class, "conv", this); } public void jumpTo(BotStep step) { syncPopLast(stack); print("Jumping to " + step); noteEvent(new EvtJumpTo(step)); if (step == null) return; syncAdd(stack, new ActiveSequence(step)); change(); } public void callSubroutine(BotStep step) { if (step == null) return; noteEvent(new EvtCallSubroutine(step)); print("Calling subroutine " + step); syncAdd(stack, new ActiveSequence(step)); change(); } public void removeInputHandler(IInputHandler h) { if (inputHandler == h) cset(this, "inputHandler", null); } public void scheduleNextStep() { botMod().addScheduledAction(new Action_NextStep(this)); } public void noteEvent(Concept event) { events.add(event); } public boolean isActive() { return lastPing + botMod().activeConversationTimeout() >= now(); } public String botImg() { if (avatar.has()) return avatar.get().image.get().imageURL(); else return botMod().botImageForDomain(domainObj.get()); } public void addUndoState() { UndoState state = new UndoState(syncShallowCloneElements(stack)); print("Made undo state: " + state); undoStates = syncAddOrCreate(undoStates, state); change(); } public Ref mirrorPost = new Ref(); public Ref detailedMirrorPost = new Ref(); public void change() { super.change(); ((DynGazelleRocks) botMod()).rstUpdateMirrorPosts.add(this); } public void updateMirrorPost() { if (isDeleted()) return; if (!mirrorPost.has() && syncNempty(msgs)) cset(Conversation.this, "mirrorPost", cnew(UserPost.class, "title", "Conversation " + id, "type", "Conversation Mirror", "creator", ((DynGazelleRocks) botMod()).internalUser(), "botInfo", "Conversation Mirror Bot")); cset(mirrorPost.get(), "text", lines_rtrim(msgs)); if (!detailedMirrorPost.has() && syncNempty(msgs)) cset(Conversation.this, "detailedMirrorPost", cnew(UserPost.class, "title", "Conversation " + id + " with details", "type", "Detailed Conversation Mirror", "creator", ((DynGazelleRocks) botMod()).internalUser(), "botInfo", "Conversation Mirror Bot")); cset(detailedMirrorPost.get(), "text", indentedStructure(msgs)); } public void delete() { cdelete(mirrorPost.get()); super.delete(); } } abstract static public class ScheduledAction extends Concept implements Runnable { public long time; } abstract static public class ScheduledActionOnConversation extends ScheduledAction { public Ref conv = new Ref(); } static public class Action_NextStep extends ScheduledActionOnConversation { public int executedSteps = -1; public Action_NextStep() { } public Action_NextStep(Conversation conv) { this.conv.set(conv); } public Action_NextStep(Conversation conv, int executedSteps) { this.conv.set(conv); this.executedSteps = executedSteps; } public void run() { try { nextStep(conv.get(), executedSteps); } catch (Exception __e) { throw rethrow(__e); } } } static public class OnNewDialog extends ScheduledActionOnConversation { public OnNewDialog() { } public OnNewDialog(Conversation conv) { this.conv.set(conv); } public void run() { try { botMod().startMainScript(conv.get()); } catch (Exception __e) { throw rethrow(__e); } } } static public void nextStep(Conversation conv) { nextStep(conv, -1); } static public void nextStep(Conversation conv, int expectedExecutedSteps) { if (expectedExecutedSteps >= 0 && conv.executedSteps != expectedExecutedSteps) return; while (licensed()) { if (empty(conv.stack)) return; ActiveSequence seq = syncLast(conv.stack); boolean done = seq.done(); printVars_str("Active sequence", "conv", conv, "seq", seq, "done", done, "stackSize", syncL(conv.stack)); if (done) { syncPopLast(conv.stack); continue; } BotStep step = seq.currentStep(); if (botMod().enableUndoStates && step.isUndoBoundary()) conv.addUndoState(); seq.nextStep(); ++conv.executedSteps; conv.change(); if (!executeStep(step, conv)) { print("Step returned false: " + step); break; } } } static public boolean executeStep(BotStep step, Conversation conv) { if (step == null || conv == null) return false; print("Executing step " + step + " in " + conv); ExecutedStep executed = null; if (botMod().recordExecutionsAndInputs) executed = cnew(ExecutedStep.class, "step", step, "conversation", conv); Msg lastMsg = syncLast(conv.msgs); boolean result = step.run(conv); Msg newMsg = syncLast(conv.msgs); if (newMsg != null && !newMsg.fromUser && newMsg != lastMsg) cset(executed, "msg", newMsg); return result; } static public class OnUserMessage extends ScheduledActionOnConversation { public OnUserMessage() { } public OnUserMessage(Conversation conv) { this.conv.set(conv); } public void run() { try { Conversation conv = this.conv.get(); Msg msg = syncLast(conv.msgs); if (msg == null || !msg.fromUser) return; print("OnUserMessage: " + msg); if (eqic(msg.text, "!back")) { botMod().doUndo(conv); return; } if (botMod().handleGeneralUserInput(conv, msg, true)) return; IInputHandler inputHandler = conv.inputHandler; if (inputHandler != null) { InputHandled rec = null; String input = msg.text; if (botMod().recordExecutionsAndInputs) rec = cnew(InputHandled.class, "inputHandler", inputHandler, "conversation", conv, "msg", msg, "input", input); boolean result = conv.inputHandler.handleInput(input, conv); cset(rec, "handled", result); if (result) return; } botMod().handleGeneralUserInput(conv, msg, false); } catch (Exception __e) { throw rethrow(__e); } } } static public class Domain extends Concept { public String domainAndPath; public String tenantID; public Ref botImage = new Ref(); public String botName; public Ref avatar = new Ref(); public String headerColorLeft, headerColorRight; public Boolean autoOpenBot; public Ref mainScript = new Ref(); public String password = aGlobalID(); static public String _fieldOrder = "domainAndPath botImage mainScript"; public String toString() { return domainAndPath; } } static public class Form extends Concept { public String name; public RefL steps = new RefL(); public String toString() { return name; } } static public class DeliveredDomain extends Concept { public String domain; } static public class CannedAnswer extends Concept { public String hashTag, text; } static public String text(CannedAnswer a) { return a == null ? null : a.text; } static public class Lead extends Concept { static final public String _fieldOrder = "domain conversation date answers"; public Ref domain = new Ref(); public Ref conversation = new Ref(); public Timestamp date; public Map answers; } static public class ConversationFeedback extends Concept { static final public String _fieldOrder = "domain conversation date answers"; public Ref domain = new Ref(); public Ref conversation = new Ref(); public Timestamp date; public Map answers; } static public class Settings extends Concept { static final public String _fieldOrder = "mainDomainName botTypingDelay botTypingDelayPerWord botTypingMaxDelay preferredCountryCodes multiLanguageMode notificationSound talkToBotOnlyWithAuth enableWorkerChat defaultLanguage mailLeadsTo leadMailSubject"; public String mainDomainName; public double botTypingDelay; public double botTypingDelayPerWord; public double botTypingMaxDelay; public String preferredCountryCodes; public boolean multiLanguageMode = false; public Ref notificationSound = new Ref(); public boolean talkToBotOnlyWithAuth = false; public boolean enableWorkerChat = false; public Ref defaultLanguage = new Ref(); public String mailLeadsTo; public String leadMailSubject = "A new lead occurred in your chat bot"; } static public interface IInputHandler { public boolean handleInput(String s, Conversation conv); } static public DynNewBot2 botMod() { return (DynNewBot2) dm_current_mandatory(); } static public String passwordSalt() { File f = programSecretFile("password-salt"); if (fileExists(f)) return loadTextFile(f); File global = javaxSecretDir("password-salt"); if (fileExists(global)) return loadTextFile(global); return loadTextFileOrCreateWithRandomID(f); } static public class PostReferenceable extends Concept { } static public class User extends PostReferenceable { static final public String _fieldOrder = "name passwordMD5 contact isMaster botToken lastSeen"; public String name; public SecretValue passwordMD5; public String contact; public boolean isMaster = false; public SecretValue botToken = aSecretGlobalID(); public long lastSeen; public String name() { return name; } public String toString() { return nempty(name) ? "User " + name : super.toString(); } } static public class UserCreatedObject extends PostReferenceable { static final public String _fieldOrder = "creator botInfo"; public Ref creator = new Ref(); public String botInfo; } static public class UserPost extends UserCreatedObject { public String type, title, text; public boolean isPublic = true, hidden; public boolean creating = false; public long xmodified; public long bumped; static public List fieldsToSaveOnDelete = ll("id", "text", "title", "type", "creatorID", "postRefs", "postRefTags", "hidden", "isPublic", "created", "_modified", "xmodified", "botInfo", "creating"); public String text() { return text; } public RefL postRefs = new RefL(); public List postRefTags = new ArrayList(); static public String _fieldOrder = "title text type postRefs isPublic"; public String toString() { String content = nempty(title) ? shorten(title) : escapeNewLines(shorten(text)); return content + " [by " + author() + "]"; } public boolean isReply() { return nempty(postRefs); } public boolean isBotPost() { return nempty(botInfo); } public boolean isMasterMade() { return creator.has() && creator.get().isMaster; } public String author() { String author = userName(creator.get()); if (isBotPost()) author += "'s bot " + quote(botInfo); return author; } public void change() { super.change(); ((DynGazelleRocks) botMod()).distributePostChanges(this); } public List> postRefsWithTags() { return zipTwoListsToPairs_lengthOfFirst(postRefs, postRefTags); } public List postRefsWithTag(String tag) { return pairsAWhereB(postRefsWithTags(), t -> eqic_unnull(t, tag)); } public UserPost primaryRefPost() { return optCast(UserPost.class, first(postRefsWithTag(""))); } public void _setModified(long modified) { super._setModified(modified); setXModified(modified); } public void bump() { bumped = now(); _change_withoutUpdatingModifiedField(); for (UserPost p : syncInstancesOf(UserPost.class, postRefs)) p.setXModified(); } public long modifiedOrBumped() { return max(_modified, bumped); } public void setXModified() { setXModified(now()); } public void setXModified(long modified) { boolean changed = modified > xmodified; xmodified = modified; _change_withoutUpdatingModifiedField(); if (changed) ((DynGazelleRocks) botMod()).distributePostChanges(this); } public void _backRefsModified() { super._backRefsModified(); setXModified(now()); } public int distanceToUserPost() { int n = 0; UserPost post = this; while (post != null && n < 100) { if (!post.isBotPost()) return n; post = post.primaryRefPost(); } return -1; } public boolean isJavaXCode() { return eqicOrSwicPlusSpace(type, "JavaX Code"); } } abstract static public class DynGazelleRocks extends DynNewBot2 { transient public boolean inlineSearch = false; static public boolean _switchableField_webPushEnabled = true; public boolean webPushEnabled = true; static public boolean _switchableField_showPostStats = true; public boolean showPostStats = false; static public boolean _switchableField_showSuggestorBot = true; public boolean showSuggestorBot = true; static public boolean _switchableField_showMetaBotOnEveryPage = true; public boolean showMetaBotOnEveryPage = true; static public boolean _switchableField_delayAfterSuggestion = true; public int delayAfterSuggestion = 1000; static public boolean _switchableField_defaultBotPost = true; public int defaultBotPost = 238410; static public boolean _switchableField_teamPostID = true; public long teamPostID; static public boolean _switchableField_favIconID = true; public long favIconID; static public boolean _switchableField_defaultFavIconSnippet = true; public String defaultFavIconSnippet = gazelleFavIconSnippet(); static public boolean _switchableField_gazelleBotURL = true; public String gazelleBotURL = null; static public boolean _switchableField_salterService = true; public String salterService; transient public double systemLoad; transient public long processSize; public void init() { dm_require("#1017856/SystemLoad"); dm_vmBus_onMessage("systemLoad", new VF1() { public void get(Double load) { try { if (setField("systemLoad", load)) distributeDivChanges("serverLoadRightHemi"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (setField(systemLoad := load))\r\n distributeDivChanges(\"serverLoadRi..."; } }); dm_vmBus_onMessage("processSize", new VF1() { public void get(Long processSize) { try { if (setField("processSize", processSize)) distributeDivChanges("memRightHemi"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (setField(+processSize))\r\n distributeDivChanges(\"memRightHemi\");"; } }); botName = heading = adminName = "gazelle.rocks"; templateID = "#1030086"; cssID = "237267"; enableUsers = true; useWebSockets = true; showRegisterLink = true; showTalkToBotLink = false; alwaysRedirectToHttps = true; redirectOnLogout = true; showFullErrors = true; inlineSearch = true; lockWhileDoingBotActions = false; showMailSenderInfo = false; if (empty(salterService)) passwordSalt(); } public void makeIndices() { super.makeIndices(); indexConceptFieldCI(User.class, "name"); indexConceptFieldDesc(UserPost.class, "xmodified"); indexConceptFieldDesc(UserPost.class, "_modified"); indexConceptFieldCI(UserPost.class, "botInfo"); } public void start() { init(); super.start(); db_mainConcepts().modifyOnCreate = true; printConceptIndices(); onConceptsChange(new Runnable() { public int postCount = countConcepts(UserPost.class); public void run() { try { AutoCloseable __7 = enter(); try { int count = countConcepts(UserPost.class); if (count != postCount) { postCount = count; distributeDivChanges("postCount"); } } finally { _close(__7); } } catch (Exception __e) { throw rethrow(__e); } } }); internalUser(); } public void requestServed() { distributeDivChanges("webRequestsRightHemi"); } public class WebSocketInfo extends Meta implements AutoCloseable { public boolean _isTransient() { return true; } public String uri; public Map params; public Req req; public WeakReference webSocket; public Set> messageHandlers = syncLinkedHashSet(); public Set> binMessageHandlers = syncLinkedHashSet(); public Set closeHandlers = syncLinkedHashSet(); public Map misc = syncMap(); public WebSocketInfo(Object webSocket) { this.webSocket = weakRef(webSocket); setFieldToIVF1Proxy(webSocket, "onMessage", msg -> { AutoCloseable __8 = enter(); try { try { Object opCode = call(msg, "getOpCode"); byte opCodeValue = (byte) (call(opCode, "getValue")); boolean isBinary = opCodeValue == 2; if (isBinary) { byte[] data = (byte[]) (rcall("getBinaryPayload", msg)); pcallFAll(binMessageHandlers, data); } else { String data = rcall_string("getTextPayload", msg); pcallFAll(messageHandlers, data); } } catch (Throwable __e) { pcallFail(__e); } } finally { _close(__8); } }); } final public String subUri() { return subURI(); } public String subURI() { return req.subURI(); } public String uri() { return uri; } public Map params() { return params; } public String get(String param) { return mapGet(params, param); } public void setParams(Map params) { this.params = params; req.params = params; } public Object dbRepresentation; public Set> liveDivs = new HashSet(); public void eval(String jsCode) { eval(jsCode, null); } public void eval(String jsCode, Object... __) { jsCode = jsDollarVars(jsCode, __); if (empty(jsCode)) return; dm_call(webSocket.get(), "send", jsonEncode(litmap("eval", jsCode))); } public void send(String jsonData) { if (empty(jsonData)) return; dm_call(webSocket.get(), "send", jsonData); } public AutoCloseable onStringMessage(IVF1 onMsg) { return tempAdd(messageHandlers, onMsg); } public AutoCloseable onBinaryMessage(IVF1 onMsg) { return tempAdd(binMessageHandlers, onMsg); } public AutoCloseable onClose(Runnable r) { return tempAdd(closeHandlers, r); } public void callCloseHandlers() { pcallFAll(closeHandlers); } public void close() { cleanUp(webSocket.get()); } } transient public Map webSockets = syncWeakHashMap(); public void cleanMeUp_webSockets() { closeAllKeysAndClear((Map) webSockets); } public void handleWebSocket(Object ws) { set(ws, "onClose", new Runnable() { public void run() { try { var info = webSockets.get(ws); if (info != null) { try { onWebSocketClose(info); } catch (Throwable __e) { pcallFail(__e); } } webSockets.remove(ws); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var info = webSockets.get(ws);\r\n if (info != null) pcall { onWebSocketCl..."; } }); set(ws, "onOpen", new Runnable() { public void run() { try { AutoCloseable __9 = enter(); try { String uri = (String) (rcall("getUri", ws)); Map params = (Map) (rcall("getParms", ws)); print("WebSocket opened! uri: " + uri + ", params: " + params); WebSocketInfo info = new WebSocketInfo(ws); IWebRequest webRequest = proxy(IWebRequest.class, call(ws, "webRequest")); info.req = webRequestToReq(webRequest); String cookie = cookieFromWebRequest(webRequest); AuthedDialogID auth = authObject(cookie); fillReqAuthFromCookie(info.req, cookie, auth); AutoCloseable __10 = tempSetTL(currentReq, info.req); try { info.uri = uri; info.params = params; webSockets.put(ws, info); try { onNewWebSocket(info); } catch (Throwable __e) { pcallFail(__e); } long objectID = toLong(params.get("objectID")); long modified = toLong(params.get("modified")); if (objectID != 0) { UserPost c = getConceptOpt(UserPost.class, objectID); print("Modification: " + c.xmodified + " / " + c._modified + " / " + modified); if (c != null && c.xmodified > modified) reloadBody(ws); } } finally { _close(__10); } } finally { _close(__9); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter(); \r\n String uri = (String) (rcall getUri(ws));\r\n Map..."; } }); setFieldToIVF1Proxy(ws, "onMessage", msg -> { AutoCloseable __11 = enter(); try { try { WebSocketInfo info = webSockets.get(ws); if (info == null) return; String data = rcall_string("getTextPayload", msg); Map map = jsonDecodeMap(data); Object div = map.get("liveDiv"); if (div instanceof String) { String contentDesc = (String) div; syncAdd(info.liveDivs, pair(((String) div), (Object) contentDesc)); reloadDiv(ws, ((String) div), calcDivContent(contentDesc)); } } catch (Throwable __e) { pcallFail(__e); } } finally { _close(__11); } }); } public String serveRegisterForm(Map params) { String user = trim(params.get("user")); String pw = trim(params.get("f_pw")); String pw2 = trim(params.get("pw2")); String redirect = params.get("redirect"); String contact = trim(params.get("contact")); redirect = dropParamFromURL(redirect, "logout"); if (empty(redirect)) redirect = baseLink + "/"; List msgs = new ArrayList(); if (nempty(user) || nempty(pw)) { Lock __1 = dbLock(); lock(__1); try { if (empty(user)) msgs.add("Please enter a user name"); else if (l(user) < 4) msgs.add("Minimum user name length: 4 characters"); else if (l(user) > 30) msgs.add("Maximum user name length: 30 characters"); else if (hasConceptIC(User.class, "name", user)) msgs.add("This user exists, please choose a different name"); if (regexpContainsIC("[^a-z0-9\\-\\.]", user)) msgs.add("Bad characters in user name (please use only a-z, 0-9, - and .)"); if (empty(pw)) msgs.add("Please enter a password. Don't use one of your regular (important) passwords! Just make one up and let the browser save it."); else if (l(pw) < 6) msgs.add("Minimum password length: 6 characters"); if (neq(pw, pw2)) msgs.add("Passwords don't match"); if (empty(msgs)) { User userObj = cnew(User.class, "name", user, "passwordMD5", new SecretValue(hashPW(pw)), "contact", contact); vmBus_send("userCreated", userObj); return hrefresh(5.0, redirect) + "User " + user + " created! Redirecting..."; } } finally { unlock(__1); } } return hhtml(hhead(htitle("Register new user") + hsansserif() + hmobilefix() + hresponstable()) + hbody(hfullcenter(h3_htmlEncode(adminName + " | Register new user") + hpostform(hhidden("redirect", redirect) + tag("table", (empty(msgs) ? "" : tr(td() + td() + td(htmlEncode2_nlToBr(lines_rtrim(msgs))))) + tr(td_valignTop("Choose a user name:") + td_valignTop(hinputfield("user", user) + "
" + "(Minimum length 4. Characters allowed: a-z, 0-9, - and .)")) + tr(td_valignTop("Choose a password:") + td_valignTop(hpassword("f_pw", pw) + "
" + "(Minimum length 6 characters)")) + tr(td_valignTop("Repeat the password please:") + td(hpassword("pw2", pw2))) + tr(td_valignTop("Way to contact you (e.g. e-mail) - optional:") + td(hinputfield("contact", contact))) + tr(td() + td(hsubmit("Register"))), "class", "responstable"), "action", baseLink + "/register")))); } public boolean calcMasterAuthed(Req req) { return super.calcMasterAuthed(req) || req.auth != null && req.auth.user.has() && req.auth.user.get().isMaster; } public Object serveOtherPage(Req req) { String uri = req.uri; Matches m = new Matches(); if (eq(uri, "/register")) return serveRegisterForm(req.params); if (eq(uri, "/becomeMaster") && req.auth != null && req.auth.user != null) { String pw = trim(req.params.get("masterPW")); if (eq(pw, realPW())) { cset(req.auth.user, "isMaster", true); return "You are master, " + req.auth.user + "!"; } if (nempty(pw)) return "Bad master PW"; return hhtml(hhead(htitle("Become master") + hsansserif() + hmobilefix() + hresponstable()) + hbody(hfullcenter(h3_htmlEncode(adminName + " | Become master") + hpostform(tag("table", tr(td_valignTop("You are:") + td_valignTop(htmlEncode2(req.auth.user.get().name))) + tr(td_valignTop("Enter the master password:") + td_valignTop(hpassword("masterPW", pw))) + tr(td() + td(hsubmit("Become master user"))), "class", "responstable"), "action", baseLink + "/becomeMaster")))); } if (swic(uri, "/text/", m)) { long id = parseLong(m.rest()); UserPost post = getConceptOpt(UserPost.class, id); if (post == null) return serve404("Post with ID " + id + " not found"); if (!post.isPublic) return serve404("Post is not public"); String ct = req.params.get("ct"); Object response = nempty(ct) ? serveWithContentType(post.text(), ct) : serveText(post.text()); if (eq(ct, "text/javascript")) addHeader("Service-Worker-Allowed", "/", response); return response; } if (swic(uri, "/postRefs/", m)) { long id = parseLong(m.rest()); UserPost post = getConceptOpt(UserPost.class, id); if (post == null) return serve404("Post with ID " + id + " not found"); if (!post.isPublic) return serve404("Post is not public"); return serveJSON(lmap(__139 -> conceptID(__139), post.postRefs)); } if (swic(uri, "/postRefsWithTags/", m)) { long id = parseLong(m.rest()); UserPost post = getConceptOpt(UserPost.class, id); if (post == null) return serve404("Post with ID " + id + " not found"); if (!post.isPublic) return serve404("Post is not public"); return serveJSON(map(post.postRefsWithTags(), p -> litorderedmap("id", conceptID(p.a), "as", p.b))); } String uri2 = dropSlashPrefix(uri); if (isInteger(uri2)) { long id = parseLong(uri2); { var __5 = serveIntegerLink(req, id); if (__5 != null) return __5; } } { var __6 = serveOtherPage2(req); if (__6 != null) return __6; } return super.serveOtherPage(req); } static public boolean _switchableField_bot_maxPollSeconds = true; public double bot_maxPollSeconds = 600; static public boolean _switchableField_bot_pollInterval = true; public int bot_pollInterval = 500; public Class defaultCRUDClass() { return Sequence.class; } public Object serveOtherPage2(Req req) { Matches m = new Matches(); String uri = dropTrailingSlashIfNemptyAfterwards(req.uri); if (eq(uri, "/admin")) return hrefresh(baseLink + "/crud/" + shortClassName(defaultCRUDClass())); if (eq(uri, "/latestPost")) { UserPost post = highestConceptByField(UserPost.class, "created"); if (post == null) return serve404("No posts in database"); return servePost(post, req); } if (eq(uri, "/latestModifiedPost")) { UserPost post = highestConceptByField(UserPost.class, "_modified"); if (post == null) return serve404("No posts in database"); return servePost(post, req); } if (eq(uri, "/rootPosts")) { Collection posts = sortedByConceptIDDesc(filter(list(UserPost.class), post -> empty(post.postRefs))); framer().navBeforeTitle = true; framer().title = "Root Posts"; framer().add(ul(lmap(__200 -> postToHTMLWithDate(__200), posts))); return framer().render(); } if (eq(uri, "/allPosts")) { Collection posts = sortedByConceptIDDesc(list(UserPost.class)); framer().navBeforeTitle = true; framer().title = "All Posts"; framer().add(ul(lmap(__201 -> postToHTMLWithDate(__201), posts))); return framer().render(); } if (eq(uri, "/latestPosts")) { Collection posts = takeFirst(50, sortedByConceptIDDesc(list(UserPost.class))); framer().navBeforeTitle = true; framer().title = "Latest Posts & Replies"; framer().add(ul(lmap(__202 -> postToHTMLWithDate(__202), posts))); return framer().render(); } if (eq(uri, "/latestModifiedPosts")) { Collection posts = takeFirst(50, sortedByFieldDesc("_modified", list(UserPost.class))); framer().navBeforeTitle = true; framer().title = "Latest Modified Posts & Replies"; framer().add(ul(lmap(__203 -> postToHTMLWithDate(__203), posts))); return framer().render(); } if (eq(uri, "/mainPosts")) { Collection posts = takeFirst(50, sortedByConceptID(conceptsWhereCI(UserPost.class, "type", "Main"))); framer().navBeforeTitle = true; framer().title = "Main Posts"; framer().add(ul(lmap(__204 -> postToHTMLWithDate(__204), posts))); return framer().render(); } if (swic(uri, "/html/", m) && isInteger(m.rest())) { long id = parseLong(m.rest()); return serveHTMLPost(id); } if (swic(uri, "/htmlEmbedded/", m) && isInteger(m.rest())) { long id = parseLong(m.rest()); UserPost post = getConcept(UserPost.class, id); if (post == null) return serve404("Post not found"); HTMLFramer1 framer = framer(); framer.title = "[" + post.id + "] " + or2(post.title, shorten(post.text)); framer.add(hcomment("Post begins here") + "\n" + post.text + "\n" + hcomment("Post ends here")); return framer.render(); } if (swic(uri, "/css/", m) && isInteger(m.rest())) { long id = parseLong(m.rest()); UserPost post = getConcept(UserPost.class, id); if (post == null) return serve404("Post not found"); return serveWithContentType(post.text, "text/css"); } if (eq(uri, "/search")) { framer().navBeforeTitle = true; String q = trim(req.params.get("q")); framer().title = joinNemptiesWithColon("Search", q); framer().add(hcomment("cookie: " + req.webRequest.cookie())); framer().add(hform(hinputfield("q", q, "autofocus", true) + " " + hsubmit("Search"))); framer().add(p(small("Search help: If you search for multiple words, they can appear in any order in the text. An underscore matches any character. Plus means space. Post titles, texts and types are searched."))); if (nempty(q)) { ScoredSearcher searcher = new ScoredSearcher<>(q); long id = parseLongOpt_pcall(q); for (UserPost post : list(UserPost.class)) searcher.add(post, (post.id == id ? 4 : 0) + searcher.score(post.title) * 3 + searcher.score(post.text) * 2 + searcher.score(post.type) + searcher.score(joinWithSpace(post.postRefTags)) * 0.5); List posts = searcher.get(); framer().add(p(b(addPlusToCount(searcher.maxResults, l(posts), nPosts(posts)) + " found for " + htmlEncode2(q)))); framer().add(ul(lmap(__205 -> postToHTMLWithDate(__205), posts))); } return framer().render(); } if (eq(uri, "/jstree/replies")) { UserPost post = getConcept(UserPost.class, parseLong(req.params.get("post"))); if (post == null) return serveJSON(ll()); Collection refs = referencingPosts(post); return serveJSON(map(refs, p -> litorderedmap("id", p.id, "text", postToHTMLWithDate(post), "children", nempty(referencingPosts(p)) ? true : null, "type", "root"))); } if (startsWith(uri, "/touchPost/", m)) { long id = parseLong(m.rest()); UserPost post = getConcept(UserPost.class, id); if (post == null) return serve404("Post not found"); if (!canEditPost(post)) return "You are not authorized to do this"; touchConcept(post); return hscript("setTimeout('history.go(-1)', 1000);") + "Post " + post.id + " touched"; } if (startsWith(uri, "/hidePost/", m)) { long id = parseLong(m.rest()); UserPost post = getConcept(UserPost.class, id); if (post == null) return serve404("Post not found"); if (!canEditPost(post)) return "You are not authorized to do this"; cset(post, "hidden", true); return hrefresh(postLink(post)); } if (startsWith(uri, "/unhidePost/", m)) { long id = parseLong(m.rest()); UserPost post = getConcept(UserPost.class, id); if (post == null) return serve404("Post not found"); if (!canEditPost(post)) return "You are not authorized to do this"; cset(post, "hidden", false); return hrefresh(postLink(post)); } if (startsWith(uri, "/markSafe/", m)) { long id = parseLong(m.rest()); UserPost post = getConcept(UserPost.class, id); if (post == null) return serve404("Post not found"); UserPost codePost = optCast(UserPost.class, first(post.postRefs)); if (codePost == null) return "Code post not found"; if (!canEditPost(codePost)) return "You are not authorized to do this"; uniqCI(UserPost.class, "creator", currentUser(), "text", "Mark safe", "postRefs", ll(post)); sleepSeconds(6); touchConcept(codePost); return hrefresh(postLink(codePost)); } if (eq(uri, "/mirrorAllConversations")) { if (!req.masterAuthed) return serveAuthForm(rawLink(uri)); for (Conversation c : list(Conversation.class)) rstUpdateMirrorPosts.add(c); return "OK"; } if (startsWith(uri, "/mirrorConversation/", m)) { if (!req.masterAuthed) return serveAuthForm(rawLink(uri)); long id = parseLong(m.rest()); Conversation conv = getConcept(Conversation.class, id); if (conv == null) return "Conversation not found"; conv.updateMirrorPost(); return "Mirror post updated (" + htmlEncode2(str(conv.mirrorPost.get())) + ")"; } if (eqic(uri, "/favicon.ico")) return serveFavIcon(); if (startsWith(uri, "/bot/", m)) { req.subURI = m.rest(); String json = req.params.get("json"); Map data = new HashMap(); if (nempty(json)) data = jsonDecodeMap(json); data.putAll(withoutKey("json", req.params)); User user; String userName = (String) (data.get("_user")); if (nempty(userName)) { String botToken = (String) (data.get("_botToken")); if (botToken == null) return serveJSON("error", "Need _botToken"); user = conceptWhereIC(User.class, "name", userName); if (user == null) return serveJSON("error", "User not found"); if (!eq(botToken, getVar(user.botToken))) return serveJSON("error", "Wrong bot token"); } else user = user(req); String function = beforeSlashOrAll(req.subURI); req.subURI = substring(req.subURI, l(function) + 1); req.webRequest.noSpam(); { var __175 = servePossiblyUserlessBotFunction(req, function, data, user); if (__175 != null) return __175; } if (user == null) return serveJSON("error", "Need _user"); if (eq(function, "getCookie")) return serveJSON("cookie", req.cookie()); if (eq(function, "authTest")) return serveJSON("status", "You are authorized as " + user.name + " " + roundBracket(user.isMaster ? "master user" : "non-master user")); if (eq(function, "postCount")) return serveJSON("result", countConcepts(UserPost.class)); if (eq(function, "listPosts")) { List fields = unnull(stringToStringListOpt(__206 -> tok_identifiersInOrder(__206), data.get("fields"))); if (!fields.contains("id")) fields.add(0, "id"); long changedAfter = toLong(data.get("changedAfter")); long repliesTo = toLong(data.get("repliesTo")); double pollFor = min(bot_maxPollSeconds, toLong(data.get("pollFor"))); long startTime = sysNow(); if (changedAfter > 0 && changedAfter == now()) sleep(1); Collection posts; while (true) { if (repliesTo != 0) { posts = referencingPosts(getConcept(UserPost.class, repliesTo)); if (changedAfter != 0) posts = objectsWhereFieldGreaterThan(posts, "_modified", changedAfter); } else { posts = changedAfter == 0 ? list(UserPost.class) : conceptsWithFieldGreaterThan_sorted(UserPost.class, "_modified", changedAfter); } if (nempty(posts) || pollFor == 0 || elapsedSeconds_sysNow(startTime) >= pollFor) return serveJSON_breakAtLevels(2, "result", map(posts, post -> mapToValues(fields, field -> getPostFieldForBot(post, field)))); sleep(bot_pollInterval); } } if (eq(function, "createPost")) { Either e = createPostArgs(user, data); if (e.isB()) return serveJSON("error", e.b()); Pair post = uniq2(UserPost.class, e.a()); if (!post.b) post.a.bump(); return serveJSON("status", post.b ? "Post created" : "Post existed already, bumped", "postID", post.a.id); } if (eq(function, "editPost")) { long postID = toLong(data.get("postID")); UserPost post = getConcept(UserPost.class, postID); if (post == null) return serveJSON("error", "Post " + postID + " not found"); Either e = createPostArgs(user, data); if (e.isB()) return serveJSON("error", e.b()); int changes = cset(post, e.a()); return serveJSON(changes > 0 ? "Post updated" : "Post updated, no changes", "postID", postID); } if (eq(function, "deletePosts")) { List ids = allToLong(tok_integersInOrder((String) data.get("ids"))); List results = new ArrayList(); List errors = new ArrayList(); for (long id : unnullForIteration(ids)) { UserPost post = getConceptOpt(UserPost.class, id); if (post == null) errors.add("Post " + id + " not found"); else { if (!user.isMaster && neq(post.creator.get(), user)) errors.add("Can't delete post " + id + " from other user"); else { deletePost(post); results.add("Post " + id + " deleted"); } } } return serveJSON(litorderedmap("results", results, "errors", errors)); } return serveBotFunction(req, function, data, user); } if (teamPostID != 0 && eq(uri, "/team")) return serveHTMLPost(teamPostID); if (startsWith(uri, "/history/", m)) { long id = parseLong(m.rest()); UserPost post = getConcept(UserPost.class, id); if (post == null) return serve404("Post not found"); return servePostHistory(post); } if (startsWith(uri, "/htmlBot/", m)) { long id = parseLong(beforeSlashOrAll(m.rest())); UserPost post = getConcept(UserPost.class, id); if (post == null) return serve404("Post not found"); return doPost(htmlBotURLOnBotServer(id), req.params()); } if (eq(uri, "/deletedPosts")) { CloseableIterableIterator lines = linesFromFile(deletedPostsFile()); try { List posts = new ArrayList(); while (lines.hasNext()) { String line = lines.next(); if (isProperlyQuoted(line)) { Map map = safeUnstructureMap(unquote(line)); posts.add(onlyKeys(map, "id", "title", "type")); } } return serveText("Deleted posts:\n" + lines(lmap(__207 -> struct(__207), posts))); } finally { _close(lines); } } if (eq(uri, "/formToPost")) { User user = currentUser(); if (user == null) serve500("Please log in first"); Map params = cloneMap(req.params); String type = or2(getAndRemove(params, "_type"), "Form Input"); String title = getAndRemove(params, "_title"); List postRefs = map(id -> getConceptOpt(UserPost.class, parseLong(id)), tok_integersInOrder(getAndRemove(params, "_postRefs"))); List postRefTags = lines(getAndRemove(params, "_postRefTags")); String text = sortLinesAlphaNumIC(mapToLines(params, (k, v) -> urlencode(k) + "=" + urlencode(v))); Pair p = uniq2(UserPost.class, "creator", user, "text", text, "type", type, "title", title, "postRefs", postRefs, "postRefTags", postRefTags); return (p.b ? "Post " + p.a.id + " created" : "Post " + p.a.id + " exists") + hrefresh(2.0, "/" + p.a.id); } if (eq(uri, "/webPushSubscribe")) { Map data = jsonDecodeMap(mapGet(req.webRequest.files(), "postData")); printVars_str("webPushSubscribe", "data", data); cnew(WebPushSubscription.class, "data", data, "clientIP", req.webRequest.clientIP()); return serveJSON(litmap("message", "success")); } if (eq(uri, "/changePassword")) { if (!req.masterAuthed) return serveAuthForm(rawLink(uri)); String name = assertNempty(req.get("user")); String newPW = assertNempty(req.get("newPW")); User user = conceptWhereCI(User.class, "name", name); if (user == null) return "User not found"; cset(user, "passwordMD5", new SecretValue(hashPW(newPW))); return "PW updated"; } if (eq(uri, "/webPushNotify")) { if (!req.masterAuthed) return serveAuthForm(rawLink(uri)); String msg = or2(req.params.get("msg"), "Hello user. It is " + localTimeWithSeconds() + " on the server"); WebPushSubscription sub = getConcept(WebPushSubscription.class, toLong(req.params.get("webPushSubID"))); if (sub == null) return serve404("webPushSubID not found"); String mod = dm_require("#1030463/WebPushKeyManager"); dm_call(mod, "sendNotification", sub.data, msg); return "Push message sent"; } if (eq(uri, "/hashPW") && req.masterAuthed) return hashPW(req.params.get("pw")); return null; } public Object servePostHistory(UserPost post) { return serveText(unquoteAllLines(loadTextFile(postHistoryFile(post)))); } public Either createPostArgs(User user, Map data) { String text = (String) (data.get("text")); String type = (String) (data.get("type")); String title = (String) (data.get("title")); String botInfo = or2((String) data.get("botInfo"), "Made by bot"); List postRefTags = unnull(lines((String) data.get("refTags"))); List postRefs = new ArrayList(); Object _refs = data.get("refs"); if (_refs instanceof String) for (String s : tok_integersInOrder((String) _refs)) { UserPost ref = getConcept(UserPost.class, parseLong(s)); if (ref == null) return eitherB("Post " + s + " not found"); postRefs.add(ref); } if (empty(text) && empty(title)) return eitherB("Need either a text or a title"); boolean isPublic = eqOneOf(data.get("isPublic"), null, true, "1", "t", "true"); return eitherA(litparams("creator", user, "text", text, "type", type, "title", title, "isPublic", isPublic, "botInfo", botInfo, "postRefs", postRefs, "postRefTags", postRefTags)); } public Object serveBotFunction(Req req, String function, Map data, User user) { return serveJSON("error", "You are logged in correctly but function is unknown: " + function); } public Object servePossiblyUserlessBotFunction(Req req, String function, Map data, User user) { return null; } public Object servePost(UserPost post, Req req) { if (!post.isPublic) return serve404("Post is not public"); HTMLFramer1 framer = framer(); framer.add(hjs("webSocketQuery = " + jsQuote("?objectID=" + post.id + "&modified=" + post.xmodified) + ";\n" + "if (ws != null) ws.url = ws.url.split(\"?\")[0] + webSocketQuery;")); framer.title = "[" + post.id + "] " + or2(post.title, shorten(post.text)); framer.add(p("By " + htmlEncode2(post.author()) + ". " + renderConceptDate(post))); if (nempty(post.type)) framer.add(p("Post type: " + htmlEncode2(post.type))); List actions = new ArrayList(); if (eqic(post.type, "HTML")) actions.add(targetBlank("/html/" + post.id, "Show as HTML page")); if (eqic(post.type, "HTML (embedded)")) actions.add(targetBlank("/htmlEmbedded/" + post.id, "Show as HTML page")); if (eqicOneOf(post.type, "JavaX Code (HTML Bot)", "JavaX Code (Live Home Page)")) actions.add(targetBlank(htmlBotURL(post.id), "Show as HTML page")); if (eqic(post.type, "Conversation HTML")) actions.add(targetBlank("/demo?cookie=htmlDemo&_autoOpenBot=1&chatContentsPost=" + post.id, "Show in chat box")); if (canEditPost(post)) { actions.add(ahref(conceptEditLink(post), "Edit post")); actions.add(ahref(touchLink(post), "Touch post")); actions.add(post.hidden ? ahref(unhideLink(post), "Unhide post") : ahref(hideLink(post), "Hide post")); } actions.add(ahref(replyLink(post), "Reply")); actions.add(ahref(conceptDuplicateLink(post), "Duplicate")); actions.add(ahref(conceptEditLink(post, "onlyFields", "title"), "Rename")); if (postHasHistory(post)) actions.add(ahref("/history/" + post.id, "History")); actions.add(ahref(baseLink + "/text/" + post.id, "Raw Text")); if (post.isJavaXCode()) { actions.add(targetBlank(simulateBotLink(post), "Talk to this bot")); actions.add(ahref(gazelleBotURL + "/transpilation/" + post.id, "Show Java transpilation")); } framer.add(p_vbar(actions)); List postRefs = cloneList(post.postRefs); if (nempty(postRefs)) { framer.add(p("In reference to:")); List> l = post.postRefsWithTags(); framer.add(ul(mapPairsToList(l, (ref, as) -> htmlEncode2(as) + " " + objectToHTML(ref)))); } String text = post.text; String html = null; if (post.isJavaXCode()) { try { JavaXHyperlinker hl = new JavaXHyperlinker(); hl.targetBlank = true; html = hl.codeToHTML(text); } catch (Throwable __e) { pcallFail(__e); } } if (html == null) html = htmlEncodeWithLinking(post.text); if (eq(req.params.get("showLineFeeds"), "1")) html = html_showLineFeedsForPRE(html); framer.add(div(sourceCodeToHTML_noEncode(html), "style", hstyle_sourceCodeLikeInRepo())); Collection refs = referencingPosts(post); refs = reversed(refs); Pair, List> p = filterAntiFilter(refs, post2 -> !post2.hidden); if (nempty(p.a)) { framer.add(p("Referenced by posts (latest first):")); UserPost latestCodeSafetyPost = highestBy(p2 -> p2.modifiedOrBumped(), filter(p.a, p2 -> eqic(p2.botInfo, "Code Safety Checker"))); framer.add(ul(map(p.a, p2 -> { String html2 = htmlEncode2(squareBracketIfNempty(getPostRefTag(p2, post))) + " " + objectToHTML(p2); if (p2 == latestCodeSafetyPost && cic(p2.text, "Unknown identifiers:")) html2 += " " + hbuttonLink("/markSafe/" + p2.id, htmlEncode2("Mark safe")); return html2; }))); } if (nempty(p.b)) { framer.add(p("Referenced by hidden posts:")); framer.add(ul(map(p.b, p2 -> htmlEncode2(squareBracketIfNempty(getPostRefTag(p2, post))) + " " + objectToHTML(p2)))); } if (showPostStats) { String stats = nLines(countLines(post.text)) + ", distance to user post: " + post.distanceToUserPost(); framer.add(p_alignRight(small(span_title(stats, "Post stats")))); } return framer.render(); } public String getPostRefTag(UserPost a, UserPost b) { return get(a.postRefTags, indexOf(a.postRefs, b)); } public String htmlEncodeWithLinking(String text) { String html = htmlEncode2(text); return regexpReplace(html, gazelle_postMentionRegexp(), matcher -> { UserPost post = getConceptOpt(UserPost.class, parseLong(matcher.group(1))); return post == null ? matcher.group() : ahref(postLink(post), matcher.group()); }); } public List referencingPosts(UserPost post) { return sortedByCalculatedField(p -> p.modifiedOrBumped(), instancesOf(UserPost.class, allBackRefs(post))); } public List referencingPostsWithTag(UserPost post, String tag) { return filter(referencingPosts(post), p -> eqic_unnull(getPostRefTag(p, post), tag)); } public String serveAuthForm(String redirect) { return hAddToHead(super.serveAuthForm(redirect), hInitWebSocket()); } public String authFormMoreContent() { return navDiv(); } public String navDiv() { return div_vbar(navLinks(), "style", "margin-bottom: 0.5em"); } public Object handleAuth(Req req, String cookie) { String name = trim(req.params.get("user")), pw = trim(req.params.get("pw")); if (nempty(name) && nempty(pw) && nempty(cookie)) { Domain authDomain; User user = findOrCreateUserForLogin(name, pw); if (user == null) return errorMsg("User " + htmlEncode2(name) + " not found"); if (!eq(getVar(user.passwordMD5), hashPW(pw))) return errorMsg("Bad password, please try again"); cset(uniq(AuthedDialogID.class, "cookie", cookie), "restrictedToDomain", null, "master", user.isMaster, "user", user); String redirect = req.params.get("redirect"); if (nempty(redirect)) return hrefresh(redirect); } return null; } public User findOrCreateUserForLogin(String name, String pw) { return conceptWhereCI(User.class, "name", name); } public Object serve2(Req req) { if (req.auth != null) { cset(req.auth, "userMode", false); if (req.auth.user.get() != null) cset(req.auth.user.get(), "lastSeen", now()); } return super.serve2(req); } public String hashPW(String pw) { if (nempty(salterService)) return assertMD5(postPage(salterService, "pw", pw)); else return md5(pw + passwordSalt()); } public Req currentReq() { return currentReq.get(); } final public boolean isMasterAuthed() { return inMasterMode(); } final public boolean masterAuthed() { return inMasterMode(); } public boolean inMasterMode() { return inMasterMode(currentReq()); } final public boolean isMasterAuthed(Req req) { return inMasterMode(req); } final public boolean masterAuthed(Req req) { return inMasterMode(req); } public boolean inMasterMode(Req req) { return req.masterAuthed && !(req.auth != null && req.auth.userMode); } public Map filtersForClass(Class c, Req req) { if (c == UserPost.class) { if (req.auth != null && !inMasterMode(req)) return litmap("creator", req.auth.user.get()); } return super.filtersForClass(c, req); } public String loggedInUserDesc_html(Req req) { if (req.auth == null) return ahref(loginLink(), "not logged in"); if (req.auth.user.get() == null) return req.masterAuthed ? "master user" : "anonymous user " + req.auth.id; return "user " + req.auth.user.get().name; } public String loginLink() { return baseLink + "/"; } public HCRUD_Concepts crudData(Class c, Req req) { HCRUD_Concepts cc = super.crudData(c, req); if (c == UserPost.class) { cc.useDynamicComboBoxes = true; cc.lsMagic = true; cc.itemName = () -> "Post"; cc.dropEmptyListValues = false; if (eq(req.params.get("noace"), "1")) cc.addRenderer("text", new HCRUD_Data.TextArea(80, 20)); else cc.addRenderer("text", new HCRUD_Data.AceEditor(80, 20)); cc.addRenderer("postRefTags", new HCRUD_Data.FlexibleLengthList(new HCRUD_Data.TextField(20))); cc.addRenderer("type", new HCRUD_Data.ComboBox(true, itemPlus("", userPostTypesByPopularity()))); cc.fieldHelp("type", "Type of post (any format, optional)", "title", "Title for this post (any format, optional)", "text", "Text contents of this post (any format)", "nameInRepo", "Name in repository (not really used yet)", "botInfo", "Info on which bot made this post (if any)"); cc.massageItemMapForList = (item, map) -> { applyFunctionToValue(__140 -> shorten(__140), map, "text", "title", "type", "nameInRepo"); List refs = ((UserPost) item).postRefs; map.put("postRefs", new HTML(joinWithBR(lmap(__141 -> objectToHTML(__141), refs)))); }; cc.getObject = id -> { Map map = cc.getObject_base(id); List refs = (List) (map.get("postRefs")); List tags = (List) (map.get("postRefTags")); print("counts:" + l(refs) + "/" + l(tags)); map.put("postRefTags", padList(tags, l(refs), "")); return map; }; cc.emptyObject = () -> { Map item = cc.emptyObject_base(); item.put("creator", req.auth.user.get()); return item; }; cc.getObjectForDuplication = id -> { Map item = cc.getObjectForDuplication_base(id); item.put("creator", req.auth.user.get()); UserPost post = getConcept(UserPost.class, toLong(id)); List postRefs = cloneList((List) item.get("postRefs")); List tags = cloneList((List) item.get("postRefTags")); for (int i = 0; i < l(tags); i++) if (eqic(tags.get(i), "created from")) { remove(postRefs, i); tags.remove(i--); } int idx = l(postRefs); postRefs.add(post); listSet(tags, idx, "created from"); item.put("postRefs", postRefs); item.put("postRefTags", tags); print("tags", tags); return item; }; cc.fieldsToHideInCreationForm = litset("hidden", "creating"); cc.lockDB = true; cc.afterUpdate = (post, oldValues) -> { Map newValues = cgetAll_cloneLists(post, keys(oldValues)); for (Map.Entry __0 : _entrySet(newValues)) { String field = __0.getKey(); Object newVal = __0.getValue(); Object oldVal = oldValues.get(field); if (eq(oldVal, newVal)) { printVars_str("field", field, "oldVal", oldVal); continue; } IF1 f = o -> o instanceof Concept ? ((Concept) o).id : null; Object oldValForLog = defaultMetaTransformer().transform(f, oldVal); Object newValForLog = defaultMetaTransformer().transform(f, newVal); Map logEntry = litorderedmap("date", now(), "field", field, "oldVal", oldValForLog, "newVal", newValForLog); printStruct("logEntry", logEntry); logStructure(postHistoryFile(((UserPost) post)), logEntry); } }; cc.actuallyDeleteConcept = post -> deletePost(((UserPost) post)); } return cc; } public HCRUD makeCRUD(Class c, Req req) { HCRUD crud = super.makeCRUD(c, req); if (c == UserPost.class) { crud.refreshAfterCommand = (params, msgs) -> { UserPost post = getConcept(UserPost.class, toLong(crud.objectIDToHighlight)); return post != null ? hrefresh(postLink(post)) : crud.refreshAfterCommand_base(params, msgs); }; crud.renderCmds = map -> { UserPost post = getConcept(UserPost.class, toLong(crud.itemID(map))); return joinNemptiesWithVBar(crud.renderCmds_base(map), ahref(postLink(post), "Show post"), ahref(touchLink(post), "Touch", "title", "Mark post as modified so it is looked at by bots again")); }; crud.uneditableFields = litset("xmodified", "creating", "bumped"); if (showSuggestorBot) crud.moreSelectizeOptions = name -> ", onChange: function() { console.log(\"selectize onChange\"); sugTrigger(); }"; crud.showQuickSaveButton = true; crud.massageFormMatrix = (map, matrix) -> { if (showSuggestorBot) { List entries = ((HCRUD_Concepts) crud.data).comboBoxItems(conceptsWhereIC(UserPost.class, "type", "JavaX Code (Post Edit Suggestor)")); String js = hscript(replaceVars("\r\n const suggestorSelector = $(\"[name=suggestorID]\");\r\n var sugLoading = false, sugTriggerAgain = false;\r\n\r\n function sugTrigger() {\r\n //console.log(\"sugTrigger\");\r\n if (sugLoading) { sugTriggerAgain = true; return; }\r\n\r\n const sugText = suggestorSelector.text();\r\n //console.log(\"sugText=\" + sugText);\r\n const sugMatch = sugText.match(/\\d+/);\r\n if (!sugMatch) {\r\n //$(\"#suggestorResult\").html(\"\");\r\n $(\"#suggestorResult\").hide();\r\n return;\r\n }\r\n const suggestorID = sugMatch[0];\r\n\r\n // get form data as JSON\r\n \r\n var data = {};\r\n $(suggestorSelector).closest(\"form\").serializeArray().map(function(x){data[x.name] = x.value;});\r\n const json = JSON.stringify(data);\r\n console.log(\"JSON: \" + json);\r\n \r\n const url = \"" + gazelleBotURL + "/chatBotReply/\" + suggestorID;\r\n console.log(\"Loading \" + url);\r\n sugLoading = true;\r\n $.post(url, {q : json},\r\n function(result) {\r\n console.log(\"Suggestor result: \" + result);\r\n const answer = !result ? \"\" : JSON.parse(result).answer;\r\n if (answer) {\r\n $(\"#suggestorResult .sectionContents\").html(answer);\r\n $(\"#suggestorResult\").show();\r\n } else\r\n $(\"#suggestorResult\").hide();\r\n //$(\"#suggestorResult\").html(answer ? \"Suggestor says: \" + answer : \"\");\r\n }\r\n ).always(function() {\r\n console.log(\"sug loading done\");\r\n setTimeout(function() {\r\n sugLoading = false;\r\n if (sugTriggerAgain) { sugTriggerAgain = false; sugTrigger(); }\r\n }, delayAfterSuggestion);\r\n });\r\n }\r\n\r\n $(document).ready(function() {\r\n $(\"input[type=text], input[type=hidden], textarea, select\").on('input propertychange change', sugTrigger);\r\n sugTrigger();\r\n });\r\n suggestorSelector.change(sugTrigger);\r\n ", "delayAfterSuggestion", delayAfterSuggestion)); long defaultSuggestor = parseFirstLong(userDefaults(req.auth.user.get()).get("Default Suggestor Bot")); String selectedSuggestor = firstWhereFirstLongIs(entries, defaultSuggestor); matrix.add(0, ll("Suggestor Bot", crud.addHelpText("Choose a bot to assist you in editing this post [feature in development]", p_alignRight(crud.renderComboBox("suggestorID", selectedSuggestor, entries, false))) + htitledSectionWithDiv("Suggestion", "", "id", "suggestorResult", "style", "display: none", "innerDivStyle", "max-height: 150px; overflow: auto") + js)); } }; crud.flexibleLengthListLeeway = 3; } if (c == User.class) { crud.allowCreate = false; } return crud; } public String authFormHeading() { return h3_htmlEncode("Welcome to the Gazelle AI System") + p(hsnippetimg_scaleToWidth(200, "#1101482", 425, 257, "title", "Gazelle")); } public void makeFramer(Req req) { super.makeFramer(req); req.framer.renderTitle = () -> h1(ahref(baseLink + "/", himgsnippet("#1102967", "style", "height: 1em; vertical-align: bottom", "title", "Gazelle.rocks Logo")) + " " + req.framer.encodedTitle()); req.framer.add(() -> navDiv()); if (showMetaBotOnEveryPage && !eq(req.params.get("_reloading"), "1")) req.framer.willRender.add(new Runnable() { public void run() { try { req.framer.add(hscript("var botConfig = \"codePost=" + defaultBotPost + "\"; ") + hjssrc(baseLink + "/script")); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "req.framer.add(hscript(\"var botConfig = \\\"codePost=\" + defaultBotPost + \"\\\"; ..."; } }); } public HTMLFramer1 framer() { return framer(currentReq.get()); } public HTMLFramer1 framer(Req req) { if (req.framer == null) makeFramer(req); return req.framer; } public String postLink(UserPost post) { return objectLink(post); } public String postLink(long postID) { return objectLink(getConcept(UserPost.class, postID)); } public String touchLink(UserPost post) { return baseLink + "/touchPost/" + post.id; } public String hideLink(UserPost post) { return baseLink + "/hidePost/" + post.id; } public String unhideLink(UserPost post) { return baseLink + "/unhidePost/" + post.id; } public String objectLink(Concept c) { return baseLink + "/" + c.id; } public String objectToHTML(Concept c) { return c == null ? "-" : ahref(objectLink(c), htmlEncode2(str(c))); } public String postToHTMLWithDate(UserPost post) { return post == null ? "" : objectToHTML(post) + " " + span(htmlEncode2(renderHowLongAgoPlusModified(post.created, post._modified)), "style", "color: #888"); } public boolean canEditPost(UserPost post) { User user = currentUser(); return user != null && (user.isMaster || user == post.creator.get()); } public User currentUser() { Req req = currentReq.get(); return req != null && req.auth != null ? req.auth.user.get() : null; } public String replyLink(UserPost post) { return appendQueryToURL(crudLink(UserPost.class), "cmd", "new", "fList_postRefs_0", post == null ? null : post.id); } public String newPostLink() { return replyLink(null); } public List navLinks(Object... __) { return gazelle_navLinks(baseLink, inlineSearch && !eq(currentReq.get().uri, "/search") ? "" : null, paramsPlus(__, "withTeam", teamPostID != 0)); } public List botCmdClasses() { return ll(); } public List crudClasses(Req req) { List l = super.crudClasses(req); l = listMinusSet(l, hiddenCrudClasses()); l.add(UserPost.class); l.add(UploadedImage.class); if (req.masterAuthed) { l.add(User.class); } return l; } @Override public Collection cruddableClasses(Req req) { return addAllAndReturnCollection(super.cruddableClasses(req), WebPushSubscription.class); } public Set hiddenCrudClasses() { return litset(Lead.class, ConversationFeedback.class, Domain.class, UserKeyword.class, UploadedSound.class, Settings.class); } public Object getPostFieldForBot(UserPost post, String field) { if (eq(field, "creatorID")) return post.creator.get().id; if (eq(field, "creatorName")) return post.creator.get().name; if (eq(field, "creatorIsMaster")) return post.creator.get().isMaster; if (eq(field, "postRefs")) return lmap(__142 -> conceptID(__142), post.postRefs); return cget(post, field); } public void deletePost(UserPost post) { if (post == null) return; print("Deleting post " + post); Lock __2 = dbLock(); lock(__2); try { long filePos = l(deletedPostsFile()); logStructure(deletedPostsFile(), mapToValues(UserPost.fieldsToSaveOnDelete, field -> getPostFieldForBot(post, field))); for (Pair p : post.postRefsWithTags()) if (p.a instanceof UserPost) logStructure(deletedRepliesFile((UserPost) p.a), litorderedmap("tag", p.b, "id", post.id, "filePos", filePos, "type", post.type)); cdelete(post); } finally { unlock(__2); } } public File deletedPostsFile() { return programFile("deleted-posts.log"); } public Object serveHTMLPost(long id) { UserPost post = getConcept(UserPost.class, id); if (post == null) return serve404("Post " + id + " not found"); return post.text; } transient public ReliableSingleThread_Multi rstDistributePostChanges = new ReliableSingleThread_Multi<>(1000, __14 -> distributePostChanges_impl(__14)); public void distributePostChanges(UserPost post) { rstDistributePostChanges.add(post); } public void distributePostChanges_impl(UserPost post) { AutoCloseable __12 = enter(); try { String uri = "/" + post.id; for (Pair p : syncMapToPairs(webSockets)) { if (eq(p.b.uri, uri)) reloadBody(p.a); } if (eqic(post.type, "Line Labels")) { UserPost parent = post.primaryRefPost(); print("Line labels post " + post.id + ", parent=" + parent); updateLineLabels(parent); } } finally { _close(__12); } } public void updateLineLabels(UserPost post) { try { if (post == null || !eqic(post.type, "Detailed Conversation Mirror")) return; print("Looking at conversation mirror " + post.id + " - " + post.title); long convID = toLong(regexpFirstGroupIC("Conversation (\\d+) with details", post.title)); Conversation conv = getConcept(Conversation.class, convID); if (conv == null) return; print("updateLineLabels " + convID + " / " + post.id); MultiMap, String> labels = new MultiMap(); for (UserPost p : referencingPostsWithTag(post, "")) if (eqic(p.type, "Line Labels")) { try { Map map = safeUnstructMapAllowingClasses(p.text(), Pair.class); print("Got labels map: " + map); putAll(labels, map); } catch (Throwable __e) { pcallFail(__e); } } boolean change = false; for (Msg msg : cloneList(conv.msgs)) { List lbls = uniquifyAndSortAlphaNum(allToUpper(labels.get(pair(msg.time, msg.text)))); if (nempty(lbls)) print("Got labels: " + lbls); if (!eq(msg.labels, lbls)) { msg.labels = lbls; change = true; } } if (change) conv.incReloadCounter(); } catch (Throwable __e) { pcallFail(__e); } } public void reloadBody(Object ws) { print("Reloading body through WebSocket"); String jsCode = " {\r\n const loc = new URL(document.location);\r\n const params = new URLSearchParams(loc.search);\r\n params.set('_reloading', '1');\r\n loc.search = params;\r\n console.log(\"Getting: \" + loc);\r\n $.get(loc, function(html) {\r\n var bodyHtml = /([\\s\\S]*)<\\/body>/.exec(html)[1];\r\n if (bodyHtml) {\r\n //$(\"body\").html(bodyHtml);\r\n $('body > *:not(.chatbot)').remove();\r\n $(\"body\").prepend(bodyHtml);\r\n }\r\n });\r\n } "; dm_call(ws, "send", jsonEncode(litmap("eval", jsCode))); } transient public ReliableSingleThread_Multi rstDistributeDivChanges = new ReliableSingleThread_Multi<>(1000, __15 -> distributeDivChanges_impl(__15), new F0() { public AutoCloseable get() { try { return enter(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return enter();"; } }); public void distributeDivChanges(String contentDesc) { rstDistributeDivChanges.add(contentDesc); } public void distributeDivChanges_impl(String contentDesc) { AutoCloseable __13 = enter(); try { String content = null; for (Pair p : syncMapToPairs(webSockets)) { for (String div : asForPairsWithB(p.b.liveDivs, contentDesc)) { if (content == null) content = calcDivContent(contentDesc); if (content == null) { print("No content for " + contentDesc); return; } reloadDiv(p.a, div, content); } } } finally { _close(__13); } } public void reloadDiv(Object ws, String div, String content) { String jsCode = replaceDollarVars(" $(\"#\" + $div).html($content);", "div", jsQuote(div), "content", jsQuote(content)); dm_call(ws, "send", jsonEncode(litmap("eval", jsCode))); } public String calcDivContent(String contentDesc) { if (eq(contentDesc, "postCount")) return nPosts(countConcepts(UserPost.class)); if (eq(contentDesc, "webRequestsRightHemi")) return n2(requestsServed); if (eq(contentDesc, "serverLoadRightHemi")) return formatDoubleX(systemLoad, 1); if (eq(contentDesc, "memRightHemi")) return str_toM(processSize); return null; } public int countUserPosts() { return countConcepts(UserPost.class, "botInfo", null) + countConcepts(UserPost.class, "botInfo", ""); } public int countBotPosts() { return countConcepts(UserPost.class) - countUserPosts(); } public Collection allUserPosts() { return filter(list(UserPost.class), p -> !p.isBotPost()); } public List userPostTypesByPopularity() { return listToTopTenCI(map(allUserPosts(), p -> p.type)); } public void startMainScript(Conversation conv) { UserPost post = getConceptOpt(UserPost.class, parseLong(mapGet(conv.botConfig, "codePost"))); if (post != null) { CustomBotStep step = uniq(CustomBotStep.class, "codePostID", post.id); if (executeStep(step, conv)) nextStep(conv); } else super.startMainScript(conv); } public String simulateBotLink(UserPost post) { return appendQueryToURL(baseLink + "/demo", "_botConfig", makePostData("codePost", post.id), "_newConvCookie", 1, "_autoOpenBot", 1); } @Override public boolean isRequestFromBot(Req req) { return startsWith(req.uri, "/bot/"); } public User internalUser() { return uniqCI(User.class, "name", "internal"); } transient public ReliableSingleThread_Multi rstUpdateMirrorPosts = new ReliableSingleThread_Multi<>(100, c -> c.updateMirrorPost()); public File postHistoryFile(UserPost post) { return programFile("Post Histories/" + post.id + ".log"); } public boolean postHasHistory(UserPost post) { return fileNempty(postHistoryFile(post)); } public File deletedRepliesFile(UserPost post) { return programFile("Deleted Replies/" + post.id + ".log"); } public String makeClassNavItem(Class c, Req req) { String html = super.makeClassNavItem(c, req); if (c == UserPost.class) { int count1 = countUserPosts(), count2 = countBotPosts(); if (count1 != 0 || count2 != 0) html += " " + roundBracket(n2(count1) + " from users, " + n2(count2) + " from bots"); } return html; } @Override public String modifyTemplateBeforeDelivery(String html, Req req) { String contentsPostID = req.params.get("chatContentsPost"); if (nempty(contentsPostID)) { html = html.replace("#N#", "99999"); html = html.replace("chatBot_interval = 1000", "chatBot_interval = 3600*1000"); html = html.replace("#INCREMENTALURL#", baseLink + "/text/" + contentsPostID + "?"); } return html; } public String headingForReq(Req req) { String codePost = decodeHQuery(req.params.get("_botConfig")).get("codePost"); if (nempty(codePost)) { UserPost post = getConcept(UserPost.class, parseLong(codePost)); return post == null ? null : post.title; } return null; } public UserPost homePagePost() { return firstThat(p -> p.isMasterMade(), conceptsWhereIC(UserPost.class, "type", "JavaX Code (Live Home Page)")); } public Object serveHomePage() { try { UserPost post = homePagePost(); if (post != null) return loadPage(htmlBotURLOnBotServer(post.id)); } catch (Throwable __e) { pcallFail(__e); } return null; } public String callHtmlBot(long id, Map params) { return id == 0 ? "" : doPost(htmlBotURLOnBotServer(id), params); } public String callHtmlBot_dropMadeByComment(long id, Map params) { return regexpReplace_direct(callHtmlBot(id, params), "^\n", ""); } public String htmlBotURL(long postID) { return baseLink + "/htmlBot/" + postID; } public String htmlBotURLOnBotServer(long postID) { return gazelleBotURL + "/htmlBot/" + postID; } public UserPost userDefaultsPost(User user) { return conceptWhereIC(UserPost.class, "creator", user, "type", "My Defaults"); } public Map userDefaults(User user) { UserPost post = userDefaultsPost(user); return post == null ? emptyMap() : parseColonPropertyCIMap(post.text); } public double favIconCacheHours() { return 24; } public Object favIconHeaders(Object response) { call(response, "addHeader", "Cache-Control", "public, max-age=" + iround(hoursToSeconds(favIconCacheHours()))); return response; } public Object serveFavIcon() { if (favIconID != 0) { UploadedFile f = getConcept(UploadedFile.class, favIconID); if (f != null) return favIconHeaders(subBot_serveFile(f.theFile(), faviconMimeType())); } return favIconHeaders(subBot_serveFile(loadLibrary(defaultFavIconSnippet), faviconMimeType())); } public String cssURL() { return gazelle_textURL(parseLong(cssID)); } public String getText(long postID) { UserPost post = getConcept(UserPost.class, postID); return post == null ? null : post.text(); } @Override public void addThingsAboveCRUDTable(Req req, Class c, List aboveTable) { if (c == User.class) aboveTable.add(p(ahref(baseLink + "/register", "Register new user"))); } public User user(Req req) { if (req == null) return null; AuthedDialogID auth = req.auth; return auth == null ? null : auth.user(); } public Object serveIntegerLink(Req req, long id) { UserPost post = getConceptOpt(UserPost.class, id); if (post == null) return null; return servePost(post, req); } public void onNewWebSocket(WebSocketInfo ws) { } public void onWebSocketClose(WebSocketInfo ws) { ws.callCloseHandlers(); } public String cookieFromWebRequest(IWebRequest req) { if (req == null) return null; { String __4 = req.cookie(); if (!empty(__4)) return __4; } return afterLastEquals(req.headers().get("cookie")); } public void makeMaster() { var users = listMinus(list(User.class), internalUser()); if (empty(users)) { infoMessage("Please first register a user in the web interface!"); return; } ShowComboBoxForm cb = new ShowComboBoxForm(); cb.desc = "Select user to upgrade"; cb.itemDesc = "User to make master"; cb.items = map(users, user -> user.id + " " + user.name); cb.action = user -> { startThread(new Runnable() { public void run() { try { enter(); long userID = parseFirstLong(user); User userObj = getConcept(User.class, userID); printVars("user", user, "userID", userID, "userObj", userObj); makeMaster(userObj); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "enter();\r\n long userID = parseFirstLong(user);\r\n User userObj = get..."; } }); }; cb.show(); } public void makeMaster(User user) { if (user == null) return; if (!swingConfirm("Turn " + user + " into a master user?")) return; cset(user, "isMaster", true); infoMessage(user + " is now my master!!"); } public Object[] popDownButtonEntries() { return objectArrayPlus(super.popDownButtonEntries(), "Make master user...", runnableThread(new Runnable() { public void run() { try { AutoCloseable __17 = enter(); try { makeMaster(); } finally { _close(__17); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter(); makeMaster();"; } })); } } static public class CustomBotStep extends BotStep implements IInputHandler { public long codePostID; public String toString() { return "CustomBotStep " + codePostID; } public boolean run(Conversation conv) { String answer; try { Map result = (Map) (postJSONPage(replyURL(), "initial", 1, "cookie", conv.cookie)); answer = (String) result.get("answer"); } catch (Throwable e) { printStackTrace(e); answer = "Error: " + e.getMessage(); } conv.add(new Msg(false, answer)); cset(conv, "inputHandler", this); return false; } public String replyURL() { return ((DynGazelleRocks) botMod()).gazelleBotURL + "/chatBotReply/" + codePostID; } public boolean handleInput(String s, Conversation conv) { String answer; try { Map result = (Map) (postJSONPage(replyURL(), "q", s, "cookie", conv.cookie)); answer = (String) result.get("answer"); } catch (Throwable e) { printStackTrace(e); answer = "Error: " + e.getMessage(); } conv.add(new Msg(false, answer)); return true; } } static public String userName(User user) { return user != null ? user.name : "?"; } static public class WebPushSubscription extends Concept { public String clientIP; public Map data; } 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 Symbol implements CharSequence { public String text; public Symbol() { } public Symbol(String text, boolean dummy) { this.text = text; } public int hashCode() { return _hashCode(text); } public String toString() { return text; } public boolean equals(Object o) { return this == o; } public int length() { return text.length(); } public char charAt(int index) { return text.charAt(index); } public CharSequence subSequence(int start, int end) { return text.substring(start, end); } } static public class 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 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 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 interface IContentsIndexedList extends List { public int[] indicesOf(A o); } 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); } } static public class ConceptShadow { public Map map; public ConceptShadow(Concept c) { map = conceptShadow_rawMap(c); map = toSortedArrayBasedMap(mapValues(__143 -> convertValue(__143), map)); } public Object convertValue(Object o) { if (o instanceof Concept.Ref) return conceptIDObject(((Concept.Ref) o).get()); if (o instanceof Concept.RefL) return lmap(__144 -> conceptIDObject(__144), (List) o); if (o instanceof Concept) return new ConceptID((Concept) o); return o; } public String toString() { return "ConceptShadow " + map; } public Object get(Object key) { return mapGet(map, key); } public boolean equals(Object o) { if (o instanceof ConceptShadow) return eq(map, ((ConceptShadow) o).map); return false; } public int hashCode() { return _hashCode(map); } public long id() { return toLong(get("id")); } } 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 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 HTMLPaginator { public String startParam = "start"; public String baseLink; public int start, step = 50; public int max; public void processParams(Map params) { start = parseInt(mapGet(params, startParam)); } public String renderNav(Object... __) { return pageNav2(baseLink, max, start, step, startParam, __); } public IntRange visibleRange() { return intRange(start, min(max, start + step)); } } 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 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 RealmCopy { public Object dest = mc(); public IdentityHashMap seen = new IdentityHashMap(); public HashMap classMap = new HashMap(); public HashMap> fieldsForClass = new HashMap(); public boolean fullCopy = false; public boolean nonTransientOnly = false; public boolean handleEnclosingInstancesProperly = false; public VStack.Computable copyComputation(Object o) { return new CopyObject(o); } public Object copy(Object o) { return evalInVStack(copyComputation(o)); } public class CopyObject extends VStackComputableWithStep implements IFieldsToList { public Object o; public CopyObject() { } public CopyObject(Object o) { this.o = o; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + o + ")"; } public Object[] _fieldsToList() { return new Object[] { o }; } public void step(VStack stack) { if (o == null || o instanceof String || o instanceof Number) { { stack._return(o); return; } } Object oo = seen.get(o); if (oo != null) stack._return(oo); dispatchByType(stack, o); } } public void dispatchByType(VStack stack, Object o) { if (o instanceof Object[]) { stack.replace(new CopyObjectArray((Object[]) o)); return; } if (o instanceof Collection) if (!overrideCollectionOrMapCopy((Collection) o)) { stack.replace(new CopyCollection((Collection) o)); return; } if (o instanceof Map) if (!overrideCollectionOrMapCopy((Map) o)) { stack.replace(new CopyMap((Map) o)); return; } { stack.replace(new CopyObjectFieldByField(o)); return; } } public class CopyObjectArray extends VStackComputableWithStep implements IFieldsToList { public Object[] o; public CopyObjectArray() { } public CopyObjectArray(Object[] o) { this.o = o; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + o + ")"; } public Object[] _fieldsToList() { return new Object[] { o }; } public Object[] out; public int i; public void step(VStack stack) { if (step == 0) { out = newObjectArrayOfSameType(o); seen.put(o, out); ++step; } if (stack.hasSubResult()) out[i++] = stack.subResult(); if (i >= o.length) { stack._return(out); return; } stack.call(new CopyObject(o[i])); } } public class CopyCollection extends VStackComputableWithStep implements IFieldsToList { public Collection o; public CopyCollection() { } public CopyCollection(Collection o) { this.o = o; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + o + ")"; } public Object[] _fieldsToList() { return new Object[] { o }; } public Collection out; public Iterator it; public void step(VStack stack) { if (step == 0) { out = similarEmptyCollection(o); seen.put(o, out); it = iterator(o); ++step; } if (stack.hasSubResult()) out.add(stack.subResult()); if (!it.hasNext()) { stack._return(out); return; } stack.call(new CopyObject(it.next())); } } public class CopyMap extends VStackComputableWithStep implements IFieldsToList { public Map o; public CopyMap() { } public CopyMap(Map o) { this.o = o; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + o + ")"; } public Object[] _fieldsToList() { return new Object[] { o }; } public Map out; public Iterator it; public Map.Entry entry; public Object copiedKey; public void step(VStack stack) { if (step == 0) { out = similarEmptyMap(o); seen.put(o, out); it = iterator(o.entrySet()); ++step; } if (stack.hasSubResult()) { if (step == 1) { copiedKey = stack.subResult(); stack.call(new CopyObject(entry.getValue())); { ++step; return; } } else { out.put(copiedKey, stack.subResult()); step = 1; } } if (!it.hasNext()) { stack._return(out); return; } entry = it.next(); stack.call(new CopyObject(entry.getKey())); } } public class CopyObjectFieldByField extends VStackComputableWithStep implements IFieldsToList { public Object o; public CopyObjectFieldByField() { } public CopyObjectFieldByField(Object o) { this.o = o; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + o + ")"; } public Object[] _fieldsToList() { return new Object[] { o }; } public String className; public Class c, destClass; public Object out; public Object enclosing; public List fields; public Iterator itField; public Field field; public Field[] enclosingFields; public void step(VStack stack) { if (step == 0) { c = o.getClass(); destClass = classMap.get(c); if (destClass == null) { destClass = findDestClass(c); classMap.put(c, destClass); } if (destClass == c && !fullCopy) { stack._return(o); return; } enclosingFields = thisDollarOneFields(c); if (handleEnclosingInstancesProperly && nempty(enclosingFields)) stack.push(new CopyObject(fieldGet(first(enclosingFields), o))); { step = 1; return; } } else if (step == 1) { try { if (stack.hasSubResult()) out = unlisted_gen(destClass, stack.subResult()); else if (nempty(enclosingFields)) out = unlisted_gen(destClass, (Object) null); else out = unlisted_gen(destClass); } catch (Throwable _e) { printVars_str("c", c, "destClass", destClass, "enclosingFields", enclosingFields); throw rethrow(_e); } seen.put(o, out); fields = getOrCreate(fieldsForClass, c, () -> nonTransientOnly ? nonStaticNonTransientFieldObjects(o) : nonStaticFieldObjects(o)); itField = iterator(fields); { ++step; return; } } if (stack.hasSubResult()) { setOpt(out, field.getName(), stack.subResult()); } if (!itField.hasNext()) { stack._return(out); return; } field = itField.next(); stack.push(new CopyObject(fieldGet(field, o))); } } public Class findDestClass(Class c) { Class destClass = null; String className = c.getName(); className = loadableUtilsClassNameToMain(className); if (!isAnonymousClassName(className)) destClass = getClass_vmName_withLoadableUtils(dest, className); return or(destClass, c); } transient public IF1 overrideCollectionOrMapCopy; public boolean overrideCollectionOrMapCopy(Object o) { return overrideCollectionOrMapCopy != null ? overrideCollectionOrMapCopy.get(o) : overrideCollectionOrMapCopy_base(o); } final public boolean overrideCollectionOrMapCopy_fallback(IF1 _f, Object o) { return _f != null ? _f.get(o) : overrideCollectionOrMapCopy_base(o); } public boolean overrideCollectionOrMapCopy_base(Object o) { return false; } } static public class CancelPoint implements AutoCloseable { volatile public boolean closed = false; public void close() { closed = true; } } static public class FieldIndicator implements IFieldsToList { public String field; public boolean forward = false; public FieldIndicator() { } public FieldIndicator(String field, boolean forward) { this.forward = forward; this.field = field; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + field + ", " + forward + ")"; } public boolean equals(Object o) { if (!(o instanceof FieldIndicator)) return false; FieldIndicator __1 = (FieldIndicator) o; return eq(field, __1.field) && eq(forward, __1.forward); } public int hashCode() { int h = 698778197; h = boostHashCombine(h, _hashCode(field)); h = boostHashCombine(h, _hashCode(forward)); return h; } public Object[] _fieldsToList() { return new Object[] { field, forward }; } } static public class LASValueDescriptor { public LASValueDescriptor() { } public boolean knownValue() { return false; } public Object value() { return null; } public Type type() { return javaClass(); } public Class javaClass() { return null; } public boolean javaClassIsExact() { return false; } public boolean canBeNull() { return true; } public boolean canFail() { return false; } public boolean willFail() { return false; } static public class Exact extends LASValueDescriptor implements IFieldsToList { public Class c; public boolean canBeNull = false; public Exact() { } public Exact(Class c, boolean canBeNull) { this.canBeNull = canBeNull; this.c = c; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + c + ", " + canBeNull + ")"; } public boolean equals(Object o) { if (!(o instanceof Exact)) return false; Exact __1 = (Exact) o; return eq(c, __1.c) && eq(canBeNull, __1.canBeNull); } public int hashCode() { int h = 67394271; h = boostHashCombine(h, _hashCode(c)); h = boostHashCombine(h, _hashCode(canBeNull)); return h; } public Object[] _fieldsToList() { return new Object[] { c, canBeNull }; } public Class javaClass() { return c; } public boolean javaClassIsExact() { return true; } public boolean canBeNull() { return canBeNull; } } static public class NonExact extends LASValueDescriptor implements IFieldsToList { public Class c; public boolean canBeNull = false; public NonExact() { } public NonExact(Class c, boolean canBeNull) { this.canBeNull = canBeNull; this.c = c; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + c + ", " + canBeNull + ")"; } public boolean equals(Object o) { if (!(o instanceof NonExact)) return false; NonExact __2 = (NonExact) o; return eq(c, __2.c) && eq(canBeNull, __2.canBeNull); } public int hashCode() { int h = 1445514322; h = boostHashCombine(h, _hashCode(c)); h = boostHashCombine(h, _hashCode(canBeNull)); return h; } public Object[] _fieldsToList() { return new Object[] { c, canBeNull }; } public Class javaClass() { return c; } public boolean javaClassIsExact() { return false; } public boolean canBeNull() { return canBeNull; } } static public class NonExactType extends LASValueDescriptor implements IFieldsToList { static final public String _fieldOrder = "type canBeNull"; public Type type; public boolean canBeNull = false; public NonExactType() { } public NonExactType(Type type, boolean canBeNull) { this.canBeNull = canBeNull; this.type = type; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + type + ", " + canBeNull + ")"; } public boolean equals(Object o) { if (!(o instanceof NonExactType)) return false; NonExactType __3 = (NonExactType) o; return eq(type, __3.type) && eq(canBeNull, __3.canBeNull); } public int hashCode() { int h = 1099847340; h = boostHashCombine(h, _hashCode(type)); h = boostHashCombine(h, _hashCode(canBeNull)); return h; } public Object[] _fieldsToList() { return new Object[] { type, canBeNull }; } public Type type() { return type; } public boolean javaClassIsExact() { return false; } public boolean canBeNull() { return canBeNull; } } static public LASValueDescriptor nonExactCanBeNull(Type c) { return new NonExact(typeToClass(c), true); } static public class KnownValue extends LASValueDescriptor implements IFieldsToList { public Object value; public KnownValue() { } public KnownValue(Object value) { this.value = value; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + value + ")"; } public boolean equals(Object o) { if (!(o instanceof KnownValue)) return false; KnownValue __4 = (KnownValue) o; return eq(value, __4.value); } public int hashCode() { int h = -1456305138; h = boostHashCombine(h, _hashCode(value)); return h; } public Object[] _fieldsToList() { return new Object[] { value }; } public boolean knownValue() { return true; } public Object value() { return value; } public Class javaClass() { return value == null ? null : value.getClass(); } public boolean javaClassIsExact() { return value != null; } public boolean canBeNull() { return value == null; } } static public class WillFail extends LASValueDescriptor { public boolean canFail() { return true; } public boolean willFail() { return true; } } static public LASValueDescriptor fromClass(Class c) { return new NonExact(c, true); } public String toString() { return "LASValueDescriptor " + javaClass(); } } static public interface IMultiSet extends IntSize { public int add(A key); public int get(A key); public Set keySet(); } public interface IF0WithChangeListeners extends IF0, IHasChangeListeners { } 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 HTML implements IF0, IFieldsToList { public String html; public HTML() { } public HTML(String html) { this.html = html; } public boolean equals(Object o) { if (!(o instanceof HTML)) return false; HTML __1 = (HTML) o; return eq(html, __1.html); } public int hashCode() { int h = 2228139; h = boostHashCombine(h, _hashCode(html)); return h; } public Object[] _fieldsToList() { return new Object[] { html }; } public String get() { return html; } public String toString() { return html; } } 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); } } abstract static public class ConceptFieldIndexBase_certainValues implements IConceptIndex, IPartialFieldIndex { public Concepts concepts; public Class cc; public String field; public Map objectToValue = syncHashMap(); public MultiSetMap valueToObject; public ConceptFieldIndexBase_certainValues() { init(); } public ConceptFieldIndexBase_certainValues(Class cc, String field) { this(db_mainConcepts(), cc, field); } public ConceptFieldIndexBase_certainValues(Concepts concepts, Class cc, String field) { this(); this.field = field; this.cc = cc; this.concepts = concepts; concepts.addConceptIndex(this); for (A c : list(concepts, cc)) updateImpl(c); register(); } abstract public void init(); abstract public void register(); public abstract boolean isApplicableValue(Val value); 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); if (isApplicableValue(newValue)) { valueToObject.put(newValue, c); put(objectToValue, c, newValue); } else utils.remove(objectToValue, c); } 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 Collection getAllIfApplicable(Val value) { if (!isApplicableValue(value)) return null; return unnullForIteration(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; } } 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 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); } } static public class HTMLAceEditor implements Htmlable { public String text; public String name = "text"; public String id; public Map divParams = litmap("style", "width: 80ch; height: 20em"); public String onKeyDown; public HTMLAceEditor() { } public HTMLAceEditor(String text) { this.text = text; } public String headStuff() { return hscriptsrc("https://botcompany.de/ace-builds/src-noconflict/ace.js") + hscriptsrc("https://botcompany.de/ace-builds/src-noconflict/ext-language_tools.js"); } public String html() { id = "ace_" + name; return div(htmlEncode2(text), params_stylePlus("display: none", paramsPlus(mapToParams(divParams), "id", id))) + hhiddenWithIDAndName(name) + hscript(replaceDollarVars(" (function() {\r\n ace.require(\"ace/ext/language_tools\");\r\n var editor = ace.edit($id);\r\n editor.setTheme(\"ace/theme/ambience\");\r\n editor.getSession().setTabSize(2);\r\n editor.getSession().setUseSoftTabs(true);\r\n editor.getSession().setUseWrapMode(true);\r\n document.getElementById($id).style.fontSize='15px';\r\n editor.setOptions({\r\n enableBasicAutocompletion: true\r\n });\r\n \r\n var div = $(\"#\" + $id);\r\n var hiddenVal = document.getElementById($name);\r\n function updateHidden() {\r\n div.trigger('input'); // for auto-expand\r\n //hiddenVal.value = editor.getValue();\r\n var newVal = editor.getValue();\r\n if (hiddenVal.value != newVal)\r\n $(hiddenVal).val(newVal).trigger('change');\r\n }\r\n updateHidden();\r\n \r\n editor.session.on('change', updateHidden);\r\n $onKeyDown\r\n \r\n div.show();\r\n //editor.focus();\r\n })() ", "id", jsQuote(id), "name", jsQuote(name), "onKeyDown", empty(onKeyDown) ? "" : "editor.textInput.getElement().onkeydown = " + onKeyDown + ";")); } public String complete() { return linesLL(headStuff(), html()); } } 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(); 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() { return assertIdentifier(consume()); } public String consumeIdentifierOpt() { return isIdentifier(t()) ? consume() : 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; } } public interface IMultiMap { public Set keySet(); public Collection get(A a); public int size(); public int keyCount(); } 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 interface IRGBImage extends MakesBufferedImage { public int getIntPixel(int x, int y); } 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 interface ISetter { public void set(A a); } 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 }; } } abstract static public class HAbstractRenderable { public String baseLink = ""; public MakeFrame makeFrame = (title, contents) -> h1_title(title) + contents; static public interface MakeFrame { public String makeFrame(String title, String contents); } public HAbstractRenderable() { } public HAbstractRenderable(String baseLink) { this.baseLink = baseLink; } public HAbstractRenderable makeFrame(MakeFrame makeFrame) { this.makeFrame = makeFrame; return this; } public String baseLinkPlus(String uri) { return nempty(uri) ? appendSlash(baseLink) + uri : baseLink; } public String frame(String title, String contents) { return makeFrame.makeFrame(title, contents); } public String refreshWithMsgs(String... msgs) { return refreshWithMsgs(asList(msgs)); } public String refreshWithMsgs(List msgs, Object... __) { String anchor = (String) (optPar("anchor", __)); Map params = (Map) (optPar("params", __)); return hrefresh(addAnchorToURL(appendQueryToURL(baseLink, mapPlus(params, "msg", htmlEncode_nlToBr(lines_rtrim(msgs)))), anchor)); } public String renderMsgs(Map params) { return pUnlessEmpty(params.get("msg")); } } 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 }; } } 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 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 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 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 class ForEach_vstack extends VStackComputableWithStep implements IFieldsToList { public Iterable l; public IVF1 body; public ForEach_vstack() { } public ForEach_vstack(Iterable l, IVF1 body) { this.body = body; this.l = l; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + l + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { l, body }; } public Iterator it; public void step(VStack stack) { if (step == 0) { if (l == null) { stack._return(); return; } it = iterator(l); ++step; } if (!it.hasNext()) { stack._return(); return; } body.get(it.next()); } } static public interface IVF3 { public void get(A a, B b, C c); } static public class ShowComboBoxForm { public String desc; public String itemDesc; public List items; public String defaultValue; public IVF1 action; public JComboBox cb; public String selected() { return selectedItem(cb); } final public void show() { run(); } public void run() { cb = jComboBox(items, defaultValue); showFormTitled(desc, "", jlabel(desc), itemDesc, cb, runnableThread(new Runnable() { public void run() { try { String item = selected(); printVars("item", item, "action", action); if (nempty(item)) action.get(item); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String item = selected();\r\n printVars(+item, +action);\r\n if (ne..."; } })); } } static public class GazelleV_LeftArrowScript { abstract static public class Base extends HasTokenRangeWithSrc { public RuntimeException rethrowWithSrc(Throwable e) { return rethrowWithSrc("", e); } public RuntimeException rethrowWithSrc(String msg, Throwable e) { if (tokenRangeWithSrc() != null) throw new ScriptError(tokenRangeWithSrc(), msg, e); else throw rethrow(e); } public String indented() { return indentedScriptStruct(this); } public String shortenedSrc() { return shortenSrc(tokenRangeWithSrc()); } } static public class ScriptError extends RuntimeException implements IHasTokenRangeWithSrc { public ScriptError(TokenRangeWithSrc src, Throwable reason) { super(reason); tokenRangeWithSrc(src); } public ScriptError(TokenRangeWithSrc src, String msg, Throwable reason) { super(msg, reason); tokenRangeWithSrc(src); } final public ScriptError setTokenRangeWithSrc(TokenRangeWithSrc tokenRangeWithSrc) { return tokenRangeWithSrc(tokenRangeWithSrc); } public ScriptError tokenRangeWithSrc(TokenRangeWithSrc tokenRangeWithSrc) { this.tokenRangeWithSrc = tokenRangeWithSrc; return this; } final public TokenRangeWithSrc getTokenRangeWithSrc() { return tokenRangeWithSrc(); } public TokenRangeWithSrc tokenRangeWithSrc() { return tokenRangeWithSrc; } public TokenRangeWithSrc tokenRangeWithSrc; public TokenRangeWithSrc src() { return tokenRangeWithSrc(); } public String toString() { return super.toString() + "\n " + src() + " {{ " + shortenSrc(src()) + " }}"; } } static public String shortenSrc(TokenRangeWithSrc src) { return src == null ? null : shorten(nlToSpace(src.text())); } public interface Evaluable extends IF0, IHasTokenRangeWithSrc { public default Object get() { return get(new FlexibleVarContext()); } public Object get(VarContext ctx); public default LASValueDescriptor returnType() { return null; } public default Evaluable optimize() { return this; } public default Evaluable optimizeForReturnValueNotNeeded() { return this; } } abstract static public class EvaluableBase extends Base implements Evaluable { final public EvaluableBase setReturnType(LASValueDescriptor returnType) { return returnType(returnType); } public EvaluableBase returnType(LASValueDescriptor returnType) { this.returnType = returnType; return this; } final public LASValueDescriptor getReturnType() { return returnType(); } public LASValueDescriptor returnType() { return returnType; } public LASValueDescriptor returnType; public boolean returnValueNeeded = true; public Evaluable optimizeForReturnValueNotNeeded() { returnValueNeeded = false; return optimize(); } } static public AtomicLong scriptIDCounter = new AtomicLong(); static public long scriptID() { return incAtomicLong(scriptIDCounter); } static public class ListFromScript extends EvaluableBase implements IFieldsToList { public Script script; public ListFromScript() { } public ListFromScript(Script script) { this.script = script; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + script + ")"; } public Object[] _fieldsToList() { return new Object[] { script }; } public Object get(VarContext ctx) { return script.getAsList(ctx); } } static public class Script extends EvaluableBase { transient public long id = scriptID(); public Map functionDefs; public Evaluable[] steps; public Map params; public Script() { } public Script(List steps) { this.steps = toTypedArray(Evaluable.class, steps); } public Object get(VarContext ctx) { Object result = null; var pingSource = pingSource(); for (var step : steps) { ping(pingSource); result = step.get(ctx); var exiting = ctx.exitFromScript; if (exiting != null) { if (exiting == this) { ctx.exitFromScript = null; result = ctx.returnValue; ctx.returnValue(null); return result; } return null; } } return result; } public Object getAsList(VarContext ctx) { Object result = null; var pingSource = pingSource(); List list = new ArrayList(); for (var step : steps) { ping(pingSource); list.add(step.get(ctx)); var exiting = ctx.exitFromScript; if (exiting != null) { if (exiting == this) { ctx.exitFromScript = null; result = ctx.returnValue; ctx.returnValue(null); list.add(result); return list; } return null; } } return list; } public String toStringLong() { return pnlToLines(steps); } public String toString() { return "Script " + n2(id); } public FunctionDef getFunction(String name) { return mapGet(functionDefs, name); } final public Script optimize() { return optimizeScript(); } public Script optimizeScript() { int n = returnValueNeeded ? steps.length - 1 : steps.length; for (int i = 0; i < n; i++) steps[i] = steps[i].optimizeForReturnValueNotNeeded(); for (var f : values(functionDefs)) f.optimize(); return this; } } static public class FunctionDef extends Base implements IFieldsToList { public String name; public String[] args; public Script body; public FunctionDef() { } public FunctionDef(String name, String[] args, Script body) { this.body = body; this.args = args; this.name = name; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + name + ", " + args + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { name, args, body }; } final public FunctionDef setReturnType(Type returnType) { return returnType(returnType); } public FunctionDef returnType(Type returnType) { this.returnType = returnType; return this; } final public Type getReturnType() { return returnType(); } public Type returnType() { return returnType; } public Type returnType = Object.class; final public FunctionDef setArgTypes(LASValueDescriptor[] argTypes) { return argTypes(argTypes); } public FunctionDef argTypes(LASValueDescriptor[] argTypes) { this.argTypes = argTypes; return this; } final public LASValueDescriptor[] getArgTypes() { return argTypes(); } public LASValueDescriptor[] argTypes() { return argTypes; } public LASValueDescriptor[] argTypes; final public FunctionDef setSynthetic(boolean synthetic) { return synthetic(synthetic); } public FunctionDef synthetic(boolean synthetic) { this.synthetic = synthetic; return this; } final public boolean getSynthetic() { return synthetic(); } public boolean synthetic() { return synthetic; } public boolean synthetic = false; public FunctionDef(String name, List args, Script body) { this.args = toStringArray(args); this.body = body; this.name = name; } public Object callFromOutside(Object... args) { return call(new FlexibleVarContext(), args); } public Object call(VarContext ctx, Object... args) { VarContext ctx2 = new FlexibleVarContext(ctx); int n = min(l(args), l(this.args)); for (int i = 0; i < n; i++) ctx2.put(this.args[i], args[i]); return body.get(ctx2); } public void optimize() { body = body.optimize(); } public boolean isConstructor() { return eq(name, ""); } } static public class Assignment extends EvaluableBase implements IFieldsToList { public String var; public Evaluable expression; public Assignment() { } public Assignment(String var, Evaluable expression) { this.expression = expression; this.var = var; } public Object[] _fieldsToList() { return new Object[] { var, expression }; } public Object get(VarContext ctx) { Object o = expression.get(ctx); ctx.set(var, o); return o; } public String toString() { return var + " <- " + expression; } } static public class VarDeclaration extends EvaluableBase implements IFieldsToList { public String var; public Class type; public Evaluable expression; public VarDeclaration() { } public VarDeclaration(String var, Class type, Evaluable expression) { this.expression = expression; this.type = type; this.var = var; } public Object[] _fieldsToList() { return new Object[] { var, type, expression }; } public Object get(VarContext ctx) { Object o = expression == null ? null : expression.get(ctx); ctx.set(var, o); return o; } public String toString() { return "var " + var + " <- " + expression; } } static public class AssignmentToOuterVar extends EvaluableBase implements IFieldsToList { public String var; public Evaluable expression; public AssignmentToOuterVar() { } public AssignmentToOuterVar(String var, Evaluable expression) { this.expression = expression; this.var = var; } public Object[] _fieldsToList() { return new Object[] { var, expression }; } public Object get(VarContext ctx) { var parent = ctx.parent(); assertNotNull("No outer variable context", parent); Object o = expression.get(ctx); parent.set(var, o); return o; } public String toString() { return "outer " + var + " <- " + expression; } } static public class NewObject extends EvaluableBase { public NewObject() { } public Class c; public Evaluable[] args; public NewObject(Class c) { this(c, null); } public NewObject(Class c, Evaluable[] args) { this.args = args; this.c = c; returnType(new LASValueDescriptor.Exact(c, false)); } public Object get(VarContext ctx) { try { return preciseNuObject(c, evalArgs(args, ctx)); } catch (Throwable e) { throw rethrowWithSrc(e); } } public String toString() { return "new " + formatFunctionCall(className(c), args); } } static public class NewObject_LASClass extends NewObject { public NewObject_LASClass() { } public ResolvableLASClass lasClass; public NewObject_LASClass(ResolvableLASClass lasClass) { this.lasClass = lasClass; } public NewObject_LASClass(ResolvableLASClass lasClass, Evaluable[] args) { this.args = args; this.lasClass = lasClass; } public void resolve() { if (c == null) c = lasClass.get(); } public Object get(VarContext ctx) { resolve(); return super.get(ctx); } public String toString() { return "new " + formatFunctionCall(str(lasClass), args); } } static public class NewObject_UnknownClass extends NewObject implements IFieldsToList { public Evaluable classExpr; public Evaluable[] args; public NewObject_UnknownClass() { } public NewObject_UnknownClass(Evaluable classExpr, Evaluable[] args) { this.args = args; this.classExpr = classExpr; } public Object[] _fieldsToList() { return new Object[] { classExpr, args }; } public Object get(VarContext ctx) { try { Class c = (Class) (classExpr.get(ctx)); return preciseNuObject(c, evalArgs(args, ctx)); } catch (Throwable e) { throw rethrowWithSrc(e); } } public String toString() { return "new " + formatFunctionCall(classExpr, args); } } static public class CallFunction extends EvaluableBase implements IFieldsToList { public FunctionDef f; public Evaluable[] args; public CallFunction() { } public CallFunction(FunctionDef f, Evaluable[] args) { this.args = args; this.f = f; } public Object[] _fieldsToList() { return new Object[] { f, args }; } public Object get(VarContext ctx) { var evaledArgs = evalArgs(args, ctx); if (ctx.exiting()) return null; return f.call(ctx, evaledArgs); } public String toString() { return formatFunctionCall(f.name, args); } } static public class GetVar extends EvaluableBase implements IFieldsToList { public String var; public GetVar() { } public GetVar(String var) { this.var = var; } public Object[] _fieldsToList() { return new Object[] { var }; } public Object get(VarContext ctx) { return ctx.get(var); } public String toString() { return var; } } static public class Const extends EvaluableBase implements IFieldsToList { public Object value; public Const() { } public Const(Object value) { this.value = value; } public Object[] _fieldsToList() { return new Object[] { value }; } public Object get(VarContext ctx) { return value; } public String toString() { return strOrClassName(value); } public LASValueDescriptor returnType() { return new LASValueDescriptor.KnownValue(value); } public Object _serialize() { boolean ok = isUnproblematicValue(value); return ok ? this : toStringWithClass(value); } } static public class GetStaticField extends EvaluableBase implements IFieldsToList { public Field field; public GetStaticField() { } public GetStaticField(Field field) { this.field = field; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + field + ")"; } public Object[] _fieldsToList() { return new Object[] { field }; } public Object get(VarContext ctx) { try { return field.get(null); } catch (Exception __e) { throw rethrow(__e); } } public String _serialize() { return str(field); } } abstract static public class CallOnTarget extends EvaluableBase implements IFieldsToList { public Evaluable target; public CallOnTarget() { } public CallOnTarget(Evaluable target) { this.target = target; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + target + ")"; } public Object[] _fieldsToList() { return new Object[] { target }; } final public CallOnTarget setAllowNullReference(boolean allowNullReference) { return allowNullReference(allowNullReference); } public CallOnTarget allowNullReference(boolean allowNullReference) { this.allowNullReference = allowNullReference; return this; } final public boolean getAllowNullReference() { return allowNullReference(); } public boolean allowNullReference() { return allowNullReference; } public boolean allowNullReference = false; public Object handleNullReference() { if (allowNullReference) return null; else throw new NullPointerException(); } abstract public Object evalOnTarget(VarContext ctx, Object object); public Object get(VarContext ctx) { try { Object object = target.get(ctx); if (object == null) return handleNullReference(); return evalOnTarget(ctx, object); } catch (Throwable e) { throw rethrowWithSrc(e); } } } static public class CallMethodOrGetField extends CallOnTarget { public CallMethodOrGetField() { } public String name; public CallMethodOrGetField(Evaluable target, String name) { this.name = name; this.target = target; } public Object evalOnTarget(VarContext ctx, Object object) { try { return preciseGetOrCallMethod(object, name); } catch (Throwable e) { throw rethrowWithSrc("Was getting " + name, e); } } } static public class GetField extends CallOnTarget { public GetField() { } public String name; public GetField(Evaluable target, String name) { this.name = name; this.target = target; } public Object evalOnTarget(VarContext ctx, Object object) { try { return _get(object, name); } catch (Throwable e) { throw rethrowWithSrc("Was getting " + name, e); } } } static public class GetVarContext extends EvaluableBase { public Object get(VarContext ctx) { return ctx; } } static public class ThrowMethodNotFoundException extends EvaluableBase implements IFieldsToList { public CallMethod instruction; public ThrowMethodNotFoundException() { } public ThrowMethodNotFoundException(CallMethod instruction) { this.instruction = instruction; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + instruction + ")"; } public Object[] _fieldsToList() { return new Object[] { instruction }; } public Object get(VarContext ctx) { throw fail("Method not found: " + instruction); } } static public class ThrowNullPointerException extends EvaluableBase implements IFieldsToList { public CallMethod instruction; public ThrowNullPointerException() { } public ThrowNullPointerException(CallMethod instruction) { this.instruction = instruction; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + instruction + ")"; } public Object[] _fieldsToList() { return new Object[] { instruction }; } public Object get(VarContext ctx) { throw fail("Null pointer exception: " + instruction); } } static public class CallMethod extends CallOnTarget { public CallMethod() { } public String methodName; public Evaluable[] args; public CallMethod(Evaluable target, String methodName, Evaluable[] args) { this.args = args; this.methodName = methodName; this.target = target; } public Object evalOnTarget(VarContext ctx, Object object) { return newPreciseCall(object, methodName, evalArgs(args, ctx)); } public String toString() { return target + "." + formatFunctionCall(methodName, args); } public Evaluable optimize() { var targetType = target.returnType(); if (targetType != null && targetType.knownValue()) { Object o = targetType.value(); if (o == null) return allowNullReference ? _const(null) : new ThrowNullPointerException(this); Class[] argTypes = new Class[l(args)]; for (int i = 0; i < l(args); i++) { var type = args[i].returnType(); if (type == null || !type.javaClassIsExact()) return this; argTypes[i] = type.javaClass(); } List methods = findMethodsNamed_cached(o, methodName); if (any(methods, m -> m.isVarArgs())) return this; var __4 = findMethod_withPrimitiveWidening_onTypes(o, methodName, argTypes); var method = __4.a; var widening = __4.b; if (method == null) return new ThrowMethodNotFoundException(this); return new DirectMethodCallOnKnownTarget(widening, o instanceof Class ? null : o, method, args); } return this; } } static public Object[] evalArgs(Evaluable[] args, VarContext ctx) { return mapToArrayOrNull(args, arg -> arg.get(ctx)); } static public class CallMethodOrGlobalFunction extends CallMethod { public CallMethodOrGlobalFunction() { } public MethodOnObject globalFunction; static final public Object methodNotFoundSentinel = new Object(); public CallMethodOrGlobalFunction(Evaluable target, String methodName, MethodOnObject globalFunction, Evaluable[] args) { this.args = args; this.globalFunction = globalFunction; this.methodName = methodName; this.target = target; } public String toString() { return target + "." + formatFunctionCall(methodName + "+", args); } public Object evalOnTarget(VarContext ctx, Object o) { Object[] realArgs = evalArgs(args, ctx); Object result = newPreciseCall_sentinel(o, methodName, methodNotFoundSentinel, realArgs); if (result != methodNotFoundSentinel) return result; return newPreciseCall(globalFunction.object, globalFunction.method, itemPlusArray(o, realArgs)); } } static public class CallMethodOrGetFieldOrGlobalFunction extends CallMethodOrGetField { public CallMethodOrGetFieldOrGlobalFunction() { } public MethodOnObject globalFunction; static final public Object notFoundSentinel = new Object(); public CallMethodOrGetFieldOrGlobalFunction(Evaluable target, String name, MethodOnObject globalFunction) { this.globalFunction = globalFunction; this.name = name; this.target = target; } public String toString() { return target + "." + name + "+"; } public Object evalOnTarget(VarContext ctx, Object o) { try { Object result = preciseGetOrCallMethod_sentinel(o, name, notFoundSentinel); if (result != notFoundSentinel) return result; return newPreciseCall(globalFunction.object, globalFunction.method, o); } catch (Throwable e) { throw rethrowWithSrc("Was getting " + name, e); } } } abstract static public class LambdaBase extends EvaluableBase implements IFieldsToList { public Class intrface; public LambdaBase() { } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + intrface + ")"; } public Object[] _fieldsToList() { return new Object[] { intrface }; } transient public Method implementedMethod; public LambdaBase(Class intrface) { this.intrface = intrface; implementedMethod = findSingleInterfaceMethodOrFail(intrface); } } static public class LambdaMethodOnArgument extends LambdaBase { public String methodName; public Evaluable[] args; public LambdaMethodOnArgument(Class intrface, String methodName, Evaluable[] args) { super(intrface); this.args = args; this.methodName = methodName; } public Object get(VarContext ctx) { return proxyFromInvocationHandler(intrface, (proxy, method, actualArgs) -> { if (method.getDeclaringClass() == intrface) return forwardCall(actualArgs[0], ctx); else return handleObjectMethodsInProxyInvocationHandler(this, implementedMethod, method, proxy, actualArgs); }); } public Object forwardCall(Object target, VarContext ctx) { return call(target, methodName, evalArgs(args, ctx)); } } static public class LambdaDef extends EvaluableBase implements IFieldsToList { public Class intrface; public String[] args; public Evaluable body; public LambdaDef() { } public Object[] _fieldsToList() { return new Object[] { intrface, args, body }; } transient public Method implementedMethod; public LambdaDef(Class intrface, String[] args, Evaluable body) { this.body = body; this.args = args; this.intrface = intrface; implementedMethod = findSingleInterfaceMethodOrFail(intrface); if (implementedMethod.getParameterCount() != l(args)) throw fail("Bad parameter count for lambda: " + implementedMethod + " vs: " + joinWithComma(args)); } public Object get(VarContext ctx) { return proxyFromInvocationHandler(intrface, (proxy, method, actualArgs) -> { ping(); if (method.getDeclaringClass() == intrface) { var ctx2 = new FlexibleVarContext(ctx); var argNames = args; for (int i = 0; i < l(args); i++) ctx2.put(argNames[i], actualArgs[i]); return body.get(ctx2); } else return handleObjectMethodsInProxyInvocationHandler(this, implementedMethod, method, proxy, actualArgs); }); } public String toString() { return "Lambda(" + shortenedSrc() + ")"; } } abstract static public class CurriedLambdaBase extends EvaluableBase implements IFieldsToList { public Class intrface; public Evaluable[] curriedArgs; public CurriedLambdaBase() { } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + intrface + ", " + curriedArgs + ")"; } public Object[] _fieldsToList() { return new Object[] { intrface, curriedArgs }; } transient public Method implementedMethod; public CurriedLambdaBase(Class intrface, Evaluable[] curriedArgs) { this.curriedArgs = curriedArgs; this.intrface = intrface; implementedMethod = findSingleInterfaceMethodOrFail(intrface); } public Object get(VarContext ctx) { try { Object[] curriedArguments = evalArgs(curriedArgs, ctx); return proxyFromInvocationHandler(intrface, (proxy, method, actualArgs) -> { try { if (method.getDeclaringClass() == intrface) return forwardCall(ctx, concatMethodArgs(curriedArguments, actualArgs)); else return handleObjectMethodsInProxyInvocationHandler(this, implementedMethod, method, proxy, actualArgs); } catch (Throwable e) { throw rethrowWithSrc(e); } }); } catch (Throwable e) { throw rethrowWithSrc(e); } } abstract public Object forwardCall(VarContext ctx, Object[] args); } static public class CurriedMethodLambda extends CurriedLambdaBase { public CurriedMethodLambda() { } public Object target; public String targetMethod; public CurriedMethodLambda(Class intrface, Object target, String targetMethod, Evaluable[] curriedArgs) { super(intrface, curriedArgs); this.targetMethod = targetMethod; this.target = target; } public Object forwardCall(VarContext ctx, Object[] args) { return call(target, targetMethod, args); } } static public class CurriedScriptFunctionLambda extends CurriedLambdaBase { public FunctionDef f; public CurriedScriptFunctionLambda(Class intrface, FunctionDef f, Evaluable[] curriedArgs) { super(intrface, curriedArgs); this.f = f; } public Object forwardCall(VarContext ctx, Object[] args) { return f.call(ctx, args); } } static public class CurriedConstructorLambda extends CurriedLambdaBase { public Constructor[] ctors; public CurriedConstructorLambda(Class intrface, Constructor[] ctors, Evaluable[] curriedArgs) { super(intrface, curriedArgs); this.ctors = ctors; } public Object forwardCall(VarContext ctx, Object[] args) { return preciseNuObject(ctors, args); } } static public class DirectMethodCallOnKnownTarget extends EvaluableBase implements IFieldsToList { public boolean widening = false; public Object target; public Method method; public Evaluable[] args; public DirectMethodCallOnKnownTarget() { } public DirectMethodCallOnKnownTarget(boolean widening, Object target, Method method, Evaluable[] args) { this.args = args; this.method = method; this.target = target; this.widening = widening; } public Object[] _fieldsToList() { return new Object[] { widening, target, method, args }; } public Object get(VarContext ctx) { var evaluatedArgs = evalArgs(args, ctx); return widening ? invokeMethodWithWidening(method, target, evaluatedArgs) : invokeMethod(method, target, evaluatedArgs); } public String toString() { return (target == null ? "" : target + ".") + formatFunctionCall(str(method), args); } public LASValueDescriptor returnType() { return LASValueDescriptor.fromClass(method.getReturnType()); } } static public class While extends EvaluableBase implements IFieldsToList { public Evaluable condition; public Evaluable body; public While() { } public While(Evaluable condition, Evaluable body) { this.body = body; this.condition = condition; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + condition + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { condition, body }; } public Object get(VarContext ctx) { while (!ctx.exiting() && (Boolean) condition.get(ctx)) { body.get(ctx); } return null; } } abstract static public class ForEachBase extends EvaluableBase implements IFieldsToList { public Evaluable collection; public Evaluable body; public ForEachBase() { } public ForEachBase(Evaluable collection, Evaluable body) { this.body = body; this.collection = collection; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + collection + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { collection, body }; } public Object get(VarContext ctx) { var coll = collection.get(ctx); Iterator iterator; List out; try { if (coll == null) out = new ArrayList(); else if (coll.getClass().isArray()) { if (coll instanceof Object[]) { var array = (Object[]) coll; out = emptyList(array.length); for (var element : array) { if (ctx.exiting()) return null; processElement(ctx, out, element); } } else if (coll instanceof byte[]) { var array = (byte[]) coll; out = emptyList(array.length); for (var element : array) { if (ctx.exiting()) return null; processElement(ctx, out, element); } } else if (coll instanceof short[]) { var array = (short[]) coll; out = emptyList(array.length); for (var element : array) { if (ctx.exiting()) return null; processElement(ctx, out, element); } } else if (coll instanceof double[]) { var array = (double[]) coll; out = emptyList(array.length); for (var element : array) { if (ctx.exiting()) return null; processElement(ctx, out, element); } } else if (coll instanceof float[]) { var array = (float[]) coll; out = emptyList(array.length); for (var element : array) { if (ctx.exiting()) return null; processElement(ctx, out, element); } } else if (coll instanceof int[]) { var array = (int[]) coll; out = emptyList(array.length); for (var element : array) { if (ctx.exiting()) return null; processElement(ctx, out, element); } } else if (coll instanceof long[]) { var array = (long[]) coll; out = emptyList(array.length); for (var element : array) { if (ctx.exiting()) return null; processElement(ctx, out, element); } } else if (coll instanceof char[]) { var array = (char[]) coll; out = emptyList(array.length); for (var element : array) { if (ctx.exiting()) return null; processElement(ctx, out, element); } } else if (coll instanceof boolean[]) { var array = (boolean[]) coll; out = emptyList(array.length); for (var element : array) { if (ctx.exiting()) return null; processElement(ctx, out, element); } } else throw fail("todo for each with: " + coll); } else if (coll instanceof Iterable) { out = emptyList((Iterable) coll); iterator = ((Iterable) coll).iterator(); try { while (iterator.hasNext()) { if (ctx.exiting()) return null; var element = iterator.next(); processElement(ctx, out, element); } } finally { if (iterator instanceof AutoCloseable) { try { ((AutoCloseable) iterator).close(); } catch (Exception __e) { throw rethrow(__e); } } } } else throw fail("Not iterable: " + className(coll)); } finally { loopDone(ctx); } return out; } abstract public void processElement(VarContext ctx, List out, Object o); abstract public void loopDone(VarContext ctx); } static public class ForEach extends ForEachBase { public ForEach() { } public String var; public ForEach(Evaluable collection, String var, Evaluable body) { this.body = body; this.var = var; this.collection = collection; } public void processElement(VarContext ctx, List out, Object o) { ctx.set(var, o); out.add(body.get(ctx)); } public void loopDone(VarContext ctx) { ctx.unset(var); } } static public class ForIterator extends EvaluableBase implements IFieldsToList { static final public String _fieldOrder = "iterable var body"; public Evaluable iterable; public String var; public Evaluable body; public ForIterator() { } public ForIterator(Evaluable iterable, String var, Evaluable body) { this.body = body; this.var = var; this.iterable = iterable; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + iterable + ", " + var + ", " + body + ")"; } public boolean equals(Object o) { if (!(o instanceof ForIterator)) return false; ForIterator __5 = (ForIterator) o; return eq(iterable, __5.iterable) && eq(var, __5.var) && eq(body, __5.body); } public int hashCode() { int h = -214906825; h = boostHashCombine(h, _hashCode(iterable)); h = boostHashCombine(h, _hashCode(var)); h = boostHashCombine(h, _hashCode(body)); return h; } public Object[] _fieldsToList() { return new Object[] { iterable, var, body }; } public Object get(VarContext ctx) { VarContext subContext = new FlexibleVarContext(ctx); var iterable = this.iterable.get(ctx); Iterator iterator = iterator_gen(iterable); return new MapI(value -> { subContext.set(var, value); return body.get(subContext); }, iterator); } } static public class ForNested extends EvaluableBase implements IFieldsToList { static final public String _fieldOrder = "iterable var body"; public Evaluable iterable; public String var; public Evaluable body; public ForNested() { } public ForNested(Evaluable iterable, String var, Evaluable body) { this.body = body; this.var = var; this.iterable = iterable; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + iterable + ", " + var + ", " + body + ")"; } public boolean equals(Object o) { if (!(o instanceof ForNested)) return false; ForNested __6 = (ForNested) o; return eq(iterable, __6.iterable) && eq(var, __6.var) && eq(body, __6.body); } public int hashCode() { int h = -1363247360; h = boostHashCombine(h, _hashCode(iterable)); h = boostHashCombine(h, _hashCode(var)); h = boostHashCombine(h, _hashCode(body)); return h; } public Object[] _fieldsToList() { return new Object[] { iterable, var, body }; } public Object get(VarContext ctx) { VarContext subContext = new FlexibleVarContext(ctx); var iterable = this.iterable.get(ctx); Iterator iterator = iterator_gen(iterable); return nestedIterator(iterator, value -> { subContext.set(var, value); return iterator_gen(body.get(subContext)); }); } } static public class ForPairs extends ForEachBase { public ForPairs() { } public String varA, varB; public ForPairs(Evaluable collection, Evaluable body, String varA, String varB) { this.varB = varB; this.varA = varA; this.body = body; this.collection = collection; } public void processElement(VarContext ctx, List out, Object o) { Pair p = (Pair) o; ctx.set(varA, p.a); ctx.set(varB, p.b); out.add(body.get(ctx)); } public void loopDone(VarContext ctx) { ctx.unset(varA); ctx.unset(varB); } } static public class ForKeyValue extends EvaluableBase implements IFieldsToList { public Evaluable map; public Evaluable body; public String varA; public String varB; public ForKeyValue() { } public ForKeyValue(Evaluable map, Evaluable body, String varA, String varB) { this.varB = varB; this.varA = varA; this.body = body; this.map = map; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + map + ", " + body + ", " + varA + ", " + varB + ")"; } public Object[] _fieldsToList() { return new Object[] { map, body, varA, varB }; } public Object get(VarContext ctx) { Map theMap = (Map) map.get(ctx); List out; try { if (theMap != null) { out = emptyList(theMap.size()); for (var entry : theMap.entrySet()) { if (ctx.exiting()) return null; ctx.set(varA, entry.getKey()); ctx.set(varB, entry.getValue()); out.add(body.get(ctx)); } } else out = new ArrayList(); } finally { ctx.unset(varA); ctx.unset(varB); } return out; } } static public class ForIntTo extends EvaluableBase implements IFieldsToList { public Evaluable endValue; public String var; public Evaluable body; public ForIntTo() { } public ForIntTo(Evaluable endValue, String var, Evaluable body) { this.body = body; this.var = var; this.endValue = endValue; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + endValue + ", " + var + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { endValue, var, body }; } public Evaluable optimize() { if (!returnValueNeeded) body = body.optimizeForReturnValueNotNeeded(); return this; } public Object get(VarContext ctx) { int n = (Integer) endValue.get(ctx), i = 0; List out = returnValueNeeded ? new ArrayList() : null; try { ctx.put(var, i); while (i < n) { if (ctx.exiting()) return null; Object o = body.get(ctx); { if (out != null) out.add(o); } ctx.set(var, i = (Integer) ctx.get(var) + 1); } } finally { ctx.unset(var); } return out; } } static public class ForIndex extends EvaluableBase { public ForIndex() { } public Evaluable collection, body; public String varIndex, varElement; public ForIndex(Evaluable collection, Evaluable body, String varIndex, String varElement) { this.varElement = varElement; this.varIndex = varIndex; this.body = body; this.collection = collection; } public Object get(VarContext ctx) { return new ForIndex_instance(collection, body, varIndex, varElement).get(ctx); } } static public class ForIndex_instance extends ForEachBase { public String varIndex, varElement; public int index; public ForIndex_instance(Evaluable collection, Evaluable body, String varIndex, String varElement) { this.varElement = varElement; this.varIndex = varIndex; this.body = body; this.collection = collection; } public void processElement(VarContext ctx, List out, Object o) { ctx.set(varIndex, index++); ctx.set(varElement, o); out.add(body.get(ctx)); } public void loopDone(VarContext ctx) { ctx.unset(varIndex); ctx.unset(varElement); } } static public class IfThen extends EvaluableBase implements IFieldsToList { public Evaluable condition; public Evaluable body; public Evaluable elseBranch; public IfThen() { } public IfThen(Evaluable condition, Evaluable body, Evaluable elseBranch) { this.elseBranch = elseBranch; this.body = body; this.condition = condition; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + condition + ", " + body + ", " + elseBranch + ")"; } public Object[] _fieldsToList() { return new Object[] { condition, body, elseBranch }; } public IfThen(Evaluable condition, Evaluable body) { this.condition = condition; this.body = body; } public Object get(VarContext ctx) { if ((Boolean) condition.get(ctx)) return body.get(ctx); else if (elseBranch != null) return elseBranch.get(ctx); else return null; } } static public class ReturnFromScript extends EvaluableBase implements IFieldsToList { public Script script; public Evaluable value; public ReturnFromScript() { } public ReturnFromScript(Script script, Evaluable value) { this.value = value; this.script = script; } public Object[] _fieldsToList() { return new Object[] { script, value }; } public Object get(VarContext ctx) { Object result = value.get(ctx); ctx.exitFromScript(script); ctx.returnValue(result); return null; } public String toString() { return formatFunctionCall("ReturnFromScript", script, value); } } static public class Continue extends EvaluableBase implements IFieldsToList { public Script loopBody; public Continue() { } public Continue(Script loopBody) { this.loopBody = loopBody; } public Object[] _fieldsToList() { return new Object[] { loopBody }; } public Object get(VarContext ctx) { ctx.exitFromScript(loopBody); ctx.returnValue(null); return null; } public String toString() { return formatFunctionCall("Continue", loopBody); } } static public class RepeatN extends EvaluableBase implements IFieldsToList { public Evaluable n; public Evaluable body; public RepeatN() { } public RepeatN(Evaluable n, Evaluable body) { this.body = body; this.n = n; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + n + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { n, body }; } public Object get(VarContext ctx) { long count = ((Number) n.get(ctx)).longValue(); for (int _repeat_0 = 0; _repeat_0 < count; _repeat_0++) { if (ctx.exiting()) return null; body.get(ctx); } return null; } } static public class BoolAnd extends EvaluableBase implements IFieldsToList { public Evaluable a; public Evaluable b; public BoolAnd() { } public BoolAnd(Evaluable a, Evaluable b) { this.b = b; this.a = a; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + a + ", " + b + ")"; } public boolean equals(Object o) { if (!(o instanceof BoolAnd)) return false; BoolAnd __7 = (BoolAnd) o; return eq(a, __7.a) && eq(b, __7.b); } public int hashCode() { int h = 1729330797; h = boostHashCombine(h, _hashCode(a)); h = boostHashCombine(h, _hashCode(b)); return h; } public Object[] _fieldsToList() { return new Object[] { a, b }; } public Object get(VarContext ctx) { if (!((Boolean) a.get(ctx))) return false; return b.get(ctx); } } static public class BoolOr extends EvaluableBase implements IFieldsToList { public Evaluable a; public Evaluable b; public BoolOr() { } public BoolOr(Evaluable a, Evaluable b) { this.b = b; this.a = a; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + a + ", " + b + ")"; } public boolean equals(Object o) { if (!(o instanceof BoolOr)) return false; BoolOr __8 = (BoolOr) o; return eq(a, __8.a) && eq(b, __8.b); } public int hashCode() { int h = 1995447949; h = boostHashCombine(h, _hashCode(a)); h = boostHashCombine(h, _hashCode(b)); return h; } public Object[] _fieldsToList() { return new Object[] { a, b }; } public Object get(VarContext ctx) { if (((Boolean) a.get(ctx))) return true; return b.get(ctx); } } static public class TempBlock extends EvaluableBase implements IFieldsToList { public Evaluable tempExpr; public Evaluable body; public TempBlock() { } public TempBlock(Evaluable tempExpr, Evaluable body) { this.body = body; this.tempExpr = tempExpr; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + tempExpr + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { tempExpr, body }; } public Object get(VarContext ctx) { AutoCloseable __2 = (AutoCloseable) (tempExpr.get(ctx)); try { return body.get(ctx); } finally { _close(__2); } } } static public class WillReturn extends EvaluableBase implements IFieldsToList { public Evaluable exp; public Evaluable body; public WillReturn() { } public WillReturn(Evaluable exp, Evaluable body) { this.body = body; this.exp = exp; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + exp + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { exp, body }; } public Object get(VarContext ctx) { body.get(ctx); return exp.get(ctx); } } static public class ClassDef extends EvaluableBase implements IFieldsToList { public ResolvableLASClass lasClass; public ClassDef() { } public ClassDef(ResolvableLASClass lasClass) { this.lasClass = lasClass; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + lasClass + ")"; } public boolean equals(Object o) { if (!(o instanceof ClassDef)) return false; ClassDef __9 = (ClassDef) o; return eq(lasClass, __9.lasClass); } public int hashCode() { int h = 757052301; h = boostHashCombine(h, _hashCode(lasClass)); return h; } public Object[] _fieldsToList() { return new Object[] { lasClass }; } public Object get(VarContext ctx) { return lasClass.get(); } } static public class SetField extends EvaluableBase implements IFieldsToList { public Evaluable target; public String name; public Evaluable expr; public SetField() { } public SetField(Evaluable target, String name, Evaluable expr) { this.expr = expr; this.name = name; this.target = target; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + target + ", " + name + ", " + expr + ")"; } public Object[] _fieldsToList() { return new Object[] { target, name, expr }; } final public SetField setAllowNullReference(boolean allowNullReference) { return allowNullReference(allowNullReference); } public SetField allowNullReference(boolean allowNullReference) { this.allowNullReference = allowNullReference; return this; } final public boolean getAllowNullReference() { return allowNullReference(); } public boolean allowNullReference() { return allowNullReference; } public boolean allowNullReference = false; public Object handleNullReference() { if (allowNullReference) return null; else throw new NullPointerException(); } public Object get(VarContext ctx) { try { Object value = expr.get(ctx); Object object = target.get(ctx); if (object == null) handleNullReference(); else set(object, name, value); return value; } catch (Throwable e) { throw rethrowWithSrc(e); } } } static public class SetStaticField extends EvaluableBase implements IFieldsToList { public Field field; public Evaluable expr; public SetStaticField() { } public SetStaticField(Field field, Evaluable expr) { this.expr = expr; this.field = field; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + field + ", " + expr + ")"; } public Object[] _fieldsToList() { return new Object[] { field, expr }; } public Object get(VarContext ctx) { try { Object value = expr.get(ctx); field.set(null, value); return value; } catch (Throwable e) { throw rethrowWithSrc(e); } } } static public class Throw extends EvaluableBase implements IFieldsToList { public Evaluable expr; public Throw() { } public Throw(Evaluable expr) { this.expr = expr; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + expr + ")"; } public Object[] _fieldsToList() { return new Object[] { expr }; } public Object get(VarContext ctx) { throw asRuntimeException((Throwable) expr.get(ctx)); } } static public class TryCatch extends EvaluableBase implements IFieldsToList { public Evaluable body; public String var; public Evaluable catchBlock; public TryCatch() { } public TryCatch(Evaluable body, String var, Evaluable catchBlock) { this.catchBlock = catchBlock; this.var = var; this.body = body; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + body + ", " + var + ", " + catchBlock + ")"; } public Object[] _fieldsToList() { return new Object[] { body, var, catchBlock }; } public Object get(VarContext ctx) { try { return body.get(ctx); } catch (Throwable e) { var addVar = var == null ? null : ctx.tempPut(var, e); AutoCloseable __3 = addVar; try { return catchBlock.get(ctx); } finally { _close(__3); } } } } static public class TryFinally extends EvaluableBase implements IFieldsToList { public Evaluable body; public Evaluable finallyBlock; public TryFinally() { } public TryFinally(Evaluable body, Evaluable finallyBlock) { this.finallyBlock = finallyBlock; this.body = body; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + body + ", " + finallyBlock + ")"; } public Object[] _fieldsToList() { return new Object[] { body, finallyBlock }; } public Object get(VarContext ctx) { try { return body.get(ctx); } finally { finallyBlock.get(ctx); } } } static public structure_Data structureDataForLAS() { structure_Data d = new structure_Data(); d.skipDefaultValues(true); d.shouldIncludeField = field -> { String c = shortClassName(field.getDeclaringClass()); String f = field.getName(); boolean shouldInclude = !(eq(c, "HasTokenRangeWithSrc") && eq(f, "src")); return shouldInclude; }; return d; } static public boolean isUnproblematicValue(Object o) { return o == null || o instanceof Number || o instanceof String || o instanceof Boolean || o instanceof Class; } static public String scriptStruct(Object o) { String s = struct(o, structureDataForLAS()); List tok = structTok(s); String prefix = shortName(GazelleV_LeftArrowScript.class) + "$"; for (int i = 1; i < l(tok); i += 2) tok.set(i, replacePrefix(prefix, "$", tok.get(i))); return join(tok); } static public String indentedScriptStruct(Object o) { return indentStructureString(scriptStruct(o)); } static public Evaluable _const(Object o) { return new Const(o); } static public class Then extends CallOnTarget { public CallOnTarget call1, call2; public Then(CallOnTarget call1, CallOnTarget call2) { this.call2 = call2; this.call1 = call1; target = call1.target; call1.target = null; } public Object evalOnTarget(VarContext ctx, Object object) { call1.evalOnTarget(ctx, object); return call2.evalOnTarget(ctx, object); } } static public class Synchronized extends EvaluableBase implements IFieldsToList { public Evaluable target; public Evaluable body; public Synchronized() { } public Synchronized(Evaluable target, Evaluable body) { this.body = body; this.target = target; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + target + ", " + body + ")"; } public Object[] _fieldsToList() { return new Object[] { target, body }; } public Evaluable optimize() { if (!returnValueNeeded) body = body.optimizeForReturnValueNotNeeded(); return this; } public Object get(VarContext ctx) { synchronized (target.get(ctx)) { return body.get(ctx); } } } } static public class LazyVar implements IF0 { public LazyVar() { } public LazyVar(A v) { this.v = v; if (v == null) calculating = new Var(); } public LazyVar(IF0 f) { this.f = f; } public IF0 f; public Var> calculating; public A v; public A get() { boolean meCalc = false; if (v != null) return v; synchronized (this) { meCalc = calculating == null; if (meCalc) calculating = new Var(); } if (meCalc) { OKOrError b = okOrError(() -> f.get()); calculating.set(b); synchronized (this) { return v = b.get(); } } else { waitUntilNotNull(calculating); return v; } } public synchronized boolean isEvaluated() { return f == null; } public synchronized boolean has() { return get() != null; } public String toString() { return isEvaluated() ? str(get()) : "LazyVar"; } } 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 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 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 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 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; } } public interface ILASClassLoader { public Class defineLASClass(String name, IF0 generateClass); public Object rememberClassBytes(boolean rememberClassBytes); } 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 LASClassDef extends HasTokenRangeWithSrc { final public LASClassDef setUserGivenName(String userGivenName) { return userGivenName(userGivenName); } public LASClassDef userGivenName(String userGivenName) { this.userGivenName = userGivenName; return this; } final public String getUserGivenName() { return userGivenName(); } public String userGivenName() { return userGivenName; } public String userGivenName; final public LASClassDef setClassDefPrefix(String classDefPrefix) { return classDefPrefix(classDefPrefix); } public LASClassDef classDefPrefix(String classDefPrefix) { this.classDefPrefix = classDefPrefix; return this; } final public String getClassDefPrefix() { return classDefPrefix(); } public String classDefPrefix() { return classDefPrefix; } public String classDefPrefix = "userCode."; final public LASClassDef setFullCompilation(boolean fullCompilation) { return fullCompilation(fullCompilation); } public LASClassDef fullCompilation(boolean fullCompilation) { this.fullCompilation = fullCompilation; return this; } final public boolean getFullCompilation() { return fullCompilation(); } public boolean fullCompilation() { return fullCompilation; } public boolean fullCompilation = false; final public LASClassDef setVerbose(boolean verbose) { return verbose(verbose); } public LASClassDef verbose(boolean verbose) { this.verbose = verbose; return this; } final public boolean getVerbose() { return verbose(); } public boolean verbose() { return verbose; } public boolean verbose = true; final public LASClassDef setSuperClass(Type superClass) { return superClass(superClass); } public LASClassDef superClass(Type superClass) { this.superClass = superClass; return this; } final public Type getSuperClass() { return superClass(); } public Type superClass() { return superClass; } public Type superClass = Object.class; public List fields = new ArrayList(); public Map fieldsByName = new HashMap(); public List methods = new ArrayList(); public MultiMap methodsByName = new MultiMap(); public List methodBodies = new ArrayList(); public List interfaces = new ArrayList(); public GazelleV_LeftArrowScript.FunctionDef initializerMethod; public List initializers = new ArrayList(); public BitSet isFieldInitializer = new BitSet(); static public class FieldDef { final public FieldDef setName(String name) { return name(name); } public FieldDef name(String name) { this.name = name; return this; } final public String getName() { return name(); } public String name() { return name; } public String name; final public FieldDef setType(Type type) { return type(type); } public FieldDef type(Type type) { this.type = type; return this; } final public Type getType() { return type(); } public Type type() { return type; } public Type type; final public FieldDef setInitializer(GazelleV_LeftArrowScript.Evaluable initializer) { return initializer(initializer); } public FieldDef initializer(GazelleV_LeftArrowScript.Evaluable initializer) { this.initializer = initializer; return this; } final public GazelleV_LeftArrowScript.Evaluable getInitializer() { return initializer(); } public GazelleV_LeftArrowScript.Evaluable initializer() { return initializer; } public GazelleV_LeftArrowScript.Evaluable initializer; public Set modifiers; public boolean hasModifier(String modifier) { return contains(modifiers, modifier); } public void addModifier(String modifier) { modifiers = createOrAddToSet(modifiers, modifier); } } public String structForHash() { return GazelleV_LeftArrowScript.scriptStruct(litorderedmap("userGivenName", userGivenName, "fields", fields, "methods", methods, "fullCompilation", fullCompilation)); } public String classHash_cache; public String classHash() { if (classHash_cache == null) classHash_cache = classHash_load(); return classHash_cache; } public String classHash_load() { String struct = structForHash(); if (verbose) print("structForHash", struct); return md5(struct); } public String finalClassName() { return classDefPrefix() + finalClassNameWithoutPrefix(); } public String finalClassNameWithoutPrefix() { return or2(userGivenName, "C") + "_" + classHash(); } public byte[] toBytes_cache; public byte[] toBytes() { if (toBytes_cache == null) toBytes_cache = toBytes_load(); return toBytes_cache; } public byte[] toBytes_load() { ClassMaker classMaker = new ClassMaker(finalClassName(), className(typeToClass(superClass)), mapToStringArray(interfaces, i -> className(typeToClass(i)))); var cp = classMaker.getConstantPool(); for (var field : fields) { var type = field.type; var fg = new FieldGen(Const.ACC_PUBLIC, typeToBCELType(type), field.name, cp); fg.isTransient(field.hasModifier("transient")); if (type instanceof ParameterizedType) fg.addAttribute(new org.apache.bcel.classfile.Signature(cp.addUtf8("Signature"), 2, cp.addUtf8(typeToVMSignature((ParameterizedType) type)), cp.getConstantPool())); classMaker.addField(fg); } if (nempty(initializers)) { addMethod(initializerMethod = new GazelleV_LeftArrowScript.FunctionDef("$initFields", new String[0], new GazelleV_LeftArrowScript.Script(initializers)).returnType(void.class)); if (!hasUserDefinedDefaultConstructor()) addMethod(new GazelleV_LeftArrowScript.FunctionDef("", new String[0], new GazelleV_LeftArrowScript.Script(emptyList())).returnType(void.class)); } for (var method : methods) if (fullCompilation) fullyCompileMethod(classMaker, method); else semiCompileMethod(classMaker, method); if (!hasUserDefinedDefaultConstructor()) classMaker.addDefaultConstructor(); if (srcRef() != null) classMaker.addField(new FieldGen(Const.ACC_PUBLIC | Const.ACC_STATIC, classToBCELType(TokenRangeWithSrc.class), srcRefField(), classMaker.getConstantPool())); return classMaker.toBytes(); } public TokenRangeWithSrc srcRef() { return tokenRangeWithSrc(); } public void addToInitializerMethod(FieldDef field) { isFieldInitializer.set(l(initializers)); initializers.add(new GazelleV_LeftArrowScript.SetField(new GazelleV_LeftArrowScript.GetVar("this"), field.name, field.initializer)); } public boolean hasUserDefinedDefaultConstructor() { return any(methods, m -> m.isConstructor() && empty(m.args)); } public void semiCompileMethod(ClassMaker classMaker, GazelleV_LeftArrowScript.FunctionDef method) { int iMethod = l(methodBodies); methodBodies.add(method); String bodyFieldName = "_body" + iMethod; classMaker.addField(new FieldGen(Const.ACC_PUBLIC | Const.ACC_STATIC, classToBCELType(GazelleV_LeftArrowScript.Evaluable.class), bodyFieldName, classMaker.getConstantPool())); int nArgs = l(method.args); MethodMaker mm = new MethodMaker(classMaker.cg(), Const.ACC_PUBLIC, typeToBCEL(method.returnType), method.name, mapToArray(__208 -> typeToBCEL(__208), method.argTypes)); int iThis = 0, iCtx = mm.frameSize; if (method.isConstructor()) { mm.aload(iThis); mm.invokeConstructor(typeToClass(superClass)); if (initializerMethod != null) { mm.aload(iThis); mm.il.append(mm.factory.createInvoke(classMaker.className(), initializerMethod.name, mm.wrapType(void.class), mm.wrapTypes(new Class[0]), Const.INVOKESPECIAL)); } } mm.newObject(FlexibleVarContext.class); mm.astore(iCtx); mm.aload(iCtx); mm.stringConstant("this"); mm.aload(iThis); mm.invokeVirtual(VarContext.class, void.class, "put", String.class, Object.class); for (int iArg = 0; iArg < nArgs; iArg++) { mm.aload(iCtx); mm.stringConstant(method.args[iArg]); mm.aloadArgWithAutoboxing(iArg); mm.invokeVirtual(VarContext.class, void.class, "put", String.class, Object.class); } mm.getStaticField(classMaker.className(), bodyFieldName, GazelleV_LeftArrowScript.Evaluable.class); mm.aload(iCtx); mm.invokeInterface(GazelleV_LeftArrowScript.Evaluable.class, Object.class, "get", VarContext.class); Type type = method.returnType(); if (type == void.class) mm._return(); else { if (type instanceof Class && isPrimitiveType((Class) type)) { Class c = (Class) type; Class boxed = primitiveToBoxedType(c); mm.checkCast(typeToBCEL(boxed)); mm.invokeVirtual(boxed, c, c + "Value"); mm.returnPrimitive(c); } else { if (type != Object.class) mm.checkCast(typeToBCEL(type)); mm.areturn(); } } mm.done(); } public void fullyCompileMethod(ClassMaker classMaker, GazelleV_LeftArrowScript.FunctionDef method) { MethodMaker mm = new MethodMaker(classMaker, typeToClass(method.returnType()), method.name, repArray(Class.class, Object.class, l(method.args))); var tbc = new LASToByteCode(mm) { public JVMStackCellType compileGetVar(GazelleV_LeftArrowScript.GetVar code) { if (eq(code.var, "this")) { mm.aload(0); return JVMStackCellType.objValue; } int iArg = indexOf(method.args, code.var); if (iArg >= 0) { mm.aload(iArg + 1); return JVMStackCellType.objValue; } return super.compileGetVar(code); } }; tbc.postConversion = stackTop -> mm.convertToObject(stackTop); tbc.compileScript(method.body); mm.areturn(); mm.done(); } public void init(Class c) { for (int iMethod = 0; iMethod < l(methodBodies); iMethod++) { String bodyFieldName = "_body" + iMethod; set(c, bodyFieldName, methodBodies.get(iMethod).body); } setOpt(c, srcRefField(), srcRef()); } public ResolvableLASClass resolvable(ILASClassLoader lasClassLoader) { return new ResolvableLASClass(lasClassLoader, this); } public Object typeToBCEL(LASValueDescriptor descriptor) { return or(descriptor == null ? null : descriptor.javaClass(), Object.class); } public Object typeToBCEL(Type type) { { var __1 = resolvableClassToName(type); if (__1 != null) return __1; } return typeToClass(type); } public void addField(FieldDef field) { fields.add(field); fieldsByName.put(field.name, field); if (field.initializer != null) addToInitializerMethod(field); } public void addMethod(GazelleV_LeftArrowScript.FunctionDef method) { methods.add(method); methodsByName.put(method.name, method); } public String srcRefField() { return "__srcRef"; } } 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 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 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(); } } public interface G2Drawable { public void drawOn(Graphics2D g); default public void drawOn(BufferedImage img) { drawOn(img.createGraphics()); } } static public class OptimizedMultiSet implements IMultiSet { public OptimizedMultiSet() { } public Map map = new HashMap(); transient public MultiSetMap byCount = multiSetMap_innerLinkedHashSet_outerRevTreeMap(); public int size; public int add(A a) { return add(a, 1); } public int add(A a, int count) { if (count <= 0) return 0; size += count; Integer i = map.get(a); if (i != null) byCount.remove(i += count, a); else i = count; map.put(a, i); byCount.add(i, a); return i; } public void remove(A a) { Integer i = map.get(a); if (i != null) { --size; byCount.remove(i, a); if (--i > 0) { map.put(a, i); byCount.add(i, a); } else map.remove(a); } } public void removeAll(A a) { Integer i = map.get(a); if (i == null) return; map.remove(a); byCount.remove(i, a); size -= i; } public boolean isEmpty() { return map.isEmpty(); } public String toString() { return str(map); } public A getMostPopularEntry() { return firstValue(byCount); } public A leastPopularEntry() { return first(lastValue(castMultiSetMapToNavigableMap(byCount))); } public void _doneLoading() { rebuildByCount(); } public void rebuildByCount() { byCount.clear(); for (Map.Entry __0 : _entrySet(map)) { A entry = __0.getKey(); int count = __0.getValue(); byCount.put(count, entry); } } public int get(A a) { return map.get(a); } public int size() { return size; } public int uniqueSize() { return map.size(); } final public List getSortedListDescending() { return highestFirst(); } public List highestFirst() { return asList(multiSetMapValuesIterator(byCount)); } public void truncate(int maxSize) { assertTrue(maxSize >= 0); while (uniqueSize() > maxSize) removeAll(leastPopularEntry()); } public synchronized Set keySet() { return map.keySet(); } } 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 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); } } static public interface Htmlable { default public String headStuff() { return ""; } public String html(); } 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 HCRUD_Data { public Map renderers = new HashMap(); public Map fieldHelp = new HashMap(); public Object currentValue; public boolean humanizeFieldNames = true; public Map rawFormValues; abstract static public class Renderer { public String metaInfo; transient public IF1 preprocessValue; public Object preprocessValue(Object value) { return preprocessValue != null ? preprocessValue.get(value) : preprocessValue_base(value); } final public Object preprocessValue_fallback(IF1 _f, Object value) { return _f != null ? _f.get(value) : preprocessValue_base(value); } public Object preprocessValue_base(Object value) { return value; } } static public class NotEditable extends Renderer { } static public class TextArea extends Renderer implements IFieldsToList { public int cols; public int rows; public TextArea() { } public TextArea(int cols, int rows) { this.rows = rows; this.cols = cols; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + cols + ", " + rows + ")"; } public boolean equals(Object o) { if (!(o instanceof TextArea)) return false; TextArea __1 = (TextArea) o; return cols == __1.cols && rows == __1.rows; } public int hashCode() { int h = -939552902; h = boostHashCombine(h, _hashCode(cols)); h = boostHashCombine(h, _hashCode(rows)); return h; } public Object[] _fieldsToList() { return new Object[] { cols, rows }; } public TextArea(int cols, int rows, IF1 preprocessValue) { this.cols = cols; this.rows = rows; this.preprocessValue = preprocessValue; } } static public class AceEditor extends TextArea { public AceEditor() { } public AceEditor(int cols, int rows) { this.rows = rows; this.cols = cols; } } static public class TextField extends Renderer implements IFieldsToList { public int cols; public TextField() { } public TextField(int cols) { this.cols = cols; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + cols + ")"; } public boolean equals(Object o) { if (!(o instanceof TextField)) return false; TextField __2 = (TextField) o; return cols == __2.cols; } public int hashCode() { int h = 942981037; h = boostHashCombine(h, _hashCode(cols)); return h; } public Object[] _fieldsToList() { return new Object[] { cols }; } } static public class AbstractComboBox extends Renderer implements IFieldsToList { public AbstractComboBox() { } public String toString() { return shortClassName_dropNumberPrefix(this); } public boolean equals(Object o) { return o instanceof AbstractComboBox; } public int hashCode() { int h = -1802496065; return h; } public Object[] _fieldsToList() { return null; } public boolean editable = false; transient public IF1 valueToEntry; public String valueToEntry(Object value) { return valueToEntry != null ? valueToEntry.get(value) : valueToEntry_base(value); } final public String valueToEntry_fallback(IF1 _f, Object value) { return _f != null ? _f.get(value) : valueToEntry_base(value); } public String valueToEntry_base(Object value) { return strOrNull(value); } } static public class ComboBox extends AbstractComboBox implements IFieldsToList { public List entries; public ComboBox() { } public ComboBox(List entries) { this.entries = entries; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + entries + ")"; } public boolean equals(Object o) { if (!(o instanceof ComboBox)) return false; ComboBox __3 = (ComboBox) o; return eq(entries, __3.entries); } public int hashCode() { int h = -547674755; h = boostHashCombine(h, _hashCode(entries)); return h; } public Object[] _fieldsToList() { return new Object[] { entries }; } public ComboBox(String... entries) { this(asList(entries)); } public ComboBox(boolean editable, String... entries) { this(entries); this.editable = editable; } public ComboBox(boolean editable, List entries) { this(entries); this.editable = editable; } public ComboBox(List entries, IF1 valueToEntry) { this.entries = entries; this.valueToEntry = valueToEntry; } } static public class DynamicComboBox extends AbstractComboBox implements IFieldsToList { public String info; public DynamicComboBox() { } public DynamicComboBox(String info) { this.info = info; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + info + ")"; } public boolean equals(Object o) { if (!(o instanceof DynamicComboBox)) return false; DynamicComboBox __4 = (DynamicComboBox) o; return eq(info, __4.info); } public int hashCode() { int h = -737505636; h = boostHashCombine(h, _hashCode(info)); return h; } public Object[] _fieldsToList() { return new Object[] { info }; } public String url; } static public class CheckBox extends Renderer implements IFieldsToList { public CheckBox() { } public String toString() { return shortClassName_dropNumberPrefix(this); } public boolean equals(Object o) { return o instanceof CheckBox; } public int hashCode() { int h = 1601505219; return h; } public Object[] _fieldsToList() { return null; } { metaInfo = "Bool"; } } static public class FlexibleLengthList extends Renderer implements IFieldsToList { public Renderer itemRenderer; public FlexibleLengthList() { } public FlexibleLengthList(Renderer itemRenderer) { this.itemRenderer = itemRenderer; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + itemRenderer + ")"; } public boolean equals(Object o) { if (!(o instanceof FlexibleLengthList)) return false; FlexibleLengthList __5 = (FlexibleLengthList) o; return eq(itemRenderer, __5.itemRenderer); } public int hashCode() { int h = -1874811153; h = boostHashCombine(h, _hashCode(itemRenderer)); return h; } public Object[] _fieldsToList() { return new Object[] { itemRenderer }; } } public String itemName() { return "object"; } public String itemNamePlural() { return plural(itemName()); } public List> list() { return null; } public List> list(IntRange range) { return subListOrFull(list(), range); } public String idField() { return "id"; } public Map emptyObject() { return null; } public Map getObject(Object id) { return null; } public Map getObjectForEdit(Object id) { return getObject(id); } transient public IF1> getObjectForDuplication; public Map getObjectForDuplication(Object id) { return getObjectForDuplication != null ? getObjectForDuplication.get(id) : getObjectForDuplication_base(id); } final public Map getObjectForDuplication_fallback(IF1> _f, Object id) { return _f != null ? _f.get(id) : getObjectForDuplication_base(id); } public Map getObjectForDuplication_base(Object id) { return getObject(id); } public Object createObject(Map fullMap, String fieldPrefix) { throw unimplemented(); } public String deleteObject(Object id) { throw unimplemented(); } public boolean objectCanBeDeleted(Object id) { return true; } transient public IF1 objectCanBeEdited; public boolean objectCanBeEdited(Object id) { return objectCanBeEdited != null ? objectCanBeEdited.get(id) : objectCanBeEdited_base(id); } final public boolean objectCanBeEdited_fallback(IF1 _f, Object id) { return _f != null ? _f.get(id) : objectCanBeEdited_base(id); } public boolean objectCanBeEdited_base(Object id) { return true; } public String updateObject(Object id, Map fullMap, String fieldPrefix) { throw unimplemented(); } public Renderer getRenderer(String field) { return renderers.get(field); } final public Renderer getRenderer(String field, Object value) { this.currentValue = value; try { return getRenderer(field); } finally { this.currentValue = null; } } public String fieldHelp(String field) { return fieldHelp.get(field); } public HCRUD_Data addRenderer(String field, Renderer renderer) { renderers.put(field, renderer); return this; } public HCRUD_Data fieldHelp(String field, String help, String... more) { fieldHelp.put(field, help); for (int i = 0; i + 1 < l(more); i += 2) fieldHelp.put(more[i], more[i + 1]); return this; } public String fieldNameToHTML(String name) { String help = fieldHelp.get(name); return spanTitle(help, htmlencode2(humanizeFieldNames ? humanizeLabel(name) : name)); } public Set filteredFields() { return null; } public List comboBoxSearch(String info, String query) { return null; } public String titleForObjectID(Object id) { return null; } public Pair defaultSortField() { return null; } abstract public class Item extends AbstractMap { public Object id; public Map fullMap; public Item(Object id) { this.id = id; } abstract public Map calcFullMap(); public Map fullMap() { if (fullMap == null) fullMap = calcFullMap(); return fullMap; } public int size() { return l(fullMap()); } public Set> entrySet() { return fullMap().entrySet(); } public boolean containsKey(Object o) { return fullMap().containsKey(o); } public Object get(Object o) { if (fullMap == null && eq(o, idField())) return id; return fullMap().get(o); } public Object put(String key, Object value) { return fullMap().put(key, value); } } } 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; } } 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 IBest { public boolean put(A a, double score); } static public interface IAutoCloseableF0 extends IF0, AutoCloseable { } 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; } } 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 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); } } static public class NotTooOften { public long minDelay; public long lastTime; public NotTooOften() { } public NotTooOften(long minDelay) { this.minDelay = minDelay; } public NotTooOften(double minSeconds) { minDelay = toMS(minSeconds); } final public boolean yo() { return canDoAgain_willDoIfTrue(); } final public boolean get() { return canDoAgain_willDoIfTrue(); } public boolean canDoAgain_willDoIfTrue() { ping(); if (lastTime == 0 || now() >= lastTime + minDelay) { lastTime = now(); return true; } return false; } public void dO(Runnable r) { if (get()) { if (r != null) r.run(); } } } public interface IHasTokenRangeWithSrc { public IHasTokenRangeWithSrc setTokenRangeWithSrc(TokenRangeWithSrc src); public TokenRangeWithSrc tokenRangeWithSrc(); default public String srcText() { var src = tokenRangeWithSrc(); return src == null ? null : src.text(); } } 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()); } } public interface IDoublePt { public double x_double(); public double y_double(); } static public interface ISubList { public List rootList(); public List parentList(); public int subListOffset(); } 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 enum JVMStackCellType { none, objValue, intValue, longValue, floatValue, doubleValue } 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 LASToByteCode implements IFieldsToList { public MethodMaker m; public LASToByteCode() { } public LASToByteCode(MethodMaker m) { this.m = m; } public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + m + ")"; } public Object[] _fieldsToList() { return new Object[] { m }; } public boolean callPing = true; final public LASToByteCode setIVarContext(int iVarContext) { return iVarContext(iVarContext); } public LASToByteCode iVarContext(int iVarContext) { this.iVarContext = iVarContext; return this; } final public int getIVarContext() { return iVarContext(); } public int iVarContext() { return iVarContext; } public int iVarContext = -1; public GazelleV_LeftArrowScript.Script returnableScript; final public LASToByteCode setPostConversion(IF1 postConversion) { return postConversion(postConversion); } public LASToByteCode postConversion(IF1 postConversion) { this.postConversion = postConversion; return this; } final public IF1 getPostConversion() { return postConversion(); } public IF1 postConversion() { return postConversion; } public IF1 postConversion; public JVMStackCellType compileScript(GazelleV_LeftArrowScript.Script script) { returnableScript = script; var stackTop = compile(script); if (postConversion != null) stackTop = postConversion.get(stackTop); return stackTop; } public void compileToObject(GazelleV_LeftArrowScript.Evaluable code) { m.convertToObject(compile(code)); } public JVMStackCellType compile(GazelleV_LeftArrowScript.Evaluable code) { if (code instanceof GazelleV_LeftArrowScript.Const) { Object o = ((GazelleV_LeftArrowScript.Const) code).value; if (o == null) { m.add(new ACONST_NULL()); return JVMStackCellType.objValue; } else if (o instanceof String) { m.stringConstant((String) o); return JVMStackCellType.objValue; } else if (o instanceof Integer) { m.intConstant((Integer) o); return JVMStackCellType.intValue; } else if (o instanceof Double) { m.doubleConstant((Double) o); return JVMStackCellType.doubleValue; } else if (o instanceof Class) { m.classConstant((Class) o); return JVMStackCellType.objValue; } else if (o instanceof Boolean) { m.boolConstant((Boolean) o); return JVMStackCellType.intValue; } else throw fail("Can't compile const value: " + toStringWithClass(o)); } else if (code instanceof GazelleV_LeftArrowScript.Script) { var stackTop = JVMStackCellType.none; for (var step : ((GazelleV_LeftArrowScript.Script) code).steps) { if (stackTop != JVMStackCellType.none) m.add(new POP()); stackTop = compile(step); } return stackTop; } else if (code instanceof GazelleV_LeftArrowScript.CallMethod) { compileToObject(((GazelleV_LeftArrowScript.CallMethod) code).target); m.stringConstant(((GazelleV_LeftArrowScript.CallMethod) code).methodName); argumentsAsArray(((GazelleV_LeftArrowScript.CallMethod) code).args); m.invokeStatic(utils.class, Object.class, "call", Object.class, String.class, Object[].class); return JVMStackCellType.objValue; } else if (code instanceof GazelleV_LeftArrowScript.CallMethodOrGetField) { compileToObject(((GazelleV_LeftArrowScript.CallMethodOrGetField) code).target); m.stringConstant(((GazelleV_LeftArrowScript.CallMethodOrGetField) code).name); m.invokeStatic(utils.class, Object.class, "preciseGetOrCallMethod", Object.class, String.class); return JVMStackCellType.objValue; } else if (code instanceof GazelleV_LeftArrowScript.SetField) { compileToObject(((GazelleV_LeftArrowScript.SetField) code).target); m.stringConstant(((GazelleV_LeftArrowScript.SetField) code).name); compileToObject(((GazelleV_LeftArrowScript.SetField) code).expr); m.invokeStatic(utils.class, Object.class, "set", Object.class, String.class, Object.class); return JVMStackCellType.none; } else if (code instanceof GazelleV_LeftArrowScript.NewObject) { m.classConstant(((GazelleV_LeftArrowScript.NewObject) code).c); argumentsAsArray(((GazelleV_LeftArrowScript.NewObject) code).args); m.invokeStatic(utils.class, Object.class, "nuObject", Class.class, Object[].class); return JVMStackCellType.objValue; } else if (code instanceof GazelleV_LeftArrowScript.Assignment) { compileToObject(((GazelleV_LeftArrowScript.Assignment) code).expression); m.astore(iTemp()); loadVarContext(); m.stringConstant(((GazelleV_LeftArrowScript.Assignment) code).var); m.aload(iTemp()); m.invokeVirtual(VarContext.class, void.class, "set", String.class, Object.class); m.aload(iTemp()); return JVMStackCellType.objValue; } else if (code instanceof GazelleV_LeftArrowScript.While) { var loopStart = m.il.append(new NOP()); BranchInstruction branch1 = null; if (callPing) { m.invokeStatic(utils.class, boolean.class, "ping"); branch1 = new IFEQ(null); m.add(branch1); } compileToBool(((GazelleV_LeftArrowScript.While) code).condition); var branch2 = new IFEQ(null); m.add(branch2); m.discardStackTop(compile(((GazelleV_LeftArrowScript.While) code).body)); m.add(new GOTO(loopStart)); var loopEnd = m.il.append(new NOP()); { if (branch1 != null) branch1.setTarget(loopEnd); } branch2.setTarget(loopEnd); return JVMStackCellType.none; } else if (code instanceof GazelleV_LeftArrowScript.IfThen) { compileToBool(((GazelleV_LeftArrowScript.IfThen) code).condition); var branch1 = new IFEQ(null); m.add(branch1); var stackTop = compile(((GazelleV_LeftArrowScript.IfThen) code).body); if (stackTop == JVMStackCellType.none) { branch1.setTarget(m.here()); return stackTop; } else { m.convertToObject(stackTop); var jumpToEnd = m.forwardGoto(); branch1.setTarget(m.here()); m.loadNull(); jumpToEnd.setTarget(m.here()); return JVMStackCellType.objValue; } } else if (code instanceof GazelleV_LeftArrowScript.GetVar) { return compileGetVar((GazelleV_LeftArrowScript.GetVar) code); } else if (code instanceof GazelleV_LeftArrowScript.ReturnFromScript) { if (((GazelleV_LeftArrowScript.ReturnFromScript) code).script != returnableScript) throw fail("Can only return from current script"); var stackTop = compile(((GazelleV_LeftArrowScript.ReturnFromScript) code).value); if (postConversion != null) stackTop = postConversion.get(stackTop); m.returnWithType(stackTop); return JVMStackCellType.none; } throw fail("Can't compile yet: " + className(code)); } public void argumentsAsArray(GazelleV_LeftArrowScript.Evaluable[] args) { int n = l(args); m.intConst(n); m.add(new ANEWARRAY(m.classRef(Object.class))); for (int iArg = 0; iArg < n; iArg++) { m.dup(); m.intConst(iArg); compileToObject(args[iArg]); m.add(new AASTORE()); } } public void loadVarContext() { assertTrue("Need VarContext", iVarContext >= 0); m.aload(iVarContext); } public Integer iTemp_cache; public int iTemp() { if (iTemp_cache == null) iTemp_cache = iTemp_load(); return iTemp_cache; } public int iTemp_load() { return m.newLocalVar(); } public void compileToBool(GazelleV_LeftArrowScript.Evaluable condition) { var stackTop = compile(condition); if (stackTop == JVMStackCellType.objValue) { m.checkCast(Boolean.class); m.invokeVirtual(Boolean.class, boolean.class, "booleanValue"); } else if (stackTop == JVMStackCellType.intValue) { } else throw fail("Can't convert to bool: " + stackTop); } public JVMStackCellType compileGetVar(GazelleV_LeftArrowScript.GetVar code) { loadVarContext(); m.stringConstant(code.var); m.invokeVirtual(VarContext.class, Object.class, "get", String.class); return JVMStackCellType.objValue; } } 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 ResolvableLASClass implements IResolvableClass { public ResolvableLASClass() { } transient public ILASClassLoader lasClassLoader; public LASClassDef classDef; public Class resolvedClass; public ResolvableLASClass(ILASClassLoader lasClassLoader, LASClassDef classDef) { this.classDef = classDef; this.lasClassLoader = lasClassLoader; } public String resolveToClassName() { return classDef.finalClassName(); } final public Class resolveToClass() { return get(); } public Class get() { if (resolvedClass == null) { if (lasClassLoader == null) throw fail("Need LASClassLoader to define " + classDef.userGivenName); resolvedClass = lasClassLoader.defineLASClass(classDef.finalClassName(), () -> classDef.toBytes()); classDef.init(resolvedClass); } return resolvedClass; } public String toString() { if (resolvedClass != null) return className(resolvedClass); { var __1 = userGivenName(); if (__1 != null) return __1; } if (classDef.classHash_cache != null) return classDef.finalClassNameWithoutPrefix(); return or2(userGivenName(), "script-defined class") + " [unresolved]"; } public String userGivenName() { return classDef.userGivenName; } } 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(); } } } 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 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 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 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 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 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 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)); } } static public class TokenRange extends IntRange { public TokenRange() { } public TokenRange(int start, int end) { this.end = end; this.start = start; } } public interface IPartialFieldIndex { public boolean isApplicableValue(Val val); public Collection getAll(Val val); } 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 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); } } public interface IResolvableClass extends Type { public String resolveToClassName(); public Class resolveToClass(); } static public class VarMatches extends WrappedMap { public VarMatches() { super(new LinkedHashMap()); } public VarMatches(Map map) { this(); utils.putAll(this, map); } } static public interface IF1_IntToInt { public int get(int i); } 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 interface IHasBackRefs { public void _registerBackRef(IRef ref); public void _unregisterBackRef(IRef ref); } 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 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 int clampToInt(long l) { return (int) clamp(l, Integer.MIN_VALUE, Integer.MAX_VALUE); } 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 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 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 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 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 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 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 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 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 JComponent selectImageSnippet(VF1 onSelect) { return selectSnippetID_v1(onSelect); } static public JComponent selectImageSnippet(String defaultID, VF1 onSelect) { return selectSnippetID_v1(defaultID, onSelect); } 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 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 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 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 boolean hasTransparency(BufferedImage img) { return img.getColorModel().hasAlpha(); } static public Graphics2D cloneGraphics(Graphics2D g) { return (Graphics2D) g.create(); } 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 void scaffoldCalled(Object obj, Object function, Object... args) { printShortenedFunctionCall(200, (obj == null ? "" : shorten(20, str(obj)) + " :: ") + function, args); } 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 BufferedImage toBufferedImage(Object o) { return toBufferedImageOpt(o); } 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 boolean imagesHaveSameSize(BufferedImage a, BufferedImage b) { return a != null && b != null && a.getWidth() == b.getWidth() && a.getHeight() == b.getHeight(); } static public boolean scaffoldingEnabled(Object o) { return metaGet(o, "scaffolding") != null; } static public ImageSurface showFullScreenImageSurface(BufferedImage img) { ImageSurface is = jImageSurface(img); showFullScreen(jscroll_centered(disposeFrameOnClick(is))); return is; } static public int getWidth(Component c) { return c == null ? 0 : (int) swingCall(c, "getWidth"); } static public int getHeight(Component c) { return c == null ? 0 : (int) swingCall(c, "getHeight"); } static public void 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 JScrollPane jscroll_center_borderless(Component c) { return jscroll_centered_borderless(c); } 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 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 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 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 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); } }; } 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 A lastKey(SortedMap map) { return empty(map) ? null : map.lastKey(); } 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 void callRunnableWithWrapper(Object wrapper, Runnable r) { if (wrapper == null) callF(r); else callF(wrapper, r); } 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 String fileName(File f) { return f == null ? null : f.getName(); } 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 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 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 void mapRemove(Map map, A key) { if (map != null && key != null) map.remove(key); } static public String loadConceptsStructure(String progID) { return loadTextFilePossiblyGZipped(getProgramFile(progID, "concepts.structure")); } static public String loadConceptsStructure() { return loadConceptsStructure(dbProgramID()); } 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 boolean has(String a, String b, String c) { return false; } static public boolean has(T3 t) { return false; } 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 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 URI uri(String uri) { try { return new URI(uri); } catch (Exception __e) { throw rethrow(__e); } } 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 double sqrt(double x) { return Math.sqrt(x); } 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 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 ListIterator listIterator(List l) { return l == null ? emptyListIterator() : l.listIterator(); } 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 A floorKey(NavigableMap map, A key) { if (map == null) return null; return map.floorKey(key); } static public Map.Entry higherEntry(NavigableMap map, A key) { return map == null ? null : map.higherEntry(key); } static public Map.Entry lastEntry(NavigableMap map) { return map == null ? null : map.lastEntry(); } static public SortedMap subMap(SortedMap map, A fromKey, A toKey) { return map == null ? null : map.subMap(fromKey, toKey); } 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 String humanizeShortName(Object o) { return humanizeLabel(shortName(o)); } static public List lazyMap(final Object f, final List l) { return lazilyMap(f, l); } static public List lazyMap(List l, IF1 f) { return lazilyMap(f, l); } static public List lazyMap(IF1 f, List l) { return lazilyMap(f, l); } static public List subListOrFull(List l, IntRange r) { return r == null ? l : subList(l, r.start, r.end); } static public Map mapMinusKeys(Map map, A... keys) { return mapMinusKeys(map, asList(keys)); } static public Map mapMinusKeys(Map map, Collection keys) { if (empty(keys) || empty(map)) return map; keys = asSet(keys); Map m2 = similarEmptyMap(map); for (Map.Entry __0 : _entrySet(map)) { A key = __0.getKey(); B val = __0.getValue(); if (!keys.contains(key)) m2.put(key, val); } return m2; } static public Map mapMinusKeys(Collection keys, Map map) { return mapMinusKeys(map, keys); } static public Map conceptToMap_gen_withNullValues(Object c) { Map map = litorderedmap("id", str(getLong(c, "id"))); for (String field : conceptFields_gen(c)) map.put(field, getOpt(c, field)); return map; } static public List nonStaticNonTransientFieldObjectsOfType(Class type, Object o) { return filter(nonStaticNonTransientFieldObjects(o), f -> eq(f.getType(), type)); } static public B lastValue(NavigableMap map) { if (map == null) return null; Map.Entry entry = map.lastEntry(); return entry == null ? null : entry.getValue(); } static public void removeLastKey(SortedMap map) { if (nempty(map)) map.remove(lastKey(map)); } static public List valuesAsList(Map map) { return valuesList(map); } static public List cloneKeys(Map map) { return cloneList(keys(map)); } static public String optCastString(Object o) { return optCastToString(o); } static public boolean isSingleLine(String s) { return !containsNewLine(s); } static public boolean isUntrimmed(String s) { return neq(s, trim(s)); } static public boolean englishStringToBool(String s) { return swicOneOf(s, "y", "t", "1"); } static public int cSmartSet(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 (_cSmartSetField(c, (String) values[i], values[i + 1])) ++changes; return changes; } catch (Exception __e) { throw rethrow(__e); } } static public int cSmartSet_withConverter_pcall(Concept c, Object... values) { return cSmartSet_withConverter_pcall(false, c, values); } static public int cSmartSet_withConverter_pcall(boolean verbose, Concept c, Object... values) { return cSmartSet_withConverter_pcall(verbose, new DefaultValueConverterForField(), c, values); } static public int cSmartSet_withConverter_pcall(ValueConverterForField converter, Concept c, Object... values) { return cSmartSet_withConverter_pcall(false, converter, c, values); } static public int cSmartSet_withConverter_pcall(boolean verbose, ValueConverterForField converter, Concept c, Object... values) { try { if (c == null) return 0; warnIfOddCount(values = unrollAndExpandParams(c.getClass(), values)); int changes = 0; for (int i = 0; i + 1 < l(values); i += 2) { try { if (cSmartSetField_withConverter(c, (String) values[i], values[i + 1], converter, verbose)) ++changes; } catch (Throwable __e) { pcallFail(__e); } } return changes; } catch (Exception __e) { throw rethrow(__e); } } static public boolean hasField(Object o, String field) { return findField2(o, field) != null; } static public Concept _getConcept(long id) { return getConcept(id); } static public Concept _getConcept(Concepts concepts, long id) { return getConcept(concepts, id); } static public A _getConcept(Class cc, long id) { return getConcept(cc, id); } static public A _getConcept(Concepts concepts, Class cc, long id) { return getConcept(concepts, cc, id); } 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 A trueFalseNull(Boolean b, A onTrue, A onFalse, A onNull) { return b == null ? onNull : b.booleanValue() ? onTrue : onFalse; } static public boolean hasBackRefs(Concept c) { return c != null && syncNempty(c.backRefs); } static public Class getTypeArgumentAsClass(Type type) { if (type instanceof ParameterizedType) return typeToClass(first(((ParameterizedType) type).getActualTypeArguments())); return null; } static public Type genericFieldType(Object o, String field) { Field f = getField(o, field); return f == null ? null : f.getGenericType(); } 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 Map subMapStartingWith_dropPrefix(Map map, String prefix) { if (map == null) return null; Map map2 = new HashMap(); for (Map.Entry __0 : _entrySet(map)) { String key = __0.getKey(); T value = __0.getValue(); if (startsWith(key, prefix)) map2.put(substring(key, l(prefix)), value); } return map2; } static public Map putOrCreate(Map map, A key, B value) { if (map == null) map = new HashMap(); map.put(key, value); return map; } 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 long clockTimeToSystemTime(long now) { return now == 0 ? 0 : now + clockToSysTimeDiff(); } 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 void replaceLast(List l, A a) { replaceLastElement(l, a); } static public A[] toTypedArray(Class type, Iterable c) { return toArray(c, type); } 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 String formatRecordVars(String recordName, Object... params) { return renderRecordVars(recordName, params); } static public TokenIndexedList3 tokenIndexedList3(List l) { return l instanceof TokenIndexedList3 ? ((TokenIndexedList3) l) : new TokenIndexedList3(l); } static public void tok_ifdef(List tok, IF1 isDefined) { jreplace_dyn(tok, "ifdef or ", (_tok, cIdx) -> { String flag1 = tok.get(cIdx + 2), flag2 = tok.get(cIdx + 6); boolean value = isDefined.get(flag1) || isDefined.get(flag2); return "ifdef " + value; }); tok_conditionals(tok, "ifdef", "endifdef", isDefined, true, false); } static public void tok_pcall_script(List tok) { replaceKeywordBlock(tok, "pcall", "try {", "} catch __e { pcallFail __e }"); } static public void tok_script_settable(List tok) { int i; while ((i = jfind(tok, "settable :")) >= 0) { String id = tok.get(i + 2); int iType = i + 6; String type = tok_script_scanType(tok, i + 6); String getter = "def !synthetic " + id + ": " + type + " { this !_getField_ " + id + "}"; String setter = "def !synthetic " + id + " " + id + ": " + type + " { this " + id + " <- " + id + "; this }"; replaceToken_reTok(tok, i, joinWithSpace(getter, setter)); } } 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 String spaceCombine(Object... l) { return joinNemptiesWithSpace(flattenCollections(ll(l))); } static public AutoCloseable tempRestoreMap(Map map) { if (map == null) return null; var cloned = cloneMap(map); return () -> copyMap(cloned, map); } static public boolean is(String a, String b) { 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 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 int parseHexInt(String s) { return hexToInt(s); } static public int intFromBinary(String s) { return Integer.parseInt(s, 2); } static public Number parseIntOrLong(String s) { long l = parseLong(s); return longIsInt(l) ? (Number) (int) l : (Number) l; } 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 boolean isInterface(Class c) { return c != null && c.isInterface(); } static public Field findFieldInInterfaces(Class c, String field) { if (c == null) return null; for (var intf : allInterfacesImplementedBy(c)) { var __1 = getField(intf, field); if (__1 != null) return __1; } return null; } static public boolean isStaticField(Field f) { return (f.getModifiers() & Modifier.STATIC) != 0; } static public List constructorsWithNumberOfArguments(Class c, int n) { return filter(getDeclaredConstructors_cached(c), con -> l(con.getParameterTypes()) == n); } static public A[] toArrayOrNull(Class type, Collection c) { if (empty(c)) return null; return toArray(type, 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 Class classForNameOpt_noCache(String name) { try { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } catch (Exception __e) { throw rethrow(__e); } } 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 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 B[] valuesArray(Class valueType, Map map) { if (map == null) return null; synchronized (collectionMutex(map)) { int n = map.size(); B[] array = newArray(valueType, n); var it = valueIterator(map); for (int i = 0; i < n; i++) array[i] = it.next(); return array; } } 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 boolean isAnonymousClass(Class c) { return isAnonymousClassName(className(c)); } static public String longestPrefixInTreeSet(String s, TreeSet set) { return longestPrefixInNavigableSet(s, set); } 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 List standardImports_fullyImportedPackages() { return endingWith_dropSuffix(standardImports(), ".*"); } static public List standardImports_singleClasses() { return notEndingWith(standardImports(), ".*"); } static public Field findFieldOfClass(Class c, String field) { return c == null || field == null ? null : getOpt_getFieldMap(c).get(field); } static public boolean classHasMethodNamed(Class c, String method) { if (c == null) return false; return getMethodCache(c).cache.containsKey(method); } 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 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 ISleeper_v2 sleeper() { var ps = pingSource(); return ps == null ? new MultiSleeper() : ps.sleeper(); } static public A syncPopFirst(List l) { if (empty(l)) return null; synchronized (l) { A a = first(l); l.remove(0); return 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 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 A applyWhileNotNull(IF1 f, A o) { if (f == null || o == null) return o; while (licensed()) { A o2 = f.get(o); if (o == null) break; o = o2; } return o; } static public String ok(Object o) { return format("ok *", o); } static public Map> toMap(MultiMap m) { return multiMapToMap(m); } static public MultiSetMap multiSetMap_innerLinkedHashSet_outerRevTreeMap() { return multiSetMap_outerDescTreeMap_innerLinkedHashSet(); } static public IterableIterator multiSetMapValuesIterator(MultiSetMap mm) { return nestedIterator(values(mm.data), __1 -> iterator(__1)); } 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 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 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 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 boolean isDefaultDecolorizer(Decolorizer decolorizer) { return decolorizer == null || decolorizer instanceof Decolorizer.Simple; } 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 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 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 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 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 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 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 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 MultiSetMapWithTopTen generalizedCIMultiSetMapWithTopTen() { MultiSetMapWithTopTen mm = new MultiSetMapWithTopTen(); mm.data = generalizedCIMap(); return mm; } 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 A firstKey(Map map) { return first(keys(map)); } static public A firstKey(IMultiMap map) { return map == null ? null : first(map.keySet()); } static public Timestamp tsNow() { return new Timestamp(); } static public List syncGetAndClear(Collection l) { return syncCloneAndClearList(l); } static public int lDoubleArray(double[] a) { return a == null ? 0 : a.length; } 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 int maximumSafeArraySize() { return Integer.MAX_VALUE - 8; } 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 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 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 int rgbRed(int rgb) { return (rgb >> 16) & 0xFF; } static public int rgbGreen(int rgb) { return (rgb >> 8) & 0xFF; } static public int rgbBlue(int rgb) { return rgb & 0xFF; } 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 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 int asInt(Object o) { return toInt(o); } static public Object trimIfString(Object o) { return o instanceof String ? trim((String) o) : o; } static public MultiSetMap generalizedCIMultiSetMap() { MultiSetMap mm = new MultiSetMap(); mm.data = generalizedCIMap(); return mm; } 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 A vstackCompute(VStack.Computable computation) { return vStackCompute(computation); } static public BufferedImage render(WidthAndHeight size, G2Drawable drawable) { return drawableToImage(size, drawable); } static public Stringable lambdaToToString(IF0 f) { return f == null ? null : new Stringable(f); } static public boolean notNullOrEmptyString(Object o) { return o != null && !eq(o, ""); } static public String loadTextFileResource(ClassLoader cl, String name) { return inputStreamToString(cl.getResourceAsStream(name)); } static public A getAndClear(IVar v) { A a = v.get(); v.set(null); return a; } static public int keysSize(MultiMap mm) { return lKeys(mm); } static public IterableIterator uniqueIterator(Iterator it) { HashSet set = new HashSet(); return iff(() -> { while (licensed()) { if (!it.hasNext()) return endMarker(); A a = it.next(); if (set.add(a)) return a; } return endMarker(); }); } 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 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 public List reversedKeysList(Map map) { return reversedList(keysList(map)); } static public List reversedKeysList(MultiSet ms) { return ms == null ? null : reversedKeysList(ms.map); } static public boolean hasNext(Iterator it) { return it != null && it.hasNext(); } static public void addSeparator(JMenu menu) { menu.addSeparator(); } static public void addSeparator(JPopupMenu menu) { menu.addSeparator(); } static public void truncateContainer(Container c, int n) { swing(() -> { if (c != null) while (c.getComponentCount() > n) c.remove(c.getComponentCount() - 1); }); } static public A packWindow(final A c) { { swing(() -> { Window w = getWindow(c); if (w != null) w.pack(); }); } return c; } static public VF1 toVF1(IVF1 f) { return ivf1ToVF1(f); } static public PtInComponent ptInComponentFromEvent(MouseEvent evt) { return new PtInComponent(evt.getComponent(), pt(evt.getX(), evt.getY())); } static public boolean hasParentOfType(Class type, Component c) { return parentOfType(c, type) != null; } static public long longMul(long a, long b) { return a * b; } 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 double averageBrightness(MakesBufferedImage img) { return averageBrightness(toBufferedImage(img)); } static public double averageBrightness(BufferedImage img) { return new BWImage(img).averageBrightness(); } 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 Set addToSet_create(Set set, A a) { return createOrAddToSet(set, a); } 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 Scored scoredWithMapValue(Map map, A a) { return new Scored(a, toDouble(mapGet(map, a))); } static public String joinNemptiesWithDot(Object... strings) { return joinNempties(".", strings); } static public String joinNemptiesWithDot(Iterable strings) { return joinNempties(".", strings); } static public String manifestPathInJar() { return "META-INF/MANIFEST.MF"; } static public String manifestTextForMainClass(String mainClass) { return "Manifest-Version: 1.0\n" + "Main-Class: " + mainClass + "\n\n"; } static public String compilerBotDestDirSubName() { return "JavaX-Caches/Compilations"; } static public File compilerBotDestDir() { return actualUserDir(compilerBotDestDirSubName()); } static public File compilerBotDestDir(String sub) { return newFile(compilerBotDestDir(), sub); } 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 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 ThreadLocal> showConceptsTable_dropFields = new ThreadLocal(); static public ThreadLocal showConceptsTable_postProcess = new ThreadLocal(); static public ThreadLocal showConceptsTable_afterUpdate = new ThreadLocal(); static public ThreadLocal showConceptsTable_concepts = new ThreadLocal(); static public ThreadLocal showConceptsTable_latestFirst = new ThreadLocal(); static public ThreadLocal showConceptsTable_sorter = new ThreadLocal(); static public int makeConceptsTable_idWidth = 50; static public JTable showConceptsTable(Class c) { JTable table = makeConceptsTable(c); showFrame(plural(shortClassName(c)), table); return table; } static public JTable makeConceptsTable(Class c) { List dropFields = getAndClearThreadLocal(showConceptsTable_dropFields); Object pp = getAndClearThreadLocal(showConceptsTable_postProcess); Object afterUpdate = optParam(showConceptsTable_afterUpdate); Concepts concepts = optParam(showConceptsTable_concepts, db_mainConcepts()); boolean latestFirst = boolParam(showConceptsTable_latestFirst); Object sorter = optParam(showConceptsTable_sorter); boolean useStruct = boolParam(dataToTable_useStruct); final List fields = listMinusList(concatLists(ll("id"), conceptFieldsInOrder(c)), dropFields); final JTable table = sexyTable(); tablePopupMenu(table, new VF2() { public void get(JPopupMenu menu, final Integer row) { try { addMenuItem(menu, "Delete", new Runnable() { public void run() { try { final long id = toLong(getTableCell(table, row, 0)); deleteConcept_sync(concepts, id); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final long id = toLong(getTableCell(table, row, 0));\r\n deleteConcept_syn..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addMenuItem(menu, \"Delete\", r {\r\n final long id = toLong(getTableCell(ta..."; } }); AutoCloseable __1 = tempSetTL(awtOnConceptChanges_concepts, concepts); try { awtOnConceptChanges(table, new Runnable() { public void run() { try { List data = new ArrayList(); Collection l = list(concepts, c); if (sorter != null) l = (Collection) callF(sorter, l); for (Concept cc : l) data.add(map(new F1() { public Object get(String field) { try { Object value = cget(cc, field); return useStruct ? renderForTable(value) : renderForTable_noStruct(value); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O value = cget(cc, field);\r\n ret useStruct ? renderForTable(value)\r\n ..."; } }, fields)); if (latestFirst) reverseInPlace(data); data = (List) postProcess(pp, data); fillTableWithData(table, data, map(__209 -> humanizeFormLabel(__209), fields)); if (table.getColumnCount() > 0) table.getColumnModel().getColumn(0).setMaxWidth(makeConceptsTable_idWidth); pcallF(afterUpdate, table); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "//print(\"Updating concept table\");\r\n new List data;\r\n Collection<..."; } }, true); return table; } finally { _close(__1); } } static public JTable makeConceptsTable(final Class cClass, final Object renderer) { if (renderer == null) return makeConceptsTable(cClass); final Object pp = optParam(showConceptsTable_postProcess); final Object afterUpdate = optParam(showConceptsTable_afterUpdate); final Concepts concepts = optParam(showConceptsTable_concepts, db_mainConcepts()); final boolean latestFirst = boolParam(showConceptsTable_latestFirst); Object sorter = optParam(showConceptsTable_sorter); boolean useStruct = boolParam(dataToTable_useStruct); final JTable table = sexyTable(); AutoCloseable __2 = tempSetTL(awtOnConceptChanges_concepts, concepts); try { awtOnConceptChanges(table, 1000, new Runnable() { public void run() { try { List data = new ArrayList(); Collection l = list(concepts, cClass); if (sorter != null) l = (Collection) callF(sorter, l); for (A c : l) addIfNotNull(data, (Map) pcallF(renderer, c)); if (latestFirst) reverseInPlace(data); data = (List) postProcess(pp, data); AutoCloseable __3 = tempSetTL(dataToTable_useStruct, useStruct); try { dataToTable_uneditable(data, table); pcallF(afterUpdate, table); } finally { _close(__3); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new List data;\r\n Collection l = list(concepts, cClass);\r\n if (s..."; } }); return table; } finally { _close(__2); } } static public JTable showConceptsTable(final Class c, final Object f) { JTable table = makeConceptsTable(c, f); showFrame(plural(shortClassName(c)), table); return table; } static public JTable showConceptsTable(String title, Class cClass, Object f) { return setFrameTitle(title, showConceptsTable(cClass, f)); } static public JPanel jRightAlignedLine(Component... components) { return jrightAlignedLine(components); } static public JPanel jRightAlignedLine(List components) { return jrightAlignedLine(components); } 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 A selectedConcept(JTable table, Class cc) { return (A) getConcept(toLong(selectedTableCell(table, 0))); } 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 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 int selectedRow(JTable t) { return selectedTableRow(t); } static public int tableRowCount(JTable table) { return tableRows(table); } 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 JTextArea typeWriterTextArea() { return newTypeWriterTextArea(); } static public JTextArea typeWriterTextArea(String text) { return newTypeWriterTextArea(text); } 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 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 JComponent unwrap(JComponent c) { return c instanceof JScrollPane ? unwrapScrollPane((JScrollPane) c) : c; } 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 String trimIf(boolean b, String s) { return b ? trim(s) : 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 Set fields(Object c) { return listFields(c); } 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 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 Explain explain(String input, String rules, String className) { Object parseResult = parse1(input, rules); List e = (List) (call(parseResult, "explain", className)); if (e == null) return null; return new Explain(parseResult, e); } static public NotTooOften nto_mins(double minutes) { return new NotTooOften(minutes * 60); } static public boolean tok_whitespaceContainsJavaComments(String s) { int l = l(s) - 1; for (int j = 0; j < l; j++) if (s.charAt(j) == '/') { char d = s.charAt(j + 1); if (d == '*' || d == '/') return true; } return false; } static public String assertGlobalID(String s) { return assertPossibleGlobalID(s); } 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 double mul(double a, double b) { return a * b; } 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 String hInlineSearchForm(String query, String action) { return hInlineSearchForm("q", query, action); } static public String hInlineSearchForm(String queryField, String query, String action) { return hform(hinputfield(queryField, query, "style", "width: 75px") + " " + hsubmit("Search"), "style", "display: inline", "action", action); } static public List keysDeprefixNemptyValue(Map map, String prefix) { List l = new ArrayList(); for (String s : keys(map)) if (startsWith(s, prefix) && nempty(map.get(s))) l.add(s.substring(l(prefix))); return l; } static public String hhiddenStuff(String secretHTML) { String id = aGlobalID(); String js = "document.getElementById(" + jsQuote(id) + ").innerHTML = " + jsQuote(secretHTML) + "; return false;"; return span(ahref("#", "show", "onclick", js), "id", id); } static public String yesNo_short(boolean b) { return b ? "yes" : "no"; } static public > List sortByTransformedMapKey_alphaNum(IF1 transform, Iterable c, B key) { List l = cloneList(c); sort(l, (a, b) -> cmpAlphaNum(transform.get(mapGet(a, key)), transform.get(mapGet(b, key)))); return l; } static public Map mapToMap(IF1> f, Iterable l) { Map map = new HashMap(); for (A o : unnullForIteration(l)) { Pair p = f.get(o); map.put(p.a, p.b); } return map; } static public Map mapToMap(Iterable l, IF1> f) { return mapToMap(f, l); } static public Map mapToMap(Map m, IF2> f) { return mapMapToMap(f, m); } static public Map mapToMap(IF2> f, Map m) { return mapMapToMap(f, m); } static public String unicode_downOrUpPointingTriangle(boolean down) { return down ? unicode_downPointingTriangle() : unicode_upPointingTriangle(); } static public String htmldecode_dropTagsAndComments(String html) { return htmldecode(dropTagsAndHTMLComments(html)); } static public String hCheckBoxMultiSelect_v2(Object... __) { boolean verbose = boolPar("verbose", __); return hscript(replaceDollarVars("\r\n var lastChecked;\r\n\r\n $(document).ready(function() {\r\n console.log(\"document ready\");\r\n $(\"input[type=checkbox]\").click(function(e) {\r\n var verbose = $verbose;\r\n var cls = this.className;\r\n if (verbose) console.log(\"cls=\" + cls);\r\n if (!cls) return;\r\n \r\n if (!lastChecked || lastChecked.className != cls) {\r\n lastChecked = this;\r\n return;\r\n }\r\n \r\n var $chkboxes = $('input[type=checkbox].' + cls);\r\n \r\n if (e.shiftKey) {\r\n var start = $chkboxes.index(this);\r\n var end = $chkboxes.index(lastChecked);\r\n\r\n // change checkboxes, trigger their change event in case there are handlers installed\r\n $chkboxes.slice(Math.min(start, end), Math.max(start,end)+1).prop('checked', lastChecked.checked)\r\n .each(function(idx, chkbox) {\r\n chkbox.dispatchEvent(new Event('change'));\r\n });\r\n }\r\n \r\n lastChecked = this;\r\n });\r\n });\r\n ", "verbose", verbose)); } static public String htableRaw_valignTop(List data, Object... params) { return htableRaw2(data, asList(params), ll(), ll("valign", "top")); } static public String htrickcheckboxWithText(String name, String text, boolean checked, Object... params) { String id = randomID(); return hhidden(name, checked ? "1" : "0") + hcheckbox(null, checked, paramsPlus(params, "id", id, "onclick", "this.previousElementSibling.value=this.checked ? 1 : 0")) + " " + hlabelFor(id, htmlEncode2(text)); } static public String htrickcheckboxWithText(String name, String text) { return htrickcheckboxWithText(name, text, false); } 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 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 List tok_identifiersOnly(String s) { return tok_identifiersInOrder(s); } static public Object getVarOpt(Object o) { return o instanceof IF0 ? ((IF0) o).get() : o; } static public String targetBlankIf(String link, Object contents, boolean targetBlank, Object... params) { return ahref_possiblyTargetBlank(link, contents, targetBlank, params); } static public String targetBlankIf(boolean targetBlank, String link, Object contents, Object... params) { return ahref_possiblyTargetBlank(targetBlank, link, contents, params); } static public String hoption(String text) { return tag("option", htmlEncode2(text)); } static public String unicode_DEL() { return unicodeFromCodePoint(0x2421); } static public String ahrefWithConfirm(String msg, String url, Object contents, Object... params) { return ahref(url, contents, paramsPlus(params, "onClick", "return confirm(" + jsQuote(msg) + ");")); } 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 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 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 double infinity() { return positiveInfinity(); } static public boolean step(Steppable steppable) { return steppable == null ? null : steppable.step(); } static public void vmBus_logMethodCall(String methodName, Object... argsOrVars) { vmBus_send("method_" + methodName, objectArrayPlus_inFront(argsOrVars, "thread", currentThread())); } static public String webChatBotLogsHTML2(final String baseLink, final Map params) { return withDBLock(new F0() { public String get() { try { List l = new ArrayList(); for (Conversation conv : sortByCalculatedFieldDesc(list(Conversation.class), new F1() { public Object get(Conversation c) { try { return empty(c.msgs) ? c.created : last(c.msgs).time; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "empty(c.msgs) ? c.created : last(c.msgs).time"; } })) { List> dialogs = reversed(unnull(conv.oldDialogs)); if (l(conv.msgs) > 1) l.add(webChatBotLogsHTML_formatDialog(str(conv.id), conv.msgs)); int i = 2; for (List msgs : dialogs) if (l(msgs) > 1) l.add(webChatBotLogsHTML_formatDialog(conv.id + "/" + (i++), msgs)); } int perPage = 50, n = parseIntOpt(params.get("n")); return h3_htitle("Chat Logs") + pageNav2(baseLink, l(l), n, perPage, "n") + ul(subList(l, n, n + perPage), null, "style", "margin-top: 1em"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new L l;\r\n for (Conversation conv : sortByCalculatedFieldDesc(list Conv..."; } }); } static public String haudioUpload(Object... params) { return hfileupload(paramsPlus(params, "accept", joinWithComma(mp3mimeType(), oggMimeType(), wavMimeType(), m4aMimeType()))); } static public boolean containsHTMLRedirect(String html) { return cic(html, "http-equiv") && any(__210 -> isHTMLRefreshTag(__210), findAllTagsNamed("meta", html)); } static public String gazelleFavIconSnippet() { return "#1400504"; } 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 Object eval(String text, Collection callableFunctions) { return new Eval(callableFunctions).eval(text); } static public Object eval(String text) { return new Eval().eval(text); } static public Set eval_standardsafefunctions = lithashset("bigint", "compareTo"); static public class Eval { public Collection callableFunctions; public boolean allowReadingStaticFields = false; public HashMap variables = new HashMap(); public List tok; public Object _null = new Object(); public Eval(Collection callableFunctions) { this.callableFunctions = callableFunctions; } public Eval() { callableFunctions = eval_standardsafefunctions; } public void setVar(String id, Object value) { variables.put(id, or(value, _null)); } public Object eval(String text) { tok = javaTok(text); List e = jparse(text, "exp"); return evalExp(e); } public Object evalExp(List e) { String cl = getString(e, 2); if (eq(cl, "quoted")) return unquote(get(tok, (int) get(e, 0))); if (eq(cl, "identifier")) { String id = get(tok, (int) get(e, 0)); Object val = variables.get(id); if (val != null) return val == _null ? null : val; if (allowReadingStaticFields) return get(getMainClass(), id); else throw fail("Unknown variable: " + id); } if (eq(cl, "call")) { return evalCall(e, getMainClass()); } if (eq(cl, "methodcall")) { List e_exp = (List) (get(e, 4)); List e_call = (List) (get(e, 5)); Object obj = evalExp(e_exp); return evalCall(e_call, obj); } throw fail("woot exp: " + structure(e)); } public Object evalCall(List e, Object obj) { List e_name = (List) (get(e, 4)); List e_args = (List) (get(e, 5)); String fname = get(tok, (int) get(e_name, 0)); List args = evalArgs(e_args); return callMethod(obj, fname, args); } public List evalArgs(List e) { return litlist(evalExp(e)); } public Object callMethod(Object obj, String fname, List args) { boolean mayCall = mayCallFunction(fname); if (!hasMethodNamed(obj, fname)) throw fail("Method not defined in " + getClassName(obj) + (mayCall ? "" : ", also not callable") + ": " + fname); if (!mayCallFunction(fname)) throw fail("Not allowed to call method: " + fname); return call(obj, fname, toObjectArray(args)); } public boolean mayCallFunction(String fname) { return callableFunctions.contains(fname); } } static public String assertMD5(String s) { return assertPossibleMD5(s); } 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 double hoursToSeconds(double hours) { return hours * 60 * 60; } static public double favIconCacheHours() { return 24; } static public Object favIconHeaders(Object response) { call(response, "addHeader", "Cache-Control", "public, max-age=" + iround(hoursToSeconds(favIconCacheHours()))); return response; } static public String afterLastEquals(String s) { return s == null ? null : substring(s, s.lastIndexOf('=') + 1); } static public boolean swingConfirm(Component owner, String msg) { return confirmOKCancel(owner, msg); } static public boolean swingConfirm(String msg) { return confirmOKCancel(msg); } static public Object[] objectArrayPlus(Object[] a1, Object... a2) { return arrayPlus(a1, a2); } static public double msToNanos(double ms) { return ms * 1e6; } 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 double msToSeconds(long ms) { return toSeconds(ms); } static public double msToSeconds(double ms) { return toSeconds(ms); } 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 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 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 void syncMapPutOrRemove(Map map, A key, B value) { syncMapPut2(map, key, value); } 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 int getMinimumHeight(final Component c) { return getMinimumSize(c).height; } 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 ClassLoader getVirtualParent(ClassLoader cl) { return (ClassLoader) rcallOpt("getVirtualParent", cl); } 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 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 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 List classNamesInLoadedJigsawModules() { return concatMap(loadedJigsawModuleNames(), moduleName -> classNamesInJigsawModule(moduleName)); } static public void register(Concept c) { registerConcept(c); } 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 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 boolean containsInstance(Iterable i, Class c) { if (i != null) for (Object o : i) if (isInstanceX(c, o)) return true; return false; } 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 long sysNowPlusSeconds_noPing(double seconds) { return sysNow_noPing() + secondsToMS(seconds); } static public long sysNow_noPing() { return System.nanoTime() / 1000000; } 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 String nlToSpace(String s) { return newLinesToSpaces_trim(s); } static public long incAtomicLong(AtomicLong l) { return l.incrementAndGet(); } 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(__211 -> _getClass(__211), args))); } catch (Exception __e) { throw rethrow(__e); } } static public String resolve(String host) { return hostToIP(host); } static public String strOrClassName(Object o) { if (o instanceof Class) return className((Class) o); return str(o); } 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 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 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 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 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 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 Method findSingleInterfaceMethodOrFail(Class intrface) { Method m = findSingleInterfaceMethod(intrface); if (m == null) throw fail(intrface + " is not a single method interface"); return m; } 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 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 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 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 List structTok(String s) { return javaTok_noMLS(s); } 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 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 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 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 volatile public int numberOfCores_value; static public int numberOfCores() { if (numberOfCores_value == 0) numberOfCores_value = Runtime.getRuntime().availableProcessors(); return numberOfCores_value; } static public void syncNotifyAll(Object o) { if (o != null) synchronized (o) { o.notifyAll(); } } 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 String[] mapToStringArray(Map map) { List l = new ArrayList(); for (Object o : keys(map)) { l.add(o); l.add(map.get(o)); } return toStringArray(l); } static public String[] mapToStringArray(IF1 f, Iterable l) { return toStringArray(map(f, l)); } static public String[] mapToStringArray(Iterable l, IF1 f) { return mapToStringArray(f, l); } static public org.apache.bcel.generic.Type typeToBCELType(Type t) { return classToBCELType(getRawTypeClass(t)); } static public String typeToVMSignature(Type t) { Class c = getRawTypeClass(t); if (t instanceof ParameterizedType) { List args = map(__212 -> getRawTypeClass(__212), ((ParameterizedType) t).getActualTypeArguments()); if (nempty(args)) return classNameToByteCodeFormat(c) + "<" + joinMap(args, arg -> classNameToByteCodeFormat(arg) + ";") + ">;"; } return classNameToByteCodeFormat(c) + ";"; } 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 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 isPrimitiveType(Class c) { return c != null && c.isPrimitive(); } 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 String resolvableClassToName(Type type) { if (type instanceof IResolvableClass) return ((IResolvableClass) type).resolveToClassName(); return null; } 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 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 NavigableMap> castMultiSetMapToNavigableMap(MultiSetMap m) { return (NavigableMap) multiSetMapToMap(m); } 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 int areaFromPoints(int x1, int y1, int x2, int y2) { return (x1 - x1) * (y2 - y1); } static public int rectArea(Rect r) { return r == null ? 0 : r.w * r.h; } 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 int fullAlphaMask() { return 0xFF000000; } static public void clearPopupMenu(final JPopupMenu menu) { if (menu != null) { swing(() -> { menu.removeAll(); }); } } static public String humanizeLabel(String s) { return humanizeFormLabel(s); } static public Timestamp sysTimeToTimestamp(long now) { return now == 0 ? null : new Timestamp(now - clockToSysTimeDiff()); } 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 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 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 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 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 Map putOrCreateSyncMap(Map map, A key, B value) { if (map == null) map = syncHashMap(); map.put(key, value); return map; } static public AutoCloseable tempSet(Object o, final String field, Object value) { return tempSetField(o, field, value); } 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 RuntimeException error() { throw new RuntimeException("fail"); } static public RuntimeException error(String msg) { throw new RuntimeException(msg); } 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 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 AtomicLong randomClassName_counter = new AtomicLong(); static public String randomClassName() { return "UserCode" + inc(randomClassName_counter); } static public A print_tabToSingleSpace(A o) { print(tabToSingleSpace(str(o))); return o; } 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 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 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 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 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 boolean hasJPEGExtension(File f) { return ewicOneOf(fileName(f), ".jpg", ".jpeg"); } static public void saveJPG(BufferedImage img, File file) { try { if (!ImageIO.write(img, "jpeg", mkdirsFor(file))) { print("Reconstructing image for saving JPEG"); img = reconstructBufferedImage(img); if (!ImageIO.write(img, "jpeg", file)) throw fail("Couldn't write JPEG: " + file + " (" + img + ")"); } vmBus_send("wroteFile", file); } catch (Exception __e) { throw rethrow(__e); } } static public void saveJPG(File file, BufferedImage img) { try { saveJPG(img, file); } catch (Exception __e) { throw rethrow(__e); } } static public 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 BufferedImage cloneBufferedImage(BufferedImage image) { return copyImage(image); } static public Transferable rawClipboardContents() { try { return Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); } catch (Exception __e) { throw rethrow(__e); } } 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 BufferedImage imageFromDataURL(String url) { return decodeImage(bytesFromDataURL(url)); } static public String getTextFromClipboard() { return (String) getTransferData(rawClipboardContents(), DataFlavor.stringFlavor); } 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 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 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 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 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 JScrollPane jscroll_centered_borderless(Component c) { return borderlessScrollPane(jscroll_centered(c)); } 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 String dynamicClassName(Object o) { if (o instanceof DynamicObject && ((DynamicObject) o).className != null) return "main$" + ((DynamicObject) o).className; return className(o); } static public ListIterator emptyListIterator() { return Collections.emptyListIterator(); } 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 List lazilyMap(IF1 f, List l) { return lazyMap((Object) f, l); } static public List lazilyMap(final Object f, final List l) { return new RandomAccessAbstractList() { final public int size = l(l); public HashMap data = new HashMap(); public int size() { return size; } public Object get(int i) { if (data.containsKey(i)) return data.get(i); Object o = callF(f, l.get(i)); data.put(i, o); return o; } }; } static public List lazilyMap(List l, IF1 f) { return lazilyMap(f, l); } static public String[] conceptFields_gen_drop = { "className", "fieldValues", "id", "created", "_modified", "refs", "backRefs", "_concepts" }; static public Set conceptFields_gen(Object c) { return setMinus(mergeTreeSets(allNonStaticNonTransientFields(c), keys((Map) getOpt_raw(c, "fieldValues"))), conceptFields_gen_drop); } static public Set conceptFields_gen(Class c) { return setMinus(allNonStaticNonTransientFields(c), conceptFields_gen_drop); } static public String optCastToString(Object o) { return o instanceof String ? (String) o : null; } static public boolean swicOneOf(String s, String... l) { for (String x : l) if (swic(s, x)) return true; return false; } static public boolean swicOneOf(String s, Matches m, String... l) { for (String x : l) if (swic(s, x, m)) return true; return false; } static public boolean _cSmartSetField(Concept c, String field, Object value) { try { Field f = setOpt_findField(c.getClass(), field); if (f != null && value != null) { Class actualType = f.getType(); Class type = primitiveToBoxedTypeOpt(actualType); if (type == Integer.class && !(value instanceof Integer)) { if (!setField_trueIfChanged(f, c, toInt(trimIfString(value)))) return false; if (!isTransient(f)) c.change(); return true; } if (type == Boolean.class && value instanceof String) if (actualType == Boolean.class && eq(value, "")) return _csetField(c, field, null); else return _csetField(c, field, eqicOneOf((String) value, "1", "true", "yes")); if (type == GlobalID.class && value instanceof String) return _csetField(c, field, new GlobalID((String) value)); } return _csetField(c, field, value); } catch (Exception __e) { throw rethrow(__e); } } static public Object[] unrollAndExpandParams(Class c, Object[] params) { return expandParams(c, unrollParams(params)); } 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 long clockToSysTimeDiff() { return sysNow() - now(); } 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 void replaceLastElement(List l, A a) { if (nempty(l)) l.set(l(l) - 1, a); } 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 int tok_conditionals(List tok, String keyword, String keywordEnd, IF1 pred, boolean reTokImmediately, boolean noReTok) { int changes = 0; if (tok instanceof IContentsIndexedList) { int[] l = ((IContentsIndexedList) tok).indicesOf(keyword); for (int j = l(l) - 1; j >= 0; j--) { int i = l[j]; if (isIdentifier(get(tok, i + 2))) { tok_conditionals_processConditional(tok, i, keyword, keywordEnd, pred, reTokImmediately && !noReTok); ++changes; } } } else { if (!tok.contains(keyword)) return changes; int i = l(tok); while ((i = rjfind(tok, 1, i - 1, keyword + " ")) >= 0) { ++changes; tok_conditionals_processConditional(tok, i, keyword, keywordEnd, pred, reTokImmediately && !noReTok); } } if (changes != 0 && !reTokImmediately && !noReTok) reTok(tok); return changes; } static public void tok_conditionals_processConditional(List tok, int i, String keyword, String keywordEnd, IF1 pred, boolean reTokImmediately) { int j = jfind(tok, i + 4, keywordEnd); if (j < 0) j = l(tok) - 1; String name = tok.get(i + 2); boolean has = pred.get(name); if (has) { clearTokens_maybeReTok(tok, j, j + 1, reTokImmediately); clearTokens_maybeReTok(tok, i, i + 3, reTokImmediately); } else clearTokens_maybeReTok(tok, i, j + 1, reTokImmediately); } static public List replaceKeywordBlock(List tok, String keyword, String beg, String end) { return replaceKeywordBlock(tok, keyword, beg, end, false, null); } static public List replaceKeywordBlock(List tok, String keyword, String beg, String end, Object cond) { return replaceKeywordBlock(tok, keyword, beg, end, false, cond); } static public List replaceKeywordBlock(List tok, String keyword, String beg, String end, boolean debug, Object cond) { for (int n = 0; n < 1000; n++) { int i = jfind(tok, keyword + " {", cond); if (i < 0) break; int idx = findCodeTokens(tok, i, false, "{"); int j = findEndOfBracketPart(tok, idx); if (debug) { print(toUpper(keyword) + " BEFORE\n" + join(subList(tok, i, j))); print(" THEN " + join(subList(tok, j, j + 10))); } List subList = subList(tok, i - 1, idx); tok.set(j - 1, jreplaceExpandRefs(end, subList)); replaceTokens(tok, i, idx + 1, jreplaceExpandRefs(beg, subList)); reTok(tok, i, j); if (debug) print(toUpper(keyword) + "\n" + join(subList(tok, i, j)) + "\n"); } return tok; } static public String tok_script_scanType(List tok, int iTypeStart) { int iEndOfType = tok_script_findEndOfType(tok, iTypeStart); return joinSubList_cToC(tok, iTypeStart, iEndOfType); } static public void replaceToken_reTok(List tok, int i, String t) { tokSet_withReTok(tok, i, t); } 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 copyMap(Map a, Map b) { if (a == null || b == null) return; b.clear(); b.putAll(a); } static public int hexToInt(String s) { return Integer.parseInt(s, 16); } static public boolean longIsInt(long l) { return l == (int) l; } static public A[] newArray(Class c, int n) { return typedArray(c, n); } static public Iterator valueIterator(Map map) { return map == null ? emptyItIt() : map.values().iterator(); } static public List notEndingWith(Collection l, final String suffix) { return filter(unnull(l), new F1() { public Boolean get(String s) { try { return !endsWith(s, suffix); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "!endsWith(s, suffix)"; } }); } static public List notEndingWith(String suffix, Collection l) { return notEndingWith(l, suffix); } static public int incAtomicInt(AtomicInteger i) { return i.incrementAndGet(); } static public int incAtomicInt(AtomicInteger i, int delta) { return i.addAndGet(delta); } static public MultiSetMap multiSetMap_outerDescTreeMap_innerLinkedHashSet() { return new MultiSetMap(descTreeMap()) { public Set _makeEmptySet() { return new LinkedHashSet(); } }; } 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 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 byte clampToUByte(long l) { return (byte) clamp(l, 0, 255); } static public int zeroToOneToZeroTo255(double brightness) { return iround(brightness * 255.0); } 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 int colorToIntOpaque(Color c) { return c.getRGB() | 0xFF000000; } static public TreeMap generalizedCIMap() { return new TreeMap(generalizedCIComparator()); } static public Color colorFromRGBA(int rgba) { return new Color(rgba, true); } static public BufferedImage drawableToImage(WidthAndHeight size, G2Drawable drawable) { var img = whiteImage(size); { if (drawable != null) drawable.drawOn(img); } return img; } static public String inputStreamToString(InputStream in) { return utf8streamToString(in); } static public int lKeys(MultiMap mm) { return mm == null ? 0 : mm.keysSize(); } 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 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 Rectangle maximumWindowBounds() { return maxWindowBounds(); } 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 boolean boolParam(ThreadLocal tl) { return boolOptParam(tl); } static public boolean boolParam(Object[] __, String name) { return boolOptParam(__, name); } static public boolean boolParam(String name, Object[] __) { return boolOptParam(name, __); } static public List listMinusList(Collection l, Collection stuff) { if (empty(stuff) && l instanceof List) return (List) l; List l2 = cloneList(l); for (Object o : stuff) l2.remove(o); return l2; } static public void deleteConcept_sync(long id) { deleteConcept_sync(db_mainConcepts(), id); } static public void deleteConcept_sync(Concepts concepts, long id) { withDBLock(concepts, new Runnable() { public void run() { try { concepts.deleteConcept(id); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "concepts.deleteConcept(id)"; } }); } static public void deleteConcept_sync(Concept c) { if (c != null) withDBLock(c._concepts, new Runnable() { public void run() { try { c.delete(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.delete()"; } }); } static public void deleteConcept_sync(Concept.Ref ref) { if (ref != null) deleteConcept_sync(ref.get()); } static public int awtOnConceptChanges_defaultDelay = 500; static public ThreadLocal awtOnConceptChanges_concepts = new ThreadLocal(); static public void awtOnConceptChanges(Component component, Object runnable) { awtOnConceptChanges(componentToJComponent(component), runnable, true); } static public void awtOnConceptChanges(JComponent component, final Object runnable, boolean runOnFirstTime) { awtOnConceptChanges(component, awtOnConceptChanges_defaultDelay, 0, runnable, runOnFirstTime); } static public void awtOnConceptChanges(JComponent component, int delay, final Object runnable) { awtOnConceptChanges(component, delay, delay, runnable); } static public void awtOnConceptChanges(JComponent component, int delay, int firstDelay, Object runnable) { awtOnConceptChanges(component, delay, firstDelay, runnable, true); } static public boolean awtOnConceptChanges_debug = false; static public void awtOnConceptChanges(JComponent component, int delay, int firstDelay, final Object runnable, final boolean runOnFirstTime) { final Concepts concepts = or(awtOnConceptChanges_concepts.get(), db_mainConcepts()); installTimer(component, delay, firstDelay, new Runnable() { public long c = runOnFirstTime ? -1 : concepts.changes; public boolean skip = false; public void run() { long _c = concepts.changes; if (awtOnConceptChanges_debug) print("awtOnConceptChanges: " + _c + " / " + c); if (skip) skip = false; else if (_c != c) { c = _c; call(runnable); skip = true; } } }); } static public Object renderForTable(Object o) { { var __1 = toBufferedImageOpt(o); if (__1 != null) return __1; } if (o instanceof String && containsNewLine((String) o)) return escapeNewLines((String) o); return o; } 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 void tableDependButtons(final JTable table, List buttons) { for (Component c : buttons) if (c instanceof JButton) { final JButton b = (JButton) c; table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { b.setEnabled(table.getSelectedRow() >= 0); } }); b.setEnabled(table.getSelectedRow() >= 0); } } 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 Object getMCOpt(String field) { return getOptMC(field); } static public void setMCOpt(String field, Object value) { setOptMC(field, value); } static public JCheckBox centerCheckBox(JCheckBox cb) { return setHorizontalAlignment(SwingConstants.CENTER, cb); } 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 JComponent unwrapScrollPane(JScrollPane sp) { return sp == null ? null : (JComponent) sp.getViewport().getView(); } 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 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 List listIntersectSet(Collection a, Collection b) { return listSetIntersection(a, b); } static public Object parse1_parser; static public Object parse1(String text, String rules) { return parse1(javaTok(text), rules); } static synchronized public Object parse1(List tok, String rules) { if (parse1_parser == null) parse1_parser = run_overBot("#1002719"); return call(parse1_parser, "parse", tok, rules); } 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 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 int cmpAlphaNum(String a, String b) { return alphaNumComparator().compare(a, b); } static public Map mapMapToMap(IF2> f, Map m) { if (m == null) return null; Map map = similarEmptyMap(m); for (Map.Entry e : m.entrySet()) { Pair p = f.get(e.getKey(), e.getValue()); map.put(p.a, p.b); } return map; } static public Map mapMapToMap(Map m, IF2> f) { return mapMapToMap(f, m); } static public String unicode_upPointingTriangle() { return charToString(0x25B2); } 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 List asSynchroList(Iterable l) { return syncList(cloneList(l)); } static public double positiveInfinity() { return Double.POSITIVE_INFINITY; } static public Object[] objectArrayPlus_inFront(Object[] a1, Object... a2) { return concatArrays(a2, a1); } static public String webChatBotLogsHTML() { return withDBLock(new F0() { public String get() { try { List l = new ArrayList(); for (Conversation conv : sortByCalculatedFieldDesc(list(Conversation.class), new F1() { public Object get(Conversation c) { try { return empty(c.msgs) ? c.created : last(c.msgs).time; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "empty(c.msgs) ? c.created : last(c.msgs).time"; } })) { List> dialogs = reversed(unnull(conv.oldDialogs)); l.add(webChatBotLogsHTML_formatDialog(str(conv.id + "/" + (l(dialogs) + 1)), conv.msgs)); int i = l(dialogs); for (List msgs : dialogs) l.add(webChatBotLogsHTML_formatDialog(conv.id + "/" + (i--), msgs)); } return h3_htitle("Chat Logs") + ul(l, null, "style", "margin-top: 1em"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new L l;\r\n for (Conversation conv : sortByCalculatedFieldDesc(list Conv..."; } }); } static public String webChatBotLogsHTML_formatDialog(String id, List msgs) { long startTime = collectMinLong(msgs, "time"); long endTime = collectMaxLong(msgs, "time"); List lc = new ArrayList(); for (Msg m : msgs) if (m.fromUser) lc.add("U: " + i(htmlencode(m.text))); else lc.add("B: " + htmlencode(m.text)); String time1 = formatDateAndTime(startTime); String time2 = formatDateAndTime(endTime); time2 = shortenEndTime(time2, time1); return id + " [" + htmlencode(time1) + " - " + htmlencode(time2) + "]" + ul(lc); } static public String oggMimeType() { return "audio/ogg"; } static public String wavMimeType() { return "audio/wav"; } static public String m4aMimeType() { return "audio/mp4"; } static public boolean isHTMLRefreshTag(String tag) { if (!rtagIs("meta", tag)) return false; Map params = ciTagParams(tag); return eqic(mapGet(params, "http-equiv"), "refresh"); } static public List findAllTagsNamed(List tok, String tag) { List out = new ArrayList(); for (int i = 1; i < l(tok); i += 2) if (isTag(tok.get(i), tag)) out.add(tok.get(i)); return out; } static public List findAllTagsNamed(String tag, List tok) { return findAllTagsNamed(tok, tag); } static public List findAllTagsNamed(String tag, String html) { return findAllTagsNamed(htmlTok(html), tag); } static public Object jparse_parser; static synchronized public List jparse(String text, String className) { if (jparse_parser == null) { jparse_parser = run_overBot("#1002369"); setOpt(jparse_parser, "keepRules", true); } Object parseResult = call(jparse_parser, "jparse", text); return (List) call(parseResult, "explain", className); } static public String assertPossibleMD5(String s) { if (!possibleMD5(s)) throw fail("Not an MD5 signature: " + s); return s; } static public double nanosToSeconds(double nanos) { return nanoSecondsToSeconds(nanos); } static public IMeta toIMeta(Object o) { return initIMeta(o); } static public Map makeObjectMetaMap() { return new CompactHashMap(); } static public IAutoCloseableF0 tempMetaMutex(IMeta o) { return o == null ? null : o._tempMetaMutex(); } 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 loadedJigsawModuleNames() { var moduleLayer = ModuleLayer.boot(); var modules = moduleLayer.modules(); return map(modules, mod -> mod.getName()); } 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 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 long secondsToMS(double seconds) { return toMS(seconds); } 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 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 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 Object callWithVarargs(Object o, String method, Object... args) { return call_withVarargs(o, method, args); } 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 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 Method findSingleInterfaceMethod(Class intrface) { return singletonOpt(findNonDefaultInterfaceMethods(intrface)); } 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 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 OKOrError OKOrError_ok(A a) { return new OKOrError(a); } static public OKOrError OKOrError_error(Throwable e) { return new OKOrError(false, e); } static public AutoCloseable tempOnChangeAndNow(IHasChangeListeners src, Runnable listener) { if (src == null || listener == null) return null; src.onChangeAndNow(listener); return () -> src.removeChangeListener(listener); } static public long fileModificationTime(File f) { return f == null ? 0 : f.lastModified(); } static public Class getRawTypeClass(Type t) { return typeToClass(t); } static public String classNameToByteCodeFormat(String className) { return "L" + className.replace('.', '/'); } static public String classNameToByteCodeFormat(Class c) { return classNameToByteCodeFormat(className(c)); } 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 int colorToInt(Color c) { return c.getRGB() & 0xFFFFFF; } static public Map> multiSetMapToMap(MultiSetMap m) { return m == null ? null : m.data; } 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 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 boolean rectEmpty(Rect r) { return r == null || r.w <= 0 || r.h <= 0; } static public String tabToSingleSpace(String s) { return replace(s, '\t', ' '); } 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 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 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 BufferedImage reconstructBufferedImage(BufferedImage img) { if (img == null) return null; RGBImage rgb = new RGBImage(img); rgb.uncacheBufferedImage(); return rgb.getBufferedImage(); } static public A moveCaretToEnd(A ta) { setCaretPosition(ta, textAreaTextLength(ta)); return ta; } 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 BufferedImage decodeImage(byte[] data) { try { if (empty(data)) return null; return ImageIO.read(new ByteArrayInputStream(data)); } catch (Exception __e) { throw rethrow(__e); } } 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 JScrollPane borderlessScrollPane(JScrollPane sp) { return setBorder(null, withoutViewportBorder(sp)); } static public Set mergeTreeSets(Collection... l) { TreeSet set = new TreeSet(); for (Collection o : l) if (o != null) set.addAll(o); return set; } static public boolean setField_trueIfChanged(Field f, Object o, Object value) { try { if (eq(f.get(o), value)) return false; f.set(o, value); return true; } catch (Exception __e) { throw rethrow(__e); } } static public int rjfind(List tok, String in) { return rjfind(tok, 1, in); } static public int rjfind(List tok, int startIdx, String in) { return rjfind(tok, startIdx, in, null); } static public int rjfind(List tok, int startIdx, int endIndex, String in) { return rjfind(tok, startIdx, endIndex, in, null); } static public int rjfind(List tok, String in, ITokCondition condition) { return rjfind(tok, 1, in, (Object) condition); } static public int rjfind(List tok, String in, Object condition) { return rjfind(tok, 1, in, condition); } static public int rjfind(List tok, int startIdx, String in, Object condition) { List tokin = javaTok(in); jfind_preprocess(tokin); return rjfind(tok, startIdx, tokin, condition); } static public int rjfind(List tok, int startIdx, int endIndex, String in, Object condition) { List tokin = javaTok(in); jfind_preprocess(tokin); return rjfind(tok, startIdx, endIndex, tokin, condition); } static public int rjfind(List tok, List tokin) { return rjfind(tok, 1, tokin); } static public int rjfind(List tok, int startIdx, List tokin) { return rjfind(tok, startIdx, tokin, null); } static public int rjfind(List tok, int startIdx, List tokin, Object condition) { return rfindCodeTokens(tok, startIdx, false, toStringArray(codeTokensOnly(tokin)), condition); } static public int rjfind(List tok, int startIdx, int endIndex, List tokin, Object condition) { return rfindCodeTokens(tok, startIdx, endIndex, false, toStringArray(codeTokensOnly(tokin)), condition); } static public void clearTokens_maybeReTok(List tok, int i, int j, boolean reTok) { clearTokens(tok, i, j); if (reTok) reTok(tok, i, j); } static public String toUpper(String s) { return s == null ? null : s.toUpperCase(); } static public List toUpper(Collection s) { return allToUpper(s); } static public int tok_script_findEndOfType(List tok) { return tok_script_findEndOfType(tok, 1); } static public int tok_script_findEndOfType(List tok, int i) { while (licensed()) { if (eqGet(tok, i + 2, ".") && isIdentifier(get(tok, i + 4))) { i += 4; continue; } if (eqGet(tok, i + 2, "<") && isIdentifier(get(tok, i + 4))) { i = findEndOfTypeArgs(tok, i + 2) - 1; continue; } if (eqGet(tok, i + 2, "[")) { i = findEndOfBracketPart2(tok, i + 2) - 1; continue; } break; } return i + 2; } static public String joinSubList_cToC(List l, int i, int j) { return joinSubList(l, i | 1, j & ~1); } static public void tokSet_withReTok(List tok, int i, String t) { put(tok, i, t); reTok(tok, i, i + 1); } static public A[] typedArray(Class c, int n) { return (A[]) Array.newInstance(c, n); } static public TreeMap descTreeMap() { return revTreeMap(); } 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 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 Rectangle maxWindowBounds() { return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); } static public String userHomeIfNotActual() { String home = userHome(); return eq(home, actualUserHome()) ? null : home; } 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 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 void setOptMC(String field, Object value) { setOpt(mc(), field, value); } 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 List parseInts(Iterable l) { return lambdaMap(__213 -> parseInt(__213), l); } 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 Class run_overBot(String progID) { Class main = hotwire_overBot(progID); callMain(main); return main; } static public boolean possibleGlobalID(String s) { return l(s) == globalIDLength() && allLowerCaseCharacters(s); } static public boolean rtagIs(String tag, String token) { return tagIs(token, tag); } static public Map ciTagParams(String tag) { return asCIMap(tagParams(tag)); } static public double nanoSecondsToSeconds(double nanos) { return nanos * 1e-9; } static public File javaHome() { return envJavaHome(); } static public File javaHome(String sub) { return newFile(envJavaHome(), sub); } 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 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 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 isIPv4(String s) { return s != null && l(javaTokC(s)) == 7 && jfind(javaTok(s), "...") == 1; } 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 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 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 int textAreaTextLength(JTextComponent ta) { return l(getText(ta)); } 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 JScrollPane withoutViewportBorder(JScrollPane sp) { if (sp != null) { swing(() -> { sp.setViewportBorder(null); }); } return sp; } static public int rfindCodeTokens(List tok, String... tokens) { return rfindCodeTokens(tok, 1, false, tokens); } static public int rfindCodeTokens(List tok, boolean ignoreCase, String... tokens) { return rfindCodeTokens(tok, 1, ignoreCase, tokens); } static public int rfindCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) { return rfindCodeTokens(tok, startIdx, ignoreCase, tokens, null); } static public List rfindCodeTokens_specials = litlist("*", "", "", "", "\\*"); static public boolean rfindCodeTokens_debug = false; static public int rfindCodeTokens_indexed, rfindCodeTokens_unindexed; static public int rfindCodeTokens_bails, rfindCodeTokens_nonbails; static public int rfindCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) { return rfindCodeTokens(tok, startIdx, l(tok), ignoreCase, tokens, condition); } static public int rfindCodeTokens(List tok, int startIdx, int endIndex, boolean ignoreCase, String[] tokens, Object condition) { if (rfindCodeTokens_debug) { if (eq(getClassName(tok), "main$IndexedList2")) rfindCodeTokens_indexed++; else rfindCodeTokens_unindexed++; } if (!rfindCodeTokens_specials.contains(tokens[0]) && !tok.contains(tokens[0])) { ++rfindCodeTokens_bails; return -1; } ++rfindCodeTokens_nonbails; outer: for (int i = min(endIndex, tok.size() - tokens.length * 2) | 1; i >= startIdx; i -= 2) { for (int j = 0; j < tokens.length; j++) { String p = tokens[j], t = tok.get(i + j * 2); boolean match = false; if (eq(p, "*")) match = true; else if (eq(p, "")) match = isQuoted(t); else if (eq(p, "")) match = isIdentifier(t); else if (eq(p, "")) match = isInteger(t); else if (eq(p, "\\*")) match = eq("*", t); else match = ignoreCase ? eqic(p, t) : eq(p, t); if (!match) continue outer; } if (condition == null || checkTokCondition(condition, tok, i - 1)) return i; } return -1; } static public int findEndOfTypeArgs(List cnc, int i) { int j = i + 2, level = 1; while (j < cnc.size()) { if (cnc.get(j).equals("<")) ++level; else if (cnc.get(j).equals(">")) --level; if (level == 0) return j + 1; ++j; } return cnc.size(); } static public TreeMap revTreeMap() { return new TreeMap(reverseComparator()); } 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 Class hotwire_overBot(String src) { return hotwire(src); } 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 boolean tagIs(String token, String tag) { if (!startsWith(token, "<")) return false; int l = l(tag); return regionMatchesIC(token, 1, tag, 0, l) && eqOneOf(charAt(token, l + 1), '>', ' '); } static public Map tagParams(String tag) { return getHtmlTagParameters(tag); } static public File envJavaHome() { return newFile(System.getProperty("java.home")); } 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 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 Rect pointsRect(int x1, int y1, int x2, int y2) { return new Rect(x1, y1, x2 - x1, y2 - y1); } 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 Graphics2D graphics(BufferedImage img) { return imageGraphics(img); } 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 boolean getHtmlTagParameters_debug = false; static public Map getHtmlTagParameters(String tag) { if (empty(tag)) return null; List tok = codeTokens(tok_joinMinusIdentifiers(htmlFineTok(tag))); if (getHtmlTagParameters_debug) printStruct(tok); assertEquals("<", tok.get(0)); int i = 1; if (eq(tok.get(1), "/")) ++i; String name = tok.get(i++); if (!isMinusIdentifier(name)) throw fail(tag + " (" + name + ")"); Map map = new HashMap(); while (i < l(tok)) { String t = tok.get(i); if (eqOneOf(t, "/", ">")) break; if (!isMinusIdentifier(t)) throw fail(tag + " (" + t + ")"); ++i; String value = "1"; if (eq(tok.get(i), "=")) { ++i; value = htmlunquote(tok.get(i++)); } map.put(t, value); } return map; } 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 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 ThreadLocal imageGraphics_antiAlias = new ThreadLocal(); static public Graphics2D imageGraphics(BufferedImage img) { return !isFalse(imageGraphics_antiAlias.get()) ? antiAliasGraphics(img) : createGraphics(img); } static public List tok_joinMinusIdentifiers(List tok) { for (int i = 1; i + 4 < l(tok); i += 2) if (isMinusIdentifier(get(tok, i)) && eq(get(tok, i + 2), "-") && isIdentifier(get(tok, i + 4))) { replaceSublist(tok, i, i + 5, ll(join(subList(tok, i, i + 5)))); i -= 2; } return tok; } static public List htmlFineTok(String s) { List tok = 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 break; } tok.add(quickSubstring(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) { 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 ++j; tok.add(quickSubstring(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static public boolean isMinusIdentifier(String s) { if (empty(s)) return false; if (!Character.isJavaIdentifierStart(s.charAt(0)) && !s.startsWith("-")) return false; for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)) && s.charAt(i) != '-') return false; return true; } static public String htmlunquote(String s) { if (s.startsWith("'") && s.endsWith("'") && s.length() >= 2 || s.startsWith("\"") && s.endsWith("\"") && s.length() >= 2) s = s.substring(1, s.length() - 1); return htmldecode(s); } static public Map synchroIdentityHashMap() { return synchroMap(new IdentityHashMap()); } static public void mapPut2(Map map, A key, B value) { if (map != null && key != null) if (value != null) map.put(key, value); else map.remove(key); } static public Graphics2D antiAliasGraphics(BufferedImage img) { return antiAliasOn(createGraphics(img)); } 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; } 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; } } 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 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 class Explain { static public List primitiveClasses = litlist("quoted", "identifier", "any", "int"); public Object parseResult; public List tok; public List e; public List subs = new ArrayList(); public List fullMatchClasses() { return (List) call(parseResult, "fullMatchClasses"); } static public boolean debug = false; public Explain(Object parseResult, List e) { this.e = e; this.parseResult = parseResult; tok = (List) get(parseResult, "tok"); _makeSubExplains(); } public void _makeSubExplains() { for (int i = 4; i < l(e); i++) { List sub = (List) (get(e, i)); int t1 = (int) get(sub, 0); int t2 = (int) get(sub, 1); String className = getString(sub, 2); List subE = sub; if (debug) print("subE first = " + sfu(subE)); if (!primitiveClasses.contains(className)) subE = (List) call(parseResult, "explainFull", t1, t2, className); if (debug) printF("Explaining for " + className() + ": * * * => *", t1, t2, className, subE); if (subE == null) subs.add(null); else subs.add(new Explain(parseResult, subE)); } } public String className() { return getString(e, 2); } public int fromToken() { return (int) get(e, 0); } public int toToken() { return (int) get(e, 1); } public List tok() { return concatLists(litlist(""), subList(tok, fromToken(), toToken() - 1), litlist("")); } public String string() { return join(subList(tok, fromToken(), toToken() - 1)); } public boolean containsToken(String t) { return utils.containsToken(tok(), t); } public void findAll(String className, List out) { if (eq(className, className())) out.add(string()); else for (Explain e : subs) if (e != null) e.findAll(className, out); } public List findAll(String className) { List l = new ArrayList(); findAll(className, l); return l; } public Explain find(String className) { return findFirst(className); } public Explain findFirst(String className) { if (eq(className, className())) return this; return findFirstSub(className); } public Explain findFirstSub(String className) { for (Explain e : subs) if (e != null) { Explain result = e.findFirst(className); if (result != null) return result; } return null; } public boolean is(String className) { return eq(className(), className); } public boolean has(String className) { return findFirst(className) != null; } public boolean hasSub(String className) { return findFirstSub(className) != null; } public void findAll2(String className, List out) { if (is(className)) out.add(this); for (Explain e : subs) if (e != null) e.findAll2(className, out); } public List findAll2(String className) { List l = new ArrayList(); findAll2(className, l); return l; } public Explain prune(String className) { return pruneSubs(className); } public Explain pruneSubs(String className) { for (int i = 0; i < l(subs); ) { Explain e = sub(i); if (e == null) ++i; else if (eq(e.className(), className)) subs.remove(i); else { e.pruneSubs(className); ++i; } } return this; } public Explain sub(int i) { return get(subs, i); } public String str(int i) { List sub = (List) (get(e, 4 + i)); int t1 = (int) get(sub, 0); int t2 = (int) get(sub, 1); return join(subList(tok, t1, t2 - 1)); } public List subs() { return subs; } public boolean singleEqualChild() { if (l(subs) != 1 || first(subs) == null) return false; Explain e = first(subs); return fromToken() == e.fromToken() && toToken() == e.toToken(); } public String prettierAnalysis() { return (String) call(parseResult, "prettierAnalysis"); } } 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()); } } final static public class TokenIndexedList3 extends RandomAccessAbstractList implements IContentsIndexedList, IContentsIndexedList2 { final public HashMap> index = new HashMap(); final public ArrayList list = new ArrayList(); final static public class Token extends HasIndex { public String s; public String toString() { return "Token " + quote(s) + "@" + idx; } } public TokenIndexedList3() { } public TokenIndexedList3(Collection l) { addAll(l); } public String get(int i) { return list.get(i).s; } public int size() { return list.size(); } public String set(int i, String s) { Token t = list.get(i); String old = t.s; if (eq(old, s)) return old; removeFromIdx(t); t.s = s; addToIdx(t); return old; } public boolean add(String s) { ++modCount; Token t = new Token(); t.s = s; t.idx = size(); list.add(t); addToIdx(t); return true; } public void add(int i, String s) { ++modCount; Token t = new Token(); 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 (String s : l) { Token t = new Token(); t.s = s; t.idx = j++; l2.add(t); } list.addAll(i, l2); reorder(i + n); for (Token t : l2) addToIdx(t); return true; } public String remove(int i) { ++modCount; Token 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(Token t) { TreeSet idx = index.get(t.s); idx.remove(t); if (idx.isEmpty()) index.remove(t.s); } public void addToIdx(Token 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(String o) { TreeSet idx = index.get(o); if (idx == null) return emptyIntArray(); int[] a = new int[idx.size()]; int i = 0; for (Token t : idx) a[i++] = t.idx; return a; } public TreeSet indicesOf_treeSetOfHasIndex(String o) { return (TreeSet) index.get(o); } } 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 Stringable implements IFieldsToList { public IF0 f; public Stringable() { } public Stringable(IF0 f) { this.f = f; } public Object[] _fieldsToList() { return new Object[] { f }; } public String toString() { return str(f == null ? null : f.get()); } } static final public class WidthAndHeightFinal extends Meta implements WidthAndHeight, 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"; } } 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 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 scpSet(SingleComponentPanel scp, Component c) { setSCPComponent(scp, c); } static public Object serveFavIcon(String icoSnippet) { return serveFavIcon(loadLibrary(icoSnippet)); } static public Object serveFavIcon(File icoFile) { return favIconHeaders(subBot_serveFile(icoFile, faviconMimeType())); } static public String beforeSlashOrAll(String s) { return beforeSlash_orAll(s); } static public File prepareFile(File file) { return mkdirsForFile(file); } static public File prepareFile(File dir, String name) { return mkdirsForFile(newFile(dir, name)); } static public RGBImage loadImage(String snippetIDOrURL) { return new RGBImage(loadBufferedImage(snippetIDOrURL)); } static public RGBImage loadImage(File f) { return new RGBImage(loadBufferedImage(f)); } 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 A setEditable(A a, boolean b) { if (a != null) { swing(() -> { a.setEditable(b); }); } return a; } 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 Value value(A a) { return new Value(a); } 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 void printF(String s, Object... args) { printFormat(s, args); } static public boolean containsToken(List tok, String token) { return tok.contains(token); } static public String string(Object o) { return String.valueOf(o); } static public List findAll(JFrame f, Class theClass) { List l = new ArrayList(); scanForComponents(f, theClass, l); return l; } static public double fracNonNeg(double d) { return frac_nonNeg(d); } static public double twoPi() { return Math.PI * 2; } static public String plusPrefixUnlessMinus(String s) { return startsWith(s, "-") ? s : "+" + s; } 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 JPanel centerAndEastWithMarginInbetween(Component c, final Component e) { return centerAndEast(c, withLeftMargin(e)); } static public String beforeSlash_orAll(String s) { return takeFirst(smartIndexOf(s, '/'), s); } static public String rgbMD5(RGBImage img) { return md5OfRGBImage(img); } static public void printFormat(String s, Object... args) { print(format(s, args)); } static public double frac_nonNeg(double d) { return mod(d, 1); } 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 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 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()); } } }