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 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 javax.imageio.*;
import java.math.*;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import jdk.incubator.vector.*;
class main {
final static class BWIntegralImage implements MakesBufferedImage, IBWIntegralImage {
int w, h;
int[] data; // 1 entry per pixel
BWIntegralImage() {}
BWIntegralImage(File f) { this(loadImage2(f)); }
BWIntegralImage(MakesBufferedImage img) { this(toBufferedImage(img)); }
//*(BufferedImage img) { this(BWImage(img)); }
BWIntegralImage(BufferedImage image) { try {
alloc(image.getWidth(), image.getHeight());
// Just grab directly into data array
PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, w, h, data, 0, w);
if (!pixelGrabber.grabPixels())
throw fail("Could not grab pixels");
int sum = 0;
for (int x = 0; x < w; x++) {
int packed = data[x];
int brightness = packedToBrightness(packed);
data[x] = (sum += brightness);
}
int i = w;
for (int y = 1; y < h; y++) {
sum = 0;
for (int x = 0; x < w; x++) {
int packed = data[i];
int brightness = packedToBrightness(packed);
sum += brightness;
data[i] = sum + data[i-w];
i++;
}
} // for y
} catch (Exception __e) { throw rethrow(__e); } }
BWIntegralImage(BWImage img) {
alloc(img.w(), img.h());
data = new int[w*h];
int i = 0;
for (int y = 0; y < h; y++) {
int sum = 0;
for (int x = 0; x < w; x++) {
sum += img.getByte(x, y) & 0xFF;
data[i] = y > 0 ? sum + data[i-w] : sum;
i++;
}
}
}
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];
}
// pixels outside of image are considered black
int get(int x, int y) {
return x < 0 || y < 0 || x >= w || y >= h ? 0
: data[min(y, h-1)*w+min(x, w-1)];
}
public int getIIValue(int x, int y) { 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);
}
int getPixel(int x, int y) {
return bwIntegralImage_sumRect(this, x, y, x+1, y+1);
}
int getPixel(Pt p) { return getPixel(p.x, p.y); }
public int getWidth() { return w; }
public int getHeight() { return h; }
// unoptimized
public BufferedImage getBufferedImage() {
return scaleDownUsingIntegralImageBW(this, w).getBufferedImage();
}
int packedToBrightness(int packed) {
int b = (packed & 0xFF);
int r = ((packed >> 16) & 0xFF);
int g = ((packed >> 8) & 0xFF);
return (r+g+b+1)/3;
}
}
static BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
static BufferedImage toBufferedImage(Object o) {
return toBufferedImageOpt(o);
}
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(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
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 int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x) x = d;
return x;
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static 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);
}
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static 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 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 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 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 Object get(String field, Object o) {
return get(o, field);
}
static double doubleRatio(double x, double y) {
return y == 0 ? 0 : x/y;
}
static 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 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 BWImage scaleDownUsingIntegralImageBW(int w, BWIntegralImage img) {
return scaleDownUsingIntegralImageBW(img, w);
}
static BWImage scaleDownUsingIntegralImageBW(BWIntegralImage img, int w) {
return scaleDownUsingIntegralImageBW(img, w, iround(w*img.h/(double) img.w));
}
static BWImage scaleDownUsingIntegralImageBW(BWIntegralImage img, int w, int h) {
int w1 = img.w, h1 = img.h;
BWImage out = new BWImage(w, h);
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
int x1 = x*w1/w, x2 = max(x1+1, (x+1)*w1/w);
int y1 = y*h1/h, y2 = max(y1+1, (y+1)*h1/h);
int area = (x2-x1)*(y2-y1);
int pixel = bwIntegralImage_sumRect(img, x1, y1, x2, y2)/area;
out.setByte(x, y, (byte) pixel);
}
return out;
}
static BWImage scaleDownUsingIntegralImageBW(IBWIntegralImage img, int w) { return scaleDownUsingIntegralImageBW(img, w, iround(w*img.getHeight()/(double) img.getWidth())); }
static BWImage scaleDownUsingIntegralImageBW(IBWIntegralImage img, int w, int h) {
int w1 = img.getWidth(), h1 = img.getHeight();
BWImage out = new BWImage(w, h);
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
int x1 = x*w1/w, x2 = max(x1+1, (x+1)*w1/w);
int y1 = y*h1/h, y2 = max(y1+1, (y+1)*h1/h);
int area = (x2-x1)*(y2-y1);
int pixel = bwIntegralImage_sumRect(img, x1, y1, x2, y2)/area;
out.setByte(x, y, (byte) pixel);
}
return out;
}
static boolean loadBufferedImage_useImageCache = true;
static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try {
ping();
if (snippetIDOrURLOrFile == null) return null;
if (isURL(snippetIDOrURLOrFile))
return imageIO_readURL(snippetIDOrURLOrFile);
if (isAbsolutePath(snippetIDOrURLOrFile))
return loadBufferedImage(new File(snippetIDOrURLOrFile));
if (!isSnippetID(snippetIDOrURLOrFile))
throw fail("Not a URL or snippet ID or file: " + 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();
// fall back to loading from sourceforge
}
}
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"));
//Log.info("Cached image.");
}
//Log.info("Loaded image.");
return image;
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage loadBufferedImage(File file) { try {
return file.isFile() ? ImageIO.read(file) : null;
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage toBufferedImageOpt(Object o) {
if (o instanceof BufferedImage) return (BufferedImage) o;
if (o instanceof MakesBufferedImage)
return ((MakesBufferedImage) o).getBufferedImage();
if (o instanceof File)
if (isImageFile(((File) o)))
return loadImage2(((File) o));
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");
if (eq(c, "main$PNGFile"))
return (BufferedImage) call(o, "getImage");
return null;
}
static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
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(Object o) {
return o == null ? 0
: o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: o instanceof Collection ? l((Collection) o)
: o instanceof Object[] ? l((Object[]) o)
: o instanceof boolean[] ? l((boolean[]) o)
: o instanceof byte[] ? l((byte[]) o)
: o instanceof char[] ? l((char[]) o)
: o instanceof short[] ? l((short[]) o)
: o instanceof int[] ? l((int[]) o)
: o instanceof float[] ? l((float[]) o)
: o instanceof double[] ? l((double[]) o)
: o instanceof long[] ? l((long[]) o)
: (Integer) call(o, "size");
}
static 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 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 int iround(double d) {
return (int) Math.round(d);
}
static int iround(Number n) {
return iround(toDouble(n));
}
static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static 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 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 byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x) x = d;
return x;
}
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll = false;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions = false;
static Map ping_actions = newWeakHashMap();
static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
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 boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
static BufferedImage imageIO_readURL(String url) { try {
return ImageIO.read(new URL(url));
} catch (Exception __e) { throw rethrow(__e); } }
static boolean isAbsolutePath(String s) {
return s != null && new File(s).isAbsolute();
}
static boolean isAbsolutePath(File f) {
return f != null && f.isAbsolute();
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
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 IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
static File imageSnippetsCacheDir() {
return javaxCachesDir("Image-Snippets");
}
static String snippetImageURL_http(String snippetID) {
return snippetImageURL_http(snippetID, "png");
}
static String snippetImageURL_http(String snippetID, String contentType) {
return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080");
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
static boolean print_silent = false; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal