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.*;
// auto-zoom
import static x30_pkg.x30_util.DynamicObject;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import java.awt.geom.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import javax.swing.border.*;
import javax.swing.undo.UndoManager;
import java.awt.datatransfer.StringSelection;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import java.awt.datatransfer.UnsupportedFlavorException;
import javax.swing.Icon;
class main {
static ImageSurface pixelatedZoomedImageSurface() {
return pixelatedImageSurface().setAutoZoomToDisplay(true);
}
// auto-zoom
static ImageSurface pixelatedZoomedImageSurface(MakesBufferedImage img) { return pixelatedZoomedImageSurface(toBufferedImage(img)); }
static ImageSurface pixelatedZoomedImageSurface(BufferedImage img) {
var is = pixelatedZoomedImageSurface();
is.setImage(img);
return is;
}
// fixed zoom
static ImageSurface pixelatedZoomedImageSurface(double zoom, MakesBufferedImage img) { return pixelatedZoomedImageSurface(zoom, toBufferedImage(img)); }
static ImageSurface pixelatedZoomedImageSurface(double zoom, BufferedImage img) {
return pixelatedImageSurface(img).setZoom(zoom);
}
// fixed zoom
static ImageSurface pixelatedZoomedImageSurface(double zoom) {
return pixelatedImageSurface().setZoom(zoom);
}
static ImageSurface pixelatedImageSurface() {
var is = imageSurface();
imageSurface_pixelated(is);
return is;
}
static ImageSurface pixelatedImageSurface(MakesBufferedImage img) { return pixelatedImageSurface(toBufferedImage(img)); }
static ImageSurface pixelatedImageSurface(BufferedImage img) {
var is = pixelatedImageSurface();
is.setImage(img);
return is;
}
static BufferedImage toBufferedImage(Object o) {
return toBufferedImageOpt(o);
}
static ImageSurface imageSurface(BufferedImage img) {
return swingNu(ImageSurface.class, img);
}
static ImageSurface imageSurface(MakesBufferedImage img) {
return swingNu(ImageSurface.class, img);
}
static ImageSurface imageSurface() {
return swingNu(ImageSurface.class);
}
static void imageSurface_pixelated(ImageSurface imageSurface) {
if (imageSurface == null) return;
imageSurface.setDoubleBuffered(true); // solve flickering when partially obscured
imageSurface.noAlpha = true;
imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR;
repaint(imageSurface);
}
static void imageSurface_pixelated(ImageSurface imageSurface, boolean pixelated) {
if (pixelated)
imageSurface_pixelated(imageSurface);
else
imageSurface_unpixelated(imageSurface);
}
static 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);
// Keep this because it also works on imported objects
if (eqOneOf(c, "main$BWImage", "main$RGBImage"))
return (BufferedImage) call(o, "getBufferedImage");
return null;
}
static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static A repaint(A c) {
if (c != null) c.repaint();
return c;
}
static void imageSurface_unpixelated(ImageSurface imageSurface) {
if (imageSurface == null) return;
imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_BILINEAR;
repaint(imageSurface);
}
// this copies to RGBA
static 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;
}
// this one stays in color model. inconsistent i guess
static 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 String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static Object call(Object o) {
return callF(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
//ret call_cached(o, method, args);
return call_withVarargs(o, method, args);
}
static 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);"; }});
}
// undefined color, seems to be all black in practice
// This is without alpha?
static BufferedImage newBufferedImage(int w, int h) {
return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}
static BufferedImage newBufferedImage(int w, int h, RGB rgb) {
return newBufferedImage(w, h, rgb.getColor());
}
static 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 BufferedImage newBufferedImage(Pt p, Color color) {
return newBufferedImage(p.x, p.y, color);
}
// This one is with alpha...
static BufferedImage newBufferedImage(int w, int h, int[] pixels) {
return intArrayToBufferedImage(pixels, w, h);
}
// changes & returns canvas
static BufferedImage drawImage(BufferedImage canvas, Image img, Pt p) {
return drawImageOnImage(img, canvas, p.x, p.y);
}
static void drawImage(BufferedImage g, Image img) { drawImage(graphics(g), img); }
static void drawImage(Graphics2D g, Image img) {
drawImage(g, img, 0, 0);
}
static void drawImage(Graphics2D g, Image img, Pt p) {
drawImage(g, img, p.x, p.y);
}
static void drawImage(Graphics2D g, Image img, int x, int y) {
{ if (g != null) g.drawImage(img, x, y, null); }
}
static boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
// a little kludge for stuff like eq(symbol, "$X")
static boolean eq(Symbol a, String b) {
return eq(str(a), b);
}
static Map> callF_cache = newDangerousWeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static A callF(IF0 f) {
return f == null ? null : f.get();
}
static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static B callF(A a, IF1 f) {
return f == null ? null : f.get(a);
}
static C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static void callF(A a, IVF1 f) {
if (f != null) f.get(a);
}
static void callF(IVF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Runnable r) { { if (r != null) r.run(); } return null; }
static Object callF(Object f, Object... args) {
return safeCallF(f, args);
}
static 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));
}
// used internally
static 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 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);
// try varargs
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 + "(" + joinWithComma(classNames(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);
// try varargs
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 + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) { throw rethrow(__e); } }
static Object swing(Object f) {
return swingAndWait(f);
}
static void swing(Runnable f) {
swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static A swing(IF0 f) {
return (A) swingAndWait(f);
}
static Object nuObject(String className, Object... args) { try {
return nuObject(classForName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }
// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
ret nuObject(_getClass(realm, className), args);
}*/
static A nuObject(Class c, Object... args) { try {
if (args == null || args.length == 0) return nuObjectWithoutArguments(c); // cached!
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found"
+ (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static 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 RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
static A or(A a, A b) {
return a != null ? a : b;
}
// from: https://stackoverflow.com/questions/14416107/int-array-to-bufferedimage
// pixels are RGB pixels
static BufferedImage intArrayToBufferedImage(int[] pixels, int w, int h) {
int[] bitMasks = new int[]{0xFF0000, 0xFF00, 0xFF, 0xFF000000};
SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, w, h, bitMasks);
DataBufferInt db = new DataBufferInt(pixels, pixels.length);
WritableRaster wr = Raster.createWritableRaster(sm, db, new Point());
return new BufferedImageWithMeta(ColorModel.getRGBdefault(), wr, false, null);
}
// changes & returns canvas
static BufferedImage drawImageOnImage(Image img, BufferedImage canvas, int x, int y) {
createGraphics(canvas).drawImage(img, x, y, null);
return canvas;
}
static BufferedImage drawImageOnImage(Image img, BufferedImage canvas) {
return drawImageOnImage(img, canvas, 0, 0);
}
static Graphics2D graphics(BufferedImage img) {
return imageGraphics(img);
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static String str(char[] c, int offset, int count) {
return new String(c, offset, count);
}
static Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(short[] a) { return a == null ? 0 : a.length; }
static int l(long[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(double[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Iterator i) { return iteratorCount_int_close(i); } // consumes the iterator && closes it if possible
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); }
static long l(File f) { return f == null ? 0 : f.length(); }
static int l(IMultiMap mm) { return mm == null ? 0 : mm.size(); }
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(Object... objects) { throw new Fail(objects); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static 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 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 Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
// Note: The error reporting only works with Java VM option --illegal-access=deny
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static final Map callOpt_cache = newDangerousWeakHashMap();
static 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);
// TODO: (super-rare) case where method exists static and non-static
// with different args
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); } }
// no longer synchronizes! (see #1102990)
static _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 boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static 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);
// TODO: optimize
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 String joinWithComma(Collection c) {
return join(", ", c);
}
static String joinWithComma(Object... c) {
return join(", ", c);
}
static String joinWithComma(String... c) {
return join(", ", c);
}
static String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static List classNames(Collection l) {
return getClassNames(l);
}
static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) { throw rethrow(__e); } }
static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() { public void run() { try {
result.set(callF(f));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; }});
return result.get();
}
}
static Map classForName_cache = synchroHashMap();
static Class classForName(String name) { return classForName(name, null); }
static Class classForName(String name, Object classFinder) {
// first clause is when we're in class init
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 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 Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static Object nuObjectWithoutArguments(String className) { try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) { throw rethrow(__e); } }
static A nuObjectWithoutArguments(Class c) { try {
if (nuObjectWithoutArguments_cache == null)
// in class init
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 Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors())
if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
static List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static 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 void _handleError(Error e) {
//call(javax(), '_handleError, e);
}
static Map createGraphics_modulators = synchroIdentityHashMap();
static Graphics2D createGraphics(BufferedImage img) {
Graphics2D g = img.createGraphics();
Object mod = createGraphics_modulators.get(img);
if (mod != null)
callF(mod, g);
return g;
}
// mod: voidfunc(Graphics2D)
static void createGraphics_modulate(BufferedImage img, Object mod) {
mapPut2(createGraphics_modulators, img, mod);
}
static ThreadLocal imageGraphics_antiAlias = new ThreadLocal();
static Graphics2D imageGraphics(BufferedImage img) {
return !isFalse(imageGraphics_antiAlias.get()) ? antiAliasGraphics(img) : createGraphics(img);
}
static List _registerDangerousWeakMap_preList;
static A _registerDangerousWeakMap(A map) {
return _registerDangerousWeakMap(map, null);
}
static A _registerDangerousWeakMap(A map, Object init) {
callF(init, map);
if (init instanceof String) {
final String f = (String) init;
init = new VF1