Warning : session_start(): open(/var/lib/php/sessions/sess_6m46fqieeodmsf7gibd244flrq, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import javazoom.jl.player.*;
import javazoom.jlgui.basicplayer.*;
public class main {
static int songDuration, seekValue;
static long songBytes;
static int position;
static File mp3;
static BasicPlayer player;
static Integer seekTo;
static JFrame frame;
static JSlider seeker = new JSlider();
static JLabel text = new JLabel();
static JTable table = new JTable();
static JTable lastPlayed = new JTable();
static List tableData, lastPlayedData;
public static void main(String[] args) throws Exception { SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
substanceLAF("Moderate");
// Fixing the classpath for Java Sound (MP3 + OGG)
fixContextClassLoader();
{ Thread _t_0 = new Thread("Searching Music...") {
public void run() {
try {
updateLastPlayed();
tableData = findMusicFiles();
dataToTable_uneditable(table, musicFilesTable(tableData));
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
};
_t_0.start(); }
onDoubleClick(table, new Object() { void get(int row) {
play(tableData.get(row));
}});
onDoubleClick(lastPlayed, new Object() { void get(int row) {
play(lastPlayedData.get(row));
}});
// init seeker
seeker.setMajorTickSpacing(10000); // 10 seconds
seeker.setMinorTickSpacing(10000); // 10 seconds
seeker.setPaintTicks(true);
seeker.setMaximum(1);
seeker.setValue(0);
seeker.setEnabled(false);
seeker.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
boolean adjusting = seeker.getValueIsAdjusting();
if (adjusting)
seekTo = seeker.getValue();
else if (seekTo != null) {
seek(seekTo);
seekTo = null;
}
}
});
frame = showFrame(
centerAndNorth(jtabs(
"Library", table,
"Last played", lastPlayed),
centerAndSouth(
centerAndEast(seeker, text),
hgrid(jbutton("play again", "playAgain"))
)));
frame.pack();
setFrameIconLater(frame, "#1003635");
setFrameWidth(frame, 500);
exitOnFrameClose(frame); // To immediately stop playback
hideConsole();
player = makeBasicMP3Player();
player.addBasicPlayerListener(new BasicPlayerListener() {
public void opened(Object stream, Map properties) {
for (Object key : properties.keySet())
print("opened: " + key + "=" + properties.get(key));
// Try to find duration of song
final Number bytes = (Number) properties.get("audio.length.bytes");
long microseconds = 0;
Object duration = properties.get("duration");
if (duration instanceof Number)
microseconds = ((Number) duration).longValue();
else try {
long frames = asLong(properties.get("audio.length.frames"));
long fps = asLong(properties.get("audio.framerate.fps"));
microseconds = frames*1000000/fps;
} catch (Throwable __e) { printStackTrace(__e); }
final long _microseconds = microseconds;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
songDuration = (int) (_microseconds / 1000);
seeker.setMaximum(songDuration);
seeker.setEnabled(true);
seeker.setMajorTickSpacing(10000); // 10 seconds
updateText();
songBytes = bytes.longValue();
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
});
}
public void progress(int bytesread, final long microseconds, byte[] pcmdata, Map properties) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
if (!seeker.getValueIsAdjusting()) {
int ms = (int) (microseconds / 1000) + seekValue;
seeker.setValue(ms);
position = ms;
updateText();
}
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
});
}
public void stateUpdated(BasicPlayerEvent event) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
updateStateStuff();
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
});
}
public void setController(BasicController controller) {}
});
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
});}
static void play(File f) {
if (f == null) return;
mp3 = f;
setFrameTitle(frame, f.getName() + " - " + getProgramTitle());
logStructure("player.log", litlist(now(), "Playing", f.getAbsolutePath()));
play();
updateLastPlayed();
}
static void playAgain() {
logStructure("player.log", litlist(now(), "Playing again"));
play();
}
static void play() { try {
seekValue = 0;
player.open(mp3);
player.play();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void updateStateStuff() {}
static void updateText() {
text.setText(formatMinuteAndSeconds(position/1000) + " / " + formatMinuteAndSeconds(songDuration/1000));
}
static void seek(int milliseconds) {
if (mp3 == null) return;
long bytes = (long) (milliseconds*((double) songBytes)/songDuration);
print("ms=" + milliseconds + ", songBytes=" + songBytes + ", duration=" + songDuration + ", bytes=" + bytes);
try {
seekValue = milliseconds;
player.open(mp3);
player.seek(bytes);
player.play();
} catch (Throwable __e) { printStackTrace(__e); }
}
static List findLastPlayed() {
List l = new ArrayList();
Set seen = new TreeSet();
for (String s : reversedList(scanLog("player.log"))) try {
List line = unstructureList(s);
if (eq(get(line, 1), "Playing")) {
String file = getString(line, 2);
if (seen.add(file))
l.add(new File(file));
}
} catch (Throwable __e) { printStackTrace(__e); }
return l;
}
static void updateLastPlayed() {
dataToTable_uneditable(lastPlayed, musicFilesTable(lastPlayedData = findLastPlayed()));
}
static JPanel centerAndEast(Component c, Component e) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.EAST, wrap(e));
return panel;
}
static JPanel hgrid(Object... parts) {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, parts.length));
smartAdd(panel, parts);
return panel;
}
static void setFrameIconLater(final JFrame frame, final String imageID) {
if (frame != null)
{ Thread _t_1 = new Thread("Loading Icon") {
public void run() {
try {
final Image i = imageIcon(imageID).getImage();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
frame.setIconImage(i);
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
});
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
};
_t_1.start(); }
}
static JPanel centerAndSouth(Component c, Component s) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
}
static boolean setFrameTitle(Component c, String title) {
JFrame f = getFrame(c);
if (f == null) return false;
f.setTitle(title);
return true;
}
static void dataToTable_uneditable(final JTable table, final Object data) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
dataToTable(table, data, true);
makeTableUneditable(table);
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
});
}
static void substanceLAF() {
substanceLAF(null);
}
static void substanceLAF(String skinName) {
try {
if (!substanceLookAndFeelEnabled()) {
Object x = hotwire("#1003448");
if (skinName != null)
set(x, "skinName", skinName);
runMain(x);
JFrame.setDefaultLookAndFeelDecorated(substanceLookAndFeelEnabled());
}
} catch (Throwable __e) { printStackTrace(__e); }
}
// runnable can be a func(O o) {} receving the selected item
static void onDoubleClick(final JList list, final Object runnable) {
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2) {
int idx = list.locationToIndex(evt.getPoint());
Object item = list.getModel().getElementAt(idx);
list.setSelectedIndex(idx);
callF(runnable, item);
}
}
});
}
// runnable can be a func(O o) {} receving the selected row index
static void onDoubleClick(final JTable table, final Object runnable) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2) {
int idx = table.rowAtPoint(evt.getPoint());
table.setRowSelectionInterval(idx, idx);
callF(runnable, idx);
}
}
});
}
static void setFrameWidth(JFrame frame, int w) {
frame.setSize(w, frame.getHeight());
}
static String formatMinuteAndSeconds(int secs) {
return secs/60 + ":" + formatInt(secs % 60, 2);
}
static ArrayList litlist(A... a) {
return new ArrayList (Arrays.asList(a));
}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
// get purpose 1: access a list/array (safer version of x.get(y))
static A get(List l, int idx) {
return idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
if (o.getClass().getName().equals("main$DynamicObject"))
return call(get_raw(o, "fieldValues"), "get", field);
return get_raw(o, field);
}
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 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 BasicPlayer makeBasicMP3Player() {
return new BasicPlayer();
}
static String getProgramTitle() {
return getProgramName();
}
static List findMusicFiles() {
List files;
{ JWindow _loading_window = showLoadingAnimation(); try {
files = findAllFiles(concatLists((List) findDownloadDirectories(), ll(userHome("Music"), userHome("My Documents"), "/media/CE009E97009E865D__/stuff")));
} finally { disposeWindow(_loading_window); }}
return filter(files, new Object() { Object get(File f) {
String name = f.getName().toLowerCase();
return endsWithOneOf(name, ".mp3", ".ogg", ".wav", ".flac");
}});
}
static List reversedList(List l) {
List x = cloneList(l);
Collections.reverse(x);
return x;
}
static List scanLog(String progID, String fileName) {
return scanLog(getProgramFile(progID, fileName));
}
static List scanLog(String fileName) {
return scanLog(getProgramFile(fileName));
}
static List scanLog(File file) {
List l = new ArrayList();
for (String s : toLines(file))
if (isProperlyQuoted(s))
l.add(unquote(s));
return l;
}
// x = names and components interleaving
static JTabbedPane jtabs(Object... x) {
JTabbedPane tabs = new JTabbedPane();
for (int i = 0; i+1 < l(x); i += 2) {
tabs.addTab(str(x[i]), wrap(x[i+1]));
}
return tabs;
}
static List musicFilesTable() {
return musicFilesTable(findMusicFiles());
}
static List musicFilesTable(List files) {
List data = new ArrayList();
for (File f : files)
data.add(litorderedmap("Name", f.getName(), "Location", f.getParentFile().getAbsolutePath()));
return data;
}
static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
static String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
static String getString(List l, int idx) {
return (String) get(l, idx);
}
static String getString(Object o, Object key) {
if (o instanceof Map) return getString((Map) o, key);
if (key instanceof String)
return (String) get(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
static boolean eq(Object a, Object b) {
if (a == null) return b == null;
if (a.equals(b)) return true;
if (a instanceof BigInteger) {
if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b));
if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b));
}
return false;
}
static void fixContextClassLoader() {
Thread.currentThread().setContextClassLoader(myClassLoader());
}
static long asLong(Object o) {
return toLong(o);
}
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 void print() {
print("");
}
// slightly overblown signature to return original object...
static A print(A o) {
String s = String.valueOf(o) + "\n";
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);
return o;
}
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 List unstructureList(String s) {
return (List) unstructure(s);
}
static void logStructure(File logFile, Object o) {
logQuoted(logFile, structure(o));
}
// quick version - log to file in program directory
static void logStructure(String fileName, Object o) {
logStructure(getProgramFile(fileName), o);
}
static void hideConsole() {
JFrame frame = consoleFrame();
if (frame != null) {
autoVMExit();
frame.setVisible(false);
}
}
static JPanel centerAndNorth(Component c, Component n) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.NORTH, wrap(n));
return panel;
}
static void exitOnFrameClose(JFrame frame) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
static ArrayList ll(A... a) {
return litlist(a);
}
static LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static String formatInt(int i, int digits) {
return padLeft(str(i), '0', digits);
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
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(String title, Object content, boolean showIt) {
JFrame frame = new JFrame(title);
if (content != null)
frame.getContentPane().add(wrap(content));
frame.setBounds(300, 100, 500, 400);
if (showIt)
frame.setVisible(true);
//callOpt(content, "requestFocus");
//exitOnFrameClose(frame);
// standard right-click behavior on titles
if (isSubstanceLAF())
onTitleRightClick(frame, new Runnable() { public void run() { try { showConsole(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}});
return frame;
}
static Object callF(Object f, Object... args) {
return callFunction(f, args);
}
static void makeTableUneditable(JTable table) {
for (int c = 0; c < table.getColumnCount(); c++) {
Class> col_class = table.getColumnClass(c);
table.setDefaultEditor(col_class, null); // remove editor
}
}
static boolean substanceLookAndFeelEnabled() {
return startsWith(getLookAndFeel(), "org.pushingpixels.");
}
static long toLong(Object o) {
if (o instanceof Number)
return ((Number) o).longValue();
if (o instanceof String)
return parseLong((String) o);
return 0;
}
static void smartAdd(JPanel panel, Object... parts) {
for (Object o : parts) {
Component c;
if (o instanceof String)
c = new JLabel((String) o);
else
c = wrap(o);
panel.add(c);
}
}
static List cloneList(Collection l) {
//O mutex = getOpt(l, "mutex");
/*if (mutex != null)
synchronized(mutex) {
ret new ArrayList (l);
}
else
ret new ArrayList (l);*/
// assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does.
synchronized(l) {
return new ArrayList (l);
}
}
static List findAllFiles(List dirs) {
return findAllFiles(asObjectArray(dirs));
}
// dirs are String's or File's
static List findAllFiles(Object... dirs) {
List l = new ArrayList();
for (Object dir : dirs)
findAllFiles_impl(toFile(dir), l);
return l;
}
static void findAllFiles_impl(File dir, List l) {
for (File f : listFiles(dir)) {
l.add(f);
if (f.isDirectory())
findAllFiles_impl(f, l);
}
}
static boolean isProperlyQuoted(String s) {
return s.length() >= 2
&& s.startsWith("\"")
&& s.endsWith("\"")
&& !s.endsWith("\\\"");
}
static String str(Object o) {
return String.valueOf(o);
}
static RuntimeException fail() {
throw new RuntimeException("fail");
}
static RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static RuntimeException fail(String msg) {
throw new RuntimeException(unnull(msg));
}
static RuntimeException fail(String msg, Object... args) {
throw new RuntimeException(format(msg, args));
}
static List concatLists(List ... lists) {
List l = new ArrayList ();
for (List list : lists)
if (list != null)
l.addAll(list);
return l;
}
static List concatLists(Collection> lists) {
List l = new ArrayList ();
for (List list : lists)
if (list != null)
l.addAll(list);
return l;
}
static void runMain(Object c, String... args) {
callMain(c, args);
}
static String getClassName(Object o) {
return o == null ? "null" : o.getClass().getName();
}
static JFrame getFrame(Object 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 JTable dataToTable(Object data) {
return dataToTable(showTable(), data);
}
static JTable dataToTable(Object data, String title) {
return dataToTable(showTable(title), data);
}
static JTable dataToTable(JTable table, Object data) {
return dataToTable(table, data, false);
}
static JTable dataToTable(JTable table, Object data, boolean now) {
List> rows = new ArrayList>();
List cols = new ArrayList();
if (data instanceof List) {
for (Object x : (List) data) try {
rows.add(dataToTable_makeRow(x, cols));
} catch (Throwable __e) { printStackTrace(__e); }
} else if (data instanceof Map) {
Map map = (Map) ( data);
for (Object key : map.keySet()) {
Object value = map.get(key);
rows.add(litlist(structureOrText(key), structureOrText(value)));
}
} else
print("Unknown data type: " + data);
if (now)
table.setModel(fillTableWithStrings_makeModel(rows, toStringArray(cols)));
else
fillTableWithStrings(table, rows, cols);
return table;
}
static class DynamicObject {
String className;
Map fieldValues = new TreeMap();
}
static Object unstructure(String text) {
return unstructure(text, false);
}
// TODO: backrefs for hashmap{} etc
static Object unstructure(String text, final boolean allDynamic) {
if (text == null) return null;
final List tok = javaTok(text);
final boolean debug = unstructure_debug;
class X {
int i = 1;
HashMap refs = new HashMap();
Object parse() {
String t = tok.get(i);
int refID = 0;
if (t.startsWith("m") && isInteger(t.substring(1))) {
refID = parseInt(t.substring(1));
i += 2;
t = tok.get(i);
}
if (debug)
print("parse: " + quote(t));
if (t.startsWith("\"")) {
String s = unquote(tok.get(i));
i += 2;
return s;
}
if (t.startsWith("'")) {
char c = unquoteCharacter(tok.get(i));
i += 2;
return c;
}
if (t.equals("bigint"))
return parseBigInt();
if (t.equals("d"))
return parseDouble();
if (t.equals("false") || t.equals("f")) {
i += 2; return false;
}
if (t.equals("true") || t.equals("t")) {
i += 2; return true;
}
if (t.equals("-")) {
t = tok.get(i+2);
i += 4;
return isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t));
}
if (isInteger(t) || isLongConstant(t)) {
i += 2;
if (debug)
print("isLongConstant " + quote(t) + " => " + isLongConstant(t));
if (isLongConstant(t)) return parseLong(t);
long l = parseLong(t);
return l != (int) l ? new Long(l) : new Integer((int) l);
}
if (t.equals("File")) {
File f = new File(unquote(tok.get(i+2)));
i += 4;
return f;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
i += 2;
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
print("Warning: unsatisfied back reference " + ref);
return o;
}
return parse_inner(refID);
}
// everything that can be backreferenced
Object parse_inner(int refID) {
String t = tok.get(i);
if (debug)
print("parse_inner: " + quote(t));
if (t.equals("hashset"))
return parseHashSet();
if (t.equals("treeset"))
return parseTreeSet();
if (t.equals("hashmap"))
return parseHashMap();
if (t.equals("{"))
return parseMap();
if (t.equals("["))
return parseList();
if (t.equals("array"))
return parseArray();
if (t.equals("class"))
return parseClass();
if (t.equals("l"))
return parseLisp();
if (t.equals("null")) {
i += 2; return null;
}
if (isJavaIdentifier(t)) {
Class c = allDynamic ? null : findClass(t);
DynamicObject dO = null;
Object o = null;
if (c != null)
o = nuObject(c);
else {
dO = new DynamicObject();
dO.className = t;
}
if (refID != 0)
refs.put(refID, o);
i += 2;
if (i < tok.size() && tok.get(i).equals("(")) {
consume("(");
while (!tok.get(i).equals(")")) {
// It's like parsing a map.
//Object key = parse();
//if (tok.get(i).equals(")"))
// key = onlyField();
String key = unquote(tok.get(i));
i += 2;
consume("=");
Object value = parse();
if (o != null)
setOpt(o, key, value);
else
dO.fieldValues.put(key, value);
if (tok.get(i).equals(",")) i += 2;
}
consume(")");
}
return o != null ? o : dO;
}
throw new RuntimeException("Unknown token " + (i+1) + ": " + t);
}
Object parseSet(Set set) {
set.addAll((List) parseList());
return set;
}
Object parseLisp() {
consume("l");
consume("(");
List list = new ArrayList();
while (!tok.get(i).equals(")")) {
list.add(parse());
if (tok.get(i).equals(",")) i += 2;
}
consume(")");
return newObject("main$Lisp", (String) list.get(0), subList(list, 1));
}
Object parseList() {
consume("[");
List list = new ArrayList();
while (!tok.get(i).equals("]")) {
list.add(parse());
if (tok.get(i).equals(",")) i += 2;
}
consume("]");
return list;
}
Object parseArray() {
consume("array");
consume("{");
List list = new ArrayList();
while (!tok.get(i).equals("}")) {
list.add(parse());
if (tok.get(i).equals(",")) i += 2;
}
consume("}");
return list.toArray();
}
Object parseClass() {
consume("class");
consume("(");
String name = tok.get(i);
i += 2;
consume(")");
Class c = allDynamic ? null : findClass(name);
if (c != null) return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
dO.fieldValues.put("name", name);
return dO;
}
Object parseBigInt() {
consume("bigint");
consume("(");
String val = tok.get(i);
i += 2;
if (eq(val, "-")) {
val = "-" + tok.get(i);
i += 2;
}
consume(")");
return new BigInteger(val);
}
Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tok.get(i));
i += 2;
consume(")");
return Double.parseDouble(val);
}
Object parseHashMap() {
consume("hashmap");
return parseMap(new HashMap());
}
Object parseHashSet() {
consume("hashset");
return parseSet(new HashSet());
}
Object parseTreeSet() {
consume("treeset");
return parseSet(new TreeSet());
}
Object parseMap() {
return parseMap(new TreeMap());
}
Object parseMap(Map map) {
consume("{");
while (!tok.get(i).equals("}")) {
Object key = parse();
consume("=");
Object value = parse();
map.put(key, value);
if (tok.get(i).equals(",")) i += 2;
}
consume("}");
return map;
}
void consume(String s) {
if (!tok.get(i).equals(s)) {
String prevToken = i-2 >= 0 ? tok.get(i-2) : "";
String nextTokens = join(tok.subList(i, Math.min(i+4, tok.size())));
throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");
}
i += 2;
}
}
return new X().parse();
}
static boolean unstructure_debug;
static ClassLoader myClassLoader() {
return mc().getClassLoader();
}
static void logQuoted(String logFile, String line) {
logQuoted(getProgramFile(logFile), line);
}
static void logQuoted(File logFile, String line) {
appendToFile(logFile, quote(line) + "\n");
}
static boolean endsWithOneOf(String s, String... suffixes) {
for (String x : suffixes) if (s.endsWith(x)) return true;
return false;
}
static String _userHome;
static String userHome() {
if (_userHome == null) {
if (isAndroid())
_userHome = "/storage/sdcard0/";
else
_userHome = System.getProperty("user.home");
//System.out.println("userHome: " + _userHome);
}
return _userHome;
}
static File userHome(String path) {
return new File(userDir(), path);
}
static ImageIcon imageIcon(String imageID) { try {
return new ImageIcon(loadLibrary(imageID).toURI().toURL());
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static List toLines(File f) {
return toLines(loadTextFile(f));
}
public static List toLines(String s) {
List lines = new ArrayList();
if (s == null) return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start) lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
private static int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
// compile JavaX source, load classes & return main class
// src can be a snippet ID or actual source code
// TODO: record injection?
static Class> hotwire(String src) {
try {
Class j = getJavaX();
synchronized(j) { // hopefully this goes well...
List libraries = new ArrayList();
File srcDir = (File) call(j, "transpileMain", src, libraries);
if (srcDir == null)
throw fail("transpileMain returned null (src=" + quote(src) + ")");
Object androidContext = get(j, "androidContext");
if (androidContext != null)
return (Class) call(j, "loadx2android", srcDir, src);
File classesDir = (File) call(j, "TempDirMaker_make");
String javacOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir);
System.out.println(javacOutput);
URL[] urls = new URL[libraries.size()+1];
urls[0] = classesDir.toURI().toURL();
for (int i = 0; i < libraries.size(); i++)
urls[i+1] = libraries.get(i).toURI().toURL();
// make class loader
URLClassLoader classLoader = new URLClassLoader(urls);
// load & return main class
Class> theClass = classLoader.loadClass("main");
callOpt(j, "registerSourceCode", theClass, loadTextFile(new File(srcDir, "main.java")));
call(j, "setVars", theClass, isSnippetID(src) ? src: null);
if (isSnippetID(src))
callOpt(j, "addInstance", src, theClass);
if (!_inCore())
hotwire_copyOver(theClass);
return theClass;
}
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
public static String unquote(String s) {
if (s.startsWith("[")) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i+1, s.length()-i-1);
}
}
if (s.startsWith("\"") /*&& s.endsWith("\"")*/ && s.length() > 1) {
String st = s.substring(1, s.endsWith("\"") ? s.length()-1 : s.length());
StringBuilder sb = new StringBuilder(st.length());
for (int i = 0; i < st.length(); i++) {
char ch = st.charAt(i);
if (ch == '\\') {
char nextChar = (i == st.length() - 1) ? '\\' : st
.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
&& st.charAt(i + 1) <= '7') {
code += st.charAt(i + 1);
i++;
if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
&& st.charAt(i + 1) <= '7') {
code += st.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
// Hex Unicode: u????
case 'u':
if (i >= st.length() - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + st.charAt(i + 2) + st.charAt(i + 3)
+ st.charAt(i + 4) + st.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar; // added by Stefan
}
i++;
}
sb.append(ch);
}
return sb.toString();
} else
return s; // return original
}
static List findDownloadDirectories() {
List dirs = loadListFromFile("#1003186", "userDownloadDirectories");
return existingDirectoriesOnly(concatLists(
stringsToFiles(dirs),
litlist(new File(userHome(), "Downloads"))
));
}
static File getProgramFile(String progID, String fileName) {
return new File(getProgramDir(progID), fileName);
}
static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
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_findField(Class> c, String field) {
for (Field f : c.getDeclaredFields())
if (f.getName().equals(field))
return f;
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static Field set_findStaticField(Class> c, String field) {
for (Field f : c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static int l(Object[] array) {
return array == null ? 0 : array.length;
}
static int l(byte[] array) {
return array == null ? 0 : array.length;
}
static int l(int[] array) {
return array == null ? 0 : array.length;
}
static int l(char[] array) {
return array == null ? 0 : array.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(String s) {
return s == null ? 0 : s.length();
}
static String structure(Object o) {
HashSet refd = new HashSet();
return structure_2(structure_1(o, 0, new IdentityHashMap(), refd), refd);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static String structure_1(Object o, int stringSizeLimit, IdentityHashMap seen, HashSet refd) {
if (o == null) return "null";
// these are never back-referenced (for readability)
if (o instanceof String)
return quote(stringSizeLimit != 0 ? shorten((String) o, stringSizeLimit) : (String) o);
if (o instanceof BigInteger)
return "bigint(" + o + ")";
if (o instanceof Double)
return "d(" + quote(str(o)) + ")";
if (o instanceof Long)
return o + "L";
if (o instanceof Integer)
return str(o);
if (o instanceof Boolean)
return ((Boolean) o).booleanValue() ? "t" : "f";
if (o instanceof Character)
return quoteCharacter((Character) o);
if (o instanceof File)
return "File " + quote(((File) o).getPath());
// referencable objects follow
Integer ref = seen.get(o);
if (ref != null) {
refd.add(ref);
return "r" + ref;
}
ref = seen.size()+1;
seen.put(o, ref);
String r = "m" + ref + " "; // marker
String name = o.getClass().getName();
StringBuilder buf = new StringBuilder();
if (o instanceof HashSet)
return r + "hashset " + structure_1(new ArrayList((Set) o), stringSizeLimit, seen, refd);
if (o instanceof TreeSet)
return r + "treeset " + structure_1(new ArrayList((Set) o), stringSizeLimit, seen, refd);
if (o instanceof Collection) {
for (Object x : (Collection) o) {
if (buf.length() != 0) buf.append(", ");
buf.append(structure_1(x, stringSizeLimit, seen, refd));
}
return r + "[" + buf + "]";
}
if (o instanceof Map) {
for (Object e : ((Map) o).entrySet()) {
if (buf.length() != 0) buf.append(", ");
buf.append(structure_1(((Map.Entry) e).getKey(), stringSizeLimit, seen, refd));
buf.append("=");
buf.append(structure_1(((Map.Entry) e).getValue(), stringSizeLimit, seen, refd));
}
return r + (o instanceof HashMap ? "hashmap" : "") + "{" + buf + "}";
}
if (o.getClass().isArray()) {
int n = Array.getLength(o);
for (int i = 0; i < n; i++) {
if (buf.length() != 0) buf.append(", ");
buf.append(structure_1(Array.get(o, i), stringSizeLimit, seen, refd));
}
return r + "array{" + buf + "}";
}
if (o instanceof Class)
return r + "class(" + quote(((Class) o).getName()) + ")";
if (o instanceof Throwable)
return r + "exception(" + quote(((Throwable) o).getMessage()) + ")";
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
if (buf.length() != 0) buf.append(", ");
buf.append(i);
}
return "bitset{" + buf + "}";
}
// Need more cases? This should cover all library classes...
if (name.startsWith("java.") || name.startsWith("javax."))
return r + String.valueOf(o);
String shortName = o.getClass().getName().replaceAll("^main\\$", "");
if (shortName.equals("Lisp")) {
buf.append("l(" + structure_1(getOpt(o, "head"), stringSizeLimit, seen, refd));
List args = (List) ( getOpt(o, "args"));
if (nempty(args))
for (int i = 0; i < l(args); i++) {
buf.append(", ");
Object arg = args.get(i);
// sweet shortening
if (arg != null && eq(arg.getClass().getName(), "main$Lisp") && isTrue(call(arg, "isEmpty")))
arg = get(arg, "head");
buf.append(structure_1(arg, stringSizeLimit, seen, refd));
}
buf.append(")");
return r + str(buf);
}
int numFields = 0;
String fieldName = "";
if (shortName.equals("DynamicObject")) {
shortName = (String) get(o, "className");
Map fieldValues = (Map) get(o, "fieldValues");
for (String _fieldName : fieldValues.keySet()) {
fieldName = _fieldName;
Object value = fieldValues.get(fieldName);
if (value != null) {
if (buf.length() != 0) buf.append(", ");
buf.append(fieldName + "=" + structure_1(value, stringSizeLimit, seen, refd));
}
++numFields;
}
} else {
// regular class
Class c = o.getClass();
while (c != Object.class) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
fieldName = field.getName();
// skip outer object reference
if (fieldName.indexOf("$") >= 0) continue;
Object value;
try {
field.setAccessible(true);
value = field.get(o);
} catch (Exception e) {
value = "?";
}
// put special cases here...
if (value != null) {
if (buf.length() != 0) buf.append(", ");
buf.append(fieldName + "=" + structure_1(value, stringSizeLimit, seen, refd));
}
++numFields;
}
c = c.getSuperclass();
}
}
String b = buf.toString();
if (numFields == 1 && structure_allowShortening)
b = b.replaceAll("^" + fieldName + "=", ""); // drop field name if only one
String s = shortName;
if (buf.length() != 0)
s += "(" + b + ")";
return r + s;
}
// drop unused markers
static String structure_2(String s, HashSet refd) {
List tok = javaTok(s);
StringBuilder out = new StringBuilder();
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
if (t.startsWith("m") && isInteger(t.substring(1))
&& !refd.contains(parseInt(t.substring(1))))
continue;
out.append(t).append(tok.get(i+1));
}
return str(out);
}
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 List filter(List l, Object pred) {
List x = new ArrayList();
for (Object o : l)
if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
static synchronized void autoVMExit() {
AutoVMExit.install();
}
static class AutoVMExit extends TimerTask {
static boolean installed;
static boolean disabled;
int lastObjectCount = -1;
static java.util.Timer timer;
static int firstDelay = 30000;
static int delay = 5000;
public static void install() {
if (!installed) {
installed = true;
if (!disabled) {
timer = new java.util.Timer("AutoVMExit");
timer.scheduleAtFixedRate(new AutoVMExit(), firstDelay, delay);
}
}
}
/** Looks for objects that give us a reason to keep the VM alive.
* Right now we count windows and tray icons. */
public void run() {
int objectCount = 0;
// Scan for windows
Window[] windowList = Window.getWindows();
for (Window window : windowList) {
if (window.isVisible())
++objectCount;
}
// Scan for tray icons
try {
objectCount += SystemTray.getSystemTray().getTrayIcons().length;
} catch (Throwable e) {
// ignore
}
//System.out.println("Windows: " + objectCount);
if (objectCount == 0 && lastObjectCount == 0) {
System.out.println("AutoVMExit: No windows open or tray icons installed - exiting");
System.exit(0);
}
lastObjectCount = objectCount;
}
public static void disable() {
disabled = true;
if (timer != null)
timer.cancel();
}
public static int getFirstDelay() {
return firstDelay;
}
public static void setFirstDelay(int firstDelay) {
AutoVMExit.firstDelay = firstDelay;
}
public static int getDelay() {
return delay;
}
public static void setDelay(int delay) {
AutoVMExit.delay = delay;
}
}
static String getProgramName_cache;
static synchronized String getProgramName() {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitle(getProgramID());
return getProgramName_cache;
}
// action can be Runnable or a function name
static JButton newButton(String text, final Object action) {
JButton btn = new JButton(text);
btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) {
callFunction(action);
}});
return btn;
}
// c = Component or something implementing swing()
static Component wrap(Object swingable) {
Component c = (Component) ( swingable instanceof Component ? swingable : call(swingable, "swing"));
if (c instanceof JTable || c instanceof JList || c instanceof JTextArea)
return new JScrollPane(c);
return c;
}
static void onTitleRightClick(final JFrame frame, final Runnable r) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
if (!isSubstanceLAF())
print("Can't add title right click!");
else {
JComponent titleBar = getTitlePaneComponent(frame);
titleBar.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
if (evt.getButton() != MouseEvent.BUTTON1)
r.run();
}
});
}
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
});
}
static List existingDirectoriesOnly(File... dirs) {
return existingDirectoriesOnly(asList(dirs));
}
static List existingDirectoriesOnly(List dirs) {
List l = new ArrayList();
if (dirs != null)
for (File dir : dirs)
if (dir.isDirectory())
l.add(dir);
return l;
}
static Object callFunction(Object f, Object... args) {
if (f == null) return null;
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
} else if (f instanceof String)
return call(mc(), (String) f, args);
else
return call(f, "get", args);
//else throw fail("Can't call a " + getClassName(f));
}
static String quote(String s) {
if (s == null) return "null";
return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\"";
}
static String quote(long l) {
return quote("" + l);
}
static String quote(char c) {
return quote("" + c);
}
static String shorten(String s, int max) {
if (s == null) return "";
return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}
static List loadListFromFile(String progID, String fileName) {
return unnull((List) loadStructureFromFile(getProgramFile(progID, fileName)));
}
static String quoteCharacter(char c) {
if (c == '\'') return "'\\''";
if (c == '\\') return "'\\\\'";
return "'" + c + "'";
}
public static String join(String glue, Iterable strings) {
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String[] strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(Iterable strings) {
return join("", strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static boolean isSubstanceLAF() {
return substanceLookAndFeelEnabled();
}
// currently finds only inner classes of class "main"
// returns null on not found
// this is the simple version that is not case-tolerant
static Class findClass(String name) {
try {
return Class.forName("main$" + name);
} catch (ClassNotFoundException e) {
return null;
}
}
static JTable showTable(Object data, String title) {
return dataToTable(data, title);
}
static JTable showTable() {
return showTable(new ArrayList>(), new ArrayList());
}
static JTable showTable(String title) {
return showTable(new ArrayList>(), new ArrayList(), title);
}
static JTable showTable(List> rows, List cols) {
return showTable(rows, cols, autoFrameTitle());
}
static JTable showTable(List> rows, List cols, String title) {
JFrame frame = new JFrame(title);
frame.setBounds(10, 10, 500, 400);
centerFrame(frame);
JTable tbl = new JTable();
fillTableWithStrings(tbl, rows, cols);
frame.getContentPane().add(new JScrollPane(tbl));
frame.setVisible(true);
return tbl;
}
static boolean isJavaIdentifier(String s) {
if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++)
if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static void showConsole() {
JFrame frame = consoleFrame();
if (frame != null)
frame.setVisible(true);
}
static String programID;
static String getProgramID() {
return nempty(programID) ? formatSnippetID(programID) : "?";
}
// TODO: ask JavaX instead
static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static String unnull(String s) {
return s == null ? "" : s;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Object[] unnull(Object[] a) {
return a == null ? new Object[0] : a;
}
// replacement for class JavaTok
// maybe incomplete, might want to add floating point numbers
// todo also: extended multi-line strings
static List javaTok(String s) {
List tok = new ArrayList();
int l = s.length();
int i = 0;
while (i < l) {
int j = i;
char c; String cc;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j+2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l) break;
c = s.charAt(i); // cc is not needed in rest of loop body
cc = s.substring(i, Math.min(i+2, l));
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (cc.equals("[[")) {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (cc.equals("[=") && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
return tok;
}
static List javaTok(List tok) {
return javaTok(join(tok));
}
static boolean _inCore() {
return false;
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static Object newObject(Class c, Object... args) {
return nuObject(c, args);
}
static Object newObject(String className, Object... args) {
return nuObject(className, args);
}
static boolean isLongConstant(String s) {
if (!s.endsWith("L")) return false;
s = s.substring(0, l(s)-1);
return isInteger(s);
}
static Class __javax;
static Class getJavaX() {
return __javax;
}
static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static List subList(List l, int startIndex, int endIndex) {
startIndex = max(0, min(l(l), startIndex));
endIndex = max(0, min(l(l), endIndex));
if (startIndex > endIndex) return litlist();
return l.subList(startIndex, endIndex);
}
static String[] toStringArray(List list) {
return list.toArray(new String[list.size()]);
}
static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof List)
return toStringArray((List) o);
else
throw fail("Not a list or array: " + structure(o));
}
static File getProgramDir() {
return programDir();
}
static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
static String programTitle() {
return getProgramName();
}
static boolean isTrue(Object o) {
return booleanValue(o);
}
static long parseLong(String s) {
if (s == null) return 0;
return Long.parseLong(dropSuffix("L", s));
}
static long parseLong(Object s) {
return Long.parseLong((String) s);
}
static String getSnippetTitle(String id) { try {
return loadPage(new URL("http://tinybrain.de:8080/tb-int/getfield.php?id=" + parseSnippetID(id) + "&field=title"));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void hotwire_copyOver(Class c) {
synchronized(StringBuffer.class) {
Object print_log = get(getMainClass(), "print_log");
if (print_log != null)
setOpt(c, "print_log", print_log);
Object mainBot = getMainBot();
if (mainBot != null)
setOpt(c, "mainBot", mainBot);
setOpt(c, "creator_class", new WeakReference(mc()));
}
}
static void callMain(Object c, String... args) {
callOpt(c, "main", new Object[] {args});
}
static String getLookAndFeel() {
return getClassName(UIManager.getLookAndFeel());
}
static boolean isInteger(String s) {
return s != null && Pattern.matches("\\-?\\d+", s);
}
// Let's just generally synchronize this to be safe.
static synchronized void appendToFile(String path, String s) { try {
new File(path).getParentFile().mkdirs();
//print("[Logging to " + path + "]");
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path, true), "UTF-8"));
writer.write(s);
writer.close();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void appendToFile(File path, String s) {
if (path != null)
appendToFile(path.getPath(), s);
}
static Class mc() {
return getMainClass();
}
static void dataToTable_dynSet(List l, int i, String s) {
while (i >= l.size()) l.add("");
l.set(i, s);
}
static List dataToTable_makeRow(Object x, List cols) {
if (instanceOf(x, "DynamicObject"))
x = get_raw(x, "fieldValues");
if (x instanceof Map) {
Map m = (Map) ( x);
List row = new ArrayList();
for (Object _field : m.keySet()) {
String field = (String) ( _field);
Object value = m.get(field);
int col = cols.indexOf(field);
if (col < 0) {
cols.add(field);
col = cols.size()-1;
}
dataToTable_dynSet(row, col, structureOrText(value));
}
return row;
}
return litlist(structureOrText(x));
}
// extended over Class.isInstance() to handle primitive types
static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class) return arg instanceof Boolean;
if (type == int.class) return arg instanceof Integer;
if (type == long.class) return arg instanceof Long;
if (type == float.class) return arg instanceof Float;
if (type == short.class) return arg instanceof Short;
if (type == char.class) return arg instanceof Character;
if (type == byte.class) return arg instanceof Byte;
if (type == double.class) return arg instanceof Double;
return type.isInstance(arg);
}
static File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
static String format(String pat, Object... args) {
return format3(pat, args);
}
static File toFile(Object o) {
if (o instanceof File) return (File) o;
if (o instanceof String) return new File((String) o);
throw fail("Not a file: " + o);
}
static Object nuObject(String className, Object... args) { try {
return nuObject(Class.forName(className), args);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Object nuObject(Object realm, String className, Object... args) {
return nuObject(_getClass(realm, className), args);
}
static Object nuObject(Class c, Object... args) { try {
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return m.newInstance(args);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName());
}
static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static Object callOpt(Object o, String method, Object... args) {
try {
if (o == null) return null;
if (o instanceof Class) {
Method m = callOpt_findStaticMethod((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = callOpt_findMethod(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (!m.getName().equals(method)) {
if (debug) System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static double parseDouble(String s) {
return Double.parseDouble(s);
}
static Object[] asObjectArray(List l) {
return toObjectArray(l);
}
static File[] listFiles(File dir) {
File[] files = dir.listFiles();
return files == null ? new File[0] : files;
}
static String padLeft(String s, char c, int n) {
return rep(c, n-l(s)) + s;
}
public static String loadTextFile(String fileName) {
try {
return loadTextFile(fileName, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(String fileName, String defaultContents) throws IOException {
if (!new File(fileName).exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
}
public static String loadTextFile(File fileName) {
try {
return loadTextFile(fileName, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(File fileName, String defaultContents) throws IOException {
try {
return loadTextFile(fileName.getPath(), defaultContents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
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 boolean nempty(Collection c) {
return !isEmpty(c);
}
static boolean nempty(CharSequence s) {
return !isEmpty(s);
}
static boolean nempty(Object[] o) {
return !isEmpty(o);
}
static void smartSet(Field f, Object o, Object value) throws Exception {
f.setAccessible(true);
// take care of common case (long to int)
if (f.getType() == int.class && value instanceof Long)
value = ((Long) value).intValue();
f.set(o, value);
}
static void fillTableWithStrings(final JTable table, List> rows, List colNames) {
fillTableWithStrings(table, rows, toStringArray(colNames));
}
// thread-safe
static void fillTableWithStrings(final JTable table, List> rows, String... colNames) {
final DefaultTableModel model = fillTableWithStrings_makeModel(rows, colNames);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
setTableModel(table, model);
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
});
}
static DefaultTableModel fillTableWithStrings_makeModel(List> rows, String... colNames) {
Object[][] data = new Object[rows.size()][];
int w = 0;
for (int i = 0; i < rows.size(); i++) {
List l = rows.get(i);
Object[] r = new Object[l.size()];
for (int j = 0; j < l.size(); j++)
r[j] = l.get(j);
data[i] = r;
w = Math.max(w, l.size());
}
Object[] columnNames = new Object[w];
for (int i = 0; i < w; i++)
columnNames[i] = i < l(colNames) ? colNames[i] : "?";
return new DefaultTableModel(data, columnNames);
}
static char unquoteCharacter(String s) {
assertTrue(s.startsWith("'") && s.length() > 1);
return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length()-1 : s.length()) + "\"").charAt(0);
}
static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
static String structureOrText(Object o) {
return o instanceof String ? (String) o : structure(o);
}
static void setOpt(Object o, String field, Object value) {
if (o instanceof Class) setOpt((Class) o, field, value);
else try {
Field f = setOpt_findField(o.getClass(), field);
if (f != null)
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void setOpt(Class c, String field, Object value) {
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_findField(Class> c, String field) {
for (Field f : c.getDeclaredFields())
if (f.getName().equals(field))
return f;
return null;
}
static Field setOpt_findStaticField(Class> c, String field) {
for (Field f : c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
return null;
}
static List stringsToFiles(List l) {
List x = new ArrayList();
for (String s : l)
x.add(new File(s));
return x;
}
static Object getOpt(Object o, String field) {
if (o instanceof String) o = getBot ((String) o);
if (o == null) return null;
if (o instanceof Class) return getOpt((Class) o, field);
if (o.getClass().getName().equals("main$DynamicObject"))
return call(getOpt_raw(o, "fieldValues"), "get", field);
if (o instanceof Map) return ((Map) o).get(field);
return getOpt_raw(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 {
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static File userDir() {
return new File(userHome());
}
static File userDir(String path) {
return new File(userHome(), path);
}
static boolean isAndroid() { return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0; }
static Map litmap(Object... x) {
TreeMap map = new TreeMap();
litmap_impl(map, x);
return map;
}
static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length-1; i += 2)
if (x[i+1] != null)
map.put(x[i], x[i+1]);
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(List a, List b) {
if (a == null || l(b) > l(a)) return false;
for (int i = 0; i < l(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static 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(Collection s) {
return s == null ? new ArrayList()
: s instanceof ArrayList ? (ArrayList) s : new ArrayList(s);
}
static Object loadStructureFromFile(File f) {
return unstructure(loadTextFile(f));
}
static Object getBot(String botID) {
return callOpt(getMainBot(), "getBot", botID);
}
static File loadBinarySnippet(String snippetID) { try {
long id = parseSnippetID(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (f == null) {
byte[] data = loadDataSnippetImpl(snippetID);
DiskSnippetCache_putLibrary(id, data);
f = DiskSnippetCache_getLibrary(id);
}
return f;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static JComponent getTitlePaneComponent(Window window) {
if (!substanceLookAndFeelEnabled()) return null;
JRootPane rootPane = null;
if (window instanceof JFrame) {
JFrame f = (JFrame) window;
rootPane = f.getRootPane();
}
if (window instanceof JDialog) {
JDialog d = (JDialog) window;
rootPane = d.getRootPane();
}
if (rootPane != null) {
Object /*SubstanceRootPaneUI*/ ui = rootPane.getUI();
return (JComponent) call(ui, "getTitlePane");
}
return null;
}
static void setTableModel(JTable table, TableModel model) {
int i = table.getSelectedRow();
table.setModel(model);
if (i >= 0 && i < model.getRowCount())
table.setRowSelectionInterval(i, i);
}
static Object mainBot;
static Object getMainBot() {
return mainBot;
}
static void centerFrame(JFrame frame) {
frame.setLocationRelativeTo(null); // magic trick
}
static int min(int a, int 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 byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static void assertTrue(Object o) {
assertEquals(true, o);
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static String autoFrameTitle() {
return "? - " + formatSnippetID(getProgramID());
}
static Class getMainClass() { try {
return Class.forName("main");
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Class getMainClass(Object o) { try {
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static int max(int a, int b) {
return Math.max(a, b);
}
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 int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static ThreadLocal loadPage_charset = new ThreadLocal();
static boolean loadPage_allowGzip = true, loadPage_debug;
public static String loadPageSilently(String url) {
try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPageSilently(URL url) {
try {
IOException e = null;
for (int tries = 0; tries < 60; tries++)
try {
URLConnection con = url.openConnection();
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
print("Retrying because of: " + e);
sleepSeconds(1);
}
throw e;
} catch (IOException e) { throw new RuntimeException(e); }
}
static String loadPage_preprocess(String url) {
if (url.startsWith("tb/"))
url = "tinybrain.de:8080/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
public static String loadPage(String url) {
try {
return loadPage(new URL(loadPage_preprocess(url)));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPage(URL url) {
print("Loading: " + url.toExternalForm());
return loadPageSilently(url);
}
public static String loadPage(URLConnection con, URL url) throws IOException {
String computerID = getComputerID();
try {
if (computerID != null)
con.setRequestProperty("X-ComputerID", computerID);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
} catch (Throwable e) {} // fails if within doPost
String contentType = con.getContentType();
if (contentType == null)
throw new IOException("Page could not be read: " + url);
//print("Content-Type: " + contentType);
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null) charset = loadPage_guessCharset(contentType);
InputStream in = con.getInputStream();
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = new GZIPInputStream(in);
}
Reader r = new InputStreamReader(in, charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
//Log.info("Chars read: " + buf.length());
buf.append((char) ch);
}
return buf.toString();
}
static String loadPage_guessCharset(String contentType) {
Pattern p = Pattern.compile("text/[a-z]+;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(contentType);
/* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
return m.matches() ? m.group(1) : "ISO-8859-1";
}
static String format3(String pat, Object... args) {
if (args.length == 0) return pat;
List tok = javaTokPlusPeriod(pat);
int argidx = 0;
for (int i = 1; i < tok.size(); i += 2)
if (tok.get(i).equals("*"))
tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null"));
return join(tok);
}
static String format3_formatArg(Object arg) {
if (arg == null) return "null";
if (arg instanceof String) {
String s = (String) arg;
return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s);
}
if (arg instanceof Integer || arg instanceof Long) return String.valueOf(arg);
return quote(structure(arg));
}
static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class _getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) { try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static boolean instanceOf(Object o, String className) {
if (o == null) return false;
String c = o.getClass().getName();
return eq(c, className) || eq(c, "main$" + className);
}
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) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
return false;
}
static File programDir() {
return programDir(getProgramID());
}
static File programDir(String snippetID) {
return new File(javaxDataDir(), formatSnippetID(snippetID));
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static String rep(int n, char c) {
return repeat(c, n);
}
static String rep(char c, int n) {
return repeat(c, n);
}
static List rep(A a, int n) {
return repeat(a, n);
}
static boolean booleanValue(Object o) {
return eq(true, o);
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0) throw fail("0 is not a snippet ID");
return id;
}
static Object[] toObjectArray(List list) {
return list.toArray(new Object[list.size()]);
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
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 shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
static String getComputerID() { try {
return computerID();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
// Data files are immutable, use centralized cache
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = new File(getGlobalCache(), "data_" + snippetID + ".jar");
return file.exists() ? file : null;
}
public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data);
}
static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
+ parseSnippetID(snippetID) + "&contentType=application/binary");
System.err.println("Loading library: " + url);
try {
data = loadBinaryPage(url.openConnection());
} catch (IOException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL("http://data.tinybrain.de/blobs/"
+ parseSnippetID(snippetID));
System.err.println("Loading library: " + url);
data = loadBinaryPage(url.openConnection());
}
System.err.println("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
static void assertEquals(Object x, Object y) {
assertEquals(null, x, y);
}
static void assertEquals(String msg, Object x, Object y) {
if (!(x == null ? y == null : x.equals(y)))
throw fail((msg != null ? msg + ": " : "") + structure(x) + " != " + structure(y));
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static Class getClass(Object realm, String name) { try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static boolean isNonNegativeInteger(String s) {
return s != null && Pattern.matches("\\d+", s);
}
static String classNameToVM(String name) {
return name.replace(".", "$");
}
// This is made for NL parsing.
// It's javaTok extended with "..." token, "$n" and "#n" and
// special quotes (which are converted to normal ones).
static List javaTokPlusPeriod(String s) {
List tok = new ArrayList();
int l = s.length();
int i = 0;
while (i < l) {
int j = i;
char c; String cc;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j+2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l) break;
c = s.charAt(i);
cc = s.substring(i, Math.min(i+2, l));
// scan for non-whitespace
if (c == '\u201C' || c == '\u201D') c = '"'; // normalize quotes
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
char _c = s.charAt(j);
if (_c == '\u201C' || _c == '\u201D') _c = '"'; // normalize quotes
if (_c == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
if (j-1 >= i+1) {
tok.add(opener + s.substring(i+1, j-1) + opener);
i = j;
continue;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for things like "this one's"
else if (Character.isDigit(c))
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else if (cc.equals("[[")) {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (cc.equals("[=") && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else if (s.substring(j, Math.min(j+3, l)).equals("..."))
j += 3;
else if (c == '$' || c == '#')
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
return tok;
}
static void sleepSeconds(long s) {
if (s > 0) sleep(s*1000);
}
static File javaxDataDir_dir; // can be set to work on different base dir
static File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static String repeat(char c, int n) {
n = max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++)
chars[i] = c;
return new String(chars);
}
static List repeat(A a, int n) {
List l = new ArrayList ();
for (int i = 0; i < n; i++)
l.add(a);
return l;
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (Exception e) { throw new RuntimeException(e); }
}
static void sleep() { try {
print("Sleeping.");
synchronized(main.class) { main.class.wait(); }
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static File getGlobalCache() {
File file = new File(userHome(), ".tinybrain/snippet-cache");
file.mkdirs();
return file;
}
static String _computerID;
public static String computerID() { try {
if (_computerID == null) {
File file = new File(userHome(), ".tinybrain/computer-id");
_computerID = loadTextFile(file.getPath(), null);
if (_computerID == null) {
_computerID = makeRandomID(12);
saveTextFile(file.getPath(), _computerID);
}
}
return _computerID;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
/** writes safely (to temp file, then rename) */
public static void saveBinaryFile(String fileName, byte[] contents) throws IOException {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
fileOutputStream.write(contents);
fileOutputStream.close();
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
}
static void saveBinaryFile(File fileName, byte[] contents) {
try {
saveBinaryFile(fileName.getPath(), contents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static byte[] loadBinaryPage(String url) throws IOException {
return loadBinaryPage(new URL(url).openConnection());
}
public static byte[] loadBinaryPage(URLConnection con) throws IOException {
//setHeaders(con);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
InputStream inputStream = con.getInputStream();
int n = 0;
while (true) {
int ch = inputStream.read();
if (ch < 0)
break;
buf.write(ch);
if (++n % 100000 == 0)
System.err.println(" " + n + " bytes loaded.");
}
inputStream.close();
return buf.toByteArray();
}
/** writes safely (to temp file, then rename) */
public static void saveTextFile(String fileName, String contents) throws IOException {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
if (contents != null) {
FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
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 (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
}
public static void saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
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 void printStackTrace(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static JWindow showLoadingAnimation() {
return showAnimationInTopRightCorner("#1003543", "Hold on user...");
}
static void disposeWindow(final Window window) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
window.dispose();
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
});
}
// automatically switches to AWT thread for you
// text is optional text below image
static JWindow showAnimationInTopRightCorner(final String imageID, final String text) {
return (JWindow) swingAndWait(new Object() { Object get() {
JLabel label = new JLabel(imageIcon(imageID));
if (nempty(text)) {
label.setText(text);
label.setVerticalTextPosition(SwingConstants.BOTTOM);
label.setHorizontalTextPosition(SwingConstants.CENTER);
}
return showInTopRightCorner(label);
}});
}
static JWindow showAnimationInTopRightCorner(final String imageID) {
return showAnimationInTopRightCorner(imageID, "");
}
static String getStackTrace(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
static void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(r);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() { public void run() { try {
result.set(callF(f));
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}});
return result.get();
}
}
static int showInTopRightCorner_inset = 20;
static JWindow showInTopRightCorner(Component c) {
JWindow w = new JWindow();
w.add(c);
w.pack();
w.setLocation(getScreenSize().width-w.getWidth()-showInTopRightCorner_inset, showInTopRightCorner_inset);
w.setVisible(true);
return w;
}
static boolean isAWTThread() {
return SwingUtilities.isEventDispatchThread();
}
static Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
static class Var {
A v;
Var() {}
Var(A v) {
this.v = v;}
synchronized void set(A a) { v = a; }
synchronized A get() { return v; }
}
}