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 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 javax.swing.event.AncestorListener; import javax.swing.event.AncestorEvent; import javax.swing.Timer; import javax.swing.Timer; public class main { public static void main(String[] args) throws Exception { final JWindow window = showAnimationInTopRightCorner("#1005611", "Please click somewhere"); // TODO: onClosing(window, "trackOneClick_cancel"); trackOneClick(new Object() { void get(Point p) { window.dispose(); showAnimation("#1005611", "You clicked at " + p.x + "/" + p.y, 3); pointArrowsToArea(new Rectangle(p.x, p.y, 0, 0), 5); } public String toString() { return "window.dispose();\n showAnimation(\"#1005611\", \"You clicked at \" + p.x + \"/\" + p.y, 3);\n pointArrowsToArea(new Rectangle(p.x, p.y, 0, 0), 5);"; }}); } static JWindow showAnimation(String imageID, double seconds) { return showAnimationInTopRightCorner(imageID, seconds); } static JWindow showAnimation(String imageID) { return showAnimationInTopRightCorner(imageID); } static JWindow showAnimation(String imageID, String text, double seconds) { return showAnimationInTopRightCorner(imageID, text, seconds); } // onClick: voidfunc(Point, int) - 2nd parameter is button (1 to 3) // or voidfunc(Point) static void trackOneClick(final Object onClick) { forwardOneClick(new Object() { Object get(final Point p, final int button) { swingLater(new Runnable() { public void run() { try { // Let the window go away first callFOpt(onClick, p, button); callFOpt(onClick, p); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); return false; // don't forward click } public String toString() { return "awt { // Let the window go away first\n callFOpt(onClick, p, button);\n callFOpt(onClick, p);\n }\n false; // don't forward click"; }}); } static int pointArrowsToArea_inset = 20; static List pointArrowsToArea(Rectangle r) { int midX = r.x+r.width/2, midY = r.y+r.height/2; int inset = pointArrowsToArea_inset; String iLeft = "#1005637", iDown = "#1005636", iRight = "#1005634", iUp = "#1005635"; List windows = new ArrayList(); BufferedImage img = loadImage2(iLeft); addIfNotNull(windows, freeFloatingAnimation(iLeft, r.x+r.width+inset, midY-img.getHeight()/2)); img = loadImage2(iDown); addIfNotNull(windows, freeFloatingAnimation(iDown, midX, r.y-inset-img.getHeight())); img = loadImage2(iRight); addIfNotNull(windows, freeFloatingAnimation(iRight, r.x-inset-img.getWidth(), midY-img.getHeight()/2)); img = loadImage2(iUp); addIfNotNull(windows, freeFloatingAnimation(iUp, midX, r.y+r.height+inset)); return windows; } static List pointArrowsToArea(Rectangle r, double seconds) { return disposeWindowsAfter(secondsToMS(seconds), pointArrowsToArea(r)); } static boolean showAnimationInTopRightCorner_alwaysOnTop = true; // automatically switches to AWT thread for you // text is optional text below image static JWindow showAnimationInTopRightCorner(final String imageID, final String text) { if (isHeadless()) return null; return (JWindow) swingAndWait(new Object() { Object get() { JLabel label = new JLabel(imageIcon(imageID)); 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 __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); if (showAnimationInTopRightCorner_alwaysOnTop) window.setAlwaysOnTop(true); return window; } public String toString() { return "JLabel label = new JLabel(imageIcon(imageID));\n if (nempty(text)) {\n label.setText(text);\n label.setVerticalTextPosition(SwingConstants.BOTTOM);\n label.setHorizontalTextPosition(SwingConstants.CENTER);\n }\n final JWindow window = showInTopRightCorner(label);\n onClick(label, r { window.dispose() });\n if (showAnimationInTopRightCorner_alwaysOnTop)\n window.setAlwaysOnTop(true);\n ret window;"; }}); } static JWindow showAnimationInTopRightCorner(final String imageID) { return showAnimationInTopRightCorner(imageID, ""); } static JWindow showAnimationInTopRightCorner(String imageID, double seconds) { return showAnimationInTopRightCorner(imageID, "", seconds); } static JWindow showAnimationInTopRightCorner(String imageID, String text, double seconds) { if (isHeadless()) return null; return disposeWindowAfter(iround(seconds*1000), showAnimationInTopRightCorner(imageID, text)); } static List disposeWindowsAfter(long delay, final List l) { swingLater(delay, new Runnable() { public void run() { try { for (Window w : unnull(l)) w.dispose() ; } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); return l; } static Boolean isHeadless_cache; static boolean isHeadless() { if (isHeadless_cache != null) return isHeadless_cache; if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true; // Also check if AWT actually works. // If DISPLAY variable is set but no X server up, this will notice. try { isAWTThread(); return isHeadless_cache = false; } catch (Throwable _e) { return isHeadless_cache = true; } } static void onClick(JComponent c, final Object runnable) { c.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { callF(runnable, e); } }); } static int iround(double d) { return (int) Math.round(d); } static Object callFOpt(Object f, Object... args) { if (f == null) return null; if (f instanceof Runnable) { ((Runnable) f).run(); return null; } else if (f instanceof String) return callOpt(mc(), (String) f, args); else return callOpt(f, "get", args); } static int forwardOneClick_windowSize = 11; // odd should look nice. Set to 1 for an invisible window static int forwardOneClick_clickDelay = 0; // Delay in ms between closing window and forwarding click. 0 seems to work fine. static int forwardOneClick_trackingSpeed = 10; // How often to move the window (ms) // onClick: voidfunc(Point, int) - 2nd parameter is button (1 to 3) // if you make it a func and return false, click is not forwarded static void forwardOneClick(final Object onClick) { swingNowOrLater(new Runnable() { public void run() { try { final JWindow window = new JWindow(); final int windowSize = forwardOneClick_windowSize; window.setSize(windowSize, windowSize); window.setVisible(true); window.setAlwaysOnTop(true); JPanel panel = singleColorPanel(Color.red); window.setContentPane(panel); revalidate(window); final Robot robot = new Robot(); panel.addMouseListener(new MouseAdapter() { public void mouseReleased(final MouseEvent e) { window.setVisible(false); final int b = e.getButton(); final int mod = b == 1 ? InputEvent.BUTTON1_DOWN_MASK : b == 2 ? InputEvent.BUTTON2_DOWN_MASK : InputEvent.BUTTON3_DOWN_MASK; final Point point = getMouseLocation(); swingLater(forwardOneClick_clickDelay, new Runnable() { public void run() { try { if (isFalse(callF(onClick, point, b))) return; robot.mousePress(mod); robot.mouseRelease(mod); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); } }); swingEvery(window, forwardOneClick_trackingSpeed, new Runnable() { public void run() { try { Point p = getMouseLocation(); window.setLocation(p.x-windowSize/2, p.y-windowSize/2); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); } static boolean nempty(Collection c) { return !isEmpty(c); } static boolean nempty(CharSequence s) { return !isEmpty(s); } static boolean nempty(Object[] o) { return !isEmpty(o); } static boolean nempty(Map m) { return !isEmpty(m); } static boolean nempty(Iterator i) { return i != null && i.hasNext(); } static A disposeWindowAfter(int delay, final A w) { if (w != null) swingLater(delay, new Runnable() { public void run() { try { w.dispose(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); return w; } // Note: Doesn't show anything if are is not completely in allowed bounds static JWindow freeFloatingAnimation(String imageID, int x, int y, double seconds) { return disposeWindowAfter(iround(seconds*1000), freeFloatingAnimation(imageID, x, y)); } static JWindow freeFloatingAnimation(final String imageID, final int x, final int y) { return (JWindow) swingAndWait(new Object() { Object get() { JLabel label = new JLabel(imageIcon(imageID)); label.setOpaque(false); JWindow w = new JWindow(); w.setLocation(x, y); w.add(label); // add it to get appropriate size through pack() w.pack(); Rectangle maxBounds = maxWindowBounds(); Rectangle r = w.getBounds(); if (!maxBounds.contains(r)) return null; /*w.setLocation( max(0, min(x, maxBounds.x+maxBounds.width-w.getWidth())), max(0, min(y, maxBounds.y+maxBounds.height-w.getHeight())));*/ Rectangle r2 = intersectWithScreen(r); BufferedImage background = shootScreen2(r2); //w.setLayout(null); w.remove(label); JLayeredPane layeredPane = new JLayeredPane(); Rectangle bounds = new Rectangle(0, 0, w.getContentPane().getWidth(), w.getContentPane().getHeight()); w.add(layeredPane); JLabel lBackground = new JLabel(imageIcon(background)); lBackground.setBounds(0, 0, r2.width, r2.height); layeredPane.add(lBackground, new Integer(1)); label.setBounds(bounds); layeredPane.add(label, new Integer(2)); revalidate(w); w.setAlwaysOnTop(true); w.setVisible(true); return w; } public String toString() { return "JLabel label = new JLabel(imageIcon(imageID));\n label.setOpaque(false);\n JWindow w = new JWindow();\n w.setLocation(x, y);\n w.add(label); // add it to get appropriate size through pack()\n w.pack();\n Rectangle maxBounds = maxWindowBounds();\n Rectangle r = w.getBounds();\n if (!maxBounds.contains(r)) null;\n /*w.setLocation(\n max(0, min(x, maxBounds.x+maxBounds.width-w.getWidth())),\n max(0, min(y, maxBounds.y+maxBounds.height-w.getHeight())));*/\n \n Rectangle r2 = intersectWithScreen(r);\n BufferedImage background = shootScreen2(r2);\n //w.setLayout(null);\n w.remove(label);\n JLayeredPane layeredPane = new JLayeredPane();\n Rectangle bounds = new Rectangle(0, 0, w.getContentPane().getWidth(), w.getContentPane().getHeight());\n w.add(layeredPane);\n JLabel lBackground = new JLabel(imageIcon(background));\n lBackground.setBounds(0, 0, r2.width, r2.height);\n layeredPane.add(lBackground, new Integer(1));\n label.setBounds(bounds);\n layeredPane.add(label, new Integer(2));\n revalidate(w);\n \n w.setAlwaysOnTop(true);\n w.setVisible(true);\n ret w;"; }}); } static JWindow showInTopRightCorner(Component c) { JWindow w = new JWindow(); w.add(c); w.pack(); moveToTopRightCorner(w); w.setVisible(true); return w; } static BufferedImage loadImage2(String snippetIDOrURL) { return loadBufferedImage(snippetIDOrURL); } static BufferedImage loadImage2(File file) { return loadBufferedImage(file); } static void addIfNotNull(Collection l, A a) { if (a != null) l.add(a); } static ImageIcon imageIcon(String imageID) { try { return new ImageIcon(loadBinarySnippet(imageID).toURI().toURL()); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static ImageIcon imageIcon(BufferedImage img) { return new ImageIcon(img); } static long secondsToMS(double seconds) { return toMS(seconds); } static void swingAndWait(Runnable r) { try { if (isAWTThread()) r.run(); else EventQueue.invokeAndWait(r); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__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 __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); return result.get(); } } static JPanel singleColorPanel(Color color) { JPanel p = new JPanel(); p.setOpaque(true); p.setBackground(color); return p; } static Rectangle intersectWithScreen(Rectangle r) { return r.intersection(screenRectangle()); } static Object callOpt(Object o) { if (o == null) return null; return callF(o); } static Object callOpt(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Method m = callOpt_findStaticMethod((Class) o, method, args, false); if (m == null) return null; m.setAccessible(true); return m.invoke(null, args); } else { Method m = callOpt_findMethod(o, method, args, false); if (m == null) return null; m.setAccessible(true); return m.invoke(o, args); } } catch (Exception e) { throw new RuntimeException(e); } } static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (!m.getName().equals(method)) { if (debug) System.out.println("Method name mismatch: " + method); continue; } if ((m.getModifiers() & Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug)) continue; return m; } c = c.getSuperclass(); } return null; } static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) { Class c = o.getClass(); while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug)) return m; } c = c.getSuperclass(); } return null; } private static boolean callOpt_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 String unnull(String s) { return s == null ? "" : s; } static List unnull(List l) { return l == null ? emptyList() : l; } static Iterable unnull(Iterable i) { return i == null ? emptyList() : i; } static Object[] unnull(Object[] a) { return a == null ? new Object[0] : a; } static BitSet unnull(BitSet b) { return b == null ? new BitSet() : b; } static Object callF(Object f, Object... args) { return callFunction(f, args); } static Object mc() { return getMainClass(); } static long toMS(double seconds) { return (long) (seconds*1000); } static void swingLater(long delay, final Runnable r) { javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { r.run(); }}); timer.setRepeats(false); timer.start(); } static void swingLater(Runnable r) { SwingUtilities.invokeLater(r); } static Point getMouseLocation() { return MouseInfo.getPointerInfo().getLocation(); } static boolean isAWTThread() { return isTrue(callOpt(getClass("javax.swing.SwingUtilities"), "isEventDispatchThread")); } static void swingEvery(JComponent component, long delay, Runnable r) { installTimer(component, delay, r); } static void swingEvery(JComponent component, long delay, long firstDelay, Runnable r) { installTimer(component, r, delay, firstDelay); } static void swingEvery(RootPaneContainer frame, long delay, Runnable r) { installTimer(frame, delay, r); } static boolean isEmpty(Collection c) { return c == null || c.isEmpty(); } static boolean isEmpty(CharSequence s) { return s == null || s.length() == 0; } static boolean isEmpty(Object[] a) { return a == null || a.length == 0; } static boolean isEmpty(Map map) { return map == null || map.isEmpty(); } static boolean isFalse(Object o) { return eq(false, o); } static BufferedImage shootScreen2() { return shootScreen2(screenRectangle()); } static BufferedImage shootScreen2(Rectangle area) { try { return new Robot().createScreenCapture(area); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static void revalidate(Component c) { if (c == null || !c.isShowing()) return; // magic combo to actually relayout and repaint c.revalidate(); c.repaint(); } static boolean loadBufferedImage_useImageCache = true; static BufferedImage loadBufferedImage(String snippetIDOrURL) { try { if (isURL(snippetIDOrURL)) return ImageIO.read(new URL(snippetIDOrURL)); if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL); String snippetID = "" + parseSnippetID(snippetIDOrURL); try { // TODO: androidify File dir = new File(System.getProperty("user.home"), ".tinybrain/image-cache"); 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(snippetID); System.err.println("Loading image: " + imageURL); BufferedImage image = ImageIO.read(new URL(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 (IOException e) { throw new RuntimeException(e); } } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static BufferedImage loadBufferedImage(File file) { try { return ImageIO.read(file); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Rectangle maxWindowBounds() { return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); } static File loadBinarySnippet(String snippetID) { try { long id = parseSnippetID(snippetID); File f = DiskSnippetCache_getLibrary(id); if (f == null) { byte[] data = loadDataSnippetImpl(snippetID); DiskSnippetCache_putLibrary(id, data); f = DiskSnippetCache_getLibrary(id); } return f; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static int moveToTopRightCorner_inset = 20; static void moveToTopRightCorner(Window w) { w.setLocation(getScreenSize().width-w.getWidth()-moveToTopRightCorner_inset, moveToTopRightCorner_inset); } static Class getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } static Class getClass(Object o) { return o instanceof Class ? (Class) o : o.getClass(); } static Class getClass(Object realm, String name) { try { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Object callFunction(Object f, Object... args) { if (f == null) return null; if (f instanceof Runnable) { ((Runnable) f).run(); return null; } else if (f instanceof String) return call(mc(), (String) f, args); else return call(f, "get", args); //else throw fail("Can't call a " + getClassName(f)); } static boolean isURL(String s) { return s.startsWith("http://") || s.startsWith("https://"); } // extended over Class.isInstance() to handle primitive types 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 String snippetImageURL(String snippetID) { long id = parseSnippetID(snippetID); String url; if (id == 1000010 || id == 1000012) url = "http://tinybrain.de:8080/tb/show-blobimage.php?id=" + id; else url = "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=image/png"; return url; } static boolean eq(Object a, Object b) { if (a == null) return b == null; if (a.equals(b)) return true; if (a instanceof BigInteger) { if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b)); if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b)); } return false; } static RuntimeException fail() { throw new RuntimeException("fail"); } static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); } static RuntimeException fail(String msg) { throw new RuntimeException(unnull(msg)); } // disabled for now to shorten some programs /*static RuntimeException fail(S msg, O... args) { throw new RuntimeException(format(msg, args)); }*/ static Rectangle screenRectangle() { return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); } public static boolean isSnippetID(String s) { try { parseSnippetID(s); return true; } catch (RuntimeException e) { return false; } } // Data files are immutable, use centralized cache public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException { File file = new File(getGlobalCache(), "data_" + snippetID + ".jar"); return file.exists() ? file : null; } public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data); } static byte[] loadDataSnippetImpl(String snippetID) throws IOException { byte[] data; try { URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + parseSnippetID(snippetID) + "&contentType=application/binary"); System.err.println("Loading library: " + url); try { data = loadBinaryPage(url.openConnection()); } catch (RuntimeException e) { data = null; } if (data == null || data.length == 0) { url = new URL("http://data.tinybrain.de/blobs/" + parseSnippetID(snippetID)); System.err.println("Loading library: " + url); data = loadBinaryPage(url.openConnection()); } System.err.println("Bytes loaded: " + data.length); } catch (FileNotFoundException e) { throw new IOException("Binary snippet #" + snippetID + " not found or not public"); } return data; } static List emptyList() { return new ArrayList(); //ret Collections.emptyList(); } 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; } // first delay = delay static void installTimer(JComponent component, Runnable r, long delay) { installTimer(component, r, delay, delay); } // first delay = delay static void installTimer(RootPaneContainer frame, long delay, Runnable r) { installTimer(frame.getRootPane(), r, delay, delay); } // first delay = delay static void installTimer(JComponent component, long delay, Runnable r) { installTimer(component, r, delay, delay); } static void installTimer(JComponent component, long delay, long firstDelay, Runnable r) { installTimer(component, r, delay, firstDelay); } static void installTimer(final JComponent component, final Runnable r, final long delay, final long firstDelay) { installTimer(component, r, delay, firstDelay, true); } static void installTimer(final JComponent component, final Runnable r, final long delay, final long firstDelay, final boolean repeats) { swingLater(new Runnable() { public void run() { try { final Timer timer = new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { /* pcall 1*/ if (!allPaused()) r.run(); /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } }}); timer.setInitialDelay(toInt(firstDelay)); timer.setRepeats(repeats); bindTimerToComponent(timer, component); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); } static void installTimer(JFrame frame, long delay, long firstDelay, Runnable r) { installTimer(frame.getRootPane(), r, delay, firstDelay); } static Dimension getScreenSize() { return Toolkit.getDefaultToolkit().getScreenSize(); } static Class getMainClass() { return main.class; } static Class getMainClass(Object o) { try { return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main"); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static 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); throw fail("woot not int: " + getClassName(o)); } static int toInt(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } // hmm, this shouldn't call functions really. That was just // for coroutines. static boolean isTrue(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); if (o == null) return false; return ((Boolean) callF(o)).booleanValue(); } static boolean isTrue(Object pred, Object arg) { return booleanValue(callF(pred, arg)); } static 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 String classNameToVM(String name) { return name.replace(".", "$"); } static boolean allPaused() { return ping_pauseAll; } static boolean booleanValue(Object o) { return eq(true, o); } static String getClassName(Object o) { return o == null ? "null" : o.getClass().getName(); } static void bindTimerToComponent(final Timer timer, JFrame f) { bindTimerToComponent(timer, f.getRootPane()); } static 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) { } }); } /** writes safely (to temp file, then rename) */ public static void saveBinaryFile(String fileName, byte[] contents) throws IOException { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = new FileOutputStream(tempFileName); fileOutputStream.write(contents); fileOutputStream.close(); 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); } static void saveBinaryFile(File fileName, byte[] contents) { try { saveBinaryFile(fileName.getPath(), contents); } catch (IOException e) { throw new RuntimeException(e); } } static byte[] loadBinaryPage(String url) { try { return loadBinaryPage(new URL(url).openConnection()); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} public static byte[] loadBinaryPage(URLConnection con) { try { //setHeaders(con); ByteArrayOutputStream buf = new ByteArrayOutputStream(); InputStream inputStream = con.getInputStream(); int n = 0; while (true) { int ch = inputStream.read(); if (ch < 0) break; buf.write(ch); if (++n % 100000 == 0) System.err.println(" " + n + " bytes loaded."); } inputStream.close(); return buf.toByteArray(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Object call(Object o) { return callFunction(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) { try { if (o instanceof Class) { Method m = call_findStaticMethod((Class) o, method, args, false); m.setAccessible(true); return m.invoke(null, args); } else { Method m = call_findMethod(o, method, args, false); m.setAccessible(true); return m.invoke(o, args); } } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } } static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (!m.getName().equals(method)) { if (debug) System.out.println("Method name mismatch: " + method); continue; } if ((m.getModifiers() & Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug)) continue; return m; } c = c.getSuperclass(); } throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + _c.getName()); } static Method call_findMethod(Object o, String method, Object[] args, boolean debug) { Class c = o.getClass(); while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (m.getName().equals(method) && call_checkArgs(m, args, debug)) return m; } c = c.getSuperclass(); } throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName()); } private static boolean call_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 int parseInt(String s) { return empty(s) ? 0 : Integer.parseInt(s); } static File getGlobalCache() { File file = new File(userHome(), ".tinybrain/snippet-cache"); file.mkdirs(); return file; } static boolean empty(Collection c) { return isEmpty(c); } static boolean empty(String s) { return isEmpty(s); } static boolean empty(Map map) { return map == null || map.isEmpty(); } static boolean empty(Object[] o) { return o == null || o.length == 0; } static 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); throw fail("unknown type for 'empty': " + getType(o)); } static volatile boolean ping_pauseAll; static int ping_sleep = 100; // poll pauseAll flag every 100 static volatile boolean ping_anyActions; static Map ping_actions = synchroMap(new WeakHashMap()); // returns true if it did anything static boolean ping() { try { if (ping_pauseAll && !isAWTThread()) { do Thread.sleep(ping_sleep); while (ping_pauseAll); return true; } if (ping_anyActions) { Object action; synchronized(mc()) { 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 (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static String _userHome; static String userHome() { if (_userHome == null) { if (isAndroid()) _userHome = "/storage/sdcard0/"; else _userHome = System.getProperty("user.home"); //System.out.println("userHome: " + _userHome); } return _userHome; } static File userHome(String path) { return new File(userDir(), path); } static long parseLong(String s) { if (s == null) return 0; return Long.parseLong(dropSuffix("L", s)); } static long parseLong(Object s) { return Long.parseLong((String) s); } static Thread currentThread() { return Thread.currentThread(); } static String getType(Object o) { return getClassName(o); } static Map synchroMap() { return synchroHashMap(); } static Map synchroMap(Map map) { return Collections.synchronizedMap(map); } static String dropSuffix(String suffix, String s) { return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s; } static File userDir() { return new File(userHome()); } static File userDir(String path) { return new File(userHome(), path); } static boolean isAndroid() { return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0; } 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(int[] a) { return a == null ? 0 : a.length; } static int l(float[] 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(Map m) { return m == null ? 0 : m.size(); } static int l(CharSequence s) { return s == null ? 0 : s.length(); } static int l(Object o) { return l((List) o); // incomplete } static Map synchroHashMap() { return Collections.synchronizedMap(new HashMap()); } static class Var { A v; Var() {} Var(A v) { this.v = v;} synchronized void set(A a) { v = a; } synchronized A get() { return v; } } static void printStackTrace(Throwable e) { // we go to system.out now - system.err is nonsense print(getStackTrace(e)); } static void printStackTrace() { printStackTrace(new Throwable()); } static void printStackTrace(String indent, Throwable e) { if (endsWithLetter(indent)) indent += " "; printIndent(indent, getStackTrace(e)); } static void swingNowOrLater(Runnable r) { if (isAWTThread()) r.run(); else swingLater(r); } // get purpose 1: access a list/array (safer version of x.get(y)) static A get(List l, int idx) { return idx >= 0 && idx < l(l) ? l.get(idx) : 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; } static Class get_dynamicObject = DynamicObject.class; // get purpose 2: access a field by reflection or a map static Object get(Object o, String field) { try { 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) { f.setAccessible(true); return f.get(o); } if (get_dynamicObject != null && get_dynamicObject.isInstance(o)) return call(get_raw(o, "fieldValues"), "get", field); } catch (Exception e) { throw asRuntimeException(e); } throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName()); } static Object get_raw(Object o, String field) { try { Field f = get_findField(o.getClass(), field); f.setAccessible(true); return f.get(o); } catch (Exception e) { throw new RuntimeException(e); } } static Object get(Class c, String field) { try { Field f = get_findStaticField(c, field); f.setAccessible(true); 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() & 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 void printIndent(Object o) { print(indentx(str(o))); } static void printIndent(String indent, Object o) { print(indentx(indent, str(o))); } static void printIndent(int indent, Object o) { print(indentx(indent, str(o))); } static RuntimeException asRuntimeException(Throwable t) { return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } static String getStackTrace(Throwable throwable) { StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); return writer.toString(); } static boolean endsWithLetter(String s) { return nempty(s) && isLetter(last(s)); } static volatile StringBuffer local_log = new StringBuffer(); // not redirected static volatile StringBuffer 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 int print_maxLineLength = 0; // 0 = unset static boolean print_silent; // total mute if set static void print() { print(""); } // slightly overblown signature to return original object... static A print(A o) { ping(); if (print_silent) return o; String s = String.valueOf(o) + "\n"; print_noNewLine(s); return o; } static void print_noNewLine(String s) { // TODO if (print_maxLineLength != 0) StringBuffer loc = local_log; StringBuffer 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); System.out.print(s); } static void print(long l) { print(String.valueOf(l)); } static void print(char c) { print(String.valueOf(c)); } static void print_append(StringBuffer buf, String s, int max) { synchronized(buf) { buf.append(s); max /= 2; if (buf.length() > max) try { int newLength = max/2; int ofs = buf.length()-newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } } } static Object getOpt(Object o, String field) { return getOpt_cached(o, field); } static Object getOpt_raw(Object o, String field) { try { Field f = getOpt_findField(o.getClass(), field); if (f == null) return null; f.setAccessible(true); return f.get(o); } catch (Exception e) { throw new RuntimeException(e); } } static Object getOpt(Class c, String field) { try { if (c == null) return null; Field f = getOpt_findStaticField(c, field); if (f == null) return null; f.setAccessible(true); return f.get(null); } catch (Exception e) { throw new RuntimeException(e); } } static Field getOpt_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } 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 String indentx(String s) { return indentx(indent_default, s); } static String indentx(int n, String s) { return dropSuffix(repeat(' ', n), indent(n, s)); } static String indentx(String indent, String s) { return dropSuffix(indent, indent(indent, s)); } static A last(List l) { return l.isEmpty() ? null : l.get(l.size()-1); } static char last(String s) { return empty(s) ? '#' : s.charAt(l(s)-1); } static String str(Object o) { return String.valueOf(o); } static boolean isLetter(char c) { return Character.isLetter(c); } static final WeakHashMap> getOpt_cache = new WeakHashMap(); static final HashMap getOpt_special = new HashMap(); // just a marker static { getOpt_cache.put(Class.class, getOpt_special); getOpt_cache.put(String.class, getOpt_special); } static Object getOpt_cached(Object o, String field) { try { if (o == null) return null; 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 getOpt((Class) o, field); if (o instanceof String) return getOpt(getBot((String) 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 ((DynamicObject) o).fieldValues.get(field); return null; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // used internally - we are in synchronized block static HashMap getOpt_makeCache(Class c) { HashMap map; if (isSubtypeOf(c, Map.class)) map = getOpt_special; else { map = new HashMap(); Class _c = c; do { for (Field f : _c.getDeclaredFields()) { f.setAccessible(true); String name = f.getName(); if (!map.containsKey(name)) map.put(name, f); } _c = _c.getSuperclass(); } while (_c != null); } getOpt_cache.put(c, map); return map; } static Object getBot(String botID) { return callOpt(getMainBot(), "getBot", botID); } static boolean isSubtypeOf(Class a, Class b) { return b.isAssignableFrom(a); // << always hated that method, let's replace it! } static int indent_default = 2; static String indent(int indent) { return repeat(' ', indent); } static String indent(int indent, String s) { return indent(repeat(' ', indent), s); } static String indent(String indent, String s) { return indent + s.replace("\n", "\n" + indent); } static String indent(String s) { return indent(indent_default, s); } static List indent(String indent, List lines) { List l = new ArrayList(); for (String s : lines) l.add(indent + s); return l; } static String repeat(char c, int n) { n = max(n, 0); char[] chars = new char[n]; for (int i = 0; i < n; i++) chars[i] = c; return new String(chars); } static List repeat(A a, int n) { List l = new ArrayList(); for (int i = 0; i < n; i++) l.add(a); return l; } static Object mainBot; static Object getMainBot() { return mainBot; } 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 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 byte max(byte[] c) { byte x = -128; for (byte d : c) if (d > x) x = d; return x; } static boolean DynamicObject_loading; static class DynamicObject { String className; // just the name, without the "main$" Map fieldValues = new TreeMap(); DynamicObject() {} // className = just the name, without the "main$" DynamicObject(String className) { this.className = className;} } }