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 org.pushingpixels.substance.api.*;
import org.pushingpixels.substance.api.skin.*;
class main {
static int w = 32, h = 16, ww = 400, hh = 200;
static DirectSurface ds;
static BufferedImage img;
static boolean continuous = false, rareRepaint = true, shootInParallel = true;
static int speed = 0;
static volatile BufferedImage src = null;
static long screenshotTime = 0;
static int frames;
static long start;
static class DirectSurface extends Surface {
BufferedImage img;
DirectSurface() {}
DirectSurface(BufferedImage img) {
this.img = img;}
public void render(int w, int h, Graphics2D g) {
g.drawImage(img, 0, 0, null);
}
public Dimension getPreferredSize() {
return new Dimension(img.getWidth(), img.getHeight());
}
}
public static void main(final String[] args) throws Exception { { swingAndWait(new Runnable() { public void run() { try { substance();
img = newBufferedImage(ww, hh);
showPackedFrame(ds = new DirectSurface(img));
shootMaybe();
if (shootInParallel) { Thread _t_0 = new Thread() {
public void run() { try {
while (licensed()) { try {
shootMaybe();
} catch (Throwable __e) { printStackTrace2(__e); } sleepSeconds(100); }
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
{ Thread _t_1 = new Thread() {
public void run() { try {
PerSecondCounter fps = new PerSecondCounter(5);
long consoleUpdate = 0;
while (licensed()) {
if (!shootInParallel) shootMaybe();
++frames;
start = sysNow();
for (int y = 0; y < hh; y += h)
for (int x = 0; x < ww; x += w) {
int srcw, srch;
if (src != null) {
srcw = src.getWidth();
srch = src.getHeight();
} else {
Dimension ss = screenSize();
srcw = ss.width; srch = ss.height;
}
int srcX = random(srcw-w), srcY = random(srch-h);
if (continuous)
drawImageOnImage(screenshot(srcX, srcY, w, h), img, x, y);
else
copyImagePart(src, srcX, srcY, img, x, y, w, h);
if (!rareRepaint) ds.paintImmediately(x, y, w, h);
sleep(speed);
}
if (rareRepaint) ds.repaint();
//consoleStatus(iterationsPerSecond(frames, sysNow()-start) + " fps");
fps.inc();
if (sysNow() >= consoleUpdate+1000) {
consoleUpdate = sysNow();
consoleStatus(iround(fps.get()) + " fps");
}
}
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_1); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "substance();\n img = newBufferedImage(ww, hh);\n showPackedFrame(ds = new Direct..."; }}); }}
static void shootMaybe() {
if (!continuous && (src == null || sysNow() > screenshotTime+1000)) {
src = screenshot();
screenshotTime = sysNow();
}
}
static JFrame showPackedFrame(String title, Component contents) {
return packFrame(showFrame(title, contents));
}
static JFrame showPackedFrame(Component contents) {
return packFrame(showFrame(contents));
}
// changes & returns canvas
static BufferedImage drawImageOnImage(BufferedImage img, BufferedImage canvas, int x, int y) {
Graphics2D g = canvas.createGraphics();
g.drawImage(img, x, y, null);
g.dispose();
return canvas;
}
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.");
sleepQuietly();
} catch (Exception __e) { throw rethrow(__e); } }
static Random random_random = new Random();
static int random(int n) {
return n <= 0 ? 0 : random_random.nextInt(n);
}
static double random(double max) {
return random()*max;
}
static double random() {
return random_random.nextInt(100001)/100000.0;
}
static double random(double min, double max) {
return min+random()*(max-min);
}
// min <= value < max
static int random(int min, int max) {
return min+random(max-min);
}
static A random(List l) {
return oneOf(l);
}
static A random(Collection c) {
return oneOf(asList(c));
}
static void consoleStatus(String status) {
consoleTitleStatus(status);
}
static long sysNow() {
return System.nanoTime()/1000000;
}
static int iround(double d) {
return (int) Math.round(d);
}
static Dimension screenSize() {
return getScreenSize();
}
// undefined color, seems to be all black in practice
static BufferedImage newBufferedImage(int w, int h) {
return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}
static BufferedImage newBufferedImage(int w, int h, Color color) {
BufferedImage img = newBufferedImage(w, h);
Graphics2D g = img.createGraphics();
g.setColor(color);
g.fillRect(0, 0, w, h);
return img;
}
static void copyImagePart(BufferedImage src, int srcx, int srcy, BufferedImage dest, int destx, int desty, int w, int h) {
Graphics2D g = dest.createGraphics();
BufferedImage sub = src.getSubimage(srcx, srcy, w, h);
g.drawImage(sub, destx, desty, null);
g.dispose();
}
static Map _registerThread_threads = Collections.synchronizedMap(new WeakHashMap());
static Thread _registerThread(Thread t) {
_registerThread_threads.put(t, true);
return t;
}
static void _registerThread() { _registerThread(Thread.currentThread()); }
static BufferedImage screenshot() {
return shootScreen2();
}
static BufferedImage screenshot(Rectangle area) { try {
return shootScreen2(area);
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage screenshot(Rect area) {
return shootScreen2(area);
}
static BufferedImage screenshot(int x, int y, int w, int h) {
return shootScreen2(x, y, w, h);
}
static int packFrame_minw = 150, packFrame_minh = 50;
static JFrame packFrame(final Component c) {
return (JFrame) swing(new Object() { Object get() { try {
JFrame frame = getFrame(c);
if (frame == null) return null;
frame.pack();
int maxW = getScreenWidth()-50, maxH = getScreenHeight()-50;
frame.setSize(
min(maxW, max(frame.getWidth(), packFrame_minw)),
min(maxH, max(frame.getHeight(), packFrame_minh)));
return frame;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JFrame frame = getFrame(c);\r\n if (frame == null) null;\r\n frame.pack();\r\n ..."; }});
}
static JFrame packFrame(ButtonGroup g) {
return packFrame(getFrame(g));
}
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());
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl();
return true;
}
// returns true when it slept
static boolean ping_impl() { 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 (Exception __e) { throw rethrow(__e); } }
static boolean shootScreen_useScrot = true; // Use program "scrot" to make full-screen screenshots (on Linux); prevents the bug https://bugs.openjdk.java.net/browse/JDK-7168628
static BufferedImage shootScreen2() {
return shootScreen2(screenRectangle());
}
static BufferedImage shootScreen2(Rectangle area) { try {
if (shootScreen_useScrot && eq(area, screenRectangle())) {
if (!isOnPATH("scrot")) shootScreen2_fallback();
if (shootScreen_useScrot) {
File f = prepareProgramFile(randomID(12) + ".png");
try {
String cmd = "scrot " + bashQuote(f);
String out = backtick(cmd);
if (f.exists())
return loadPNG(f);
shootScreen2_fallback();
} catch (Throwable e) {
print(e);
shootScreen2_fallback();
} finally {
f.delete();
}
}
}
return new Robot().createScreenCapture(area);
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage shootScreen2(Rect area) {
return shootScreen2(area.getRectangle());
}
static BufferedImage shootScreen2(int x, int y, int w, int h) {
return shootScreen2(new Rectangle(x, y, w, h));
}
// internal
static void shootScreen2_fallback() {
if (shootScreen_useScrot) {
print("Scrot failed. Reverting to internal screenshots.");
shootScreen_useScrot = false;
}
}
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 RuntimeException fail() {
throw new RuntimeException("fail");
}
static RuntimeException fail(Throwable e) {
throw asRuntimeException(e);
}
static RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static RuntimeException fail(String msg) {
throw new RuntimeException(unnull(msg));
}
static RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
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 Object print_byThread_lock = new Object();
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) {
F1 f = print_byThread.get();
if (f != null)
if (isFalse(f.get(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);
}
}
}
static A oneOf(List l) {
return l.isEmpty() ? null : l.get(new Random().nextInt(l.size()));
}
static char oneOf(String s) {
return empty(s) ? '?' : s.charAt(random(l(s)));
}
static String oneOf(String... l) {
return oneOf(asList(l));
}
static void sleepQuietly() { try {
assertFalse(isAWTThread());
synchronized(main.class) { main.class.wait(); }
} catch (Exception __e) { throw rethrow(__e); } }
static void consoleTitleStatus(String status) {
titleStatus(consoleFrame(), status);
}
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 rethrow(__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;
}
}
// TODO: test if android complains about this
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isAWTThread_awt();
}
static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
static boolean frameTooSmall(JFrame frame) {
return frame.getWidth() < 100 || frame.getHeight() < 50;
}
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 {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) { return isHeadless_cache = true; }
}
static File prepareProgramFile(String name) {
return mkdirsForFile(getProgramFile(name));
}
static File prepareProgramFile(String progID, String name) {
return mkdirsForFile(getProgramFile(progID, name));
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static boolean isOnPATH(String cmd) {
String path = System.getenv("PATH");
List dirs = splitAt(path, File.pathSeparator);
String c = isWindows() ? cmd + ".exe" : cmd;
for (String dir : dirs)
if (new File(dir, c).isFile())
return true;
return false;
}
static WeakHashMap makeFrame_myFrames = new WeakHashMap();
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);
makeFrame_myFrames.put(frame, Boolean.TRUE);
JComponent wrapped = wrap(content);
if (wrapped != null)
frame.getContentPane().add(wrapped);
frame.setBounds(300, 100, 500, 400);
if (showIt)
frame.setVisible(true);
//callOpt(content, "requestFocus");
//exitOnFrameClose(frame);
standardTitlePopupMenu(frame);
return frame;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (getFrame(content) != null)\r\n ret setFrameTitle((Component) content, tit..."; }});
}
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 RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static Object mc() {
return getMainClass();
}
static void setFrameContents(JFrame frame, Object contents) {
frame.getContentPane().removeAll();
frame.getContentPane().add(wrap(contents));
revalidate(frame);
}
/** possibly improvable */
static String bashQuote(String text) {
if (text == null) return null;
return "\"" + text
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r") + "\"";
}
static String bashQuote(File f) {
return bashQuote(f.getAbsolutePath());
}
static Thread currentThread() {
return Thread.currentThread();
}
static void titleStatus(Component c, String status) {
if (getFrame(c) == null) return;
String s = getFrameTitle(c);
String sep = " - ";
setFrameTitle(c, replaceLeader(status, sep, s));
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || a.equals(b);
}
static Rectangle screenRectangle() {
return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
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 assertFalse(Object o) {
assertEquals(false, o);
}
static boolean assertFalse(boolean b) {
if (b) throw fail("oops");
return b;
}
static boolean assertFalse(String msg, boolean b) {
if (b) throw fail(msg);
return b;
}
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 int getScreenWidth() {
return getScreenSize().width;
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static void frameStandardSize(JFrame frame) {
frame.setBounds(300, 100, 500, 400);
}
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 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)
: o instanceof Map ? l((Map) o)
: l((Collection) o); // incomplete
}
static int getScreenHeight() {
return getScreenSize().height;
}
static Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static int randomID_defaultLength = 12;
static String randomID(int length) {
return makeRandomID(length);
}
static String randomID() {
return randomID(randomID_defaultLength);
}
static BufferedImage loadPNG(File file) {
return loadBufferedImage(file);
}
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 int backtick_exitValue;
static boolean backtick_verbose;
static ThreadLocal backtick_scriptFile = new ThreadLocal();
static ThreadLocal backtick_uninterruptable = new ThreadLocal(); // Great trick, thanks to Tim Bunce @ http://stackoverflow.com/questions/12856620/how-to-handle-signals-in-bash-during-synchronous-execution
static String backtick(String cmd) { try {
File outFile = File.createTempFile("_backtick", "");
backtickToFile(cmd, outFile);
String result = loadTextFile(outFile.getPath(), "");
if (backtick_verbose) {
//print("backtick: script length after=" + backtick_scriptFile->length());
print("[[\n" + result + "]]");
}
return result;
} catch (Exception __e) { throw rethrow(__e); } }
static Process backtickToFile(String cmd, File outFile) { try {
try {
Process process = backtickToFile_noWait(cmd, outFile);
process.waitFor();
backtick_exitValue = process.exitValue();
if (backtick_verbose)
System.out.println("Process return code: " + backtick_exitValue);
return process;
} finally {
deleteFile(backtick_scriptFile.get());
backtick_scriptFile.set(null);
}
} catch (Exception __e) { throw rethrow(__e); } }
static Process backtickToFile_noWait(String cmd, File outFile) { try {
File scriptFile = File.createTempFile("_backtick", isWindows() ? ".bat" : "");
backtick_scriptFile.set(scriptFile);
if (backtick_verbose)
print("backtick: scriptFile " + f2s(scriptFile));
cmd = trim(cmd);
if (numLines(cmd) > 1) throw fail("No multi-line commands allowed");
String command = cmd + " >" + bashQuote(outFile.getPath()) + " 2>&1";
if (!isTrue(backtick_uninterruptable.get()) && !isWindows()) command = fixNewLines("\r\ninterruptable() {\r\n\r\n # handle options\r\n local setsid=\"\"\r\n local debug=false\r\n while true; do\r\n case \"${1:-}\" in\r\n --killall) setsid=setsid; shift ;;\r\n --debug) debug=true; shift ;;\r\n --*) echo \"Invalid option: $1\" 1>&2; exit 1;;\r\n *) break;; # no more options\r\n esac\r\n done\r\n\r\n # start the specified command\r\n $setsid \"$@\" &\r\n local child_pid=$!\r\n\r\n # arrange to propagate a signal to the child process\r\n trap '\r\n exec 1>&2\r\n set +e\r\n trap \"\" SIGPIPE # ensure a possible sigpipe from the echo does not prevent the kill\r\n echo \"${BASH_SOURCE[0]} caught SIGTERM while executing $* (pid $child_pid), sending SIGTERM to it\"\r\n # (race) child may have exited in which case kill will report an error\r\n # if setsid is used then prefix the pid with a \"-\" to indicate that the signal\r\n # should be sent to the entire process group\r\n kill ${setsid:+-}$child_pid\r\n exit 143\r\n ' SIGTERM\r\n # ensure that the trap doesn't persist after we return\r\n trap 'trap - SIGTERM' RETURN\r\n\r\n $debug && echo \"interruptable wait (child $child_pid, self $$) for: $*\"\r\n\r\n # An error status from the child process will trigger an exception (via set -e)\r\n # here unless the caller is checking the return status\r\n wait $child_pid # last command, so status of waited for command is returned\r\n}\r\n\r\ninterruptable ") + command;
//Log.info("[Backtick] " + command);
if (backtick_verbose) {
print("backtick: command " + command);
print("backtick: saving to " + scriptFile.getPath());
}
saveTextFile(scriptFile.getPath(), command);
if (backtick_verbose)
print("backtick: command length=" + l(command) + ", file length=" + scriptFile.length());
String[] command2;
if (isWindows())
command2 = new String[] { scriptFile.getPath() };
else
command2 = new String[] { "/bin/bash", scriptFile.getPath() };
if (backtick_verbose)
print("backtick: command2 " + structure(command2));
return Runtime.getRuntime().exec(command2);
} catch (Exception __e) { throw rethrow(__e); } }
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(); }
public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}
static void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(r);
} catch (Exception __e) { throw rethrow(__e); } }
static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() { public void run() { try {
result.set(callF(f));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; }});
return result.get();
}
}
static void revalidate(Component c) {
if (c == null || !c.isShowing()) return;
// magic combo to actually relayout and repaint
c.revalidate();
c.repaint();
}
static String getType(Object o) {
return getClassName(o);
}
/** writes safely (to temp file, then rename) */
static void saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
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);
} finally {
action.done();
}
}
static void saveTextFile(File fileName, String contents) { try {
saveTextFile(fileName.getPath(), contents);
} catch (Exception __e) { throw rethrow(__e); } }
// TODO: returns empty first, but not empty last
static List splitAt(String s, String splitter) {
List parts = new ArrayList();
int i = 0;
if (s != null)
while (i < l(s)) {
int j = indexOf(s, splitter, i);
if (j < 0) j = l(s);
parts.add(substring(s, i, j));
i = j+l(splitter);
}
return parts;
}
static int numLines(String s) {
return countLines(s);
}
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 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;
}
static void standardTitlePopupMenu(final JFrame 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("Duplicate Program", "duplicateThisProgram"));
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 rethrow(__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 rethrow(__e); } } public String toString() { return "shootWindowGUI_external(frame, 500)"; }}));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n menu.add(jmenuItem(\"Restart P..."; }});
}
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
// 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;
}
// 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 (o instanceof DynamicObject)
return ((DynamicObject) 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 String getFrameTitle(Component c) {
JFrame f = getFrame(c);
return f == null ? null : f.getTitle();
}
static boolean deleteFile(File file) {
return file != null && file.delete();
}
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 Class __javax;
static Class getJavaX() {
return __javax;
}
static Class getMainClass() {
return main.class;
}
static Class getMainClass(Object o) { try {
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) { throw rethrow(__e); } }
static String replaceLeader(String a, String sep, String b) {
return joinStrings(sep, a, dropUpToFirst(b, sep));
}
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 f, String defaultContents) {
return f == null ? defaultContents : loadTextFile(f.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 String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
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 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 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 + ": " : "") + y + " != " + x);
return y;
}
static boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
return structure(o, new structure_Data());
}
static String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack))
popLast(d.stack).run();
}
static void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static class structure_Data {
PrintWriter out;
int stringSizeLimit;
int shareStringsLongerThan = 20;
IdentityHashMap