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.awt.datatransfer.StringSelection;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import javax.swing.Timer;
import org.pushingpixels.substance.api.*;
import org.pushingpixels.substance.api.skin.*;
public class main {
static JLabel l;
public static void main(final String[] args) throws Exception { { swingAndWait(new Runnable() { public void run() { try { substance();
final JFrame frame = showFullScreen(jTiledBackground("#1007195",
setForeground(Color.white,
setFontSize(40,
centerLabel(
standardLabelPopupMenu(
l = new JLabel("BLA!")))))));
awtEvery(l, 1000, new Runnable() { public void run() { try {
l.setText(randomID(20));
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "l.setText(randomID(20));"; }});
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "substance();\n final JFrame frame = showFullScreen(jTiledBackground(\"#1007195\",\n setForeground(Color.white,\n setFontSize(40,\n centerLabel(\n standardLabelPopupMenu(\n l = new JLabel(\"BLA!\")))))));\n \n awtEvery(l, 1000, r {\n l.setText(randomID(20));\n });"; }}); }}
static JFrame showFullScreen(final JComponent c) {
return (JFrame) swingAndWait(new Object() { 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();
window.setUndecorated(true);
if (dec) JFrame.setDefaultLookAndFeelDecorated(true);
registerEscape(window, new Runnable() { public void run() { try { window.dispose() ;
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "window.dispose()"; }});
window.add(wrap(c));
gd.setFullScreenWindow(window);
// Only this hides the task bar in Peppermint Linux w/Substance
for (int i = 100; i <= 1000; i += 100)
awtLater(i, new Runnable() { public void run() { try { window.toFront() ;
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "window.toFront()"; }});
return window;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()\r\n .getDefaultScreenDevice();\r\n if (!gd.isFullScreenSupported())\r\n fail(\"No full-screen mode supported!\");\r\n bool dec = JFrame.isDefaultLookAndFeelDecorated();\r\n if (dec) JFrame.setDefaultLookAndFeelDecorated(false);\r\n final new JFrame window;\r\n window.setUndecorated(true);\r\n if (dec) JFrame.setDefaultLookAndFeelDecorated(true);\r\n registerEscape(window, r { window.dispose() });\r\n window.add(wrap(c));\r\n gd.setFullScreenWindow(window);\r\n \r\n // Only this hides the task bar in Peppermint Linux w/Substance\r\n for (int i = 100; i <= 1000; i += 100)\r\n awtLater(i, r { window.toFront() });\r\n \r\n ret window;"; }});
}
static void awtEvery(JComponent component, long delay, Runnable r) {
swingEvery(component, delay, r);
}
static void awtEvery(JComponent component, long delay, long firstDelay, Runnable r) {
swingEvery(component, delay, firstDelay, r);
}
static void awtEvery(RootPaneContainer frame, long delay, Runnable r) {
swingEvery(frame, delay, r);
}
static int randomID_defaultLength = 12;
static String randomID(int length) {
return makeRandomID(length);
}
static String randomID() {
return randomID(randomID_defaultLength);
}
static JPanel jTiledBackground(String imageID, Component contents) {
final BufferedImage tileImage = loadImage2(imageID);
JPanel panel = new JPanel(new BorderLayout()) {
protected void paintComponent(Graphics g) {
int width = getWidth();
int height = getHeight();
for (int x = 0; x < width; x += tileImage.getWidth())
for (int y = 0; y < height; y += tileImage.getHeight())
g.drawImage(tileImage, x, y, this);
}
};
panel.add(BorderLayout.CENTER, jtransparent_recursive(contents));
return panel;
}
static JLabel standardLabelPopupMenu(final JLabel l) {
componentPopupMenu(l, new Object() { void get(JPopupMenu menu) { try {
addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(l.getText());
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "copyTextToClipboard(l.getText());"; }});
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(l.getText());\r\n });"; }});
return l;
}
static A setForeground(Color color, A a) {
if (a != null) a.setForeground(color);
return a;
}
static JLabel centerLabel(JLabel l) {
if (l != null) l.setHorizontalAlignment(SwingConstants.CENTER);
return l;
}
static A setFontSize(int size, A a) {
if (a != null) a.setFont(sansSerif(size));
return a;
}
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);
}
// independent timer
static void awtLater(int delay, final Object r) {
swingLater(delay, r);
}
static void awtLater(Object r) {
swingLater(r);
}
// dependent timer (runs only when component is visible)
static void awtLater(JComponent component, int delay, Object r) {
installTimer(component, r, delay, delay, false);
}
static void awtLater(JFrame frame, int delay, Object r) {
awtLater(frame.getRootPane(), delay, r);
}
static String makeRandomID(int length) {
Random random = new 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 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));
}
static RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
// disabled for now to shorten some programs
/*static RuntimeException fail(S msg, O... args) {
throw new RuntimeException(format(msg, args));
}*/
static A jtransparent_recursive(A a) {
if (a instanceof JPanel) {
((JPanel) a).setOpaque(false);
for (Component c : getSwingChildren(a))
jtransparent_recursive(c);
}
return a;
}
static Font sansSerif(int fontSize) {
return new Font(Font.SANS_SERIF, Font.PLAIN, fontSize);
}
static class componentPopupMenu_Maker {
List menuMakers = new ArrayList();
}
static Map componentPopupMenu_map = new WeakHashMap();
static ThreadLocal componentPopupMenu_mouseEvent = new ThreadLocal();
// menuMaker = voidfunc(JPopupMenu)
static void componentPopupMenu(final JComponent component, final Object menuMaker) {
swingNowOrLater(new Runnable() { public void run() { try {
componentPopupMenu_Maker maker = componentPopupMenu_map.get(component);
if (maker == null) {
componentPopupMenu_map.put(component, maker = new componentPopupMenu_Maker());
final componentPopupMenu_Maker _maker = maker;
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) { displayMenu(e); }
public void mouseReleased(MouseEvent e) { displayMenu(e); }
void displayMenu(MouseEvent e) {
if (e.isPopupTrigger()) {
JPopupMenu menu = new JPopupMenu();
int emptyCount = menu.getComponentCount();
componentPopupMenu_mouseEvent.set(e);
for (Object menuMaker : _maker.menuMakers)
pcallF(menuMaker, menu);
// show menu if any items in it
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
maker.menuMakers.add(menuMaker);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "componentPopupMenu_Maker maker = componentPopupMenu_map.get(component);\n if (maker == null) {\n componentPopupMenu_map.put(component, maker = new componentPopupMenu_Maker);\n final componentPopupMenu_Maker _maker = maker;\n component.addMouseListener(new MouseAdapter {\n public void mousePressed(MouseEvent e) { displayMenu(e); }\n public void mouseReleased(MouseEvent e) { displayMenu(e); }\n \n void displayMenu(MouseEvent e) {\n if (e.isPopupTrigger()) {\n new JPopupMenu menu;\n int emptyCount = menu.getComponentCount();\n \n componentPopupMenu_mouseEvent.set(e);\n for (Object menuMaker : _maker.menuMakers)\n pcallF(menuMaker, menu);\n \n // show menu if any items in it\n if (menu.getComponentCount() != emptyCount)\n menu.show(e.getComponent(), e.getX(), e.getY());\n }\n }\n });\n }\n maker.menuMakers.add(menuMaker);"; }});
}
static BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
static void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static String copyTextToClipboard(String text) {
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
return text;
}
// c = JComponent or something implementing swing()
static JComponent wrap(Object swingable) {
JComponent c = (JComponent) ( swingable instanceof JComponent ? swingable : callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList
|| c instanceof JTextArea || c instanceof JEditorPane
|| c instanceof JTextPane)
return new JScrollPane(c);
return c;
}
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); } } public String toString() { return "result.set(callF(f));"; }});
return result.get();
}
}
static void registerEscape(JFrame frame, final Runnable r) {
String name = "Escape";
Action action = abstractAction(name, r);
JComponent pnl = frame.getRootPane();
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
pnl.getActionMap().put(name, action);
pnl.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name);
}
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 AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
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 void swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(r));
timer.setRepeats(false);
timer.start();
}
static void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
// first delay = delay
static Timer installTimer(JComponent component, Object r, long delay) {
return installTimer(component, r, delay, delay);
}
// first delay = delay
static Timer installTimer(RootPaneContainer frame, long delay, Object r) {
return installTimer(frame.getRootPane(), r, delay, delay);
}
// first delay = delay
static Timer installTimer(JComponent component, long delay, Object r) {
return installTimer(component, r, delay, delay);
}
static void installTimer(JComponent component, long delay, long firstDelay, Object r) {
installTimer(component, r, delay, firstDelay);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) {
return installTimer(component, r, delay, firstDelay, true);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) {
return (Timer) swingAndWait(new Object() { Object get() { try {
Timer timer = new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) {
try { /* pcall 1*/
if (!allPaused())
callF(r);
/* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); }
}});
timer.setInitialDelay(toInt(firstDelay));
timer.setRepeats(repeats);
bindTimerToComponent(timer, component);
return timer;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "Timer timer = new Timer(toInt(delay), actionListener {\r\n pcall {\r\n if (!allPaused())\r\n callF(r);\r\n }\r\n });\r\n timer.setInitialDelay(toInt(firstDelay));\r\n timer.setRepeats(repeats);\r\n bindTimerToComponent(timer, component);\r\n ret timer;"; }});
}
static Timer installTimer(JFrame frame, long delay, long firstDelay, Object r) {
return installTimer(frame.getRootPane(), r, delay, firstDelay);
}
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isTrue(callOpt(getClass("javax.swing.SwingUtilities"), "isEventDispatchThread"));
}
static List getSwingChildren(Component c) {
if (c instanceof Container)
return asList(((Container) c).getComponents());
return emptyList();
}
static JMenuItem jmenuItem(String text, final Object r) {
JMenuItem mi = new JMenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
static boolean loadBufferedImage_useImageCache = true;
static BufferedImage loadBufferedImage(String snippetIDOrURL) { try {
if (snippetIDOrURL == null) return null;
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 {
File dir = getCacheProgramDir("Image-Snippets");
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 file.isFile() ? ImageIO.read(file) : null;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
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 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 {
callOpt(getClass("javax.swing.SwingUtilities"), "isEventDispatchThread");
return isHeadless_cache = false;
} catch (Throwable e) { return isHeadless_cache = true; }
}
static Runnable toRunnable(final Object o) {
if (o instanceof Runnable) return (Runnable) o;
return new Runnable() { public void run() { try { callF(o) ;
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "callF(o)"; }};
}
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 ArrayList asList(A[] a) {
return new ArrayList(Arrays.asList(a));
}
static ArrayList asList(int[] a) {
ArrayList l = new ArrayList();
for (int i : a) l.add(i);
return l;
}
static 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 ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
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 allPaused() {
return ping_pauseAll;
}
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) {
}
});
}
static File getCacheProgramDir() {
return getCacheProgramDir(getProgramID());
}
static File getCacheProgramDir(String snippetID) {
return new File(userHome(), "JavaX-Caches/" + formatSnippetIDOpt(snippetID));
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static ActionListener actionListener(final Object runnable) {
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { pcallF(runnable); }};
}
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 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 Object pcallFunction(Object f, Object... args) {
try { /* pcall 1*/ return callFunction(f, args); /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); }
return null;
}
static int isAndroid_flag;
static boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static Object mc() {
return getMainClass();
}
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 booleanValue(Object o) {
return eq(true, o);
}
static String getClassName(Object o) {
return o == null ? "null" : o.getClass().getName();
}
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 programID;
static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
// TODO: ask JavaX instead
static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
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 String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
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 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 boolean empty(float[] a) { return a == null || a.length == 0; }
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static Thread currentThread() {
return Thread.currentThread();
}
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 Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
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 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 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 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 File userDir() {
return new File(userHome());
}
static File userDir(String path) {
return new File(userHome(), path);
}
static String getType(Object o) {
return getClassName(o);
}
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 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 String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
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 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 long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o instanceof String ? l((String) o)
: l((Collection) o); // incomplete
}
static int l(MultiSet ms) { return ms == null ? 0 : ms.size(); }
static Object mainBot;
static Object getMainBot() {
return mainBot;
}
static ThreadLocal DynamicObject_loading = new ThreadLocal();
static class DynamicObject {
String className; // just the name, without the "main$"
Map fieldValues = new HashMap();
DynamicObject() {}
// className = just the name, without the "main$"
DynamicObject(String className) {
this.className = className;}
}
static class Var {
A v; // you can access this directly if you use one thread
Var() {}
Var(A v) {
this.v = v;}
synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
synchronized A get() { return v; }
synchronized boolean has() { return v != null; }
synchronized void clear() { v = null; }
}
// uses HashMap by default
static class MultiSet {
Map map = new HashMap();
public MultiSet(boolean useTreeMap) {
if (useTreeMap)
map = new TreeMap();
}
public MultiSet() {
}
public MultiSet(Collection c) {
addAll(c);
}
public void add(A key) {
add(key, 1);
}
public void addAll(Collection c) {
if (c != null) for (A a : c)
add(a);
}
void addAll(MultiSet ms) {
for (A a : ms.keySet())
add(a, ms.get(a));
}
public void add(A key, int count) {
if (map.containsKey(key))
map.put(key, map.get(key)+count);
else
map.put(key, count);
}
public int get(A key) {
return key != null && map.containsKey(key) ? map.get(key) : 0;
}
public boolean contains(A key) {
return map.containsKey(key);
}
public void remove(A key) {
Integer i = map.get(key);
if (i != null && i > 1)
map.put(key, i - 1);
else
map.remove(key);
}
public List getTopTen() {
return getTopTen(10);
}
public List getTopTen(int maxSize) {
List list = getSortedListDescending();
return list.size() > maxSize ? list.subList(0, maxSize) : list;
}
List highestFirst() {
return getSortedListDescending();
}
List lowestFirst() {
return reversedList(getSortedListDescending());
}
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;
}
public int getNumberOfUniqueElements() {
return map.size();
}
int uniqueSize() {
return map.size();
}
public Set asSet() {
return map.keySet();
}
Set keySet() { // synonym for idiots
return map.keySet();
}
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;
}
public void removeAll(A key) {
map.remove(key);
}
public int size() {
int size = 0;
for (int i : map.values())
size += i;
return size;
}
public MultiSet mergeWith(MultiSet set) {
MultiSet result = new MultiSet();
for (A a : set.asSet()) {
result.add(a, set.get(a));
}
return result;
}
public boolean isEmpty() {
return map.isEmpty();
}
public String toString() {
return str(map);
}
public void clear() {
map.clear();
}
Map asMap() {
return cloneMap(map);
}
}
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 msg) {
printStackTrace(new Throwable(msg));
}
static void printStackTrace(String indent, Throwable e) {
if (endsWithLetter(indent)) indent += " ";
printIndent(indent, getStackTrace(e));
}
static String str(Object o) {
return String.valueOf(o);
}
static String str(char[] c) {
return new String(c);
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
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 l != null && 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 Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array)
if (o != null)
set.add(o);
return set;
}
static Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array)
if (o != null)
set.add(o);
return set;
}
static Set asSet(Collection l) {
TreeSet set = new TreeSet();
for (String o : l)
if (o != null)
set.add(o);
return set;
}
static List reversedList(Collection l) {
List x = cloneList(l);
Collections.reverse(x);
return x;
}
static Map cloneMap(Map map) {
if (map == null) return litmap();
// assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does.
synchronized(map) {
return new HashMap(map);
}
}
static void substance() {
substanceLAF();
}
static void substance(String skinName) {
substanceLAF(skinName);
}
static void addAll(Collection c, Collection b) {
c.addAll(b);
}
static void addAll(Collection c, Object[] b) {
c.addAll(Arrays.asList(b));
}
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 List cloneList(Collection l) {
//O mutex = getOpt(l, "mutex");
/*if (mutex != null)
synchronized(mutex) {
ret new ArrayList(l);
}
else
ret new ArrayList(l);*/
// assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does.
synchronized(l) {
return new ArrayList(l);
}
}
static Map litmap(Object... x) {
TreeMap map = new TreeMap();
litmap_impl(map, x);
return map;
}
static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length-1; i += 2)
if (x[i+1] != null)
map.put(x[i], x[i+1]);
}
static boolean endsWithLetter(String s) {
return nempty(s) && isLetter(last(s));
}
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 String substanceLAF_defaultSkin = "Creme";
static void substanceLAF() {
substanceLAF(null);
}
static void substanceLAF(String skinName) {
try { /* pcall 1*/
enableSubstance_impl(or2(skinName, substanceLAF_defaultSkin));
/* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); }
}
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 volatile ThreadLocal print_byThread; // special handling by thread
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) {
if (print_byThread != null) {
Object f = print_byThread.get();
if (f != null)
if (isFalse(callF(f, s))) return;
}
print_raw(s);
}
static void print_raw(String s) {
s = fixNewLines(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);
}
}
}
// Substance
// Trident (required by Substance)
static void enableSubstance_impl(final String skinName) { swingAndWait(new Runnable() { public void run() { try {
if (!substanceLookAndFeelEnabled())
enableSubstance_impl_2(skinName);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "if (!substanceLookAndFeelEnabled())\r\n enableSubstance_impl_2(skinName);"; }}); }
static void enableSubstance_impl_2(String skinName) { try {
ClassLoader cl = main.class.getClassLoader();
UIManager.getDefaults().put("ClassLoader", cl);
Thread.currentThread().setContextClassLoader(cl);
String skinClassName = "org.pushingpixels.substance.api.skin." + addSuffix(skinName, "Skin");
SubstanceSkin skin = (SubstanceSkin) nuObject(cl.loadClass(skinClassName));
SubstanceLookAndFeel.setSkin(skin);
JFrame.setDefaultLookAndFeelDecorated(true);
updateLookAndFeelOnAllWindows();
if (substanceLookAndFeelEnabled())
print("Substance L&F enabled.");
else
print("Could not enable Substance L&F?");
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
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 int last(int[] a) {
return l(a) != 0 ? a[l(a)-1] : 0;
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static String or2(String a, String b) {
return nempty(a) ? a : b;
}
static boolean isLetter(char c) {
return Character.isLetter(c);
}
static boolean substanceLookAndFeelEnabled() {
return startsWith(getLookAndFeel(), "org.pushingpixels.");
}
static String addSuffix(String s, String suffix) {
return s.endsWith(suffix) ? s : s + suffix;
}
static void updateLookAndFeelOnAllWindows() {
for (Window window : Window.getWindows())
SwingUtilities.updateComponentTreeUI(window);
renewConsoleFrame();
}
static Object nuObject(String className, Object... args) { try {
return nuObject(Class.forName(className), args);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__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 {
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return (A) m.newInstance(args);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__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 new RuntimeException("Constructor " + c.getName() + getClasses(args) + " not found");
}
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 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 List getClasses(Object[] array) {
List l = new ArrayList();
for (Object o : array) l.add(_getClass(o));
return l;
}
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 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 void renewConsoleFrame() {
setConsoleFrame(renewFrame(consoleFrame()));
}
static String getLookAndFeel() {
return getClassName(UIManager.getLookAndFeel());
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(List a, List b) {
if (a == null || l(b) > l(a)) return false;
for (int i = 0; i < l(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static void setConsoleFrame(JFrame frame) {
setOpt(get(getJavaX(), "console"), "frame", frame);
}
static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class _getClass(Object o) {
return o == null ? null
: o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) { try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static JFrame renewFrame(final JFrame frame) {
if (frame == null) return null;
return (JFrame) swing(new Object() { Object get() { try {
Container content = frame.getContentPane();
JFrame frame2 = makeFrame(frame.getTitle());
frame2.setBounds(frame.getBounds());
try { /* pcall 1*/ frame2.setIconImages(frame.getIconImages()); /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); }
frame2.setDefaultCloseOperation(frame.getDefaultCloseOperation());
for (WindowListener wl : frame.getWindowListeners())
frame2.addWindowListener(wl);
frame.setContentPane(new JPanel());
frame2.setContentPane(content);
frame2.setVisible(true);
frame.dispose();
return frame2;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "Container content = frame.getContentPane();\r\n JFrame frame2 = makeFrame(frame.getTitle());\r\n frame2.setBounds(frame.getBounds());\r\n pcall { frame2.setIconImages(frame.getIconImages()); }\r\n frame2.setDefaultCloseOperation(frame.getDefaultCloseOperation());\r\n for (WindowListener wl : frame.getWindowListeners())\r\n frame2.addWindowListener(wl);\r\n frame.setContentPane(new JPanel);\r\n frame2.setContentPane(content);\r\n frame2.setVisible(true);\r\n frame.dispose();\r\n ret frame2;"; }});
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static JFrame makeFrame() {
return makeFrame((Component) null);
}
static JFrame makeFrame(Object content) {
return makeFrame(programTitle(), content);
}
static JFrame makeFrame(String title) {
return makeFrame(title, null);
}
static JFrame makeFrame(String title, Object content) {
return makeFrame(title, content, true);
}
static JFrame makeFrame(final String title, final Object content, final boolean showIt) {
return (JFrame) swing(new Object() { Object get() { try {
if (getFrame(content) != null)
return setFrameTitle((Component) content, title);
final JFrame frame = new JFrame(title);
if (content != null)
frame.getContentPane().add(wrap(content));
frame.setBounds(300, 100, 500, 400);
if (showIt)
frame.setVisible(true);
//callOpt(content, "requestFocus");
//exitOnFrameClose(frame);
// standard right-click behavior on titles
if (isSubstanceLAF())
titlePopupMenu(frame,
new Object() { void get(JPopupMenu menu) { try {
boolean alwaysOnTop = frame.isAlwaysOnTop();
menu.add(jmenuItem("Restart Program", "restart"));
menu.add(jmenuItem("Show Console", "showConsole"));
menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() { public void run() { try {
toggleAlwaysOnTop(frame) ;
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "toggleAlwaysOnTop(frame)"; }}));
menu.add(jMenuItem("Shoot Window", new Runnable() { public void run() { try { shootWindowGUI_external(frame, 500) ;
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "shootWindowGUI_external(frame, 500)"; }}));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n menu.add(jmenuItem(\"Restart Program\", f restart));\r\n menu.add(jmenuItem(\"Show Console\", f showConsole));\r\n menu.add(jCheckBoxMenuItem(\"Always On Top\", alwaysOnTop, r {\r\n toggleAlwaysOnTop(frame) }));\r\n menu.add(jMenuItem(\"Shoot Window\", r { shootWindowGUI_external(frame, 500) }));"; }});
return frame;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "if (getFrame(content) != null)\r\n ret setFrameTitle((Component) content, title);\r\n final JFrame frame = new JFrame(title);\r\n if (content != null)\r\n frame.getContentPane().add(wrap(content));\r\n frame.setBounds(300, 100, 500, 400);\r\n if (showIt)\r\n frame.setVisible(true);\r\n //callOpt(content, \"requestFocus\");\r\n //exitOnFrameClose(frame);\r\n \r\n // standard right-click behavior on titles\r\n if (isSubstanceLAF())\r\n titlePopupMenu(frame,\r\n new O { void get(JPopupMenu menu) { try {\n \r\n bool alwaysOnTop = frame.isAlwaysOnTop();\r\n menu.add(jmenuItem(\"Restart Program\", f restart));\r\n menu.add(jmenuItem(\"Show Console\", f showConsole));\r\n menu.add(jCheckBoxMenuItem(\"Always On Top\", alwaysOnTop, r {\r\n toggleAlwaysOnTop(frame) }));\r\n menu.add(jMenuItem(\"Shoot Window\", r { shootWindowGUI_external(frame, 500) }));\r\n \n} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}\n public S toString() { ret \"bool alwaysOnTop = frame.isAlwaysOnTop();\\r\\n menu.add(jmenuItem(\\\"Restart Program\\\", f restart));\\r\\n menu.add(jmenuItem(\\\"Show Console\\\", f showConsole));\\r\\n menu.add(jCheckBoxMenuItem(\\\"Always On Top\\\", alwaysOnTop, r {\\r\\n toggleAlwaysOnTop(frame) }));\\r\\n menu.add(jMenuItem(\\\"Shoot Window\\\", r { shootWindowGUI_external(frame, 500) }));\"; }});\r\n ret frame;"; }});
}
static Class __javax;
static Class getJavaX() {
return __javax;
}
static Object swing(Object f) {
return swingAndWait(f);
}
static 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 void setOpt(Object o, String field, Object value) { try {
if (o == null) return;
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) {
setOpt((Class) o, field, value);
return;
}
return;
}
Field f = map.get(field);
if (f != null)
smartSet(f, o, value); // possible improvement: skip setAccessible
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static 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 Field setOpt_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 boolean isSubstanceLAF() {
return substanceLookAndFeelEnabled();
}
static A setFrameTitle(A c, String title) {
JFrame f = getFrame(c);
if (f == null)
showFrame(title, c);
else
f.setTitle(title);
return c;
}
static A setFrameTitle(String title, A c) {
return setFrameTitle(c, title);
}
// magically find a field called "frame" in main class :-)
static JFrame setFrameTitle(String title) {
Object f = getOpt(mc(), "frame");
if (f instanceof JFrame)
return setFrameTitle((JFrame) f, title);
return null;
}
// menuMaker = voidfunc(JPopupMenu)
static void titlePopupMenu(final Component c, final Object menuMaker) {
swingNowOrLater(new Runnable() { public void run() { try {
if (!isSubstanceLAF())
print("Can't add title right click!");
else {
JComponent titleBar = getTitlePaneComponent(getFrame(c));
componentPopupMenu(titleBar, menuMaker);
}
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "if (!isSubstanceLAF())\n print(\"Can't add title right click!\");\n else {\n JComponent titleBar = getTitlePaneComponent(getFrame(c));\n componentPopupMenu(titleBar, menuMaker);\n }"; }});
}
static String programTitle() {
return getProgramName();
}
static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked);
mi.addActionListener(actionListener(r));
return mi;
}
static JMenuItem jMenuItem(String text, Object r) {
return jmenuItem(text, r);
}
static JFrame getFrame(Object 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;
}
static void toggleAlwaysOnTop(JFrame frame) {
frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
}
static void shootWindowGUI_external(JFrame frame) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame);
}
static void shootWindowGUI_external(final JFrame frame, int delay) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame, delay);
}
static void smartSet(Field f, Object o, Object value) throws Exception {
f.setAccessible(true);
// take care of common case (long to int)
if (f.getType() == int.class && value instanceof Long)
value = ((Long) value).intValue();
try {
f.set(o, value);
} catch (Exception e) {
try {
if (f.getType().getName().equals("main$Concept$Ref")) {
f.set(o, nuObject("main$Concept$Ref", o, value));
return;
}
if (o.getClass().getName().equals("main$Concept$Ref")) {
f.set(o, call(o, "get"));
return;
}
} catch (Throwable _e) {}
throw e;
}
}
static JComponent getTitlePaneComponent(Window window) {
if (!substanceLookAndFeelEnabled()) return null;
JRootPane rootPane = null;
if (window instanceof JFrame) {
JFrame f = (JFrame) window;
rootPane = f.getRootPane();
}
if (window instanceof JDialog) {
JDialog d = (JDialog) window;
rootPane = d.getRootPane();
}
if (rootPane != null) {
Object /*SubstanceRootPaneUI*/ ui = rootPane.getUI();
return (JComponent) call(ui, "getTitlePane");
}
return null;
}
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
static JFrame showFrame() {
return makeFrame();
}
static JFrame showFrame(Object content) {
return makeFrame(content);
}
static JFrame showFrame(String title) {
return makeFrame(title);
}
static JFrame showFrame(String title, Object content) {
return makeFrame(title, content);
}
static JFrame showFrame(final JFrame frame) {
if (frame != null) { swingAndWait(new Runnable() { public void run() { try {
if (frameTooSmall(frame)) frameStandardSize(frame);
frame.setVisible(true);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "if (frameTooSmall(frame)) frameStandardSize(frame);\r\n frame.setVisible(true);"; }}); }
return frame;
}
// make or update frame
static 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 Object first(Object list) {
return empty((List) list) ? null : ((List) list).get(0);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Class hotwireOnce(String programID) {
return hotwireCached(programID, false);
}
static String getProgramName_cache;
static synchronized String getProgramName() {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitleOpt(programID());
return getProgramName_cache;
}
static TreeMap hotwireCached_cache = new TreeMap();
static Class hotwireCached(String programID) {
return hotwireCached(programID, true);
}
static synchronized Class hotwireCached(String programID, boolean runMain) {
programID = formatSnippetID(programID);
Class c = hotwireCached_cache.get(programID);
if (c == null) {
c = hotwire(programID);
if (runMain)
callMain(c);
hotwireCached_cache.put(programID, c);
}
return c;
}
static void setFrameContents(JFrame frame, Object contents) {
frame.getContentPane().removeAll();
frame.getContentPane().add(wrap(contents));
revalidate(frame);
}
static String getSnippetTitleOpt(String s) {
return isSnippetID(s) ? getSnippetTitle(s) : s;
}
static List ll(A... a) {
return litlist(a);
}
static boolean frameTooSmall(JFrame frame) {
return frame.getWidth() < 100 || frame.getHeight() < 50;
}
static void frameStandardSize(JFrame frame) {
frame.setBounds(300, 100, 500, 400);
}
static String programID() {
return getProgramID();
}
static ArrayList litlist(A... a) {
return new ArrayList(Arrays.asList(a));
}
static String getSnippetTitle(String id) { try {
if (!isSnippetID(id)) return "?";
return trim(loadPageSilently(new URL("http://tinybrain.de:8080/tb-int/getfield.php?id=" + parseSnippetID(id) + "&field=title" + standardCredentials())));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String getSnippetTitle(long id) {
return getSnippetTitle(fsI(id));
}
static void callMain(Object c, String... args) {
callOpt(c, "main", new Object[] {args});
}
static void revalidate(Component c) {
if (c == null || !c.isShowing()) return;
// magic combo to actually relayout and repaint
c.revalidate();
c.repaint();
}
static Class> hotwire(String src) {
if (isAndroid()) {
Class j = getJavaX();
synchronized(j) { // hopefully this goes well...
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);
}
}
return hotwire_overInternalBot(src);
}
static String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder();
quote_impl(s, out);
return out.toString();
}
static 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
out.append(c);
}
out.append('"');
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static String fsI(String id) {
return formatSnippetID(id);
}
static String fsI(long id) {
return formatSnippetID(id);
}
static String standardCredentials() {
String user = standardCredentialsUser();
String pass = standardCredentialsPass();
if (nempty(user) && nempty(pass))
return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
return "";
}
static ThreadLocal loadPage_charset = new ThreadLocal();
static boolean loadPage_allowGzip = true, loadPage_debug;
static boolean loadPage_anonymous; // don't send computer ID
static int loadPage_verboseness = 100000;
static int loadPage_retries = 60; // seconds
public static String loadPageSilently(String url) {
try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPageSilently(URL url) {
try {
IOException e = null;
for (int tries = 0; tries < loadPage_retries; tries++)
try {
URLConnection con = openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPageThroughProxy_enabled) {
print("Trying proxy because of: " + e);
try {
return loadPageThroughProxy(str(url));
} catch (Throwable e2) {
print(" " + exceptionToStringShort(e2));
}
}
sleepSeconds(1);
}
throw e;
} catch (IOException e) { throw new RuntimeException(e); }
}
static String loadPage_preprocess(String url) {
if (url.startsWith("tb/"))
url = "tinybrain.de:8080/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
public static String loadPage(String url) {
try {
url = loadPage_preprocess(url);
print("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPage(URL url) {
print("Loading: " + hideCredentials(url.toExternalForm()));
return loadPageSilently(url);
}
public static String loadPage(URLConnection con, URL url) throws IOException {
try {
if (!loadPage_anonymous)
setHeaders(con);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
} catch (Throwable e) {} // fails if within doPost
String contentType = con.getContentType();
if (contentType == null)
throw new IOException("Page could not be read: " + url);
//print("Content-Type: " + contentType);
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null) charset = loadPage_guessCharset(contentType);
InputStream in = con.getInputStream();
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = new GZIPInputStream(in);
}
Reader r = new InputStreamReader(in, charset);
StringBuilder buf = new StringBuilder();
int n = 0;
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
if ((n % loadPage_verboseness) == 0) print(" " + n + " chars read");
}
return buf.toString();
}
static String loadPage_guessCharset(String contentType) {
Pattern p = Pattern.compile("text/[a-z]+;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(contentType);
String match = m.matches() ? m.group(1) : null;
if (loadPage_debug)
print("loadPage: contentType=" + contentType + ", match: " + match);
/* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
return or(match, "ISO-8859-1");
}
static Class> hotwire_overInternalBot(String progID) { try {
File jar = CompilerBot.compileSnippet(progID);
assertTrue(jar.getAbsolutePath(), jar.isFile());
// collect urls (program + libraries)
List urls = litlist(jar.toURI().toURL());
String dehlibs = unnull(loadTextFileFromZip(jar, "libraries"));
Matcher matcher = Pattern.compile("\\d+").matcher(dehlibs);
while (matcher.find()) {
String libID = matcher.group();
urls.add(loadLibrary(libID).toURI().toURL());
}
// make class loader
URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[l(urls)]));
// load & return main class
Class> theClass = classLoader.loadClass("main");
Class j = getJavaX();
// We don't use this right now
// S src = loadTextFileFromZip(jar, "main.java");
// call(j, "registerSourceCode", theClass, src);
synchronized(j) { // hopefully this goes well...
call(j, "setVars", theClass, progID);
callOpt(j, "addInstance", progID, theClass);
}
hotwire_copyOver(theClass);
return theClass;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static String standardCredentialsUser() {
return trim(loadTextFile(new File(userHome(), ".tinybrain/username")));
}
static void assertTrue(Object o) {
assertEquals(true, o);
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static String hideCredentials(String url) {
return url.replaceAll("&_pass=[^&]*", "&_pass=");
}
static void setHeaders(URLConnection con) throws IOException {
String computerID = getComputerID();
if (computerID != null) try {
con.setRequestProperty("X-ComputerID", computerID);
con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
} catch (Throwable e) {
//printShortException(e);
}
}
static String exceptionToStringShort(Throwable e) {
e = getInnerException(e);
String msg = unnull(e.getMessage());
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + ": " + msg;
else
return msg;
}
static final boolean loadPageThroughProxy_enabled = false;
static String loadPageThroughProxy(String url) {
return null;
}
static void hotwire_copyOver(Class c) {
synchronized(StringBuffer.class) {
for (String field : litlist("print_log", "print_silent", "androidContext")) {
Object o = getOpt(mc(), field);
if (o != null)
setOpt(c, field, o);
}
Object mainBot = getMainBot();
if (mainBot != null)
setOpt(c, "mainBot", mainBot);
setOpt(c, "creator_class", new WeakReference(mc()));
}
}
static File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
static URLConnection openConnection(URL url) { try {
ping();
return url.openConnection();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void sleepSeconds(double s) {
if (s > 0) sleep(round(s*1000));
}
static String loadTextFileFromZip(File inZip, String fileName) {
return loadTextFileFromZipFile(inZip, fileName);
}
static A or(A a, A b) {
return a != null ? a : b;
}
static String standardCredentialsPass() {
return trim(loadTextFile(new File(userHome(), ".tinybrain/userpass")));
}
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 String getComputerID() { try {
return computerID();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void sleep(long ms) {
ping();
if (ms < 0) return;
// allow spin locks
if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) { throw new RuntimeException(e); }
}
static void sleep() { try {
print("Sleeping.");
synchronized(main.class) { main.class.wait(); }
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String baseClassName(String className) {
return substring(className, className.lastIndexOf('.')+1);
}
static String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
static A assertEquals(Object x, A y) {
return assertEquals(null, x, y);
}
static A assertEquals(String msg, Object x, A y) {
if (!(x == null ? y == null : x.equals(y)))
throw fail((msg != null ? msg + ": " : "") + x + " != " + y);
return y;
}
static Throwable getInnerException(Throwable e) {
while (e.getCause() != null)
e = e.getCause();
return e;
}
static String loadTextFileFromZipFile(File inZip, String fileName) { try {
ZipFile zip = new ZipFile(inZip);
try {
ZipEntry entry = zip.getEntry(fileName);
if (entry == null)
//fail("Entry " + fileName + " not found in zip file: " + inZip.getAbsolutePath());
return null;
InputStream fin = zip.getInputStream(entry);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copyStream(fin, baos);
fin.close();
return fromUTF8(baos.toByteArray());
} finally {
zip.close();
}
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public static String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(String fileName, String defaultContents) {
try {
if (!new File(fileName).exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(File fileName, String defaultContents) {
return loadTextFile(fileName.getPath(), defaultContents);
}
public static 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 builder.toString();
}
static long round(double d) {
return Math.round(d);
}
// 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 String _computerID;
public static String computerID() { try {
if (_computerID == null) {
File file = new File(userHome(), ".tinybrain/computer-id");
_computerID = loadTextFile(file.getPath(), null);
if (_computerID == null) {
_computerID = makeRandomID(12);
saveTextFile(file.getPath(), _computerID);
}
}
return _computerID;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static 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 (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String substring(String s, int x) {
return safeSubstring(s, x);
}
static String substring(String s, int x, int y) {
return safeSubstring(s, x, y);
}
static String fromUTF8(byte[] bytes) {
return fromUtf8(bytes);
}
static File getGlobalCache() {
File file = new File(userHome(), ".tinybrain/snippet-cache");
file.mkdirs();
return file;
}
/** writes safely (to temp file, then rename) */
public static void saveTextFile(String fileName, String contents) throws IOException {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
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());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
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);
}
public static void saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** 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 = newFileOutputStream(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);
}
}
// hopefully covers all cases :)
static String safeSubstring(String 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.substring(x, y);
}
static String safeSubstring(String s, int x) {
return safeSubstring(s, x, l(s));
}
static byte[] loadBinaryPage(String url) { try {
print("Loading " + url);
return loadBinaryPage(new URL(url).openConnection());
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static byte[] loadBinaryPage(URLConnection con) { try {
setHeaders(con);
return loadBinaryPage_noHeaders(con);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static byte[] loadBinaryPage_noHeaders(URLConnection con) { try {
setHeaders(con);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
InputStream inputStream = con.getInputStream();
long len = 0;
try { len = con.getContentLengthLong(); } 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 (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String fromUtf8(byte[] bytes) { try {
return new String(bytes, "UTF-8");
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static FileOutputStream newFileOutputStream(File path) throws IOException {
return newFileOutputStream(path.getPath());
}
static FileOutputStream newFileOutputStream(String path) throws IOException {
return newFileOutputStream(path, false);
}
static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
FileOutputStream f = new // Line break for ancient translator
FileOutputStream(path, append);
callJavaX("registerIO", f, path, true);
return f;
}
public static void copyFile(File src, File dest) { try {
mkdirsForFile(dest);
FileInputStream inputStream = new FileInputStream(src.getPath());
FileOutputStream outputStream = newFileOutputStream(dest.getPath());
try {
copyStream(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static A println(A a) {
return print(a);
}
public static File mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) // is null if file is in current dir
dir.mkdirs();
return file;
}
static Object callJavaX(String method, Object... args) {
return callOpt(getJavaX(), method, args);
}
static class CompilerBot {
static boolean verbose;
// returns jar path
static File compileSnippet(String snippetID) {
String transpiledSrc = getServerTranspiled2(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 compile(transpiledSrc, libs);
}
static File compile(String src) {
return compile(src, "");
}
static File compile(String src, String libs) {
return compile(src, libs, null);
}
static File compile(String src, String dehlibs, String javaTarget) {
if (verbose)
print("Compiling " + l(src) + " chars");
String md5 = md5(dehlibs + "\n" + src);
File jar = getJarFile(md5);
if (jar == null || jar.length() <= 22) {
// have to compile
javaCompileToJar_standard(src, dehlibs, jar);
} else {
if (verbose)
print("Getting classes from cache (" + jar.getAbsolutePath() + ", " + jar.length() + " bytes)");
touchFile(jar); // so we can find the unused ones easier
}
return jar;
}
static File getJarFile(String md5) {
assertTrue(isMD5(md5));
return new File(getCacheProgramDir("#1002203"), md5 + ".jar");
}
}
static void showConsole() {
showFrame(consoleFrame());
}
static String getServerTranspiled2(String id) {
String transpiled = loadCachedTranspilation(id);
String md5 = null;
if (isOfflineMode()) return transpiled;
if (transpiled != null)
md5 = md5(transpiled);
String transpiledSrc = getServerTranspiled(formatSnippetID(id), md5);
if (eq(transpiledSrc, "SAME")) {
print("SAME");
return transpiled;
}
return transpiledSrc;
}
// will create the file or update its last modified timestamp
static void touchFile(File file) { try {
closeRandomAccessFile(newRandomAccessFile(mkdirsForFile(file), "rw"));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void restart() {
Object j = getJavaX();
call(j, "cleanRestart", get(j, "fullArgs"));
}
static String md5(String text) { try {
if (text == null) return "-";
return bytesToHex(md5_impl(text.getBytes("UTF-8"))); // maybe different than the way PHP does it...
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String md5(byte[] data) {
if (data == null) return "-";
return bytesToHex(md5_impl(data));
}
static MessageDigest md5_md;
/*static byte[] md5_impl(byte[] data) { try {
if (md5_md == null)
md5_md = MessageDigest.getInstance("MD5");
return ((MessageDigest) md5_md.clone()).digest(data);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}*/
static byte[] md5_impl(byte[] data) { try {
return MessageDigest.getInstance("MD5").digest(data);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String md5(File file) { try {
return md5(loadBinaryFile(file));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static boolean isMD5(String s) {
return l(s) == 32 && isLowerHexString(s);
}
static File javaCompileToJar_standard(String src, File destJar) {
return javaCompileToJar_standard(src, "", destJar);
}
// returns path to jar
static synchronized File javaCompileToJar_standard(String src, String dehlibs, File destJar) {
String javaTarget = null; // use default target
print("Compiling " + l(src) + " chars");
String md5 = md5(src);
File jar = destJar;
Class j = getJavaX();
if (javaTarget != null)
setOpt(j, "javaTarget", javaTarget);
//setOpt(j, "verbose", true);
File srcDir = (File) ( call(j, "TempDirMaker_make"));
String className = "main";
String fileName = className + ".java";
File mainJava = new File(srcDir, fileName);
//print("main java: " + mainJava.getAbsolutePath());
saveTextFile(mainJava, src);
File classesDir = (File) call(j, "TempDirMaker_make");
List libraries = new ArrayList();
Matcher m = Pattern.compile("\\d+").matcher(dehlibs);
while (m.find()) {
String libID = m.group();
//print("libID=" + quote(libID));
assertTrue(isSnippetID(libID));
libraries.add(loadLibrary(libID));
}
String compilerOutput;
try {
compilerOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir);
} catch (Throwable e) {
compilerOutput = (String) get(getJavaX(), "javaCompilerOutput");
throw fail("Compile Error. " + compilerOutput + " " + e);
}
if (nempty(compilerOutput)) {
print("Compiler said: " + compilerOutput);
//fail("Compile Error. " + compilerOutput);
}
// sanity test
if (!new File(classesDir, className + ".class").exists())
throw fail("No class generated (" + className + ")");
// add sources to .jar
saveTextFile(new File(classesDir, "main.java"), src);
// add information about libraries to jar
if (nempty(dehlibs))
saveTextFile(new File(classesDir, "libraries"), dehlibs);
//print("Zipping: " + classesDir.getAbsolutePath() + " to " + jar.getAbsolutePath());
dir2zip_recurse_verbose = false;
int n = dir2zip_recurse(classesDir, jar); // cache on success only
//print("Files zipped: " + n);
return jar;
}
static 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') {
// ok
} else
return false;
}
return true;
}
static boolean dir2zip_recurse_verbose;
static int dir2zip_recurse(File inDir, File zip) {
return dir2zip_recurse(inDir, zip, "");
}
// TODO: the zero files case?
static 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 (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static 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()) {
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 = new FileInputStream(f);
copyStream(fin, outZip);
fin.close();
++n;
}
}
return n;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void closeRandomAccessFile(RandomAccessFile f) {
if (f != null) try {
f.close();
callJavaX("dropIO", f);
} catch (Throwable e) {
printStackTrace(e);
}
}
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 String getServerTranspiled(String snippetID) {
return getServerTranspiled(snippetID, null);
}
// returns "SAME" if md5 matches
static String getServerTranspiled(String snippetID, String expectedMD5) { try {
long id = parseSnippetID(snippetID);
/*S t = getTranspilationFromBossBot(id);
if (t != null) return t;*/
String text = loadPage_utf8("http://tinybrain.de:8080/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 (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String loadCachedTranspilation(String id) {
return loadTextFile(new File(getCodeProgramDir(id), "Transpilation"));
}
static RandomAccessFile newRandomAccessFile(File path, String mode) throws IOException {
RandomAccessFile f = new RandomAccessFile(path, mode);
callJavaX("registerIO", f, path, mode.indexOf('w') >= 0);
return f;
}
static boolean isOfflineMode() {
return eq("1", trim(loadProgramTextFile("#1005806", "offline-mode")));
}
public static byte[] loadBinaryFile(String fileName) {
try {
if (!new File(fileName).exists())
return null;
FileInputStream in = new FileInputStream(fileName);
byte buf[] = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream();
int l;
while (true) {
l = in.read(buf);
if (l <= 0) break;
out.write(buf, 0, l);
}
in.close();
return out.toByteArray();
} catch (IOException e) { throw new RuntimeException(e); }
}
public static byte[] loadBinaryFile(File file) {
return loadBinaryFile(file.getPath());
}
static String loadPage_utf8(URL url) {
return loadPage_utf8(url.toString());
}
static String loadPage_utf8(String url) {
loadPage_charset.set("UTF-8");
try {
return loadPage(url);
} finally {
loadPage_charset.set(null);
}
}
static void saveTranspiledCode(String progID, String code) {
saveTextFile(new File(getCodeProgramDir(progID), "Transpilation"), code);
}
static File getCodeProgramDir() {
return getCodeProgramDir(getProgramID());
}
static File getCodeProgramDir(String snippetID) {
return new File(javaxCodeDir(), formatSnippetID(snippetID));
}
static File getCodeProgramDir(long snippetID) {
return getCodeProgramDir(formatSnippetID(snippetID));
}
static String loadProgramTextFile(String name) {
return loadTextFile(getProgramFile(name));
}
static String loadProgramTextFile(String progID, String name) {
return loadTextFile(getProgramFile(progID, name));
}
static String loadProgramTextFile(String progID, String name, String defaultText) {
return loadTextFile(getProgramFile(progID, name), defaultText);
}
static void sortFilesByName(List l) {
sort(l, new Comparator() {
public int compare(File a, File b) {
return stdcompare(a.getName(), b.getName());
}
});
}
static File[] listFiles(File dir) {
File[] files = dir.listFiles();
return files == null ? new File[0] : files;
}
static File[] listFiles(String dir) {
return listFiles(new File(dir));
}
static File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
static File javaxCodeDir_dir; // can be set to work on different base dir
static File javaxCodeDir() {
return javaxCodeDir_dir != null ? javaxCodeDir_dir : new File(userHome(), "JavaX-Code");
}
static void sort(T[] a, Comparator super T> c) {
Arrays.sort(a, c);
}
static void sort(T[] a) {
Arrays.sort(a);
}
static void sort(List a, Comparator super T> c) {
Collections.sort(a, c);
}
static void sort(List a) {
Collections.sort(a);
}
static int stdcompare(Number a, Number b) {
return cmp(a, b);
}
static int stdcompare(String a, String b) {
return cmp(a, b);
}
static int stdcompare(long a, long b) {
return a < b ? -1 : a > b ? 1 : 0;
}
static int stdcompare(Object a, Object b) {
return cmp(a, b);
}
static int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static int cmp(String a, String b) {
return a == null ? b == null ? 0 : -1 : a.compareTo(b);
}
static 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 File getProgramDir() {
return programDir();
}
static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
static File programDir_mine; // set this to relocate program's data
static File programDir() {
return programDir(getProgramID());
}
static File programDir(String snippetID) {
if (programDir_mine != null && sameSnippetID(snippetID, programID()))
return programDir_mine;
return new File(javaxDataDir(), formatSnippetID(snippetID));
}
static boolean sameSnippetID(String a, String b) {
return a != null && b != null && parseSnippetID(a) == parseSnippetID(b);
}
static File javaxDataDir_dir; // can be set to work on different base dir
static File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
}