tok) {
List l = new ArrayList();
for (int i = 0; i < l(tok); i++) {
String t = tok.get(i);
if (odd(i) && eq(t, "{")) {
int j = findEndOfCurlyBracketPart(tok, i);
l.add(joinSubList(tok, i, j));
i = j-1;
} else
l.add(t);
}
return l;
}
static boolean startsWithAndEndsWith(String s, String prefix, String suffix) {
return startsWith(s, prefix) && endsWith(s, suffix);
}
static boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static boolean swic(String a, String b, Matches m) {
if (!swic(a, b)) return false;
m.m = new String[] {substring(a, l(b))};
return true;
}
static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static boolean containsNewLines(String s) {
return containsNewLine(s);
}
static String jlabel_textAsHTML_center(String text) {
return ""
+ replace(htmlencode(text), "\n", "
")
+ "
";
}
static Rectangle toRectangle(Rect r) {
return r == null ? null : r.getRectangle();
}
static Rect toRect(Rectangle r) {
return r == null ? null : new Rect(r);
}
static boolean rectContains(int x1, int y1, int w, int h, Pt p) {
return p.x >= x1 && p.y >= y1 && p.x < x1+w && p.y < y1+h;
}
static boolean rectContains(Rect a, Rect b) {
return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2();
}
static Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
static String programTitle() {
return getProgramName();
}
static JFrame setFrameIconLater(Component c, final String imageID) {
final JFrame frame = getFrame(c);
if (frame != null)
startThread("Loading Icon", new Runnable() { public void run() { try {
final Image i = imageIcon(or2(imageID, "#1005557")).getImage();
swingLater(new Runnable() { public void run() { try {
frame.setIconImage(i);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setIconImage(i);"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n swingL..."; }});
return frame;
}
static void _initFrame(JFrame f) {
myFrames_list.put(f, Boolean.TRUE);
standardTitlePopupMenu(f);
}
static Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400);
static Rectangle defaultNewFrameBounds() {
return swing(new F0() { Rectangle get() { try {
defaultNewFrameBounds_r.translate(60, 20);
if (!screenRectangle().contains(defaultNewFrameBounds_r))
defaultNewFrameBounds_r.setLocation(30+random(30), 20+random(20));
return new Rectangle(defaultNewFrameBounds_r);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "defaultNewFrameBounds_r.translate(60, 20);\r\n if (!screenRectangle().contai..."; }});
}
static void hideConsole() {
final JFrame frame = consoleFrame();
if (frame != null) {
autoVMExit();
swingLater(new Runnable() { public void run() { try {
frame.setVisible(false);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setVisible(false);"; }});
}
}
static void scanForComponents(final Component c, final Class theClass, final List l) {
if (theClass.isInstance(c))
l.add((A) c);
if (c instanceof Container) { swing(new Runnable() { public void run() { try {
for (Component comp : ((Container) c).getComponents())
scanForComponents(comp, theClass, l);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "for (Component comp : ((Container) c).getComponents())\r\n scanForComponen..."; }}); }
}
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 ArrayList cloneListSynchronizingOn(Collection l, Object mutex) {
if (l == null) return new ArrayList();
synchronized(mutex) {
return new ArrayList(l);
}
}
static List dropFirstAndLast(int n, List l) {
return new ArrayList(subList(l, n, l(l)-n));
}
static List dropFirstAndLast(List l) {
return dropFirstAndLast(1, l);
}
static String dropFirstAndLast(String s) {
return substring(s, 1, l(s)-1);
}
static String javaTok_substringN(String s, int i, int j) {
if (i == j) return "";
if (j == i+1 && s.charAt(i) == ' ') return " ";
return s.substring(i, j);
}
static String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
static List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
++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 (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && 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;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j-i
&& s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static boolean odd(int i) {
return (i & 1) != 0;
}
static boolean odd(long i) {
return (i & 1) != 0;
}
static boolean odd(BigInteger i) { return odd(toInt(i)); }
// i must point at the (possibly imaginary) opening bracket
// index returned is index of closing bracket + 1
static int findEndOfCurlyBracketPart(List cnc, int i) {
int j = i+2, level = 1;
while (j < cnc.size()) {
if (eq(cnc.get(j), "{")) ++level;
else if (eq(cnc.get(j), "}")) --level;
if (level == 0)
return j+1;
++j;
}
return cnc.size();
}
static String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
static String joinSubList(List l, int i) {
return join(subList(l, i));
}
static boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la-lb, b, 0, lb);
}
static boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b)) return false;
m.m = new String[] { substring(a, 0, l(a)-l(b)) };
return true;
}
static boolean containsNewLine(String s) {
return contains(s, '\n'); // screw \r, nobody needs it
}
static List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++)
if (eq(l.get(i), a))
l.set(i, b);
return l;
}
static String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
static String htmlencode(Object o) {
return htmlencode(str(o));
}
static String htmlencode(String s) {
if (s == null) return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
/*if (c >= 0x100)
out.append("").append(charToHex(c)).append(';');
else*/ if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&')
out.append("").append((int) c).append(';');
else
out.append(c);
}
return out.toString();
}
static String getProgramName_cache;
static String getProgramName() {
Lock __830 = downloadLock(); lock(__830); try {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitleOpt(programID());
return getProgramName_cache;
} finally { unlock(__830); } }
static void _onLoad_getProgramName() {
startThread(new Runnable() { public void run() { try { getProgramName();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getProgramName();"; }});
}
static int imageIcon_cacheSize = 10;
static boolean imageIcon_verbose;
static Map imageIcon_cache;
static Lock imageIcon_lock = lock();
static ThreadLocal imageIcon_fixGIF = new ThreadLocal();
// not going through BufferedImage preserves animations
static ImageIcon imageIcon(String imageID) { try {
if (imageID == null) return null;
Lock __119 = imageIcon_lock; lock(__119); try {
if (imageIcon_cache == null)
imageIcon_cache = new MRUCache(imageIcon_cacheSize);
imageID = fsI(imageID);
ImageIcon ii = imageIcon_cache.get(imageID);
if (ii == null) {
if (imageIcon_verbose) print("Loading image icon: " + imageID);
File f = loadBinarySnippet(imageID);
Boolean b = imageIcon_fixGIF.get();
if (!isFalse(b))
ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
else
ii = new ImageIcon(f.toURI().toURL());
} else
imageIcon_cache.remove(imageID); // move to front of cache on access
imageIcon_cache.put(imageID, ii);
return ii;
} finally { unlock(__119); } } catch (Exception __e) { throw rethrow(__e); } }
static ImageIcon imageIcon(Image img) {
return new ImageIcon(img);
}
static void swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
timer.setRepeats(false);
timer.start();
}
static void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
static void standardTitlePopupMenu(final JFrame frame) {
// standard right-click behavior on titles
if (isSubstanceLAF())
titlePopupMenu(frame,
new VF1() { public void get(JPopupMenu menu) { try {
boolean alwaysOnTop = frame.isAlwaysOnTop();
menu.add(jmenuItem("Restart Program", "restart"));
menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram"));
menu.add(jmenuItem("Show Console", "showConsole"));
menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() { public void run() { try {
toggleAlwaysOnTop(frame) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "toggleAlwaysOnTop(frame)"; }}));
menu.add(jMenuItem("Shoot Window", new Runnable() { public void run() { try { shootWindowGUI_external(frame, 500) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "shootWindowGUI_external(frame, 500)"; }}));
//addMenuItem(menu, "Bigger fonts", f swingBiggerFonts);
//addMenuItem(menu, "Smaller fonts", f swingSmallerFonts);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n menu.add(jmenuItem(\"Restar..."; }});
}
static Rectangle screenRectangle() {
return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
}
static Random random_random = new Random();
static int random(int n) {
return n <= 0 ? 0 : random_random.nextInt(n);
}
static double random(double max) {
return random()*max;
}
static double random() {
return random_random.nextInt(100001)/100000.0;
}
static double random(double min, double max) {
return min+random()*(max-min);
}
// min <= value < max
static int random(int min, int max) {
return min+random(max-min);
}
static A random(List l) {
return oneOf(l);
}
static A random(Collection c) {
if (c instanceof List) return random((List) c);
int i = random(l(c));
return collectionGet(c, i);
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static void autoVMExit() {
call(getJavaX(), "autoVMExit");
}
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 void restart() {
Object j = getJavaX();
call(j, "cleanRestart", get(j, "fullArgs"));
}
static void duplicateThisProgram() {
nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs"))));
}
static void showConsole() {
callOpt(get(javax(), "console"), "showConsole");
}
static int toInt(Object o) {
if (o == null) return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt((String) o);
throw fail("woot not int: " + getClassName(o));
}
static int toInt(long l) {
if (l != (int) l) throw fail("Too large for int: " + l);
return (int) l;
}
static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
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 contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static Lock downloadLock_lock = fairLock();
static Lock downloadLock() {
return downloadLock_lock;
}
static String getSnippetTitleOpt(String s) {
return isSnippetID(s) ? getSnippetTitle(s) : s;
}
static String fsI(String id) {
return formatSnippetID(id);
}
static String fsI(long id) {
return formatSnippetID(id);
}
static File loadBinarySnippet(String snippetID) { try {
long id = parseSnippetID(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile(snippetID);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static boolean loadBufferedImageFixingGIFs_debug;
static ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal();
static Image loadBufferedImageFixingGIFs(File file) { try {
if (!file.exists()) return null;
// Load anything but GIF the normal way
if (!isGIF(file))
return ImageIO.read(file);
if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": checking gif");
// Get GIF reader
ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
// Give it the stream to decode from
reader.setInput(ImageIO.createImageInputStream(file));
int numImages = reader.getNumImages(true);
// Get 'metaFormatName'. Need first frame for that.
IIOMetadata imageMetaData = reader.getImageMetadata(0);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
// Find out if GIF is bugged
boolean foundBug = false;
for (int i = 0; i < numImages && !foundBug; i++) {
// Get metadata
IIOMetadataNode root = (IIOMetadataNode)reader.getImageMetadata(i).getAsTree(metaFormatName);
// Find GraphicControlExtension node
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
// Get delay value
String delay = ((IIOMetadataNode)node).getAttribute("delayTime");
// Check if delay is bugged
if (Integer.parseInt(delay) == 0) {
foundBug = true;
}
break;
}
}
}
if (loadBufferedImageFixingGIFs_debug) print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
// Load non-bugged GIF the normal way
Image image;
if (!foundBug) {
image = Toolkit.getDefaultToolkit().createImage(f2s(file));
} else {
// Prepare streams for image encoding
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
{
ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream); try {
// Get GIF writer that's compatible with reader
ImageWriter writer = ImageIO.getImageWriter(reader);
// Give it the stream to encode to
writer.setOutput(ios);
writer.prepareWriteSequence(null);
for (int i = 0; i < numImages; i++) {
// Get input image
BufferedImage frameIn = reader.read(i);
// Get input metadata
IIOMetadataNode root = (IIOMetadataNode)reader.getImageMetadata(i).getAsTree(metaFormatName);
// Find GraphicControlExtension node
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
// Get delay value
String delay = ((IIOMetadataNode)node).getAttribute("delayTime");
// Check if delay is bugged
if (Integer.parseInt(delay) == 0) {
// Overwrite with a valid delay value
((IIOMetadataNode)node).setAttribute("delayTime", "10");
}
break;
}
}
// Create output metadata
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
// Copy metadata to output metadata
metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
// Create output image
IIOImage frameOut = new IIOImage(frameIn, null, metadata);
// Encode output image
writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
}
writer.endWriteSequence();
} finally { _close(ios); }}
// Create image using encoded data
byte[] data = baoStream.toByteArray();
setVar(loadBufferedImageFixingGIFs_output.get(), data);
if (loadBufferedImageFixingGIFs_debug) print("Data size: " + l(data));
image = Toolkit.getDefaultToolkit().createImage(data);
}
return image;
} catch (Exception __e) { throw rethrow(__e); } }
static boolean isSubstanceLAF() {
return substanceLookAndFeelEnabled();
}
// menuMaker = voidfunc(JPopupMenu)
// return true if menu could be added
static boolean titlePopupMenu(final Component c, final Object menuMaker) {
JComponent titleBar = getTitlePaneComponent(getPossiblyInternalFrame(c));
if (titleBar == null)
{ print("Can't add title right click!"); return false; }
else
{ componentPopupMenu(titleBar, menuMaker); return true; }
}
static void toggleAlwaysOnTop(JFrame frame) {
frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
}
static void shootWindowGUI_external(JFrame frame) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame);
}
static void shootWindowGUI_external(final JFrame frame, int delay) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame, delay);
}
static A oneOf(List l) {
return l.isEmpty() ? null : l.get(new Random().nextInt(l.size()));
}
static char oneOf(String s) {
return empty(s) ? '?' : s.charAt(random(l(s)));
}
static String oneOf(String... l) {
return oneOf(asList(l));
}
static A collectionGet(Collection c, int idx) {
if (c == null || idx < 0 || idx >= l(c)) return null;
if (c instanceof List) return listGet((List) c, idx);
Iterator it = c.iterator();
for (int i = 0; i < idx; i++) if (it.hasNext()) it.next(); else return null;
return it.hasNext() ? it.next() : null;
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static void nohupJavax(final String javaxargs) {
startThread(new Runnable() { public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs);"; }});
}
static void nohupJavax(final String javaxargs, final String vmArgs) {
startThread(new Runnable() { public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs, vmArgs);"; }});
}
// Try to get the quoting right...
static String smartJoin(String[] args) {
if (args.length == 1) return args[0];
String[] a = new String[args.length];
for (int i = 0; i < a.length; i++)
a[i] = !isJavaIdentifier(args[i]) && !isQuoted(args[i]) ? quote(args[i]) : args[i];
return join(" ", a);
}
static String smartJoin(List args) {
return smartJoin(toStringArray(args));
}
static String getSnippetTitle(String id) { try {
if (id == null) return null;
if (!isSnippetID(id)) return "?";
if (isLocalSnippetID(id)) return localSnippetTitle(id);
long parsedID = parseSnippetID(id);
String url;
if (isImageServerSnippet(parsedID))
url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery();
else if (isGeneralFileServerSnippet(parsedID))
url = "http://butter.botcompany.de:8080/files/name/" + parsedID;
else
url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies();
String title = trim(loadPageSilently(url));
if (title != null)
try { saveTextFileIfChanged(snippetTitle_cacheFile(id), title); } catch (Throwable __e) { print(exceptionToStringShort(__e)); }
return or(title, "?");
} catch (Exception __e) { throw rethrow(__e); } }
static String getSnippetTitle(long id) {
return getSnippetTitle(fsI(id));
}
// If you change this, also change DiskSnippetCache_fileToLibID
static File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
// Data files are immutable, use centralized cache
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = DiskSnippetCache_file(snippetID);
return file.exists() ? file : null;
}
public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(DiskSnippetCache_file(snippetID), data);
}
static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL(dataSnippetLink(snippetID));
print("Loading library: " + hideCredentials(url));
try {
data = loadBinaryPage(url.openConnection());
} catch (RuntimeException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL("http://data.tinybrain.de/blobs/"
+ parseSnippetID(snippetID));
print("Loading library: " + hideCredentials(url));
data = loadBinaryPage(url.openConnection());
}
print("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
static long fileSize(String path) { return getFileSize(path); }
static long fileSize(File f) { return getFileSize(f); }
static File loadDataSnippetToFile(String snippetID) { try {
snippetID = fsI(snippetID);
File f = DiskSnippetCache_file(parseSnippetID(snippetID));
List urlsTried = new ArrayList();
List errors = new ArrayList();
try {
URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
print("Loading library: " + hideCredentials(url));
try {
loadBinaryPageToFile(openConnection(url), f);
if (fileSize(f) == 0) throw fail();
} catch (Throwable e) {
errors.add(e);
url = addAndReturn(urlsTried, new URL("http://data.tinybrain.de/blobs/"
+ psI(snippetID)));
print("Trying other server: " + hideCredentials(url));
loadBinaryPageToFile(openConnection(url), f);
print("Got bytes: " + fileSize(f));
}
// TODO: check if we hit the "LOADING" message
if (fileSize(f) == 0) throw fail();
System.err.println("Bytes loaded: " + fileSize(f));
} catch (Throwable e) {
printStackTrace(e);
errors.add(e);
throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
}
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] isGIF_magic = bytesFromHex("47494638"); // Actual signature is longer, but we're lazy
static boolean isGIF(byte[] data) {
return byteArrayStartsWith(data, isGIF_magic);
}
static boolean isGIF(File f) {
return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
}
static String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static void setVar(IVar v, A value) {
if (v != null) v.set(value);
}
static boolean substanceLookAndFeelEnabled() {
return startsWith(getLookAndFeel(), "org.pushingpixels.");
}
static JComponent getTitlePaneComponent(RootPaneContainer window) {
if (window instanceof JInternalFrame)
return getInternalFrameTitlePaneComponent((JInternalFrame) window);
if (!substanceLookAndFeelEnabled() || window == null) return null;
JRootPane rootPane = window.getRootPane();
if (rootPane != null) {
Object /*SubstanceRootPaneUI*/ ui = rootPane.getUI();
return (JComponent) call(ui, "getTitlePane");
}
return null;
}
static RootPaneContainer getPossiblyInternalFrame(Component c) {
JInternalFrame f = getInternalFrame(c);
if (f != null) return f;
return optCast(RootPaneContainer.class, getWindow(c));
}
static Class hotwireOnce(String programID) {
return hotwireCached(programID, false);
}
static A listGet(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static boolean isJavaIdentifier(String s) {
if (empty(s) || !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;
}
// supports the usual quotings (", variable length double brackets) except ' quoting
static boolean isQuoted(String s) {
if (isNormalQuoted(s)) return true; // use the exact version
return isMultilineQuoted(s);
}
static String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++)
a[i] = it.next();
return a;
}
static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
static boolean isLocalSnippetID(String snippetID) {
return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID));
}
static boolean isLocalSnippetID(long snippetID) {
return snippetID >= 1000 && snippetID <= 9999;
}
static String localSnippetTitle(String snippetID) {
if (!isLocalSnippetID(snippetID)) return null;
File f = localSnippetFile(snippetID);
if (!f.exists()) return null;
return or2(getFileInfoField(dropExtension(f), "Title"), "Unnamed");
}
static boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static String imageServerURL() {
return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/");
}
static String muricaCredentialsQuery() {
return htmlQuery(muricaCredentials());
}
static boolean isGeneralFileServerSnippet(long id) {
return id >= 1400000 && id < 1500000;
}
static String tb_mainServer_default = "http://tinybrain.de:8080";
static Object tb_mainServer_override; // func -> S
static String tb_mainServer() {
if (tb_mainServer_override != null) return (String) callF(tb_mainServer_override);
return trim(loadTextFile(tb_mainServer_file(),
tb_mainServer_default));
}
static File tb_mainServer_file() {
return getProgramFile("#1001638", "mainserver.txt");
}
static boolean tb_mainServer_isDefault() {
return eq(tb_mainServer(), tb_mainServer_default);
}
static String standardCredentials_noCookies() {
return standardCredentials() + "&noCookies=1";
}
static int loadPage_defaultTimeout = 60000;
static ThreadLocal loadPage_charset = new ThreadLocal();
static boolean loadPage_allowGzip = true, loadPage_debug;
static boolean loadPage_anonymous; // don't send computer ID
static int loadPage_verboseness = 100000;
static int loadPage_retries = 1; //60; // seconds
static ThreadLocal