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.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.skin.*;
import java.nio.file.Files;
import javax.sound.sampled.*;
import org.pushingpixels.substance.api.*;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import javazoom.jl.player.*;
import java.io.*;
import java.awt.datatransfer.StringSelection;
class main {
static String keyphrase = "computer";
// bigger number means more tolerance
// 1e-40 works pretty well with few false positives
// 1e-30 gets no hits
// 1e-35 doesn't trigger reliably
// Using 1e-39 for now
static String threshold = "1e-39";
// seconds to listen after hot word
// TODO: keep listening when user said something
static int recognitionTimeout = 10;
static String icon = /*#1009669*/ "#1009667"; //#1009662;
// milliseconds before starting recognition (time for saying "yep" or "ja")
static int delayBeforeRecognition = 300;
static Object onKeyPhrase;
static boolean exited;
static String python = trim("\n#!/usr/bin/python\nfrom subprocess import Popen, PIPE, STDOUT\nimport pty\nimport os\nimport sys\n\ncmd = 'pocketsphinx_continuous -inmic yes -keyphrase #KEYPHRASE# -kws_threshold #THRESHOLD#'\n\nmaster, slave = pty.openpty()\n\np = Popen(cmd, shell=True, stdin=PIPE, stdout=slave, stderr=slave, close_fds=True)\nstdout = os.fdopen(master)\nwhile True:\n sys.stdout.write(stdout.readline())\n sys.stdout.flush()\n");
static File fPython;
static JButton btnStartStop;
static boolean paused;
public static void main(final String[] args) throws Exception { substance();
if (!isLinux()) throw fail("Get Linux!");
load("paused");
//onLeftClick(installTrayIcon(icon, "Computer!"), f jump_blip);
TrayIcon trayIcon = onLeftClick(
installTrayIcon2(resizeImage(loadImage2(icon), 24), "Computer!",
makePopupMenu(menuItem("Computer!", "jump_blip"))),
"jump_blip");
trayIcon.displayMessage(
"", "Click on EVE to activate the assistant!",
TrayIcon.MessageType.INFO/*NONE*/);
makeBot("Hot Word Detection.");
unix_killAll("pocketsphinx");
print("Key phrase is: " + keyphrase);
onKeyPhrase = new Object() { void get(String s) { try { jump() ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "jump()"; }};
{ swingAndWait(new Runnable() { public void run() { try {
showControls(jcenteredline(btnStartStop = jbutton("Listen for hot word", "startStop")));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showControls(jcenteredline(btnStartStop = jbutton(\"Listen for hot word\", f start..."; }}); }
fPython = getProgramFile("pocketsphinx.py");
makeExecutable(saveTextFile(fPython, python.replace("#THRESHOLD#", threshold).replace("#KEYPHRASE#", bashQuote(keyphrase))));
titleStatus_setBaseTitle(consoleFrame(), "Hot Word Detection");
if (!paused) {
infoBox("Say " + quote(keyphrase) + " to activate me!");
start();
}
makeBot("Hot Word Detection.");
}
static void start() {
setText(btnStartStop, "Don't listen for hot word");
{ Thread _t_0 = new Thread() {
public void run() { try {
backtickToConsole_lineBuf(f2s(fPython), new Object() { void get(String line) { try {
print("Line read: " + quote(line));
if (eq(line, keyphrase))
pcallF(onKeyPhrase, line);
else if (startsWith(line, "READY."))
consoleStatus("Ready");
else if (startsWith(line, "Listening."))
consoleStatus("Listening");
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "print(\"Line read: \" + quote(line));\n if (eq(line, keyphrase))\n pcall..."; }});
setAndSave("paused" , true);
setText(btnStartStop, "Listen for hot word");
consoleStatus("Stopped");
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
}
static void cleanMeUp() {
if (!exited) { exited = true; unix_killAll("pocketsphinx"); }
}
static void startStop() {
if (paused) {
setAndSave("paused" , false);
start();
} else {
setAndSave("paused" , true);
setText(btnStartStop, "Listen for hot word");
unix_killAll("pocketsphinx");
}
}
static void jump_blip() {
{ Thread _t_1 = new Thread() {
public void run() { try {
infoBox(botAnswerWord());
blipAndWait();
sendOpt("Chrome Speech.", "start recognition timeout " + recognitionTimeout);
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_1); }
}
static void jump() {
final String response = botAnswerWord();
infoBox(response);
{ Thread _t_2 = new Thread() {
public void run() { try { sleep(delayBeforeRecognition); sendOpt("Chrome Speech.", "start recognition timeout " + recognitionTimeout); } catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_2); }
{ Thread _t_3 = new Thread() {
public void run() { try { sendOpt("Mouth.", response); } catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_3); }
}
static String answer(String s) {
final Matches m = new Matches();
if (match("listen to hot word", s)) { if (paused) startStop(); return "OK"; }
if (match("don't listen to hot word", s)) { if (!paused) startStop(); return "OK"; }
return null;
}
static void consoleStatus(String status) {
consoleTitleStatus(status);
}
static PopupMenu makePopupMenu(Object... x) {
if (x == null) return null;
if (l(x) == 1 && x[0] instanceof PopupMenu)
return (PopupMenu) x[0];
PopupMenu m = new PopupMenu();
for (Object o : x)
if (eqOneOf(o, "***", "---", "===", ""))
m.addSeparator();
else if (o instanceof String || o instanceof Menu || o instanceof MenuItem)
call(m, "add", o);
else
print("Unknown menu item: " + o);
return m;
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static JWindow infoBox(String text) {
return infoMessage(text);
}
static JWindow infoBox(String text, double seconds) {
return infoMessage(text, seconds);
}
static JWindow infoBox(Throwable e) {
return infoMessage(e);
}
static String sendOpt(String bot, String text, Object... args) {
return sendToLocalBotOpt(bot, text, args);
}
static void blipAndWait() {
blipWait();
}
static volatile boolean sleep_noSleep;
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 {
if (sleep_noSleep) throw fail("nosleep");
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) { throw rethrow(__e); } }
// runnable takes an argument
static void onLeftClick(JComponent c, final Object runnable) {
c.addMouseListener(leftClickMouseAdapter(runnable));
}
// runnable takes no args
static TrayIcon onLeftClick(final TrayIcon c, final Object runnable) {
{ swingAndWait(new Runnable() { public void run() { try {
c.addMouseListener(leftClickMouseAdapter_noPt(runnable));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.addMouseListener(leftClickMouseAdapter_noPt(runnable));"; }}); }
return c;
}
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((int) (l(s)*1.5+2));
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 Object load(String varName) {
readLocally(varName);
return get(mc(), varName);
}
static Object load(String progID, String varName) {
readLocally(progID, varName);
return get(mc(), varName);
}
static BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
static int makeBot(String greeting) {
return makeAndroid3(greeting).port;
}
static Android3 makeBot(Android3 a) {
makeAndroid3(a);
return a;
}
static Android3 makeBot(String greeting, Object responder) {
Android3 a = new Android3(greeting);
a.responder = makeResponder(responder);
makeBot(a);
return a;
}
static Android3 makeBot() {
return makeAndroid3(getProgramTitle() + ".");
}
static String botAnswerWord() {
return eq(currentBotLanguage(), "de-DE") ? "Ja!" : "Yep!";
}
static void makeExecutable(File file) { try {
if (!isWindows())
try {
makeExecutable_java7(file);
} catch (Throwable _e) {
warn("Java 6 fallback for makeExecutable");
backtick("chmod a+rx " + bashQuote(file));
}
} catch (Exception __e) { throw rethrow(__e); } }
/** 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 boolean isLinux() {
return !isWindows() && !isMac() && !isAndroid();
}
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 String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
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 List unix_killAll(final String pattern) {
Map procs = psPidsAndCommands();
Map p2 = filterMap(procs, new Object() { Object get(Integer i, String cmd) { try { return contains(cmd, pattern) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "contains(cmd, pattern)"; }});
for (Integer pid : keys(p2))
print("Killing " + pid + ": " + p2.get(pid));
unix_killProcesses(keys(p2));
return asList(keys(p2));
}
static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
// button without action
static JButton jbutton(String text) {
return newButton(text, null);
}
static JButton jbutton(BufferedImage img, Object action) {
return setButtonImage(img, jbutton("", action));
}
static JButton jbutton(Action action) {
return new JButton(action);
}
static A setAndSave(String var, A value) {
set(mc(), var, value);
save(var);
return value;
}
static MenuItem menuItem(String text, final Object r) {
MenuItem mi = new MenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || a.equals(b);
}
static TrayIcon installTrayIcon2(Image image, String tooltip) {
return installTrayIcon2(image, tooltip, null);
}
static TrayIcon installTrayIcon2(final Image image, final String tooltip, final PopupMenu menu) { try {
return swing(new F0() { TrayIcon get() { try {
TrayIcon trayIcon = new TrayIcon(image, tooltip, menu);
SystemTray.getSystemTray().add(trayIcon);
return trayIcon;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "TrayIcon trayIcon = new TrayIcon(image, tooltip, menu);\r\n SystemTray.getSyste..."; }});
} catch (Exception __e) { throw rethrow(__e); } }
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 BufferedImage resizeImage(BufferedImage img, int newW, int newH) {
return resizeImage(img, newW, newH, Image.SCALE_SMOOTH);
}
static BufferedImage resizeImage(BufferedImage img, int newW, int newH, int scaleType) {
Image tmp = img.getScaledInstance(newW, newH, scaleType);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
static BufferedImage resizeImage(BufferedImage img, int newW) {
int newH = iround(img.getHeight()*(double) newW/img.getWidth());
return resizeImage(img, newW, newH);
}
/** 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 File saveTextFile(File fileName, String contents) { try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) { throw rethrow(__e); } }
// returns file with program output (STDOUT+STDERR)
static File backtickToConsole_lineBuf(String cmd, final Object onLine) {
Object onOutput = new Object() {
LinesBuffer buf = new LinesBuffer();
void get(String s) {
buf.append(fixNewLines(s));
for (String line : buf.getAndClearCompleteLines())
pcallF(onLine, line);
}
};
return backtickToConsoleX(cmd, onOutput);
}
static JPanel jcenteredline(final Component... components) {
//ret new CenteredLine(components);
return swing(new F0() { JPanel get() { try { return jFullCenter(hstackWithSpacing(components)) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "jFullCenter(hstackWithSpacing(components))"; }});
}
static JPanel jcenteredline(List extends Component> components) {
return jcenteredline(asArray(Component.class, components));
}
static JComponent showControls_controls;
static void showControls(final JComponent controls) {
{ swingAndWait(new Runnable() { public void run() { try {
hideControls();
JComponent _controls = withMargin(controls);
showControls_controls = _controls;
addToConsole2(showControls_controls);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "hideControls();\r\n JComponent _controls = withMargin(controls);\r\n showContr..."; }}); }
}
static boolean setText_opt = true; // optimize by calling getText first
static void setText(JTextComponent c, Object text) {
setText((Object) c, text);
}
static void setText(JLabel c, Object text) {
setText((Object) c, text);
}
static void setText(JButton c, Object text) {
setText((Object) c, text);
}
static void setText(final Object c, Object text) {
if (c == null) return;
final String s = str(text);
swingAndWait(new Runnable() { public void run() { try {
if (!setText_opt || neq(call(c, "getText"), s))
call(c, "setText", s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!setText_opt || neq(call(c, \"getText\"), s))\r\n call(c, \"setText\", s);"; }});
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
m.m = new String[] {substring(a, l(b))};
return true;
}
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 Object[] asArray(List l) {
return toObjectArray(l);
}
static A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static List beginCriticalAction_inFlight = synchroList();
static class CriticalAction {
String description;
CriticalAction() {}
CriticalAction(String description) {
this.description = description;}
void done() {
beginCriticalAction_inFlight.remove(this);
}
}
static CriticalAction beginCriticalAction(String description) {
ping();
CriticalAction c = new CriticalAction(description);
beginCriticalAction_inFlight.add(c);
return c;
}
static void cleanMeUp_beginCriticalAction() {
int n = 0;
while (nempty(beginCriticalAction_inFlight)) {
int m = l(beginCriticalAction_inFlight);
if (m != n) {
n = m;
try {
print("Waiting for " + n(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
} catch (Throwable __e) { printStackTrace2(__e); }
}
sleepInCleanUp(10);
}
}
static MouseAdapter leftClickMouseAdapter(final Object r) {
return new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1)
callF(r, new Pt(e.getPoint()));
}
};
}
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;
}
public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}
// 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 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 boolean infoMessage_alwaysOnTop = true;
static double infoMessage_defaultTime = 5.0;
// automatically switches to AWT thread for you
static JWindow infoMessage(String text) {
return infoMessage(text, infoMessage_defaultTime);
}
static JWindow infoMessage(final String text, final double seconds) {
print(text);
return infoMessage_noprint(text, seconds);
}
static JWindow infoMessage_noprint(String text) {
return infoMessage_noprint(text, infoMessage_defaultTime);
}
static JWindow infoMessage_noprint(final String text, final double seconds) {
if (isHeadless()) return null;
return (JWindow) swingAndWait(new Object() { Object get() { try {
JTextArea ta = wrappedTextArea(text);
int size = 14;
if (l(text) <= 50) size *= 2;
else if (l(text) < 100) size = iround(size*1.5);
ta.setFont(typeWriterFont(size));
JScrollPane sp = jscroll(ta);
final JWindow window = showWindow(withMargin(sp));
window.setSize(300, 150);
moveToTopRightCorner(window);
onClick(ta, new Runnable() { public void run() { try { window.dispose() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispose()"; }});
if (infoMessage_alwaysOnTop)
window.setAlwaysOnTop(true);
window.setVisible(true);
disposeWindowAfter(iround(seconds*1000), window);
return window;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JTextArea ta = wrappedTextArea(text);\r\n int size = 14;\r\n if (l(text) <= 50..."; }});
}
static JWindow infoMessage(Throwable e) {
showConsole();
printStackTrace(e);
return infoMessage(str(e));
}
static Throwable printStackTrace(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
return e;
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
/*static void printStackTrace(S indent, Throwable e) {
if (endsWithLetter(indent)) indent += " ";
printIndent(indent, getStackTrace(e));
}*/
static String str(Object o) {
return o == null ? "null" : o.toString();
}
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 boolean isMac() {
return System.getProperty("os.name").toLowerCase().contains("mac");
}
static Map psPidsAndCommands() {
if (isWindows()) throw fail("Unix only");
String psOutput = backtick("ps -aef");
List lines = toLines(psOutput);
String header = lines.get(0);
List body = dropFirst(lines);
final int i1 = header.indexOf(" PID");
final int i2 = header.indexOf("CMD");
return pairsToTreeMap(map(new Object() { Object get(String s) { try { return
pair(parseInt(trim(substring(s, i1-2, i1+4))), substring(s, i2).trim())
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "pair(parseInt(trim(substring(s, i1-2, i1+4))), substring(s, i2).trim())"; }}, body));
}
// returns file with program output (STDOUT+STDERR)
static File backtickToConsoleX(String cmd, final Object outputReceiver) {
File outputFile = createTempFile(cmd, ".out");
makeEmptyFile(outputFile); // unnecessary?
final LastLineBuffer buf = new LastLineBuffer();
TailFile tail = tailFile2(outputFile, 1000, new Object() { void get(String s) { try {
buf.append(printNoNewLine(fixNewLines(s)));
pcallF(outputReceiver, s);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "buf.append(printNoNewLine(fixNewLines(s)));\r\n pcallF(outputReceiver, s);"; }});
// make a dependent child process that is exited when we exit
print("Running: " + cmd);
try {
backtickToFile(cmd, outputFile);
} catch (Throwable __e) { printStackTrace2(__e); }
tail.stop();
return outputFile;
}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
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 (Exception __e) { throw rethrow(__e); } }
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(ping_actions) {
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 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 void save(String varName) {
saveLocally(varName);
}
static void save(String progID, String varName) {
saveLocally(progID, varName);
}
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 ActionListener actionListener(final Object runnable) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { pcallF(runnable); }};
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o 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 Class __javax;
static Class getJavaX() {
return __javax;
}
static int iround(double d) {
return (int) Math.round(d);
}
static void set(Object o, String field, Object value) {
if (o instanceof Class) set((Class) o, field, value);
else try {
Field f = set_findField(o.getClass(), field);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void set(Class c, String field, Object value) {
try {
Field f = set_findStaticField(c, field);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field set_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 set_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 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 File getProgramDir() {
return programDir();
}
static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
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 Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
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 (Exception __e) { throw rethrow(__e); } }
static BufferedImage loadBufferedImage(File file) { try {
return file.isFile() ? ImageIO.read(file) : null;
} catch (Exception __e) { throw rethrow(__e); } }
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { printStackTrace2(__e); }
return null;
}
// action can be Runnable or a function name
static JButton newButton(final String text, final Object action) {
return swing(new F0() { JButton get() { try {
JButton btn = new JButton(text);
if (action != null)
btn.addActionListener(actionListener(action));
return btn;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JButton btn = new JButton(text);\r\n if (action != null)\r\n btn.addActionLi..."; }});
}
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 boolean backtick_win_cmd; // bugfixing
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())
if (backtick_win_cmd)
command2 = new String[] { "cmd", "/c", scriptFile.getPath() };
else
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); } }
// An "Android" is a program that accepts text questions (on console or TCP) and outputs one response text per question
static boolean makeAndroid3_disable; // disable all android making
static class Android3 {
String greeting;
boolean publicOverride; // optionally set this in client
int startPort = 5000; // optionally set this in client
Responder responder;
boolean console = true;
boolean quiet; // no messages on console
boolean daemon = false;
boolean incomingSilent = false;
int incomingPrintLimit = 200;
boolean useMultiPort = true;
boolean recordHistory;
boolean verbose;
int answerPrintLimit = 500;
boolean newLineAboveAnswer, newLineBelowAnswer;
// set by system
int port;
long vport;
DialogHandler handler;
ServerSocket server;
Android3(String greeting) {
this.greeting = greeting;}
Android3() {}
synchronized void dispose() {
if (server != null) {
try {
server.close();
} catch (IOException e) {
print("[internal] " + e);
}
server = null;
}
if (vport != 0) try {
print("Disposing " + this);
removeFromMultiPort(vport);
vport = 0;
} catch (Throwable __e) { printStackTrace2(__e); }
}
public String toString() { return "Bot: " + greeting + " [vport " + vport + "]"; }
}
static abstract class Responder {
abstract String answer(String s, List history);
}
static Android3 makeAndroid3(final String greeting) {
return makeAndroid3(new Android3(greeting));
}
static Android3 makeAndroid3(final String greeting, Responder responder) {
Android3 android = new Android3(greeting);
android.responder = responder;
return makeAndroid3(android);
}
static Android3 makeAndroid3(final Android3 a) {
if (makeAndroid3_disable) return a;
if (a.responder == null)
a.responder = new Responder() {
String answer(String s, List history) {
return callStaticAnswerMethod(s, history);
}
};
if (!a.quiet)
print("[bot] " + a.greeting);
if (a.console && makeAndroid3_consoleInUse() && !readLine_noReadLine) a.console = false;
record(a);
if (a.useMultiPort)
a.vport = addToMultiPort(a.greeting,
makeAndroid3_verboseResponder(a));
if (a.console)
makeAndroid3_handleConsole(a);
if (a.useMultiPort) return a;
a.handler = makeAndroid3_makeDialogHandler(a);
if (a.quiet) startDialogServer_quiet.set(true);
try {
a.port = a.daemon
? startDialogServerOnPortAboveDaemon(a.startPort, a.handler)
: startDialogServerOnPortAbove(a.startPort, a.handler);
} finally {
startDialogServer_quiet.set(null);
}
a.server = startDialogServer_serverSocket;
return a;
}
static void makeAndroid3_handleConsole(final Android3 a) {
// Console handling stuff
if (!a.quiet)
print("You may also type on this console.");
{ Thread _t_4 = new Thread() {
public void run() { try {
List history = new ArrayList();
while (licensed()) {
String line;
try {
line = readLine();
} catch (Throwable e) {
print(getInnerMessage(e));
break;
}
if (line == null) break;
/*if (eq(line, "bye")) {
print("> bye stranger");
history = new ArrayList();
} else*/ {
history.add(line);
history.add(makeAndroid3_getAnswer(line, history, a)); // prints answer on console too
}
}
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_4); }
}
static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
return new DialogHandler() {
public void run(final DialogIO io) {
if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
io.sendLine("Sorry, not allowed");
return;
}
String dialogID = randomID(8);
io.sendLine(a.greeting + " / Your ID: " + dialogID);
List history = new ArrayList();
while (io.isStillConnected()) {
if (io.waitForLine()) {
final String line = io.readLineNoBlock();
String s = dialogID + " at " + now() + ": " + quote(line);
if (!a.incomingSilent)
print(shorten(s, a.incomingPrintLimit));
if (eq(line, "bye")) {
io.sendLine("bye stranger");
return;
}
Matches m = new Matches();
if (a.recordHistory)
history.add(line);
String answer;
if (match3("this is a continuation of talk *", s, m)
|| match3("hello bot! this is a continuation of talk *", s, m)) {
dialogID = unquote(m.m[0]);
answer = "ok";
} else try {
makeAndroid3_io.set(io);
answer = makeAndroid3_getAnswer(line, history, a);
} finally {
makeAndroid3_io.set(null);
}
if (a.recordHistory)
history.add(answer);
io.sendLine(answer);
//appendToLog(logFile, s);
}
}
}};
}
static String makeAndroid3_getAnswer(String line, List history, Android3 a) {
String answer, originalAnswer;
try {
originalAnswer = a.responder.answer(line, history);
answer = makeAndroid3_fallback(line, history, originalAnswer);
} catch (Throwable e) {
e = getInnerException(e);
printStackTrace(e);
originalAnswer = answer = e.toString();
}
if (!a.incomingSilent) {
if (originalAnswer == null) originalAnswer = "?";
if (a.newLineAboveAnswer) print();
print(">" + dropFirst(indentx(2, shorten(rtrim(originalAnswer), a.answerPrintLimit))));
if (a.newLineBelowAnswer) print();
}
return answer;
}
static String makeAndroid3_fallback(String s, List history, String answer) {
// Now we only do the safe thing instead of VM inspection - give out our process ID
if (answer == null && match3("what is your pid", s))
return getPID();
if (answer == null && match3("what is your program id", s)) // should be fairly safe, right?
return getProgramID();
if (match3("get injection id", s))
return getInjectionID();
if (answer == null) answer = "?";
if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
answer = quote(answer);
return answer;
}
static boolean makeAndroid3_consoleInUse() {
for (Object o : record_list)
if (o instanceof Android3 && ((Android3) o).console)
return true;
return false;
}
static Responder makeAndroid3_verboseResponder(final Android3 a) {
return new Responder() {
String answer(String s, List history) {
if (a.verbose)
print("> " + shorten(s, a.incomingPrintLimit));
String answer = a.responder.answer(s, history);
if (a.verbose)
print("< " + shorten(answer, a.incomingPrintLimit));
return answer;
}
};
}
static ThreadLocal makeAndroid3_io = new ThreadLocal();
static Android3 makeAndroid3() {
return makeAndroid3(getProgramTitle() + ".");
}
static String currentBotLanguage() {
return or2(loadTextFilePossiblyGZipped(getProgramFile("#1009555", "language.text")), "en-US");
}
static JPanel jFullCenter(Component c) {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(c);
return panel;
}
static MouseAdapter leftClickMouseAdapter_noPt(final Object r) {
return new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1)
pcallF(r);
}
};
}
static RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static Class mc() {
return main.class;
}
static void consoleTitleStatus(String status) {
titleStatus(consoleFrame(), status);
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static String getProgramTitle() {
return getProgramName();
}
static void hideControls() {
{ swingAndWait(new Runnable() { public void run() { try {
removeFromConsole2(showControls_controls);
showControls_controls = null;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "removeFromConsole2(showControls_controls);\r\n showControls_controls = null;"; }}); }
}
static int withMargin_defaultWidth = 6;
static JPanel withMargin(Component c) {
JPanel p = new JPanel(new BorderLayout());
int w = withMargin_defaultWidth;
p.setBorder(BorderFactory.createEmptyBorder(w, w, w, w));
p.add(c);
return p;
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static JButton setButtonImage(BufferedImage img, JButton btn) {
btn.setIcon(imageIcon(img));
return btn;
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static boolean warn_on = true;
static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
}
static Map filterMap(Map map, Object f) {
Map m2 = similarEmptyMap(map);
for (A a : keys(map)) {
B b = map.get(a);
if (isTrue(callF(f, a, b)))
m2.put(a, b);
}
return m2;
}
// requires Java 7
// assumes the file is yours
static void makeExecutable_java7(File file) { try {
if (isWindows()) return;
Set p = new HashSet(Files.getPosixFilePermissions(file.toPath()));
p.add(PosixFilePermission.OWNER_READ);
p.add(PosixFilePermission.OWNER_EXECUTE);
p.add(PosixFilePermission.GROUP_READ);
p.add(PosixFilePermission.GROUP_EXECUTE);
p.add(PosixFilePermission.OTHERS_READ);
p.add(PosixFilePermission.OTHERS_EXECUTE);
Files.setPosixFilePermissions(file.toPath(), p);
} catch (Exception __e) { throw rethrow(__e); } }
static Set keys(Map map) {
return map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static void unix_killProcesses(Collection pids) {
if (empty(pids)) return;
List pids2 = map(new Object() { Object get(Integer i) { try { return str(i) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "str(i)"; }}, pids);
String s = joinWithSpaces(pids2);
print("Killing processes: " + s);
backtick("kill " + s);
}
static String substring(String s, int x) {
return substring(s, x, l(s));
}
static String substring(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 void blipWait() {
playWAVAndWait(preload_blip());
}
static int hstackWithSpacing_spacing = 10;
// first part can be spacing value
static JPanel hstackWithSpacing(Object... parts) {
int spacing = hstackWithSpacing_spacing;
int i = 0;
if (first(parts) instanceof Integer) {
spacing = toInt(first(parts));
++i;
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.gridheight = GridBagConstraints.REMAINDER;
for (; i < l(parts); i++) {
if (i != 0)
panel.add(Box.createRigidArea(new Dimension(spacing, 0)), gbc);
panel.add(wrapForSmartAdd(parts[i]), gbc);
}
gbc.weightx = 1;
panel.add(Box.createRigidArea(new Dimension(0, 0)), gbc);
return panel;
}
static Object sleepQuietly_monitor = new Object();
static void sleepQuietly() { try {
assertFalse(isAWTThread());
synchronized(sleepQuietly_monitor) { sleepQuietly_monitor.wait(); }
} catch (Exception __e) { throw rethrow(__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;
}
static void readLocally(String progID, String varNames) {
readLocally2(mc(), progID, varNames);
}
static void readLocally(String varNames) {
readLocally2(mc(), programID(), varNames);
}
static void readLocally2(Object obj, String varNames) {
readLocally2(obj, programID(), varNames);
}
static int readLocally_stringLength;
static ThreadLocal readLocally2_allDynamic = new ThreadLocal();
// read a string variable from standard storage
// does not overwrite variable contents if there is no file
static void readLocally2(Object obj, String progID, String varNames) { try {
boolean allDynamic = isTrue(getAndClearThreadLocal(readLocally2_allDynamic));
for (String variableName : javaTokC(varNames)) {
File textFile = new File(programDir(progID), variableName + ".text");
String value = loadTextFile(textFile);
if (value != null)
set(main.class, variableName, value);
else {
File structureFile = new File(programDir(progID), variableName + ".structure");
value = loadTextFile(structureFile);
if (value == null) {
File structureGZFile = new File(programDir(progID), variableName + ".structure.gz");
if (!structureGZFile.isFile()) return;
//value = loadGZTextFile(structureGZFile);
InputStream fis = new FileInputStream(structureGZFile);
try {
GZIPInputStream gis = new GZIPInputStream(fis);
InputStreamReader reader = new InputStreamReader(gis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
//O o = unstructure_reader(bufferedReader);
Object o = unstructure_tok(javaTokC_noMLS_onReader(bufferedReader), allDynamic, null);
readLocally_set(obj, variableName, o);
} finally {
fis.close();
}
return;
}
readLocally_stringLength = l(value);
if (nempty(value))
readLocally_set(obj, variableName, allDynamic ? safeUnstructure(value) : unstructure(value));
}
}
} catch (Exception __e) { throw rethrow(__e); } }
static void readLocally_set(Object c, String varName, Object value) {
Object oldValue = get(c, varName);
if (oldValue instanceof List && !(oldValue instanceof ArrayList) && value != null) {
// Assume it's a synchroList.
value = synchroList((List) value);
}
set(c, varName, value);
}
static void addToConsole2(Component toAdd) {
JFrame frame = consoleFrame();
if (frame == null) return;
Container cp = frame.getContentPane();
Container cp2 = (Container) getCenterComponent(cp);
replaceCenterComponent(cp, centerAndSouth(cp2, toAdd));
validateFrame(frame);
}
static String makeResponder_callAnswerMethod(Object bot, String s, List history) {
String answer = (String) callOpt(bot, "answer", s, history);
if (answer == null)
answer = (String) callOpt(bot, "answer", s);
return answer;
}
static Responder makeResponder(final Object bot) {
if (bot instanceof Responder) return (Responder) bot;
if (bot instanceof String) {
String f = (String) ( bot);
return new Responder() {
String answer(String s, List history) {
String answer = (String) callOptMC((String) bot, s, history);
if (answer == null)
answer = (String) callOptMC((String) bot, s);
return answer;
}
};
}
return new Responder() {
String answer(String s, List history) {
return makeResponder_callAnswerMethod(bot, s, history);
}
};
}
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 String sendToLocalBotOpt(String bot, String text, Object... args) {
if (bot == null) return null;
text = format(text, args);
DialogIO channel = findBot(bot);
if (channel == null) {
print(quote(bot) + " not found, skipping send: " + quote(text));
return null;
}
try {
channel.readLine();
print(shorten(bot + "> " + text, 200));
channel.sendLine(text);
String s = channel.readLine();
print(shorten(bot + "< " + s, 200));
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
channel.close();
}
}
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 Font typeWriterFont() {
return typeWriterFont(14);
}
static Font typeWriterFont(int size) {
return new Font("Courier", Font.PLAIN, size);
}
static String joinWithSpaces(Collection c) {
return join(" ", c);
}
static String joinWithSpaces(String... c) {
return join(" ", c);
}
static WeakHashMap> callF_cache = new WeakHashMap();
static Object callF(Object f, Object... args) { try {
if (f instanceof String)
return callMC((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) throw fail("No get method in " + getClassName(c));
if (n == 1) return methods.get(0).invoke(f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return m.invoke(f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
m.setAccessible(true);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static A disposeWindowAfter(int delay, final A w) {
if (w != null)
swingLater(delay, new Runnable() { public void run() { try {
w.dispose();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "w.dispose();"; }});
return w;
}
static void replaceCenterComponent(Container container, Component c) {
Component old = getCenterComponent(container);
if (old != null)
container.remove(old);
container.add(c, BorderLayout.CENTER);
}
static List