Warning : session_start(): open(/var/lib/php/sessions/sess_g3tud429b57nnetd84lebp6rno, 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 java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
// class AIConcept comes from #1007160
import java.awt.dnd.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.Transferable;
import javax.swing.event.AncestorEvent;
import org.pushingpixels.substance.api.skin.*;
import java.awt.datatransfer.DataFlavor;
import javax.swing.event.AncestorListener;
import javax.swing.Timer;
import javax.swing.undo.UndoManager;
import javax.swing.Timer;
import org.pushingpixels.substance.api.*;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
class main {
static class ImportedFrom extends Concept {
static String _fieldOrder = "snippetID lastTime";
String snippetID;
long lastTime;
}
static JTable table;
static JCheckBox cbGrabImages;
volatile static boolean grabImages;
volatile static double imageGrabberDelay = 1; // seconds, min 1
static Q uploadQ;
public static void main(final String[] args) throws Exception {
grabImages = headless();
dbIndexing(AIConcept.class, "searchedForSuggestedImage");
framesBot(); // bot to activate my frames
methodsBot("AI Concepts Import.", "importFrom", "importFromAI1Lol", "export");
uploadQ = new Q(true);
startImageGrabber();
if (isHeadless()) return;
substance();
swingMain();
aiEnhancements();
}
static void swingMain() { swing(new Runnable() { public void run() { try {
showConceptsTable_postProcess.set("reversedList");
table = makeConceptsTable(AIConcept.class, new Object() { Object get(AIConcept c) { try { return
litorderedmap(
"Concept ID" , c.globalID,
"Name/Description" , c.name,
"Comments" , c.comment,
"Has Image?" , c.pngFile.has(),
//"Imported From" := c.importedFrom,
"Originating Universe" , c.originatingUniverse,
"Exportable" , c.exportable)
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "litorderedmap(\n \"Concept ID\" , c.globalID,\n \"Name/Description\" , c.nam..."; }});
showFrame(makeTitle(), tableWithSearcher(table));
onEnter(tableSearchField(table), "newConcept");
onDoubleClick(table, new Runnable() { public void run() { try { editConcept(selectedConcept()) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "editConcept(selectedConcept())"; }});
addToWindow(table, withMargin(vstack(
jRightAlignedLine(
jbutton("New Concept...", "newConcept"),
tableDependButton(table, "Edit", new Runnable() { public void run() { try { editConcept(selectedConcept()) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "editConcept(selectedConcept())"; }}),
tableDependButton(table, "Duplicate", new Runnable() { public void run() { try { newConcept(selectedConcept()) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "newConcept(selectedConcept())"; }}),
jbutton("Export", "doExport"),
jbutton("Import...", "doImport")),
withTopMargin(jRightAlignedLine(cbGrabImages = jCheckBox("Google For Images", grabImages))))));
tablePopupMenu(table, new Object() { void get(JPopupMenu menu, final int row) { try {
final String globalID = (String) getTableCell(table, row, 0);
final AIConcept c = findConcept(AIConcept.class, "globalID", globalID);
addMenuItem(menu, "Edit...", new Runnable() { public void run() { try { editConcept(c) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "editConcept(c)"; }});
addMenuItem(menu, "Delete", new Runnable() { public void run() { try {
withDBLock(new Runnable() { public void run() { try { deleteConcept(c) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "deleteConcept(c)"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "withDBLock(r { deleteConcept(c) });"; }});
if (c.searchedForSuggestedImage)
addMenuItem(menu, "Search for image again", new Runnable() { public void run() { try {
deleteConcept(c.suggestedImage);
cset(c, "suggestedImage" , null, "searchedForSuggestedImage" , false)
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "deleteConcept(c.suggestedImage);\n cset(c, \"suggestedImage\" , null, \"searc..."; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final S globalID = (S) getTableCell(table, row, 0);\n final AIConcept c = find..."; }});
tableEnableTextDrag(table);
awtOnConceptChanges(table, 1000, new Runnable() { public void run() { try {
setFrameTitle(table, makeTitle())
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setFrameTitle(table, makeTitle())"; }});
addAISuiteMenu(table, "AI");
hideConsole();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showConceptsTable_postProcess.set(f reversedList);\n table = makeConceptsTable(A..."; }}); }
static void editConcept(final AIConcept c) {
if (c == null) return;
final JTextField a = jTextField(c.name);
final JTextField b = jTextField(c.comment);
final JTextField cc = jTextField(c.globalID);
final ImageChooser ic = new ImageChooser(c.pngFile.has() ? c.pngFile.get().getImageSafe() : null);
ic.setTitleForUpload(c.name);
PNGFile png = c.suggestedImage.get();
final ImageChooser ic2 = new ImageChooser(png != null ? png.getImageSafe() : null);
final Var md5 = new Var(md5OfPNGFile(png));
awtOnConceptChanges(ic2, new Runnable() { public void run() { try {
ic2.setTitleForUpload(c.name);
PNGFile png = c.suggestedImage.get();
String newMD5 = md5OfPNGFile(png);
if (png != null && neq(md5.get(), newMD5)) {
md5.set(newMD5);
ic2.setImage(png.getImageSafe());
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ic2.setTitleForUpload(c.name);\n PNGFile png = c.suggestedImage.get();\n Str..."; }}, true);
Runnable r = new Runnable() { public void run() { try {
BufferedImage image = ic.getImage();
if (image == null && c.pngFile.has()) {
//c.pngFile->delete();
c.pngFile.clear();
cset(c, "imageMD5" , null);
} else if (image != null &&
(!c.pngFile.has() || !imagesIdentical(c.pngFile.get().getImage(), image))) {
//if (c.pngFile.has()) c.pngFile->delete();
setConceptImage(c, image);
}
cset(c, "touched" , now(),
"name" , getTextTrim(a), "comment" , getTextTrim(b),
"globalID" , getTextTrim(cc));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "BufferedImage image = ic.getImage();\n if (image == null && c.pngFile.has()) {..."; }};
Object[] params = {
"Description/Name", a,
"Comment (optional)", b,
"Global ID", cc,
"Example Image (optional)",
westAndEast(ic, withLeftMargin(20, northAndCenter(vstack(
jbutton("Accept", new Runnable() { public void run() { try {
ic.setImage(ic2.getImage());
findButton(getFrame(ic), "Save").doClick();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ic.setImage(ic2.getImage());\n findButton(getFrame(ic), \"Save\").doClick();"; }}),
jCenteredLabel("Suggested image:")), ic2))),
r };
//for i over params: print("#" + i + ": " + params[i]);
renameSubmitButton("Save", showFormTitled("Edit concept " + c.globalID, params));
}
static String searcherInput() {
return getTextTrim(tableSearchField(table));
}
static void newConcept() { newConcept(null); }
static void newConcept(final AIConcept c) {
final JTextField a = jTextField(c == null ? searcherInput() : c.name);
final JTextField b = jTextField(getString(c, "comment"));
final JTextField cc = jTextField(aGlobalID());
final JLabel lbl = jCenteredLabel("Suggested image:");
final ImageChooser ic = new ImageChooser();
final ImageChooser ic2 = new ImageChooser();
final Var md5 = new Var();
awtCalcRegularly(ic2, 500, 0, new Runnable() {
String lastTyped, lastSearched;
public void run() {
String s = getTextTrim(a);
if (nempty(s) && eq(s, lastTyped) && neq(s, lastSearched)) {
lastSearched = s;
lbl.setIcon(imageIcon("#1007255"));
try {
final BufferedImage img = quickVisualize(s);
if (img != null) { swing(new Runnable() { public void run() { try { ic2.setImage(img);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ic2.setImage(img);"; }}); }
} finally {
lbl.setIcon(null);
}
}
lastTyped = s;
}
});
Runnable r = new Runnable() { public void run() { try {
AIConcept c = cnew(AIConcept.class, "touched" , now(),
"name" , getTextTrim(a), "comment" , getTextTrim(b), "globalID" , getTextTrim(cc));
setConceptImage(c, ic.getImage());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AIConcept c = cnew(AIConcept, \"touched\" , now(),\n \"name\" , getTextTrim(a), ..."; }};
renameSubmitButton("Create", showFormTitled("New concept",
"Description/Name", a,
"Comment (optional)", b,
"Global ID", cc,
"Example Image (optional)",
westAndEast(ic, withLeftMargin(20, northAndCenter(vstack(
jbutton("Accept", new Runnable() { public void run() { try { ic.setImage(ic2.getImage()) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ic.setImage(ic2.getImage())"; }}),
lbl), ic2))),
r));
}
static AIConcept selectedConcept() {
return findConcept(AIConcept.class, "globalID" , selectedTableCell(table, 0));
}
static void doImport() {
ImportedFrom last = last(sortedByField("lastTime", list(ImportedFrom.class)));
final JTextField tf = jTextField(last == null ? "#1007208" : last.snippetID);
showFormTitled("Import A. I. Concepts",
"Snippet ID", tf, runnableThread(new Runnable() { public void run() { try {
{ JWindow _loading_window = showLoadingAnimation(); try {
importFrom(getTextTrim(tf));
} finally { disposeWindow(_loading_window); }}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "{ JWindow _loading_window = showLoadingAnimation(); try {\n importFrom(get..."; }}));
}
static void importFromAI1Lol() {
importFrom(freshConceptsFromAI1Lol(), "ai1.lol");
}
static void importFrom(String snippetID) {
snippetID = fsI(snippetID);
cset(uniq(ImportedFrom.class, "snippetID", snippetID), "lastTime" , now());
String text = loadSnippet(snippetID);
Concepts newConcepts = new Concepts(snippetID).safeLoad(text);
importFrom(newConcepts, snippetID);
}
static void importFrom(Concepts newConcepts, String snippetID) {
print(n(list(newConcepts, "AIConcept"), "concept") + " loaded from " + snippetID);
Concepts myConcepts = mainConcepts;
print("I have " + n(list(myConcepts, "AIConcept"), "concept"));
Map myIDs = indexByField(list(myConcepts, AIConcept.class), "globalID");
int nNew = 0;
for (Concept c : list(newConcepts, "AIConcept")) {
String id = getString(c, "globalID");
boolean has = myIDs.containsKey(id);
print("ID: " + id + " - " + (has ? "I have it" : "I don't have it"));
if (!has) {
// Creating
AIConcept c2 = cnew(AIConcept.class, "importedFrom" , snippetID, "imported" , now());
importFields(c, c2);
myIDs.put(id, c2);
++nNew;
} else {
// Updating
AIConcept c2 = myIDs.get(id);
if (c2.touched > c2.imported)
print(" Concept touched locally! Not changing.");
else {
long time = now();
cset(c2, "imported" , time, "touched" , time);
int changes = importFields(c, c2);
if (changes == 0)
print(" No change.");
else
print(" Updated concept! " + n(changes, "fields") + " changed");
}
}
}
infoBox("Import done. " + n(nNew, "new concepts"));
}
static int importFields(Concept c, AIConcept c2) {
c2.created = c.created;
return copyConceptFields(c, c2, "globalID", "name", "comment", "imageMD5", "originatingUniverse");
}
static void doExport() {
swingExportConcepts("AI Concepts");
}
static void export() {
swingExportConcepts_impl("AI Concepts");
}
static String makeTitle() {
return "My AI Concepts [" + countConcepts(AIConcept.class) + "]";
}
static void startImageGrabber() {
{ Thread _t_0 = new Thread("Image Grabber") {
public void run() { try {
while (licensed()) { try {
if (headless() ? grabImages : isChecked(cbGrabImages)) {
AIConcept c = findConcept(AIConcept.class, "searchedForSuggestedImage" , false);
if (c != null) {
cset(c, "searchedForSuggestedImage" , true);
if (c.suggestedImage != null || c.importedFrom != null) continue;
String query = c.name;
//Window box = infoBox("Visualizing: " + c.name);
BufferedImage img = quickVisualize(query);
//disposeWindow(box);
if (img != null) {
showAnimation(img, c.name, 4);
cset(c, "suggestedImage" , new PNGFile(quickVisualize_imagePath(query)), "suggestedImageMD5" , md5OfBufferedImage(img));
} else
infoBox("No image found");
}
}
} catch (Throwable __e) { printStackTrace2(__e); } sleepSeconds(imageGrabberDelay); }
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
}
static void setConceptImage(final AIConcept c, final BufferedImage img) {
if (img == null) {
c.pngFile.clear();
cset(c, "imageMD5" , null);
} else {
c.pngFile.set(new PNGFile(img));
cset(c, "imageMD5" , c.pngFile.get().md5());
uploadQ.add(new Runnable() { public void run() { try { uploadToImageServerIfNotThere(img, aiConceptToString(c)) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "uploadToImageServerIfNotThere(img, aiConceptToString(c))"; }});
}
}
static String aGlobalID() {
return randomID(16);
}
static LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static Boolean isHeadless_cache;
static boolean isHeadless() {
if (isHeadless_cache != null) return isHeadless_cache;
if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true;
// Also check if AWT actually works.
// If DISPLAY variable is set but no X server up, this will notice.
try {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) { return isHeadless_cache = true; }
}
static String uploadToImageServerIfNotThere(BufferedImage img, String name) {
String md5 = md5OfRGBImage(new RGBImage(img));
long id = imageServerCheckMD5(md5);
if (id == 0)
return uploadToImageServer_new(img, name);
else
return "http://ai1.lol/images/raw/" + id;
}
static JButton findButton(Component c, String name) {
for (JButton b : childrenOfType(c, JButton.class))
if (eq(b.getText(), name)) return b;
for (JButton b : childrenOfType(getFrame(c), JButton.class))
if (eq(b.getText(), name)) return b;
return null;
}
static JLabel jCenteredLabel(String text) {
return jcenteredLabel(text);
}
static JLabel jCenteredLabel() {
return jcenteredLabel();
}
static JButton renameSubmitButton(JComponent form, String newName) {
return renameButton(form, showFormSubmitButtonName(), newName);
}
static JButton renameSubmitButton(String newName, JComponent form) {
return renameSubmitButton(form, newName);
}
static String md5OfPNGFile(PNGFile png) {
return png == null ? "-" : png.md5();
}
static Object selectedTableCell(JTable t, int col) {
return getTableCell(t, t.getSelectedRow(), col);
}
static Object selectedTableCell(JTable t) {
return selectedTableCell(t, t.getSelectedColumn());
}
static RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
// optional parameters
static ThreadLocal> showConceptsTable_dropFields = new ThreadLocal();
static ThreadLocal showConceptsTable_postProcess = new ThreadLocal(); // func(L) -> L
static ThreadLocal showConceptsTable_afterUpdate = new ThreadLocal(); // voidfunc(JTable)
static int makeConceptsTable_idWidth = 50;
static JTable showConceptsTable(Class extends Concept> c) {
JTable table = makeConceptsTable(c);
showFrame(plural(shortClassName(c)), table);
return table;
}
static JTable makeConceptsTable(final Class extends Concept> c) {
List dropFields = getAndClearThreadLocal(showConceptsTable_dropFields);
final Object pp = getAndClearThreadLocal(showConceptsTable_postProcess);
final Object afterUpdate = optParam(showConceptsTable_afterUpdate);
final List fields = listMinusList(concatLists(ll("id"), conceptFieldsInOrder(c)), dropFields);
final JTable table = sexyTable();
tablePopupMenu(table, new Object() { void get(JPopupMenu menu, final int row) { try {
addMenuItem(menu, "Delete", new Runnable() { public void run() { try {
final long id = toLong(getTableCell(table, row, 0));
withDBLock(new Runnable() { public void run() { try { deleteConcept(id) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "deleteConcept(id)"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final long id = toLong(getTableCell(table, row, 0));\r\n withDBLock(r { delet..."; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "addMenuItem(menu, \"Delete\", r {\r\n final long id = toLong(getTableCell(table..."; }});
awtOnConceptChanges(table, new Runnable() { public void run() { try {
//print("Updating concept table");
List data = new ArrayList();
for (final Concept cc : list(c))
data.add(map(new Object() { Object get(String field) { try { return renderForTable(cget(cc, field)) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "renderForTable(cget(cc, field))"; }}, fields));
data = (List) postProcess(pp, data);
fillTableWithData(table, data, fields);
if (table.getColumnCount() > 0)
table.getColumnModel().getColumn(0).setMaxWidth(makeConceptsTable_idWidth);
pcallF(afterUpdate, table);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "//print(\"Updating concept table\");\r\n new List data;\r\n for (final Con..."; }}, true);
return table;
}
// f takes a concept and makes a map for display
static JTable makeConceptsTable(final Class cClass, final Object f) {
if (f == null) return makeConceptsTable(cClass);
final Object pp = optParam(showConceptsTable_postProcess);
final Object afterUpdate = optParam(showConceptsTable_afterUpdate);
final JTable table = sexyTable();
awtOnConceptChanges(table, 1000, new Runnable() { public void run() { try {
List data = new ArrayList();
for (A c : list(cClass))
addIfNotNull(data, (Map) pcallF(f, c));
data = (List) postProcess(pp, data);
dataToTable_uneditable(data, table);
pcallF(afterUpdate, table);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new List data;\r\n for (A c : list(cClass))\r\n addIfNotNull(data, (Map..."; }});
return table;
}
static JTable showConceptsTable(final Class c, final Object f) {
JTable table = makeConceptsTable(c, f);
showFrame(plural(shortClassName(c)), table);
return table;
}
static JTable showConceptsTable(String title, Class cClass, Object f) {
return setFrameTitle(title, showConceptsTable(cClass, f));
}
static String quickVisualize_progID = "#1007145";
static Lock quickVisualize_lock = lock();
static boolean quickVisualize_hasCached(String query) {
return quickVisualize_imageFile(query).length() != 0;
}
static BufferedImage quickVisualize_fromCache(String query) {
File f = quickVisualize_imageFile(query);
if (f.length() != 0) try { return loadPNG(f); } catch (Throwable __e) { printStackTrace2(__e); }
return null;
}
static String quickVisualize_preprocess(String query) {
return toUpper(shorten(trim(query), 200));
}
static BufferedImage quickVisualize(String query) {
query = quickVisualize_preprocess(query);
if (empty(query)) return null;
BufferedImage img = quickVisualize_fromCache(query);
if (img != null) return img;
File f = quickVisualize_imageFile(query);
/*L urls = googleImageSearch_multi(query);
saveTextFile(quickVisualize_urlsFile(query), joinLines(urls));
if (empty(urls)) null;
img = loadBufferedImage(first(urls));*/
Lock _lock_18 = quickVisualize_lock; lock(_lock_18); try {
img = googleImageSearchFirst(query);
if (img == null) return null;
savePNG(f, img);
return img;
} finally { _lock_18.unlock(); } }
static String quickVisualize_imagePath(String query) {
query = quickVisualize_preprocess(query);
return fsI(quickVisualize_progID) + "/" + urlencode(query) + ".png";
}
static File quickVisualize_imageFile(String query) {
query = quickVisualize_preprocess(query);
return prepareProgramFile(quickVisualize_progID, urlencode(query) + ".png");
}
static File quickVisualize_urlsFile(String query) {
query = quickVisualize_preprocess(query);
return prepareProgramFile(quickVisualize_progID, "urls-" + urlencode(query) + ".txt");
}
static Object withDBLock(Object r) {
mainConcepts.lock.lock();
try {
return callF(r);
} finally {
mainConcepts.lock.unlock();
}
}
static A withDBLock(F0 r) {
return (A) withDBLock((Object) r);
}
static void tableEnableTextDrag(final JTable table) {
TransferHandler th = new TransferHandler() {
@Override
public int getSourceActions(JComponent c) { return COPY; }
@Override
protected Transferable createTransferable(JComponent c) {
//print("Row/Column: " + table.getSelectedRow() + " / " + table.getSelectedColumn());
Object o = selectedTableCell(table);
//print("Value: " + o);
return new StringSelection(str(o));
}
};
tableEnableDrag(table, th);
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static SingleThread awtCalcRegularly(JComponent component, int delay, int firstDelay, final Object runnable) {
final SingleThread thread = new SingleThread();
installTimer(component, delay, firstDelay, new Runnable() {
public void run() {
if (!licensed()) return;
thread.go(runnable);
}
});
return thread;
}
static SingleThread awtCalcRegularly(JFrame frame, int delay, int firstDelay, final Object runnable) {
return awtCalcRegularly(getRootPane(frame), delay, firstDelay, runnable);
}
static String fsI(String id) {
return formatSnippetID(id);
}
static String fsI(long id) {
return formatSnippetID(id);
}
static String exportSnippetID;
static void swingExportConcepts(final String desc) {
{ Thread _t_0 = new Thread("Exporting") {
public void run() { try {
try {
{ JWindow _loading_window = showLoadingAnimation(); try {
try {
swingExportConcepts_impl(desc);
} catch (Throwable e) {
if (containsIC(str(e), "Not your snippet")) {
if (!confirmOKCancel("Snippet " + exportSnippetID + " does not seem to belong to you. Maybe you're not logged in. Do you want to export to a new snippet?")) return;
exportSnippetID = null;
save("exportSnippetID");
swingExportConcepts_impl(desc);
} else rethrow(e);
}
} finally { disposeWindow(_loading_window); }}
} catch (Throwable __e) { messageBox(__e); }
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
}
static void swingExportConcepts_impl(String desc) {
if (mainConcepts.countConcepts() == 0) throw fail("Nothing to export (concepts not loaded?)");
String text = mainConcepts.xfullgrab();
if (match("exportable=f", text)) throw fail("Non-exportable concepts found");
//print(javaTokWordWrap(text));
print("Size: " + l(utf8(text)));
print();
load("exportSnippetID");
if (empty(exportSnippetID)) {
infoBox("Creating a snippet for you...");
exportSnippetID = createSnippet(text, desc + " from " + computerID(), 53);
infoBox("Your snippet ID: " + exportSnippetID);
save("exportSnippetID");
} else {
String oldMD5 = getSnippetMD5(exportSnippetID);
String newMD5 = md5(text);
if (eq(oldMD5, newMD5))
infoBox("Snippet " + exportSnippetID + " already up to date!");
else {
infoBox("Updating snippet: " + exportSnippetID);
editSnippet(exportSnippetID, text);
String actualMD5 = getSnippetMD5(exportSnippetID);
if (eq(actualMD5, newMD5))
infoBox("Export to " + exportSnippetID + " complete (" + n(lUtf8(text), "bytes") + ").");
else if (eq(actualMD5, oldMD5))
infoBox("Export failed for unknown reason");
else
infoBox("Hm. Export did something, but MD5 mismatch occurred.");
}
}
}
static JTextField jTextField() {
return jTextField("");
}
static JTextField jTextField(final String text) {
return swing(new F0() { JTextField get() { try {
JTextField tf = new JTextField(unnull(text));
jenableUndoRedo(tf);
tf.selectAll();
return tf;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JTextField tf = new JTextField(unnull(text));\r\n jenableUndoRedo(tf);\r\n tf...."; }});
}
static JTextField jTextField(Object o) {
return jTextField(strOrEmpty(o));
}
static JPanel westAndEast(Component w, Component e) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.WEST, wrap(w));
panel.add(BorderLayout.EAST, wrap(e));
return panel;
}
static void dbIndexing(Object... params) {
db();
for (int i = 0; i < l(params); i += 2)
indexConceptField((Class) params[i], (String) params[i+1]);
}
static int withMargin_defaultWidth = 6;
static JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
static JPanel withMargin(final int w, final Component c) {
return swing(new F0() { JPanel get() { try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(w, w, w, w));
p.add(c);
return p;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.createEm..."; }});
}
static void addAISuiteMenu(Component c) {
addAISuiteMenu(c, "AI Suite");
}
static void addAISuiteMenu(Component c, String title) {
final Map map = (Map) ( get(hotwire("#1007449"), "aiPrograms"));
for (final String name : keys(map))
addToMenu(c, title, name, new Runnable() { public void run() { try { startOrActivate(map.get(name)) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "startOrActivate(map.get(name))"; }});
}
static A last(List l) {
return empty(l) ? null : l.get(l.size()-1);
}
static char last(String s) {
return empty(s) ? '#' : s.charAt(l(s)-1);
}
static int last(int[] a) {
return l(a) != 0 ? a[l(a)-1] : 0;
}
static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
// button without action
static JButton jbutton(String text) {
return newButton(text, null);
}
static JButton jbutton(BufferedImage img, Object action) {
return setButtonImage(img, jbutton("", action));
}
static JButton jbutton(Action action) {
return new JButton(action);
}
static void aiEnhancements() {
conceptLanguageToolTips();
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || a.equals(b);
}
static ArrayList list(A[] a) {
return asList(a);
}
static ArrayList list(int[] a) {
return asList(a);
}
static ArrayList list(Set s) {
return asList(s);
}
static class tablePopupMenu_Maker {
List menuMakers = new ArrayList();
}
static Map tablePopupMenu_map = new WeakHashMap();
static ThreadLocal tablePopupMenu_mouseEvent = new ThreadLocal();
static ThreadLocal tablePopupMenu_first = new ThreadLocal();
// menuMaker = voidfunc(JPopupMenu, int row)
static void tablePopupMenu(final JTable table, final Object menuMaker) {
final boolean first = isTrue(getAndClearThreadLocal(tablePopupMenu_first));
swingNowOrLater(new Runnable() { public void run() { try {
tablePopupMenu_Maker maker = tablePopupMenu_map.get(table);
if (maker == null) {
tablePopupMenu_map.put(table, maker = new tablePopupMenu_Maker());
final tablePopupMenu_Maker _maker = maker;
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) { displayMenu(e); }
public void mouseReleased(MouseEvent e) { displayMenu(e); }
void displayMenu(MouseEvent e) {
if (e.isPopupTrigger()) {
JPopupMenu menu = new JPopupMenu();
int row = table.rowAtPoint(e.getPoint());
if (table.getSelectedRowCount() < 2)
table.setRowSelectionInterval(row, row);
int emptyCount = menu.getComponentCount();
tablePopupMenu_mouseEvent.set(e);
for (Object menuMaker : _maker.menuMakers)
pcallF(menuMaker, menu, row);
// show menu if any items in it
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
if (first)
maker.menuMakers.add(0, menuMaker);
else
maker.menuMakers.add(menuMaker);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tablePopupMenu_Maker maker = tablePopupMenu_map.get(table);\r\n if (maker == nu..."; }});
}
static boolean isChecked(final JCheckBox checkBox) {
return checkBox != null && (boolean) swing(new Object() { Object get() { try { return checkBox.isSelected() ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "checkBox.isSelected()"; }});
}
static JButton tableDependButton(JTable tbl, JButton b) {
tableDependButtons(tbl, ll(b));
return b;
}
static JButton tableDependButton(JTable tbl, String text, Object action) {
return tableDependButton(tbl, jbutton(text, action));
}
static JTextField onEnter(JTextField tf, final Object action) {
if (action == null || tf == null) return tf;
tf.addActionListener(actionListener(action));
return tf;
}
static JButton onEnter(JButton btn, final Object action) {
if (action == null || btn == null) return btn;
btn.addActionListener(actionListener(action));
return btn;
}
static JList onEnter(JList list, Object action) {
list.addKeyListener(enterKeyListener(action));
return list;
}
// editable only
static JComboBox onEnter(final JComboBox cb, final Object action) {
JTextField text = (JTextField) cb.getEditor().getEditorComponent();
/*onEnter(text, r {
cb.hidePopup();
pcallF(action);
});*/
onEnter(text, action);
return cb;
}
// returns number of changes
static int cset(Concept c, Object... values) { try {
int changes = 0;
values = expandParams(c.getClass(), values);
warnIfOddCount(values);
for (int i = 0; i+1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i+1];
Field f = setOpt_findField(c.getClass(), field);
//print("cset: " + c.id + " " + field + " " + struct(value) + " " + f);
if (value instanceof RC) value = c._concepts.getConcept((RC) value);
value = deref(value);
if (value instanceof String && l((String) value) >= concepts_internStringsLongerThan) value = ((String) value).intern();
if (f == null) {
// TODO: keep ref if it exists
mapPut2(c.fieldValues, field, value instanceof Concept ? c.new Ref((Concept) value) : value);
c.change();
} else if (isSubtypeOf(f.getType(), Concept.Ref.class)) {
((Concept.Ref) f.get(c)).set((Concept) derefRef(value));
c.change(); ++changes;
} else {
Object old = f.get(c);
if (neq(value, old)) {
f.set(c, value);
if ((f.getModifiers() & java.lang.reflect.Modifier.TRANSIENT) == 0) c.change();
++changes;
}
}
}
return changes;
} catch (Exception __e) { throw rethrow(__e); } }
static JPanel vstack(Object... parts) {
return vstack2(parts);
}
static JPanel vstack(List parts) {
return vstack(toObjectArray(parts));
}
static Component addToWindow(final Component c, final Component toAdd) {
if (toAdd != null) { swing(new Runnable() { public void run() { try {
JFrame frame = getFrame(c);
Container cp = frame.getContentPane();
JPanel newCP = new JPanel();
newCP.setLayout(new BorderLayout());
newCP.add(BorderLayout.CENTER, cp);
newCP.add(BorderLayout.SOUTH, toAdd);
frame.setContentPane(newCP);
// magic combo to actually relayout and repaint
frame.revalidate();
frame.repaint();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFrame frame = getFrame(c);\r\n Container cp = frame.getContentPane();\r\n \r\n ..."; }}); }
return c;
}
static A uniq(Class c, Object... params) {
return uniqueConcept(c, params);
}
static A uniq(Concepts cc, Class c, Object... params) {
return uniqueConcept(cc, c, params);
}
static JComponent tableWithSearcher(final JTable t) {
final JTextField input = new JTextField();
onUpdate(input, new Runnable() {
List lastFiltered, lastOriginal;
public void run() {
String pat = trim(input.getText());
List> data = rawTableData(t);
if (eq(lastFiltered, data))
data = lastOriginal;
print("Searching " + n(l(data), "entry"));
List data2 = new ArrayList();
for (Map map : data)
if (anyValueContainsIgnoreCase(map, pat))
data2.add(map);
print("Found " + n(l(data2), "entry"));
lastFiltered = data2;
lastOriginal = data;
dataToTable(t, data2);
}
});
return northAndCenter(withLabel("Search:", input), t);
}
static void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static void addMenuItem(JMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(JMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static String aiConceptToString(AIConcept c) {
if (c == null) return "-";
return c.globalID + " - " + c.name + (nempty(c.comment) ? " / " + c.comment : "");
}
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 List sortedByField(Collection c, final String field) {
List l = new ArrayList(c);
sort(l, new Comparator () {
public int compare(A a, A b) {
return cmp(getOpt(a, field), getOpt(b, field));
}
});
return l;
}
static List sortedByField(String field, Collection c) {
return sortedByField(c, field);
}
static Android3 methodsBot(String name, final List exposedMethods) {
return makeBot(name, new Object() {
String answer(String s) {
return exposeMethods(s, exposedMethods);
}
});
}
static Android3 methodsBot(String name, final String... exposedMethods) {
return methodsBot(name, asList(exposedMethods));
}
static boolean imagesIdentical(BufferedImage img1, BufferedImage img2) {
// lazy method
return eq(rgbMD5(new RGBImage(img1)), rgbMD5(new RGBImage(img2)));
}
static int withTopMargin_defaultWidth = 6;
static JPanel withTopMargin(Component c) {
return withTopMargin(withTopMargin_defaultWidth, c);
}
static JPanel withTopMargin(final int w, final Component c) {
return swing(new F0() { JPanel get() { try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0));
p.add(c);
return p;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.createEm..."; }});
}
static void sleepSeconds(double s) {
if (s > 0) sleep(round(s*1000));
}
static Object getTableCell(JTable tbl, int row, int col) {
if (row >= 0 && row < tbl.getModel().getRowCount())
return tbl.getModel().getValueAt(row, col);
return null;
}
static void deleteConcept(long id) {
mainConcepts.deleteConcept(id);
}
static void deleteConcept(Concept c) {
if (c != null) c.delete();
}
static void deleteConcept(Concept.Ref ref) {
if (ref != null) deleteConcept(ref.get());
}
static JFrame getFrame(final Object _o) {
return swing(new F0() { JFrame get() { try {
Object o = _o;
if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JFrame) return (JFrame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGro..."; }});
}
static A setFrameTitle(A c, String title) {
JFrame f = getFrame(c);
if (f == null)
showFrame(title, c);
else
f.setTitle(title);
return c;
}
static A setFrameTitle(String title, A c) {
return setFrameTitle(c, title);
}
// magically find a field called "frame" in main class :-)
static JFrame setFrameTitle(String title) {
Object f = getOpt(mc(), "frame");
if (f instanceof JFrame)
return setFrameTitle((JFrame) f, title);
return null;
}
static JWindow infoBox(String text) {
return infoMessage(text);
}
static JWindow infoBox(String text, double seconds) {
return infoMessage(text, seconds);
}
static JWindow infoBox(Throwable e) {
return infoMessage(e);
}
static volatile boolean framesBot_has;
static Android3 framesBot() {
if (framesBot_has) return null;
framesBot_has = true;
Android3 android = new Android3();
android.greeting = programID() + " Frames.";
android.console = false;
android.responder = new Responder() {
String answer(String s, List history) {
if (match("activate frames", s)) {
swingLater(new Runnable() { public void run() { try { // prevent blocking when called from same program's AWT thread
activateMyFrames();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// prevent blocking when called from same program's AWT thread\r\n activa..."; }});
return "OK, activating frames.";
}
return null;
}
};
return makeBot(android);
}
// 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);
}
}
});
}
// other components get the pointer position
// only reacts on left button
static void onDoubleClick(JComponent c, final Object runnable) {
c.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getButton() == 1 && evt.getClickCount() == 2)
callF(runnable, evt.getPoint());
}
});
}
static int copyConceptFields(Concept a, Concept b) {
int changes = 0;
for (String field : conceptFields(a))
changes += cset(b, field, cget(a, field));
return changes;
}
static int copyConceptFields(Concept a, Concept b, String... fields) {
int changes = 0;
for (String field : fields)
changes += cset(b, field, cget(a, field));
return changes;
}
static JPanel northAndCenter(Component n, Component c) {
return centerAndNorth(c, n);
}
static JWindow showLoadingAnimation() {
return showLoadingAnimation("Hold on user...");
}
static JWindow showLoadingAnimation(String text) {
return showAnimationInTopRightCorner("#1003543", text);
}
static String md5OfBufferedImage(BufferedImage img) {
return img == null ? null : rgbMD5(new RGBImage(img));
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
f.setAccessible(true);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(Object o, String field) {
try {
Field f = get_findField(o.getClass(), field);
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.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 long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static ImageIcon imageIcon(String imageID) { try {
return new ImageIcon(loadBinarySnippet(imageID).toURI().toURL());
} catch (Exception __e) { throw rethrow(__e); } }
static ImageIcon imageIcon(BufferedImage img) {
return new ImageIcon(img);
}
static ImageIcon imageIcon(RGBImage img) {
return imageIcon(img.getBufferedImage());
}
//please include function withMargin.
static int showForm_defaultGap = 4;
static JPanel showFormTitled(final String title, final Object... _parts) {
return swing(new F0() { JPanel get() { try {
final Var frame = new Var();
JPanel panel = showForm_makePanel(frame, _parts);
frame.set(handleEscapeKey(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400)));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final new Var frame;\r\n JPanel panel = showForm_makePanel(frame, _part..."; }});
}
static JPanel showForm_makePanel(final Var frame, Object... _parts) {
List l = new ArrayList();
List parts = asList(_parts);
Runnable submit = null;
for (int i = 0; i < l(parts); i++) {
final Object o = parts.get(i), next = get(parts, i+1);
if (o instanceof Component || o instanceof String || next instanceof Component) { // smartAdd accepts strings
l.add(ll(o == null ? new JPanel() : o, next));
if (next instanceof JButton && submit == null)
submit = new Runnable() { public void run() { try { ((JButton) next).doClick() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "((JButton) next).doClick()"; }};
i++;
} else if (isRunnable(o))
l.add(ll(null, jbutton(showFormSubmitButtonName(), submit = new Runnable() { public void run() { try {
Object result = call(o);
if (neq(Boolean.FALSE, result))
disposeFrame(frame.get());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object result = call(o);\r\n if (neq(Boolean.FALSE, result))\r\n dis..."; }})));
else print("showForm: Unknown element type: " + getClassName(o));
}
JPanel panel = hvgrid((List) l, showForm_defaultGap);
if (submit != null)
for (JTextField textField : childrenOfType(panel, JTextField.class))
onEnter(textField, submit);
return panel;
}
static int countConcepts(Class c, Object... params) {
return mainConcepts.countConcepts(c, params);
}
static int countConcepts() {
return mainConcepts.countConcepts();
}
static int countConcepts(String className) {
return mainConcepts.countConcepts(className);
}
static int countConcepts(Concepts concepts, String className) {
return concepts.countConcepts(className);
}
static boolean preferCached = false;
static boolean loadSnippet_debug = false;
static ThreadLocal loadSnippet_silent = new ThreadLocal();
static String loadSnippet(String snippetID) {
try {
return loadSnippet(parseSnippetID(snippetID), preferCached);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static String loadSnippet(String snippetID, boolean preferCached) throws IOException {
return loadSnippet(parseSnippetID(snippetID), preferCached);
}
public static String loadSnippet(long snippetID) {
try {
return loadSnippet(snippetID, preferCached);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadSnippet(long snippetID, boolean preferCached) throws IOException {
String text;
// boss bot disabled for now for shorter transpilations
/*text = getSnippetFromBossBot(snippetID);
if (text != null) return text;*/
initSnippetCache();
text = DiskSnippetCache_get(snippetID);
if (preferCached && text != null)
return text;
try {
if (loadSnippet_debug && text != null) System.err.println("md5: " + md5(text));
String url = tb_mainServer() + "/getraw.php?id=" + snippetID + "&utf8=1";
if (nempty(text)) url += "&md5=" + md5(text);
url += standardCredentials();
String text2 = isTrue(loadSnippet_silent.get()) ? loadPageSilently(url) : loadPage(url);
boolean same = eq(text2, "==*#*==");
if (loadSnippet_debug) print("loadSnippet: same=" + same);
if (!same) text = text2;
} catch (RuntimeException e) {
e.printStackTrace();
throw new IOException("Snippet #" + snippetID + " not found or not public");
}
try {
initSnippetCache();
DiskSnippetCache_put(snippetID, text);
} catch (IOException e) {
System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")");
}
return text;
}
static File DiskSnippetCache_dir;
public static void initDiskSnippetCache(File dir) {
DiskSnippetCache_dir = dir;
dir.mkdirs();
}
public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
}
private static File DiskSnippetCache_getFile(long snippetID) {
return new File(DiskSnippetCache_dir, "" + snippetID);
}
public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
}
public static File DiskSnippetCache_getDir() {
return DiskSnippetCache_dir;
}
public static void initSnippetCache() {
if (DiskSnippetCache_dir == null)
initDiskSnippetCache(getGlobalCache());
}
static JFrame showFrame() {
return makeFrame();
}
static JFrame showFrame(Object content) {
return makeFrame(content);
}
static JFrame showFrame(String title) {
return makeFrame(title);
}
static JFrame showFrame(String title, Object content) {
return makeFrame(title, content);
}
static JFrame showFrame(final JFrame frame) {
if (frame != null) { swing(new Runnable() { public void run() { try {
if (frameTooSmall(frame)) frameStandardSize(frame);
frame.setVisible(true);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (frameTooSmall(frame)) frameStandardSize(frame);\r\n frame.setVisible(true);"; }}); }
return frame;
}
// make or update frame
static JFrame showFrame(String title, Object content, JFrame frame) {
if (frame == null)
return showFrame(title, content);
else {
frame.setTitle(title);
setFrameContents(frame, content);
return frame;
}
}
static Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static Thread startThread(String name, Object runnable) {
return startThread(newThread(toRunnable(runnable), name));
}
static Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static Concepts freshConceptsFromAI1Lol() {
String text = loadPage("http://ai1.lol/wiki/structure/concepts");
List list = (List) ( safeUnstructure(text));
HashMap map = new HashMap();
long iid = 0;
for (Object o : list) map.put(++iid, o);
String text2 = structure(map);
return new Concepts().safeLoad(text2);
}
static RuntimeException rethrow(Throwable e) {
throw asRuntimeException(e);
}
static List reversedList(Collection l) {
List x = cloneList(l);
Collections.reverse(x);
return x;
}
static JPanel jRightAlignedLine(Component... components) {
return jrightAlignedLine(components);
}
static JPanel jRightAlignedLine(List components) {
return jrightAlignedLine(components);
}
static int awtOnConceptChanges_defaultDelay = 1000;
static void awtOnConceptChanges(Component component, Object runnable) {
awtOnConceptChanges(componentToJComponent(component), runnable, true);
}
static void awtOnConceptChanges(JComponent component, final Object runnable, boolean runOnFirstTime) {
awtOnConceptChanges(component, awtOnConceptChanges_defaultDelay, 0, runnable, runOnFirstTime);
}
static void awtOnConceptChanges(JComponent component, int delay, final Object runnable) {
awtOnConceptChanges(component, delay, delay, runnable);
}
static void awtOnConceptChanges(JComponent component, int delay, int firstDelay, Object runnable) {
awtOnConceptChanges(component, delay, firstDelay, runnable, true);
}
static boolean awtOnConceptChanges_debug;
static void awtOnConceptChanges(JComponent component, int delay, int firstDelay, final Object runnable, final boolean runOnFirstTime) {
installTimer(component, delay, firstDelay, new Runnable() {
long c = runOnFirstTime ? -1 : changeCount();
public void run() {
long _c = changeCount();
if (awtOnConceptChanges_debug)
print("awtOnConceptChanges: " + _c + " / " + c);
if (_c != c) {
c = _c;
call(runnable);
}
}
});
}
static volatile boolean licensed_yes = true;
static boolean licensed() {
ping();
return licensed_yes;
}
static void licensed_off() {
licensed_yes = false;
}
static JTextField tableSearchField(JTable t) {
// rough
try {
return firstComponentOfType(parentOfType(t, JScrollPane.class).getParent(), JTextField.class);
} catch (Throwable __e) { printStackTrace2(__e); }
return null;
}
static void substance() {
substanceLAF();
}
static void substance(String skinName) {
substanceLAF(skinName);
}
static JCheckBox jCheckBox() {
return new JCheckBox();
}
static JCheckBox jCheckBox(boolean checked) {
return new JCheckBox("", checked);
}
static JCheckBox jCheckBox(String text, boolean checked) {
return new JCheckBox(text, checked);
}
static JCheckBox jCheckBox(String text) {
return new JCheckBox(text);
}
static JCheckBox jCheckBox(String text, boolean checked, final Object onChange) {
JCheckBox cb = jCheckBox(checked, onChange);
cb.setText(text);
return cb;
}
// onChange can be a Runnable or a voidfunc(bool)
static JCheckBox jCheckBox(boolean checked, final Object onChange) {
final JCheckBox cb = jCheckBox(checked);
cb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(onChange, cb.isSelected());
}
});
return cb;
}
static Runnable runnableThread(final Runnable r) {
return new Runnable() { public void run() { try { new Thread(r).start() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new Thread(r).start()"; }};
}
static Map _registerThread_threads = Collections.synchronizedMap(new WeakHashMap());
static Thread _registerThread(Thread t) {
_registerThread_threads.put(t, true);
return t;
}
static void _registerThread() { _registerThread(Thread.currentThread()); }
static boolean nempty(Collection c) {
return !isEmpty(c);
}
static boolean nempty(CharSequence s) {
return !isEmpty(s);
}
static boolean nempty(Object[] o) {
return !isEmpty(o);
}
static boolean nempty(Map m) {
return !isEmpty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static 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) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
static A findConcept(Class c, Object... params) {
return findConceptWhere(c, params);
}
static A findConcept(Concepts concepts, Class c, Object... params) {
return findConceptWhere(concepts, c, params);
}
static String getTextTrim(JTextComponent c) {
return trim(getText(c));
}
// tested for editable combo box - returns the contents of text field
static String getTextTrim(JComboBox cb) {
return trim(getText(cb));
}
static String getTextTrim(JComponent c) {
if (c instanceof JLabel) return trim(((JLabel) c).getText());
if (c instanceof JComboBox) return getTextTrim((JComboBox) c);
return getTextTrim((JTextComponent) c);
}
// can probably be merged with next variant
static void disposeWindow(final Window window) {
if (window != null) { swing(new Runnable() { public void run() { try {
window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); // call listeners
window.dispose();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); // ca..."; }}); }
}
static void disposeWindow(final Component c) {
disposeWindow(getWindow(c));
}
static void disposeWindow(Object o) {
if (o != null) disposeWindow((Component) o);
}
static String n(long l, String name) {
return l + " " + trim(l == 1 ? singular(name) : getPlural(name));
}
static String n(Collection l, String name) {
return n(l(l), name);
}
static String n(Map m, String name) {
return n(l(m), name);
}
static String n(Object[] a, String name) {
return n(l(a), name);
}
static boolean headless() {
return isHeadless();
}
// does not store null values
static Map indexByField(Collection c, String field) {
HashMap map = new HashMap();
for (Object a : c) {
Object val = getOpt(a, field);
if (val != null)
map.put(val, a);
}
return map;
}
static Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
//static int print_maxLineLength = 0; // 0 = unset
static boolean print_silent; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal> print_byThread; // special handling by thread
static void print() {
print("");
}
// slightly overblown signature to return original object...
static A print(A o) {
ping();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
if (print_byThread != null) {
F1 f = print_byThread.get();
if (f != null)
if (isFalse(f.get(s))) return;
}
print_raw(s);
}
static void print_raw(String s) {
s = fixNewLines(s);
// TODO if (print_maxLineLength != 0)
StringBuffer loc = local_log;
StringBuffer buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static void print(long l) {
print(String.valueOf(l));
}
static void print(char c) {
print(String.valueOf(c));
}
static void print_append(StringBuffer buf, String s, int max) {
synchronized(buf) {
buf.append(s);
max /= 2;
if (buf.length() > max) try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
}
}
static Concept cnew(String name, Object... values) {
Class extends Concept> cc = findClass(name);
Concept c = cc != null ? nuObject(cc) : new Concept(name);
csetAll(c, values);
return c;
}
static Concept cnew(Concepts concepts, String name, Object... values) {
Class extends Concept> cc = findClass(name);
concepts_unlisted.set(true);
Concept c;
try {
c = cc != null ? nuObject(cc) : new Concept(name);
} finally {
concepts_unlisted.set(null);
}
concepts.register(c);
csetAll(c, values);
return c;
}
static A cnew(Class cc, Object... values) {
A c = nuObject(cc);
csetAll(c, values);
return c;
}
static A cnew(Concepts concepts, Class cc, Object... values) {
concepts_unlisted.set(true);
A c;
try {
c = nuObject(cc);
} finally {
concepts_unlisted.set(null);
}
concepts.register(c);
csetAll(c, values);
return c;
}
static JWindow showAnimation(String imageID, double seconds) {
return showAnimationInTopRightCorner(imageID, seconds);
}
static JWindow showAnimation(String imageID) {
return showAnimationInTopRightCorner(imageID);
}
static JWindow showAnimation(BufferedImage image) {
return showAnimationInTopRightCorner(image, "");
}
static JWindow showAnimation(BufferedImage image, String text, double seconds) {
return showAnimationInTopRightCorner(image, text, seconds);
}
static JWindow showAnimation(BufferedImage image, double seconds) {
return showAnimationInTopRightCorner(image, "", seconds);
}
static JWindow showAnimation(String imageID, String text, double seconds) {
return showAnimationInTopRightCorner(imageID, text, seconds);
}
static Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
/*static void printStackTrace2(S indent, Throwable e) {
if (endsWithLetter(indent)) indent += " ";
printIndent(indent, getStackTrace2(e));
}*/
static int withLeftMargin_defaultWidth = 6;
static JPanel withLeftMargin(Component c) {
return withLeftMargin(withLeftMargin_defaultWidth, c);
}
static JPanel withLeftMargin(final int margin, final Component c) {
return swing(new F0() { JPanel get() { try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(0, margin, 0, 0));
p.add(c);
return p;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.createEm..."; }});
}
static JFrame handleEscapeKey(final JFrame frame) {
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
frame.getRootPane().registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
frame.dispose();
}
}, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
return frame;
}
static WeakHashMap makeFrame_myFrames = new WeakHashMap();
static JFrame makeFrame() {
return makeFrame((Component) null);
}
static JFrame makeFrame(Object content) {
return makeFrame(programTitle(), content);
}
static JFrame makeFrame(String title) {
return makeFrame(title, null);
}
static JFrame makeFrame(String title, Object content) {
return makeFrame(title, content, true);
}
static JFrame makeFrame(final String title, final Object content, final boolean showIt) {
return swing(new F0() { JFrame get() { try {
if (getFrame(content) != null)
return getFrame(setFrameTitle((Component) content, title));
final JFrame frame = new JFrame(title);
makeFrame_myFrames.put(frame, Boolean.TRUE);
JComponent wrapped = wrap(content);
if (wrapped != null)
frame.getContentPane().add(wrapped);
frame.setBounds(defaultNewFrameBounds());
if (showIt)
frame.setVisible(true);
//callOpt(content, "requestFocus");
//exitOnFrameClose(frame);
standardTitlePopupMenu(frame);
return frame;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (getFrame(content) != null)\r\n ret getFrame(setFrameTitle((Component) con..."; }});
}
static WeakHashMap> callF_cache = new WeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static Object callF(Object f, Object... args) { try {
if (f instanceof String)
return callMC((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) throw fail("No get method in " + getClassName(c));
if (n == 1) return methods.get(0).invoke(f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return m.invoke(f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
m.setAccessible(true);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static ArrayList asList(int[] a) {
ArrayList l = new ArrayList();
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static List listMinusList(Collection l, Collection stuff) {
if (empty(stuff) && l instanceof List) return (List) l;
List l2 = cloneList(l);
for (Object o : stuff)
l2.remove(o);
return l2;
}
static void disposeFrame(final Component c) {
disposeWindow(c);
}
static void setFrameContents(final Component c, final Object contents) {
{ swing(new Runnable() { public void run() { try {
JFrame frame = getFrame(c);
frame.getContentPane().removeAll();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrap(contents));
revalidate(frame);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFrame frame = getFrame(c);\r\n frame.getContentPane().removeAll();\r\n frame...."; }}); }
}
static boolean infoMessage_alwaysOnTop = true;
static double infoMessage_defaultTime = 5.0;
// automatically switches to AWT thread for you
static JWindow infoMessage(String text) {
return infoMessage(text, infoMessage_defaultTime);
}
static JWindow infoMessage(final String text, final double seconds) {
print(text);
return infoMessage_noprint(text, seconds);
}
static JWindow infoMessage_noprint(String text) {
return infoMessage_noprint(text, infoMessage_defaultTime);
}
static JWindow infoMessage_noprint(final String text, final double seconds) {
if (isHeadless()) return null;
return (JWindow) swingAndWait(new Object() { Object get() { try {
JTextArea ta = wrappedTextArea(text);
int size = 14;
if (l(text) <= 50) size *= 2;
else if (l(text) < 100) size = iround(size*1.5);
ta.setFont(typeWriterFont(size));
JScrollPane sp = jscroll(ta);
final JWindow window = showWindow(withMargin(sp));
window.setSize(300, 150);
moveToTopRightCorner(window);
onClick(ta, new Runnable() { public void run() { try { window.dispose() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispose()"; }});
if (infoMessage_alwaysOnTop)
window.setAlwaysOnTop(true);
window.setVisible(true);
disposeWindowAfter(iround(seconds*1000), window);
return window;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JTextArea ta = wrappedTextArea(text);\r\n int size = 14;\r\n if (l(text) <= 50..."; }});
}
static JWindow infoMessage(Throwable e) {
showConsole();
printStackTrace(e);
return infoMessage(str(e));
}
static A uniqueConcept(Class c, Object... params) {
return uniqueConcept(mainConcepts, c, params);
}
static A uniqueConcept(Concepts cc, Class c, Object... params) {
params = expandParams(c, params);
A x = findConceptWhere(cc, c, params);
if (x == null) {
x = nuObject(c);
csetAll(x, params);
}
return x;
}
static List getPlural_specials = ll("sheep", "fish");
static String getPlural(String s) {
if (containsIgnoreCase(getPlural_specials, s)) return s;
if (ewic(s, "y")) return dropSuffixIgnoreCase("y", s) + "ies";
if (ewic(s, "ss")) return s + "es";
if (ewic(s, "s")) return s;
return s + "s";
}
static String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new Object() { Object get() { try { return c.getText() ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "c.getText()"; }});
}
static String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new Object() { Object get() { try { return l.getText() ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "l.getText()"; }});
}
// returns the contents of text field for editable combo box
static String getText(final JComboBox cb) {
if (cb.isEditable())
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static String standardCredentials() {
String user = standardCredentialsUser();
String pass = standardCredentialsPass();
if (nempty(user) && nempty(pass))
return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
return "";
}
static Map singular_specials = litmap(
"children", "child", "images", "image", "chess", "chess");
static Set singular_specials2 = litset("time", "machine");
static String singular(String s) {
if (s == null) return null;
{ String _a_288 = singular_specials.get(s); if (!empty(_a_288)) return _a_288; }
{ String _a_289 = hippoSingulars().get(lower(s)); if (!empty(_a_289)) return _a_289; }
if (singular_specials2.contains(dropSuffix("s", s)))
return dropSuffix("s", s);
if (s.endsWith("ness")) return s;
if (s.endsWith("ges")) return dropSuffix("s", s);
if (endsWith(s, "bases")) return dropLast(s);
s = dropSuffix("es", s);
s = dropSuffix("s", s);
return s;
}
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 Object cget(Object c, String field) {
Object o = getOpt(c, field);
if (o instanceof Concept.Ref) return ((Concept.Ref) o).get();
return o;
}
static boolean isRunnable(Object o) {
return o instanceof Runnable || hasMethod(o, "get");
}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
// runnable = Runnable or String (method name)
static Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
static Thread newThread(Object runnable, String name) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static String unnull(String s) {
return s == null ? "" : s;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static List childrenOfType(Component c, Class theClass) {
List l = new ArrayList();
scanForComponents(c, theClass, l);
return l;
}
static JPanel vstack2(final Object... parts) {
return swing(new F0() { JPanel get() { try {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
smartAddWithLayout(panel, gbc, parts);
//gbc = (GridBagConstraints) gbc.clone();
//gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
panel.add(Box.createRigidArea(new Dimension(0, 0)), gbc);
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new GridBagLayout);\r\n new GridBagConstraints gbc;\r\n..."; }});
}
static volatile boolean sleep_noSleep;
static void sleep(long ms) {
ping();
if (ms < 0) return;
// allow spin locks
if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) { throw new RuntimeException(e); }
}
static void sleep() { try {
if (sleep_noSleep) throw fail("nosleep");
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) { throw rethrow(__e); } }
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
static void indexConceptField(Class extends Concept> c, String field) {
if (!isConceptFieldIndexed(c, field))
new ConceptFieldIndex(c, field);
}
static ActionListener actionListener(final Object runnable) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try { callF(runnable); } catch (Throwable __e) { messageBox(__e); }}};
}
static String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); } static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: l((Collection) o); // incomplete
}
static int l(Lisp l) { return l == null ? 0 : l.size(); }
static JFrame minFrameWidth(JFrame frame, int w) {
if (frame != null && frame.getWidth() < w)
frame.setSize(w, frame.getHeight());
return frame;
}
static JFrame minFrameWidth(int w, JFrame frame) {
return minFrameWidth(frame, w);
}
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() & java.lang.reflect.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 boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
throw fail(getClassName(o));
}
static File getGlobalCache() {
File file = new File(javaxCachesDir(), "Binary Snippets");
file.mkdirs();
return file;
}
static Object renderForTable(Object o) {
return or(toBufferedImageOpt(o), o);
}
static String toUpper(String s) {
return s == null ? null : s.toUpperCase();
}
static A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static A optParam(ThreadLocal tl) {
return optPar(tl);
}
static A findConceptWhere(Class c, Object... params) {
return findConceptWhere(mainConcepts, c, params);
}
static A findConceptWhere(Concepts concepts, Class c, Object... params) {
params = expandParams(c, params);
// indexed
if (concepts.fieldIndices != null)
for (int i = 0; i < l(params); i += 2) {
IFieldIndex index = concepts.getFieldIndex(c, (String) params[i]);
if (index != null) {
for (A x : index.getAll(params[i+1]))
if (checkConceptFields(x, params)) return x;
return null;
}
}
// table scan
for (A x : concepts.list(c)) if (checkConceptFields(x, params)) return x;
return null;
}
static Concept findConceptWhere(Concepts concepts, String c, Object... params) {
for (Concept x : concepts.list(c)) if (checkConceptFields(x, params)) return x;
return null;
}
// c = JComponent or something implementing swing()
static JComponent wrap(Object swingable) {
if (swingable == null) return null;
JComponent c = (JComponent) ( swingable instanceof JComponent ? swingable : callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList
|| c instanceof JTextArea || c instanceof JEditorPane
|| c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c;
}
static void db() {
conceptsAndBot();
}
static boolean frameTooSmall(JFrame frame) {
return frame.getWidth() < 100 || frame.getHeight() < 50;
}
static File prepareProgramFile(String name) {
return mkdirsForFile(getProgramFile(name));
}
static File prepareProgramFile(String progID, String name) {
return mkdirsForFile(getProgramFile(progID, name));
}
static Runnable toRunnable(final Object o) {
if (o instanceof Runnable) return (Runnable) o;
return new Runnable() { public void run() { try { callF(o) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; }};
}
static A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(String s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static boolean showAnimationInTopRightCorner_alwaysOnTop = true;
// automatically switches to AWT thread for you
// text is optional text below image
static JWindow showAnimationInTopRightCorner(String imageID, String text) {
if (isHeadless()) return null;
return showAnimationInTopRightCorner(imageIcon(imageID), text);
}
static JWindow showAnimationInTopRightCorner(final BufferedImage image, final String text) {
if (isHeadless()) return null;
return showAnimationInTopRightCorner(imageIcon(image), text);
}
static JWindow showAnimationInTopRightCorner(final ImageIcon imageIcon, final String text) {
if (isHeadless()) return null;
return (JWindow) swingAndWait(new Object() { Object get() { try {
JLabel label = new JLabel(imageIcon);
if (nempty(text)) {
label.setText(text);
label.setVerticalTextPosition(SwingConstants.BOTTOM);
label.setHorizontalTextPosition(SwingConstants.CENTER);
}
final JWindow window = showInTopRightCorner(label);
onClick(label, new Runnable() { public void run() { try { window.dispose() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispose()"; }});
if (showAnimationInTopRightCorner_alwaysOnTop)
window.setAlwaysOnTop(true);
return window;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JLabel label = new JLabel(imageIcon);\r\n if (nempty(text)) {\r\n label.setT..."; }});
}
static JWindow showAnimationInTopRightCorner(final String imageID) {
return showAnimationInTopRightCorner(imageID, "");
}
static JWindow showAnimationInTopRightCorner(String imageID, double seconds) {
return showAnimationInTopRightCorner(imageID, "", seconds);
}
static JWindow showAnimationInTopRightCorner(String imageID, String text, double seconds) {
if (isHeadless()) return null;
return disposeWindowAfter(iround(seconds*1000), showAnimationInTopRightCorner(imageID, text));
}
static JWindow showAnimationInTopRightCorner(BufferedImage img, String text, double seconds) {
return disposeWindowAfter(iround(seconds*1000), showAnimationInTopRightCorner(img, text));
}
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 (Exception __e) { throw rethrow(__e); } }
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
public static JComponent withLabel(String label, JComponent component) {
return westAndCenter(jlabel(label + " "), component);
}
static String uploadToImageServer_new(BufferedImage img, String name) {
byte[] imgData = toPNG(img);
String page = postPage("http://ai1.lol/images/raw/upload", "data", bytesToHex(imgData), "name", name);
print(page);
Matcher m = Pattern.compile("/raw/([0-9]+)").matcher(page);
if (!m.find()) return null;
return "http://ai1.lol/images/raw/" + m.group(1);
}
static void tableEnableDrag(final JTable table, TransferHandler th) {
if (table.getDragEnabled()) {
print("Table drag already enabled");
return;
}
table.setDragEnabled(true);
table.setTransferHandler(th);
table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == 1 && e.getClickCount() == 1)
table.getTransferHandler().exportAsDrag(table, e, TransferHandler.COPY);
}
});
}
static String getSnippetMD5(String id) { try {
return loadPage(new URL("http://tinybrain.de:8080/tb-int/get-md5.php?id=" + parseSnippetID(id)));
} catch (Exception __e) { throw rethrow(__e); } }
static boolean isFalse(Object o) {
return eq(false, o);
}
static long imageServerCheckMD5(String md5) {
assertTrue(isMD5(md5));
String s = loadPage("http://ai1.lol/images/raw/checkmd5/" + md5);
return parseLongOpt(s);
}
static KeyListener enterKeyListener(final Object action) {
return new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER)
pcallF(action);
}
};
}
/** writes safely (to temp file, then rename) */
static File saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists()) try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) { printStackTrace(e); }
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
return file;
} finally {
action.done();
}
}
static File saveTextFile(File fileName, String contents) { try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) { throw rethrow(__e); } }
static String plural(String s) {
return getPlural(s);
}
static String googleImageSearch(String q) {
return (String) call(hotwireOnce("#1010230"), "googleImageSearch", q);
}
static List googleImageSearch_multi(String q) {
return (List) call(hotwireOnce("#1010230"), "googleImageSearch_multi", q);
}
static BufferedImage googleImageSearchFirst(String q) {
return (BufferedImage) call(hotwireOnce("#1010230"), "googleImageSearchFirst", q);
}
static JPanel jrightAlignedLine(final Component... components) {
return swing(new F0() { RightAlignedLine get() { try { return new RightAlignedLine(components) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "RightAlignedLine(components)"; }});
}
static JPanel jrightAlignedLine(List components) {
return jrightAlignedLine(asArray(Component.class, components));
}
static Window getWindow(Object o) {
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof Window) return (Window) c;
c = c.getParent();
}
return null;
}
static void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
static String substanceLAF_defaultSkin = "Creme";
static void substanceLAF() {
substanceLAF(null);
}
static void substanceLAF(String skinName) {
try {
enableSubstance_impl(or2(skinName, substanceLAF_defaultSkin));
} catch (Throwable __e) { printStackTrace2(__e); }
}
static void savePNG(BufferedImage img, File file) { try {
File tempFile = new File(file.getPath() + "_temp");
CriticalAction ca = beginCriticalAction("Save " + f2s(file));
try {
ImageIO.write(img, "png", mkdirsFor(tempFile));
file.delete();
tempFile.renameTo(file);
} finally {
ca.done();
}
} catch (Exception __e) { throw rethrow(__e); } }
// gotta love convenience & program-smartness
static void savePNG(File file, BufferedImage img) {
savePNG(img, file);
}
static void savePNG(File file, RGBImage img) {
savePNG(file, img.getBufferedImage());
}
static String exposeMethods(String s, List methodNames) {
return exposeMethods(s, toStringArray(methodNames)); // TODO: optimize
}
static String exposeMethods(String s, String... methodNames) {
Matches m = new Matches();
if (match("call *", s, m)) {
List l;
if (isIdentifier(m.unq(0)))
l = ll(m.unq(0));
else
l = (List) unstructure(m.unq(0)); // we used to have safeUnstructure here
String method = getString(l, 0);
if (!contains(methodNames, method))
throw fail("Method not allowed: " + method);
return ok2(structure(call(mc(), method, asObjectArray(subList(l, 1)))));
}
return null;
}
static Object load(String varName) {
readLocally(varName);
return get(mc(), varName);
}
static Object load(String progID, String varName) {
readLocally(progID, varName);
return get(mc(), varName);
}
static void frameStandardSize(JFrame frame) {
frame.setBounds(300, 100, 500, 400);
}
static void addIfNotNull(Collection l, A a) {
if (a != null) l.add(a);
}
static JComponent componentToJComponent(Component c) {
if (c instanceof JComponent) return (JComponent) c;
if (c instanceof JFrame) return ((JFrame) c).getRootPane();
if (c == null) return null;
throw fail("boohoo " + getClassName(c));
}
static String shortClassName(Object o) {
if (o == null) return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
// first delay = delay
static Timer installTimer(JComponent component, Object r, long delay) {
return installTimer(component, r, delay, delay);
}
// first delay = delay
static Timer installTimer(RootPaneContainer frame, long delay, Object r) {
return installTimer(frame.getRootPane(), r, delay, delay);
}
// first delay = delay
static Timer installTimer(JComponent component, long delay, Object r) {
return installTimer(component, r, delay, delay);
}
static Timer installTimer(JComponent component, long delay, long firstDelay, Object r) {
return installTimer(component, r, delay, firstDelay);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) {
return installTimer(component, r, delay, firstDelay, true);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) {
return (Timer) swingAndWait(new Object() { Object get() { try {
final Var timer = new Var();
timer.set(new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
try {
if (!allPaused())
if (isFalse(callF(r)))
cancelTimer(timer.get());
} catch (Throwable __e) { printStackTrace2(__e); }
} catch (Throwable __e) { messageBox(__e); }}}));
timer.get().setInitialDelay(toInt(firstDelay));
timer.get().setRepeats(repeats);
bindTimerToComponent(timer.get(), component);
return timer.get();
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final new Var timer;\r\n timer.set(new Timer(toInt(delay), actionListene..."; }});
}
static Timer installTimer(JFrame frame, long delay, long firstDelay, Object r) {
return installTimer(frame.getRootPane(), r, delay, firstDelay);
}
static String showFormSubmitButtonName() {
return "Submit";
}
static A postProcess(Object f, A a) {
return callPostProcessor(f, a);
}
static String programID() {
return getProgramID();
}
static JFrame showPackedFrame(String title, Component contents) {
return packFrame(showFrame(title, contents));
}
static JFrame showPackedFrame(Component contents) {
return packFrame(showFrame(contents));
}
static String md5OfRGBImage(RGBImage img) { try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(intToBytes(img.getWidth()));
int[] pixels = img.getPixels();
for (int i = 0; i < l(pixels); i++)
m.update(intToBytes(pixels[i]));
return bytesToHex(m.digest());
} catch (Exception __e) { throw rethrow(__e); } }
static String editSnippet(String id, String text) {
return editSnippet(id, text,
standardCredentialsUser(), standardCredentialsPass());
}
static String editSnippet(String id, String text, String user, String pass) {
Map query = litmap("id", parseSnippetID(id),
"text", text,
"_user", user,
"_pass", pass,
"len", lUtf8(text));
String url = "http://tinybrain.de:8080/tb-int/update_snippet_text.php";
String page = doPost(query, url);
if (!page.contains("OK"))
throw fail("Error editing snippet " + id + ": " + quote(page));
return page;
}
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 void autoVMExit() {
call(getJavaX(), "autoVMExit");
}
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// access of static fields is not yet optimized
static Object getOpt(Class c, String field) {
try {
if (c == null) return null;
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Map litmap(Object... x) {
HashMap map = new HashMap();
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 JPanel centerAndNorth(final Component c, final Component n) {
return swing(new F0() { JPanel get() { try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.NORTH, wrap(n));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENTER,..."; }});
}
static void tableDependButtons(final JTable table, List extends Component> buttons) {
for (Component c : buttons)
if (c instanceof JButton) {
final JButton b = (JButton) ( c);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
b.setEnabled(table.getSelectedRow() >= 0);
}
});
b.setEnabled(table.getSelectedRow() >= 0);
}
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static JRootPane getRootPane(JFrame f) {
return f == null ? null : f.getRootPane();
}
static A firstComponentOfType(Component c, Class theClass) {
return first(childrenOfType(c, theClass));
}
static JMenu addToMenu(Component c, String menuName, Object... items) {
return addToMenu(getFrame(c), menuName, items);
}
static JMenu addToMenu(final JFrame frame, final String menuName, final Object... items) {
return (JMenu) swing(new Object() { Object get() { try {
JMenuBar bar = addMenuBar(frame);
JMenu menu = getMenuNamed(bar, menuName);
boolean isNew = menu == null;
if (isNew)
menu = new JMenu(menuName);
fillJMenu(menu, items);
if (isNew) {
bar.add(menu);
revalidateFrame(frame);
}
return menu;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JMenuBar bar = addMenuBar(frame);\r\n JMenu menu = getMenuNamed(bar, menuName);..."; }});
}
static int shorten_default = 100;
static String shorten(String s) { return shorten(s, shorten_default); }
static String shorten(String s, int max) {
if (s == null) return "";
if (max < 0) return s;
return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}
static String shorten(int max, String s) { return shorten(s, max); }
static void swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(r));
timer.setRepeats(false);
timer.start();
}
static void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
static void lock(Lock lock) { try {
lock.lockInterruptibly();
} catch (Exception __e) { throw rethrow(__e); } }
static void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static ReentrantLock lock() {
return fairLock();
}
static String getStackTrace2(Throwable throwable) {
return hideCredentials(getStackTrace(throwable) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
hideCredentials(str(getInnerException(throwable)))) + "\n");
}
static void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(r);
} catch (Exception __e) { throw rethrow(__e); } }
static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() { public void run() { try {
result.set(callF(f));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; }});
return result.get();
}
}
static List activateMyFrames() {
final List l = myFrames();
{ swing(new Runnable() { public void run() { try {
for (JFrame f : l)
activateFrame(f);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "for (JFrame f : l)\r\n activateFrame(f);"; }}); }
return l;
}
static JMenuItem jmenuItem(String text, final Object r) {
JMenuItem mi = new JMenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
static String defaultThreadName_name;
static String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static List cloneList(Collection l) {
if (l == null) return new ArrayList();
// assume collection's 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 HashMap findClass_cache = new HashMap();
// 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) {
synchronized(findClass_cache) {
if (findClass_cache.containsKey(name))
return findClass_cache.get(name);
if (!isJavaIdentifier(name)) return null;
Class c;
try {
c = Class.forName("main$" + name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_cache.put(name, c);
return c;
}
}
static Object safeUnstructure(String s) {
return unstructure(s, true);
}
static Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
static void setOpt(Object o, String field, Object value) { try {
if (o == null) return;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
// It's probably a subclass of Map. Use raw method
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null)
smartSet(f, o, value); // possible improvement: skip setAccessible
} catch (Exception __e) { throw rethrow(__e); } }
static void setOpt(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static void swingNowOrLater(Runnable r) {
if (isAWTThread())
r.run();
else
swingLater(r);
}
static List conceptFieldsInOrder(Concept c) {
return conceptFieldsInOrder(c.getClass());
}
static List conceptFieldsInOrder(Class extends Concept> c) {
String order = toStringOpt(getOpt(c, "_fieldOrder"));
Set set = asTreeSet(conceptFields(c));
if (order == null) return asList(set);
List fields = splitAtSpace(order);
setAddAll(fields, set);
return fields;
}
// returns informative message
static String startOrActivate(String progID) {
String msg = activateFramesOf(progID);
if (nempty(msg)) return msg;
nohupJavax(progID);
return fsI(progID) + " nohup-started.";
}
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = (Map) synchroMap(newWeakHashMap());
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl();
return true;
}
// returns true when it slept
static boolean ping_impl() { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
Object action;
synchronized(ping_actions) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static byte[] utf8(String s) {
return toUtf8(s);
}
static int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static int cmp(String a, String b) {
return a == null ? b == null ? 0 : -1 : a.compareTo(b);
}
static int cmp(Object a, Object b) {
if (a == null) return b == null ? 0 : -1;
if (b == null) return 1;
return ((Comparable) a).compareTo(b);
}
static A parentOfType(Component c, Class theClass) {
while (c != null) {
if (isInstance(theClass, c)) return (A) c;
c = c.getParent();
}
return null;
}
static void save(String varName) {
saveLocally(varName);
}
static void save(String progID, String varName) {
saveLocally(progID, varName);
}
static JLabel jcenteredLabel(String text) {
JLabel l = jLabel(text);
l.setHorizontalAlignment(JLabel.CENTER);
return l;
}
static JLabel jcenteredLabel() {
return jcenteredLabel(" ");
}
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) { printStackTrace2(__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)
setTableModel(table, fillTableWithData_makeModel(rows, toStringArray(cols)));
else
fillTableWithData(table, rows, cols);
return table;
}
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 loadPage_silent = new ThreadLocal();
static volatile int loadPage_forcedTimeout; // ms
static ThreadLocal>> loadPage_responseHeaders = new ThreadLocal();
public static String loadPageSilently(String url) { try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (Exception __e) { throw rethrow(__e); } }
public static String loadPageSilently(URL url) { try {
IOException e = null;
for (int tries = 0; tries < loadPage_retries; tries++)
try {
URLConnection con = loadPage_openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPageThroughProxy_enabled) {
print("Trying proxy because of: " + e);
try {
return loadPageThroughProxy(str(url));
} catch (Throwable e2) {
print(" " + exceptionToStringShort(e2));
}
} else if (loadPage_debug)
print(e);
sleepSeconds(1);
}
throw e;
} catch (Exception __e) { throw rethrow(__e); } }
static String loadPage_preprocess(String url) {
if (url.startsWith("tb/")) // don't think we use this anymore
url = tb_mainServer() + "/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
public static String loadPage(String url) { try {
url = loadPage_preprocess(url);
if (!isTrue(loadPage_silent.get()))
print("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (Exception __e) { throw rethrow(__e); } }
public static String loadPage(URL url) {
print("Loading: " + hideCredentials(url.toExternalForm()));
return loadPageSilently(url);
}
static String loadPage(URLConnection con, URL url) throws IOException {
return loadPage(con, url, true);
}
static String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
if (addHeaders) try {
if (!loadPage_anonymous)
setHeaders(con);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
con.setRequestProperty("X-No-Cookies", "1");
} catch (Throwable e) {} // fails if within doPost
String contentType = con.getContentType();
if (contentType == null) {
//printStruct("Headers: ", con.getHeaderFields());
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();
try {
loadPage_responseHeaders.set(con.getHeaderFields());
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = new GZIPInputStream(in);
}
Reader r = new InputStreamReader(in, charset);
StringBuilder buf = new StringBuilder();
int n = 0;
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
if ((n % loadPage_verboseness) == 0) print(" " + n + " chars read");
}
return buf.toString();
} finally { in.close(); }
}
static String loadPage_guessCharset(String contentType) {
Pattern p = Pattern.compile("text/[a-z]+;\\s*charset=([^\\s]+)\\s*");
Matcher m = p.matcher(contentType);
String match = m.matches() ? m.group(1) : null;
if (loadPage_debug)
print("loadPage: contentType=" + contentType + ", match: " + match);
/* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
return or(match, "ISO-8859-1");
}
static URLConnection loadPage_openConnection(URL url) {
URLConnection con = openConnection(url);
if (loadPage_forcedTimeout != 0)
setURLConnectionTimeouts(con, loadPage_forcedTimeout);
return con;
}
static int makeBot(String greeting) {
return makeAndroid3(greeting).port;
}
static Android3 makeBot(Android3 a) {
makeAndroid3(a);
return a;
}
static Android3 makeBot(String greeting, Object responder) {
Android3 a = new Android3(greeting);
a.responder = makeResponder(responder);
makeBot(a);
return a;
}
static Android3 makeBot() {
return makeAndroid3(getProgramTitle() + ".");
}
static List map(Iterable l, Object f) {
return map(f, l);
}
static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null) for (Object o : l)
x.add(callF(f, o));
return x;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }
static List map(Object f, Map map) {
return map(map, f);
}
static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null) for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static boolean conceptLanguageToolTips_enabled;
static void conceptLanguageToolTips() { swing(new Runnable() { public void run() { try {
if (conceptLanguageToolTips_enabled) return;
conceptLanguageToolTips_enabled = true;
{ Thread _t_0 = new Thread("conceptLanguageToolTips") {
public void run() { try {
boolean firstTime = true; // hack fix for tool tip not appearing the first time
String initialMsg = "Move mouse over a concept word to reveal its meaning!";
//repeat with ms sleep 500 {
// Don't respond to "pause" button
while (licensed_noPing()) {
try {
Component c = (Component) componentAtMouse_gen();
if (c instanceof JComponent) {
String word = wordAtMouse(), msg = firstTime ? initialMsg : "";
if (possibleGlobalID(word)) {
Lisp l = getLispTruth(word);
String name = null;
if (l != null)
name = lispToEnglish_prettier(l);
if (name == null)
name = conceptToNameOpt(word); // This reloads AI concepts
if (name != null) {
msg = word + ": " + name;
firstTime = false;
}
}
setToolTipText((JComponent) c, msg);
}
} catch (Throwable __e) { printStackTrace2(__e); }
Thread.sleep(500);
}
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (conceptLanguageToolTips_enabled) return;\r\n conceptLanguageToolTips_enabled ..."; }}); }
static boolean sexyTable_drag = true;
static JTable sexyTable() {
final JTable table = sexyTableWithoutDrag();
if (sexyTable_drag)
tableEnableTextDrag(table); // TODO: seems to interfere with double clicks
return table;
}
static BufferedImage loadPNG(File file) {
return loadBufferedImage(file);
}
// TODO: all the fringe cases (?)
static JPanel hvgrid(List> components) {
if (empty(components)) return new JPanel();
int h = l(components), w = l(first(components));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(h, w));
for (List row : components)
smartAdd(panel, row);
return panel;
}
static JPanel hvgrid(List> components, int gap) {
JPanel panel = hvgrid(components);
GridLayout g = (GridLayout) ( panel.getLayout());
g.setHgap(gap);
g.setVgap(gap);
return panel;
}
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;
}
// action can be Runnable or a function name
static JButton newButton(final String text, final Object action) {
return swing(new F0() { JButton get() { try {
JButton btn = new JButton(text);
if (action != null)
btn.addActionListener(actionListener(action));
return btn;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JButton btn = new JButton(text);\r\n if (action != null)\r\n btn.addActionLi..."; }});
}
static void messageBox(final String msg) {
if (headless()) print(msg);
else { swing(new Runnable() { public void run() { try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MESSAG..."; }}); }
}
static void messageBox(Throwable e) {
showConsole();
printStackTrace(e);
messageBox(str(innerException(e)));
}
// action = runnable or method name
static void onUpdate(JComponent c, final Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
call(r);
}
public void removeUpdate(DocumentEvent e) {
call(r);
}
public void changedUpdate(DocumentEvent e) {
call(r);
}
});
else if (c instanceof ItemSelectable) // JCheckBox and others
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
call(r);
}
});
else
print("Warning: onUpdate doesn't know " + getClassName(c));
}
static void onUpdate(List extends JComponent> l, Object r) {
for (JComponent c : l)
onUpdate(c, r);
}
static Object first(Object list) {
return empty((List) list) ? null : ((List) list).get(0);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static String md5(String text) { try {
if (text == null) return "-";
return bytesToHex(md5_impl(text.getBytes("UTF-8"))); // maybe different than the way PHP does it...
} catch (Exception __e) { throw rethrow(__e); } }
static String md5(byte[] data) {
if (data == null) return "-";
return bytesToHex(md5_impl(data));
}
static MessageDigest md5_md;
/*static byte[] md5_impl(byte[] data) ctex {
if (md5_md == null)
md5_md = MessageDigest.getInstance("MD5");
return ((MessageDigest) md5_md.clone()).digest(data);
}*/
static byte[] md5_impl(byte[] data) { try {
return MessageDigest.getInstance("MD5").digest(data);
} catch (Exception __e) { throw rethrow(__e); } }
static String md5(File file) { try {
return md5(loadBinaryFile(file));
} catch (Exception __e) { throw rethrow(__e); } }
static List ll(A... a) {
return litlist(a);
}
static void fillTableWithData(final JTable table, List rows, List colNames) {
fillTableWithData(table, rows, toStringArray(colNames));
}
// thread-safe
static void fillTableWithData(final JTable table, List rows, String... colNames) {
final DefaultTableModel model = fillTableWithData_makeModel(rows, colNames);
swingNowOrLater(new Runnable() { public void run() { try {
setTableModel(table, model);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setTableModel(table, model);"; }});
}
static DefaultTableModel fillTableWithData_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++) {
Object o = l.get(j);
if (o instanceof BufferedImage) o = imageIcon((BufferedImage) o);
if (o instanceof RGBImage) o = imageIcon((RGBImage) o);
r[j] = o;
}
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) {
public Class getColumnClass(int column) {
return or(_getClass(getValueAt(0, column)), String.class);
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
};
}
static String createSnippet(String text, String title, int type) {
return createSnippet(text, title, type, standardCredentialsUser(), standardCredentialsPass());
}
static String createSnippet(String text, String title, int type, String user, String pass) {
String addURL = "http://tinybrain.de:8080/tb-int/add_snippet.php";
Map query = litmap("type", type,
"high", 1,
"public", 1,
"text", text,
"name", title,
"_user", user,
"_pass", pass);
String answer = doPost(query, addURL);
if (!isSnippetID(answer)) throw fail(answer);
print("Snippet created. " + formatSnippetID(answer));
return formatSnippetID(answer);
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static boolean anyValueContainsIgnoreCase(Map map, String pat) {
for (Object val : values(map))
if (val instanceof String && containsIgnoreCase((String) val, pat))
return true;
return false;
}
static Class mc() {
return main.class;
}
static A jenableUndoRedo(A textcomp) {
final UndoManager undo = new UndoManager();
textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() { public void run() { try {
if (undo.canUndo()) undo.undo()
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canUndo()) undo.undo()"; }}));
textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() { public void run() { try {
if (undo.canRedo()) undo.redo()
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canRedo()) undo.redo()"; }}));
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
return textcomp;
}
static List> rawTableData(JTable t) {
int n = tableRows(t);
List l = new ArrayList();
for (int i = 0; i < n; i++)
l.add(rawTableLineAsMap(t, i));
return l;
}
static void mapPut2(Map map, A key, B value) {
if (map != null && key != null)
if (value != null) map.put(key, value);
else map.remove(key);
}
static JButton setButtonImage(BufferedImage img, JButton btn) {
btn.setIcon(imageIcon(img));
return btn;
}
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 sort(T[] a, Comparator super T> c) {
Arrays.sort(a, c);
}
static void sort(T[] a) {
Arrays.sort(a);
}
static void sort(List a, Comparator super T> c) {
Collections.sort(a, c);
}
static void sort(List a) {
Collections.sort(a);
}
static List concatLists(Collection ... lists) {
List l = new ArrayList();
for (Collection 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 Object nuObject(String className, Object... args) { try {
return nuObject(Class.forName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }
// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
ret nuObject(_getClass(realm, className), args);
}*/
static A nuObject(Class c, Object... args) { try {
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return (A) m.newInstance(args);
} catch (Exception __e) { throw rethrow(__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 fail("Constructor " + c.getName() + getClasses(args) + " not found"
+ (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
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 boolean confirmOKCancel(final Component owner, final String msg) {
return isTrue(swingAndWait(new Object() { Object get() { try { return
JOptionPane.showConfirmDialog(owner,
msg, "JavaX", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JOptionPane.showConfirmDialog(owner,\r\n msg, \"JavaX\", JOptionPane.OK_CANCEL_..."; }}));
}
static boolean confirmOKCancel(String msg) {
return confirmOKCancel(null, msg);
}
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static Object deref(Object o) {
if (o instanceof Derefable) o = ((Derefable) o).get();
return o;
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static Set keys(MultiMap mm) {
return mm.keySet();
}
static JTable dataToTable_uneditable(Object data, final JTable table) {
return dataToTable_uneditable(table, data);
}
static JTable dataToTable_uneditable(final JTable table, final Object data) {
{ swing(new Runnable() { public void run() { try {
dataToTable(table, data, true);
makeTableUneditable(table);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "dataToTable(table, data, true);\r\n makeTableUneditable(table);"; }}); }
return table;
}
static JTable dataToTable_uneditable(final Object data) {
return dataToTable_uneditable(showTable(), data);
}
static JTable dataToTable_uneditable(Object data, String title) {
return dataToTable_uneditable(showTable(title), data);
}
static boolean containsIC(Collection l, String s) {
return containsIgnoreCase(l, s);
}
static boolean containsIC(String[] l, String s) {
return containsIgnoreCase(l, s);
}
static boolean containsIC(String s, char c) {
return containsIgnoreCase(s, c);
}
static boolean containsIC(String a, String b) {
return containsIgnoreCase(a, b);
}
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 derefRef(Object o) {
if (o instanceof Concept.Ref) o = ((Concept.Ref) o).get();
return o;
}
static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static Object[] expandParams(Class c, Object[] params) {
if (l(params) == 1)
params = new Object[] { singleFieldName(c), params[0] };
else
warnIfOddCount(params);
return params;
}
static Class> hotwire(String src) {
assertFalse(_inCore());
Class j = getJavaX();
if (isAndroid()) {
synchronized(j) { // hopefully this goes well...
List libraries = new ArrayList();
File srcDir = (File) call(j, "transpileMain", src, libraries);
if (srcDir == null)
throw fail("transpileMain returned null (src=" + quote(src) + ")");
Object androidContext = get(j, "androidContext");
return (Class) call(j, "loadx2android", srcDir, src);
}
} else {
// ret hotwire_overInternalBot(src);
Class c = (Class) ( call(j, "hotwire", src));
hotwire_copyOver(c);
return c;
}
}
static JButton renameButton(JComponent c, String name) {
JButton b = first(childrenOfType(c, JButton.class));
if (b != null)
b.setText(name);
return b;
}
static JButton renameButton(JComponent c, String oldName, String newName) {
JButton b = findButton(c, oldName);
if (b != null) b.setText(newName);
return b;
}
static String[] conceptFields_drop = {"className", "fieldValues", "id", "created", "refs", "backRefs", "_concepts"};
static Set conceptFields(Concept c) {
return setMinus(mergeSets(allNonStaticFields(c), keys(c.fieldValues)), conceptFields_drop);
}
static Set conceptFields(Class extends Concept> c) {
return setMinus(allNonStaticFields(c), conceptFields_drop);
}
public static String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(File fileName, String defaultContents) {
ping();
try {
if (fileName == null || !fileName.exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(String fileName, String defaultContents) {
return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
}
public static String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer)))
builder.append(buffer, 0, n);
} finally {
reader.close();
}
return builder.toString();
}
static int lUtf8(String s) {
return l(utf8(s));
}
static boolean match(String pat, String s) {
return match3(pat, s);
}
static boolean match(String pat, String s, Matches matches) {
return match3(pat, s, matches);
}
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 boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
return structure(o, new structure_Data());
}
static String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack))
popLast(d.stack).run();
}
static void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static class structure_Data {
PrintWriter out;
int stringSizeLimit;
int shareStringsLongerThan = 20;
boolean noStringSharing;
IdentityHashMap seen = new IdentityHashMap();
//new BitSet refd;
HashMap strings = new HashMap();
HashSet concepts = new HashSet();
HashMap> fieldsByClass = new HashMap();
int n; // token count
List stack = new ArrayList();
// append single token
structure_Data append(String token) { out.print(token); ++n; return this; }
structure_Data append(int i) { out.print(i); ++n; return this; }
// append multiple tokens
structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; }
// extend last token
structure_Data app(String token) { out.print(token); return this; }
structure_Data app(int i) { out.print(i); return this; }
}
static void structure_1(final Object o, final structure_Data d) {
if (o == null) { d.append("null"); return; }
Class c = o.getClass();
boolean concept = false;
concept = o instanceof Concept;
List lFields = d.fieldsByClass.get(c);
if (lFields == null) {
// these are never back-referenced (for readability)
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; }
if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; }
if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; }
if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; }
if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; }
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f"); return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o)); return;
}
if (o instanceof File) {
d.append("File ").append(quote(((File) o).getPath())); return;
}
// referencable objects follow
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null) ref = d.strings.get((String) o);
if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
if (!(o instanceof String))
d.seen.put(o, d.n); // record token number
else {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out); d.n++; return;
}
if (o instanceof HashSet) {
d.append("hashset ");
structure_1(new ArrayList((Set) o), d);
return;
}
if (o instanceof TreeSet) {
d.append("treeset ");
structure_1(new ArrayList((Set) o), d);
return;
}
String name = c.getName();
if (o instanceof Collection
&& !startsWith(name, "main$")
/* && neq(name, "main$Concept$RefL") */) {
d.append("[");
final int l = d.n;
final Iterator it = ((Collection) o).iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.stack...."; }});
return;
}
if (o instanceof Map && !startsWith(name, "main$")) {
if (o instanceof LinkedHashMap) d.append("lhm");
else if (o instanceof HashMap) d.append("hm");
d.append("{");
final int l = d.n;
final Iterator it = ((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
boolean v;
Map.Entry e;
public void run() {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(e.getKey(), d);
}
}
}
});
return;
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o))); return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return;
}
String atype = "array", sep = ", ";
if (o instanceof int[]) {
//ret "intarray " + quote(intArrayToHex((int[]) o));
atype = "intarray";
sep = " ";
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0) d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
if (d.n != l) d.append(", ");
d.append(i);
}
d.append("}"); return;
}
// Need more cases? This should cover all library classes...
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o))); return; // Hm. this is not unstructure-able
}
if (o instanceof Lisp) {
d.append("l(", 2);
final Lisp lisp = (Lisp) ( o);
structure_1(lisp.head, d);
final Iterator it = lisp.args.iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext())
d.append(")");
else {
d.stack.add(this);
d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\")\");\r\n else {\r\n d...."; }});
return;
}
/*if (name.equals("main$Lisp")) {
fail("lisp not supported right now");
}*/
String dynName = shortDynamicClassName(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
// serialize an object with fields.
// first, collect all fields and values in fv.
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
continue;
String fieldName = field.getName();
fields.add(field);
// put special cases here...
}
cc = cc.getSuperclass();
}
lFields = asList(fields);
// Render this$1 first because unstructure needs it for constructor call.
for (int i = 0; i < l(lFields); i++) {
Field f = lFields.get(i);
if (f.getName().equals("this$1")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
d.fieldsByClass.put(c, lFields);
} // << if (lFields == null)
else { // ref handling for lFields != null
Integer ref = d.seen.get(o);
if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
d.seen.put(o, d.n); // record token number
}
LinkedHashMap fv = new LinkedHashMap();
for (Field f : lFields) {
Object value;
try {
value = f.get(o);
} catch (Exception e) {
value = "?";
}
if (value != null)
fv.put(f.getName(), value);
}
String name = c.getName();
String shortName = dropPrefix("main$", name);
// Now we have fields & values. Process fieldValues if it's a DynamicObject.
// omit field "className" if equal to class's name
if (concept && eq(fv.get("className"), shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
fv.putAll((Map) fv.get("fieldValues"));
fv.remove("fieldValues");
shortName = shortDynamicClassName(o);
fv.remove("className");
}
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
d.append(shortName);
final int l = d.n;
final Iterator it = fv.entrySet().iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext()) {
if (d.n != l)
d.append(")");
} else {
Map.Entry e = (Map.Entry) it.next();
d.append(d.n == l ? "(" : ", ");
d.append((String) e.getKey()).append("=");
d.stack.add(this);
structure_1(e.getValue(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else {\r..."; }});
}
static String rgbMD5(RGBImage img) {
return md5OfRGBImage(img);
}
static int randomID_defaultLength = 12;
static String randomID(int length) {
return makeRandomID(length);
}
static String randomID() {
return randomID(randomID_defaultLength);
}
static long round(double d) {
return Math.round(d);
}
static Font typeWriterFont() {
return typeWriterFont(14);
}
static Font typeWriterFont(int size) {
return new Font("Courier", Font.PLAIN, size);
}
static List beginCriticalAction_inFlight = synchroList();
static class CriticalAction {
String description;
CriticalAction() {}
CriticalAction(String description) {
this.description = description;}
void done() {
beginCriticalAction_inFlight.remove(this);
}
}
static CriticalAction beginCriticalAction(String description) {
ping();
CriticalAction c = new CriticalAction(description);
beginCriticalAction_inFlight.add(c);
return c;
}
static void cleanMeUp_beginCriticalAction() {
int n = 0;
while (nempty(beginCriticalAction_inFlight)) {
int m = l(beginCriticalAction_inFlight);
if (m != n) {
n = m;
try {
print("Waiting for " + n(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
} catch (Throwable __e) { printStackTrace2(__e); }
}
sleepInCleanUp(10);
}
}
static A disposeWindowAfter(int delay, final A w) {
if (w != null)
swingLater(delay, new Runnable() { public void run() { try {
w.dispose();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "w.dispose();"; }});
return w;
}
static String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[a.length-n];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static List dropLast(List l) {
return subList(l, 0, l(l)-1);
}
static List dropLast(int n, List l) {
return subList(l, 0, l(l)-n);
}
static List dropLast(Iterable l) {
return dropLast(asList(l));
}
static String dropLast(String s) {
return substring(s, 0, l(s)-1);
}
static String dropLast(String s, int n) {
return substring(s, 0, l(s)-n);
}
static String dropLast(int n, String s) {
return dropLast(s, n);
}
static String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder((int) (l(s)*1.5+2));
quote_impl(s, out);
return out.toString();
}
static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else
out.append(c);
}
out.append('"');
}
static String quoteCharacter(char c) {
if (c == '\'') return "'\\''";
if (c == '\\') return "'\\\\'";
if (c == '\r') return "'\\r'";
if (c == '\n') return "'\\n'";
if (c == '\t') return "'\\t'";
return "'" + c + "'";
}
static JTextArea wrappedTextArea(JTextArea ta) {
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
return ta;
}
static JTextArea wrappedTextArea() {
return wrappedTextArea(jtextarea());
}
static JTextArea wrappedTextArea(String text) {
JTextArea ta = wrappedTextArea();
ta.setText(text);
return ta;
}
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 HashSet litset(A... items) {
return lithashset(items);
}
static Throwable printStackTrace(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
return e;
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
/*static void printStackTrace(S indent, Throwable e) {
if (endsWithLetter(indent)) indent += " ";
printIndent(indent, getStackTrace(e));
}*/
static String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix)) return s;
return replacement + substring(s, l(prefix));
}
static JMenuBar addMenuBar(JFrame f) {
if (f == null) return null;
JMenuBar bar = f.getJMenuBar();
if (bar == null) {
f.setJMenuBar(bar = new JMenuBar());
revalidateFrame(f);
}
return bar;
}
static JMenuBar addMenuBar(Component c) {
return addMenuBar(getFrame(c));
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static JWindow showInTopRightCorner(Component c) {
JWindow w = new JWindow();
w.add(c);
w.pack();
moveToTopRightCorner(w);
w.setVisible(true);
return w;
}
static Lisp getLispTruth(String id) {
LispStatement s = lispStatements_cached().get(id);
return s == null ? null : s.term;
}
static String getType(Object o) {
return getClassName(o);
}
static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
static void showConsole() {
showFrame(consoleFrame());
}
static String dropSuffixIgnoreCase(String suffix, String s) {
return ewic(s, suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static void setTableModel(JTable table, TableModel model) {
Map widths = tableColumnWidthsByName(table);
int[] i = table.getSelectedRows();
table.setModel(model);
int n = model.getRowCount();
ListSelectionModel sel = table.getSelectionModel();
for (int j = 0; j < i.length; j++)
if (i[j] < n)
sel.addSelectionInterval(i[j], i[j]);
tableSetColumnPreferredWidths(table, widths);
}
static Set mergeSets(Set ... l) {
return joinSets(l);
}
static Class __javax;
static Class getJavaX() {
return __javax;
}
static void setHeaders(URLConnection con) throws IOException {
String computerID = getComputerID_quick();
if (computerID != null) try {
con.setRequestProperty("X-ComputerID", computerID);
con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
} catch (Throwable e) {
//printShortException(e);
}
}
static String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = unnull(e.getMessage());
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + ": " + msg;
else
return msg;
}
static Throwable getInnerException(Throwable e) {
while (e.getCause() != null)
e = e.getCause();
return e;
}
static String boolArrayToHex(boolean[] a) {
return bytesToHex(boolArrayToBytes(a));
}
static boolean match3(String pat, String s) {
return match3(pat, s, null);
}
static boolean match3(String pat, String s, Matches matches) {
if (pat == null || s == null) return false;
return match3(pat, parse3_cached(s), matches);
}
static boolean match3(String pat, List toks, Matches matches) {
List tokpat = parse3(pat);
return match3(tokpat,toks,matches);
}
static boolean match3(List tokpat, List toks, Matches matches) {
String[] m = match2(tokpat, toks);
//print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
if (m == null) return false;
if (matches != null) matches.m = m; return true;
}
// An "Android" is a program that accepts text questions (on console or TCP) and outputs one response text per question
static boolean makeAndroid3_disable; // disable all android making
static class Android3 {
String greeting;
boolean publicOverride; // optionally set this in client
int startPort = 5000; // optionally set this in client
Responder responder;
boolean console = true;
boolean quiet; // no messages on console
boolean daemon = false;
boolean incomingSilent = false;
int incomingPrintLimit = 200;
boolean useMultiPort = true;
boolean recordHistory;
boolean verbose;
int answerPrintLimit = 500;
boolean newLineAboveAnswer, newLineBelowAnswer;
// set by system
int port;
long vport;
DialogHandler handler;
ServerSocket server;
Android3(String greeting) {
this.greeting = greeting;}
Android3() {}
synchronized void dispose() {
if (server != null) {
try {
server.close();
} catch (IOException e) {
print("[internal] " + e);
}
server = null;
}
if (vport != 0) try {
print("Disposing " + this);
removeFromMultiPort(vport);
vport = 0;
} catch (Throwable __e) { printStackTrace2(__e); }
}
public String toString() { return "Bot: " + greeting + " [vport " + vport + "]"; }
}
static abstract class Responder {
abstract String answer(String s, List history);
}
static Android3 makeAndroid3(final String greeting) {
return makeAndroid3(new Android3(greeting));
}
static Android3 makeAndroid3(final String greeting, Responder responder) {
Android3 android = new Android3(greeting);
android.responder = responder;
return makeAndroid3(android);
}
static Android3 makeAndroid3(final Android3 a) {
if (makeAndroid3_disable) return a;
if (a.responder == null)
a.responder = new Responder() {
String answer(String s, List history) {
return callStaticAnswerMethod(s, history);
}
};
if (!a.quiet)
print("[bot] " + a.greeting);
if (a.console && makeAndroid3_consoleInUse() && !readLine_noReadLine) a.console = false;
record(a);
if (a.useMultiPort)
a.vport = addToMultiPort(a.greeting,
makeAndroid3_verboseResponder(a));
if (a.console)
makeAndroid3_handleConsole(a);
if (a.useMultiPort) return a;
a.handler = makeAndroid3_makeDialogHandler(a);
if (a.quiet) startDialogServer_quiet.set(true);
try {
a.port = a.daemon
? startDialogServerOnPortAboveDaemon(a.startPort, a.handler)
: startDialogServerOnPortAbove(a.startPort, a.handler);
} finally {
startDialogServer_quiet.set(null);
}
a.server = startDialogServer_serverSocket;
return a;
}
static void makeAndroid3_handleConsole(final Android3 a) {
// Console handling stuff
if (!a.quiet)
print("You may also type on this console.");
{ Thread _t_0 = new Thread() {
public void run() { try {
List history = new ArrayList();
while (licensed()) {
String line;
try {
line = readLine();
} catch (Throwable e) {
print(getInnerMessage(e));
break;
}
if (line == null) break;
/*if (eq(line, "bye")) {
print("> bye stranger");
history = new ArrayList();
} else*/ {
history.add(line);
history.add(makeAndroid3_getAnswer(line, history, a)); // prints answer on console too
}
}
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
}
static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
return new DialogHandler() {
public void run(final DialogIO io) {
if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
io.sendLine("Sorry, not allowed");
return;
}
String dialogID = randomID(8);
io.sendLine(a.greeting + " / Your ID: " + dialogID);
List history = new ArrayList();
while (io.isStillConnected()) {
if (io.waitForLine()) {
final String line = io.readLineNoBlock();
String s = dialogID + " at " + now() + ": " + quote(line);
if (!a.incomingSilent)
print(shorten(s, a.incomingPrintLimit));
if (eq(line, "bye")) {
io.sendLine("bye stranger");
return;
}
Matches m = new Matches();
if (a.recordHistory)
history.add(line);
String answer;
if (match3("this is a continuation of talk *", s, m)
|| match3("hello bot! this is a continuation of talk *", s, m)) {
dialogID = unquote(m.m[0]);
answer = "ok";
} else try {
makeAndroid3_io.set(io);
answer = makeAndroid3_getAnswer(line, history, a);
} finally {
makeAndroid3_io.set(null);
}
if (a.recordHistory)
history.add(answer);
io.sendLine(answer);
//appendToLog(logFile, s);
}
}
}};
}
static String makeAndroid3_getAnswer(String line, List history, Android3 a) {
String answer, originalAnswer;
try {
originalAnswer = a.responder.answer(line, history);
answer = makeAndroid3_fallback(line, history, originalAnswer);
} catch (Throwable e) {
e = getInnerException(e);
printStackTrace(e);
originalAnswer = answer = e.toString();
}
if (!a.incomingSilent) {
if (originalAnswer == null) originalAnswer = "?";
if (a.newLineAboveAnswer) print();
print(">" + dropFirst(indentx(2, shorten(rtrim(originalAnswer), a.answerPrintLimit))));
if (a.newLineBelowAnswer) print();
}
return answer;
}
static String makeAndroid3_fallback(String s, List history, String answer) {
// Now we only do the safe thing instead of VM inspection - give out our process ID
if (answer == null && match3("what is your pid", s))
return getPID();
if (answer == null && match3("what is your program id", s)) // should be fairly safe, right?
return getProgramID();
if (match3("get injection id", s))
return getInjectionID();
if (answer == null) answer = "?";
if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
answer = quote(answer);
return answer;
}
static boolean makeAndroid3_consoleInUse() {
for (Object o : record_list)
if (o instanceof Android3 && ((Android3) o).console)
return true;
return false;
}
static Responder makeAndroid3_verboseResponder(final Android3 a) {
return new Responder() {
String answer(String s, List history) {
if (a.verbose)
print("> " + shorten(s, a.incomingPrintLimit));
String answer = a.responder.answer(s, history);
if (a.verbose)
print("< " + shorten(answer, a.incomingPrintLimit));
return answer;
}
};
}
static ThreadLocal makeAndroid3_io = new ThreadLocal();
static Android3 makeAndroid3() {
return makeAndroid3(getProgramTitle() + ".");
}
static A setToolTipText(final A c, final Object toolTip) {
if (c == null) return null;
{ swing(new Runnable() { public void run() { try {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ..."; }}); }
return c;
}
static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static Class _getClass(Object o) {
return o == null ? null
: o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) { try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (Exception __e) { throw rethrow(__e); } }
static String getStackTrace(Throwable throwable) {
lastException(throwable);
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static String getProgramTitle() {
return getProgramName();
}
static URLConnection openConnection(URL url) { try {
ping();
callOpt(javax(), "recordOpenURLConnection", str(url));
return url.openConnection();
} catch (Exception __e) { throw rethrow(__e); } }
static String wordAtMouse() {
return (String) swing(new Object() { Object get() { try {
Component c = (Component) componentAtMouse_gen();
if (c instanceof JTextComponent) {
JTextComponent tc = (JTextComponent) ( c);
Point d = mouseToComponent(c);
int idx = tc.viewToModel(d);
String text = tc.getText();
return wordAroundIndex(text, idx);
}
return "";
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Component c = (Component) componentAtMouse_gen();\r\n if (c instanceof JTextCom..."; }});
}
static boolean hasMethod(Object o, String method, Object... args) {
return findMethod(o, method, args) != null;
}
static void saveLocally(String variableName) {
saveLocally(programID(), variableName);
}
static void saveLocally(String progID, String variableName) {
saveLocally2(mc(), progID, variableName);
}
static void saveLocally2(Object obj, String variableName) {
saveLocally2(obj, programID(), variableName);
}
static void saveLocally2(Object obj, String progID, String variableName) {
Lock _lock_575 = saveLock(); lock(_lock_575); try {
File textFile = new File(programDir(progID), variableName + ".text");
File structureFile = new File(programDir(progID), variableName + ".structure");
Object x = get(obj, variableName);
if (x == null) {
textFile.delete();
structureFile.delete();
} else if (x instanceof String) {
saveTextFile(textFile, (String) x);
structureFile.delete();
} else {
saveTextFile(structureFile, javaTokWordWrap(structure(x)));
textFile.delete();
}
} finally { _lock_575.unlock(); } }
static TreeSet asTreeSet(List l) {
TreeSet set = new TreeSet();
for (Object o : l)
if (o != null)
set.add(o);
return set;
}
static TreeSet asTreeSet(Set set) {
return set instanceof TreeSet ? (TreeSet) set : new TreeSet(set);
}
volatile static boolean conceptsAndBot_running;
static void conceptsAndBot() {
conceptsAndBot(null);
}
static void conceptsAndBot(Integer autoSaveInterval) {
if (conceptsAndBot_running) return;
conceptsAndBot_running = true;
try {
ensureDBNotRunning(dbBotStandardName());
} catch (Throwable _e) {
mainConcepts.dontSave = true; // SAFETY
throw rethrow(_e); }
if (autoSaveInterval != null)
loadAndAutoSaveConcepts(autoSaveInterval);
else
loadAndAutoSaveConcepts();
dbBot();
}
static byte[] toUtf8(String s) { try {
return s.getBytes("UTF-8");
} catch (Exception __e) { throw rethrow(__e); } }
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static List emptyList(int capacity) {
return new ArrayList(capacity);
}
// Try to match capacity
static List emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static FileOutputStream newFileOutputStream(File path) throws IOException {
return newFileOutputStream(path.getPath());
}
static FileOutputStream newFileOutputStream(String path) throws IOException {
return newFileOutputStream(path, false);
}
static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
FileOutputStream f = new // Line break for ancient translator
FileOutputStream(path, append);
callJavaX("registerIO", f, path, true);
return f;
}
static Object[] asObjectArray(List l) {
return toObjectArray(l);
}
static boolean checkConceptFields(Concept x, Object... data) {
for (int i = 0; i < l(data); i += 2)
if (neq(cget(x, (String) data[i]), deref(data[i+1])))
return false;
return true;
}
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 boolean containsIgnoreCase(Collection l, String s) {
for (String x : l)
if (eqic(x, s))
return true;
return false;
}
static boolean containsIgnoreCase(String[] l, String s) {
for (String x : l)
if (eqic(x, s))
return true;
return false;
}
static boolean containsIgnoreCase(String s, char c) {
return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}
static boolean containsIgnoreCase(String a, String b) {
return indexOfIgnoreCase(a, b) >= 0;
}
static List myFrames() {
return (List) swing(new Object() { Object get() { try {
Map map = (Map) getOpt(mc(), "makeFrame_myFrames");
return map == null ? new ArrayList() : asList(keys(map));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Map map = (Map) getOpt(mc(), \"makeFrame_myFrames\");\r\n ret ma..."; }});
}
public static byte[] loadBinaryFile(String fileName) {
try {
if (!new File(fileName).exists())
return null;
FileInputStream in = new FileInputStream(fileName);
byte buf[] = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream();
int l;
while (true) {
l = in.read(buf);
if (l <= 0) break;
out.write(buf, 0, l);
}
in.close();
return out.toByteArray();
} catch (IOException e) { throw new RuntimeException(e); }
}
public static byte[] loadBinaryFile(File file) {
return loadBinaryFile(file.getPath());
}
static A popLast(List l) {
return liftLast(l);
}
static Runnable _topLevelErrorHandling(final Runnable runnable) {
return new Runnable() { public void run() { try { try { runnable.run(); } catch (Throwable __e) { printStackTrace2(__e); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall { runnable.run(); }"; }};
}
static JMenu getMenuNamed(JMenuBar bar, String name) {
int n = bar.getMenuCount();
for (int i = 0; i < n; i++) {
JMenu m = bar.getMenu(i);
if (m != null && eq(m.getText(), name))
return m;
}
return null;
}
static String lower(String s) {
return s == null ? null : s.toLowerCase();
}
static char lower(char c) {
return Character.toLowerCase(c);
}
static boolean odd(int i) {
return (i & 1) != 0;
}
static boolean odd(long i) {
return (i & 1) != 0;
}
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;
}
static void bindTimerToComponent(final Timer timer, JFrame f) {
bindTimerToComponent(timer, f.getRootPane());
}
static void bindTimerToComponent(final Timer timer, JComponent c) {
if (c.isShowing())
timer.start();
c.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
timer.start();
}
public void ancestorRemoved(AncestorEvent event) {
timer.stop();
}
public void ancestorMoved(AncestorEvent event) {
}
});
}
static boolean _inCore() {
return false;
}
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 ArrayList litlist(A... a) {
return new ArrayList (Arrays.asList(a));
}
static void cancelTimer(javax.swing.Timer timer) {
if (timer != null) timer.stop();
}
static void nohupJavax(final String javaxargs) {
{ Thread _t_0 = new Thread() {
public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs); } catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
}
static void nohupJavax(final String javaxargs, final String vmArgs) {
{ Thread _t_1 = new Thread() {
public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs); } catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_1); }
}
static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static void fillJMenu(JMenu m, Object... x) {
if (x == null) return;
for (int i = 0; i < l(x); i++) {
Object o = x[i], y = get(x, i+1);
if (o instanceof List)
fillJMenu(m, asArray((List) o));
else if (eqOneOf(o, "***", "---", "===", ""))
m.addSeparator();
else if (o instanceof String && isRunnableX(y)) {
m.add(jmenuItem((String) o, y));
++i;
} else if (o instanceof JMenuItem)
m.add((JMenuItem) o); // "call" might use wrong method
else if (o instanceof String || o instanceof Action || o instanceof Component)
call(m, "add", o);
else
print("Unknown menu item: " + o);
}
}
static String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static A assertEquals(Object x, A y) {
return assertEquals(null, x, y);
}
static A assertEquals(String msg, Object x, A y) {
if (!(x == null ? y == null : x.equals(y)))
throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
return y;
}
static String programTitle() {
return getProgramName();
}
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 boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static String lispToEnglish_prettier(Lisp l) {
if (l == null) return "";
String pattern = conceptToNameOpt(lispForwardRawOrSame("omrvwjslbkffaxoj", l.head));
if (empty(pattern)) return clUnparse(l);
List args = map("lispToEnglish_prettier", l.args);
String s = formatXYZ_appendRest(pattern, args);
return s;
}
static void onClick(JComponent c, final Object runnable) {
c.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
callF(runnable, e);
}
});
}
// re-interpreted for buttons
static void onClick(JButton btn, final Object runnable) {
onEnter(btn, runnable);
}
static JLabel jLabel(String text) {
return jlabel(text);
}
static JLabel jLabel() {
return jlabel();
}
static byte[] intToBytes(int i) {
return new byte[] {
(byte) (i >>> 24),
(byte) (i >>> 16),
(byte) (i >>> 8),
(byte) i};
}
static void quoteToPrintWriter(String s, PrintWriter out) {
if (s == null) { out.print("null"); return; }
out.print('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"') {
out.print('\\'); out.print(c);
} else if (c == '\r')
out.print("\\r");
else if (c == '\n')
out.print("\\n");
else
out.print(c);
}
out.print('"');
}
static String singleFieldName(Class c) {
Set l = listFields(c);
if (l(l) != 1)
throw fail("No single field found in " + c + " (have " + n(l(l), "fields") + ")");
return first(l);
}
static boolean licensed_noPing() {
return licensed_yes;
}
static JWindow showWindow(Component c) {
JWindow w = new JWindow();
w.add(wrap(c));
return w;
}
static void scanForComponents(Component c, Class theClass, List l) {
if (theClass.isInstance(c))
l.add((A) c);
if (c instanceof Container)
for (Component comp : ((Container) c).getComponents())
scanForComponents(comp, theClass, l);
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static String substring(String s, int x) {
return substring(s, x, l(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
if (x > s.length()) return "";
if (y < x) y = x;
if (y > s.length()) y = s.length();
return s.substring(x, y);
}
static final WeakHashMap> getOpt_cache = new WeakHashMap();
static final HashMap getOpt_special = new HashMap(); // just a marker
static {
getOpt_cache.put(Class.class, getOpt_special);
getOpt_cache.put(String.class, getOpt_special);
}
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
/*if (o instanceof S)
ret getOpt(getBot((S) o), field);*/
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
f.setAccessible(true);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
getOpt_cache.put(c, map);
return map;
}
static Object sleepQuietly_monitor = new Object();
static void sleepQuietly() { try {
assertFalse(isAWTThread());
synchronized(sleepQuietly_monitor) { sleepQuietly_monitor.wait(); }
} catch (Exception __e) { throw rethrow(__e); } }
static Map rawTableLineAsMap(JTable tbl, int row) {
if (row >= 0 && row < tbl.getModel().getRowCount()) {
Map map = litorderedmap(); // keep order of columns
for (int i = 0; i < tbl.getModel().getColumnCount(); i++)
mapPut(map, tbl.getModel().getColumnName(i),
tbl.getModel().getValueAt(row, i));
return map;
}
return null;
}
static String ok2(String s) {
return "ok " + s;
}
public static File mkdirsFor(File file) {
return mkdirsForFile(file);
}
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 A or(A a, A b) {
return a != null ? a : b;
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static boolean isMD5(String s) {
return l(s) == 32 && isLowerHexString(s);
}
static void smartSet(Field f, Object o, Object value) throws Exception {
f.setAccessible(true);
// take care of common case (long to int)
if (f.getType() == int.class && value instanceof Long)
value = ((Long) value).intValue();
try {
f.set(o, value);
} catch (Exception e) {
try {
if (f.getType() == Concept.Ref.class) {
f.set(o, ((Concept) o).new Ref((Concept) value));
return;
}
if (o instanceof Concept.Ref) {
f.set(o, ((Concept.Ref) o).get());
return;
}
} catch (Throwable _e) {}
throw e;
}
}
static Set allNonStaticFields(Object o) {
TreeSet fields = new TreeSet();
Class _c = _getClass(o);
do {
for (Field f : _c.getDeclaredFields())
if ((f.getModifiers() & Modifier.STATIC) == 0)
fields.add(f.getName());
_c = _c.getSuperclass();
} while (_c != null);
return fields;
}
static int moveToTopRightCorner_inset = 20;
static A moveToTopRightCorner(A a) {
Window w = getWindow(a);
if (w != null)
w.setLocation(getScreenSize().width-w.getWidth()-moveToTopRightCorner_inset, moveToTopRightCorner_inset);
return a;
}
static int stdcompare(Number a, Number b) {
return cmp(a, b);
}
static int stdcompare(String a, String b) {
return cmp(a, b);
}
static int stdcompare(long a, long b) {
return a < b ? -1 : a > b ? 1 : 0;
}
static int stdcompare(Object a, Object b) {
return cmp(a, b);
}
static Object[] asArray(List l) {
return toObjectArray(l);
}
static A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static final HashMap> callMC_cache = new HashMap();
static String callMC_key;
static Method callMC_value;
// varargs assignment fixer for a single string array argument
static Object callMC(String method, String[] arg) {
return callMC(method, new Object[] {arg});
}
static Object callMC(String method, Object... args) { try {
Method me;
synchronized(callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null) return callMC_value.invoke(null, args);
List m;
synchronized(callMC_cache) {
m = callMC_cache.get(method);
}
if (m == null) {
if (callMC_cache.isEmpty()) {
callMC_makeCache();
m = callMC_cache.get(method);
}
if (m == null) throw fail("Method named " + method + " not found in main");
}
int n = m.size();
if (n == 1) {
me = m.get(0);
synchronized(callMC_cache) {
callMC_key = method;
callMC_value = me;
}
return me.invoke(null, args);
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return me.invoke(null, args);
}
throw fail("No method called " + method + " with matching arguments found in main");
} catch (Exception __e) { throw rethrow(__e); } }
static void callMC_makeCache() {
synchronized(callMC_cache) {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods())
if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
m.setAccessible(true);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
static boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
// TODO: test if android complains about this
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isAWTThread_awt();
}
static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static String shortDynamicClassName(Object o) {
if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
return ((DynamicObject) o).className;
return shortClassName(o);
}
static Thread currentThread() {
return Thread.currentThread();
}
static JPanel smartAdd(JPanel panel, List parts) {
for (Object o : parts)
addToContainer(panel, wrapForSmartAdd(o));
return panel;
}
static JPanel smartAdd(JPanel panel, Object... parts) {
return smartAdd(panel, asList(parts));
}
static boolean allPaused() {
return ping_pauseAll;
}
// Substance
// Trident (required by Substance)
static void enableSubstance_impl(final String skinName) { swing(new Runnable() { public void run() { try {
if (!substanceLookAndFeelEnabled())
enableSubstance_impl_2(skinName);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!substanceLookAndFeelEnabled())\r\n enableSubstance_impl_2(skinName);"; }}); }
static void enableSubstance_impl_2(String skinName) { try {
boolean wasEnabled = substanceLookAndFeelEnabled();
ClassLoader cl = main.class.getClassLoader();
UIManager.getDefaults().put("ClassLoader", cl);
Thread.currentThread().setContextClassLoader(cl);
String skinClassName = "org.pushingpixels.substance.api.skin." + addSuffix(skinName, "Skin");
SubstanceSkin skin = (SubstanceSkin) nuObject(cl.loadClass(skinClassName));
SubstanceLookAndFeel.setSkin(skin);
JFrame.setDefaultLookAndFeelDecorated(true);
updateLookAndFeelOnAllWindows_noRenew();
if (!wasEnabled) renewConsoleFrame();
if (substanceLookAndFeelEnabled())
print("Substance L&F enabled.");
else
print("Could not enable Substance L&F?");
} catch (Exception __e) { throw rethrow(__e); } }
static JPanel westAndCenter(final Component w, final Component c) {
return swing(new F0() { JPanel get() { try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.WEST, wrap(w));
panel.add(BorderLayout.CENTER, wrap(c));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST, w..."; }});
}
static String programID;
static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
// TODO: ask JavaX instead
static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static Object unstructure(String text) {
return unstructure(text, false);
}
static Object unstructure(String text, final boolean allDynamic) {
return unstructure(text, allDynamic, null);
}
static int structure_internStringsLongerThan = 50;
static int unstructure_tokrefs; // stats
abstract static class unstructure_Receiver {
abstract void set(Object o);
}
// classFinder: func(name) -> class (optional)
static Object unstructure(String text, boolean allDynamic,
Object classFinder) {
if (text == null) return null;
return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
}
static Object unstructure_reader(BufferedReader reader) {
return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
}
static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object classFinder) {
final boolean debug = unstructure_debug;
final class X {
int i = -1;
HashMap refs = new HashMap();
HashMap tokrefs = new HashMap();
HashSet concepts = new HashSet();
HashMap classesMap = new HashMap();
List stack = new ArrayList();
String curT;
// look at current token
String t() {
return curT;
}
// get current token, move to next
String tpp() {
String t = curT;
consume();
return t;
}
void parse(final unstructure_Receiver out) {
String t = t();
int refID = 0;
if (structure_isMarker(t, 0, l(t))) {
refID = parseInt(t.substring(1));
consume();
}
final int _refID = refID;
// if (debug) print("parse: " + quote(t));
final int tokIndex = i;
parse_inner(refID, tokIndex, new unstructure_Receiver() {
void set(Object o) {
if (_refID != 0)
refs.put(_refID, o);
if (o != null)
tokrefs.put(tokIndex, o);
out.set(o);
}
});
}
void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) {
String t = t();
// if (debug) print("parse_inner: " + quote(t));
Class c = classesMap.get(t);
if (c == null) {
if (t.startsWith("\"")) {
String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
out.set(s); return;
}
if (t.startsWith("'")) {
out.set(unquoteCharacter(tpp())); return;
}
if (t.equals("bigint")) {
out.set(parseBigInt()); return;
}
if (t.equals("d")) {
out.set(parseDouble()); return;
}
if (t.equals("fl")) {
out.set(parseFloat()); return;
}
if (t.equals("false") || t.equals("f")) {
consume(); out.set(false); return;
}
if (t.equals("true") || t.equals("t")) {
consume(); out.set(true); return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
//if (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t));
if (isLongConstant(t)) {
out.set(parseLong(t)); return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
if (debug)
print("l=" + l + ", isInt: " + isInt);
out.set(isInt ? (Object) new Integer((int) l) : (Object) new Long(l)); return;
}
if (t.equals("File")) {
consume();
File f = new File(unquote(tpp()));
out.set(f); return;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
print("Warning: unsatisfied back reference " + ref);
out.set(o); return;
}
if (t.startsWith("t") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = tokrefs.get(ref);
if (o == null)
print("Warning: unsatisfied token reference " + ref);
out.set(o); return;
}
if (t.equals("hashset")) {
parseHashSet(out); return;
}
if (t.equals("treeset")) {
parseTreeSet(out); return;
}
if (eqOneOf(t, "hashmap", "hm")) {
consume();
parseMap(new HashMap(), out);
return;
}
if (t.equals("lhm")) {
consume();
parseMap(new LinkedHashMap(), out);
return;
}
if (t.equals("{")) {
parseMap(out); return;
}
if (t.equals("[")) {
parseList(out); return;
}
if (t.equals("bitset")) {
parseBitSet(out); return;
}
if (t.equals("array") || t.equals("intarray")) {
parseArray(out); return;
}
if (t.equals("ba")) {
consume();
String hex = unquote(tpp());
out.set(hexToBytes(hex)); return;
}
if (t.equals("boolarray")) {
consume();
int n = parseInt(tpp());
String hex = unquote(tpp());
out.set(boolArrayFromBytes(hexToBytes(hex), n)); return;
}
if (t.equals("class")) {
out.set(parseClass()); return;
}
if (t.equals("l")) {
parseLisp(out); return;
}
if (t.equals("null")) {
consume(); out.set(null); return;
}
if (eq(t, "c")) {
consume("c");
t = t();
assertTrue(isJavaIdentifier(t));
concepts.add(t);
}
}
if (eq(t, "j")) {
consume("j");
out.set(parseJava()); return;
}
if (c == null && !isJavaIdentifier(t))
throw new RuntimeException("Unknown token " + (i+1) + ": " + t);
// any other class name
if (c == null) {
// First, find class
if (allDynamic) c = null;
else c = classFinder != null ? (Class) callF(classFinder, t) : findClass(t);
if (c != null)
classesMap.put(t, c);
}
// Check if it has an outer reference
consume();
boolean hasBracket = eq(t(), "(");
if (hasBracket) consume();
boolean hasOuter = hasBracket && eq(t(), "this$1");
DynamicObject dO = null;
Object o = null;
if (c != null) {
o = hasOuter ? nuStubInnerObject(c) : nuEmptyObject(c);
if (o instanceof DynamicObject) dO = (DynamicObject) o;
} else {
if (concepts.contains(t) && (c = findClass("Concept")) != null)
o = dO = (DynamicObject) nuEmptyObject(c);
else
dO = new DynamicObject();
dO.className = t;
if (debug) print("Made dynamic object " + t + " " + shortClassName(dO));
}
// Save in references list early because contents of object
// might link back to main object
if (refID != 0)
refs.put(refID, o != null ? o : dO);
tokrefs.put(tokIndex, o != null ? o : dO);
// NOW parse the fields!
final LinkedHashMap fields = new LinkedHashMap(); // preserve order
final Object _o = o;
final DynamicObject _dO = dO;
if (hasBracket) {
stack.add(new Runnable() { public void run() { try {
if (eq(t(), ")")) {
consume(")");
objRead(_o, _dO, fields);
out.set(_o != null ? _o : _dO);
} else {
final String key = unquote(tpp());
consume("=");
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object value) {
fields.put(key, value);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \")\")) {\r\n consume(\")\");\r\n objRead(_o, _dO, fie..."; }});
} else {
objRead(o, dO, fields);
out.set(o != null ? o : dO);
}
}
void objRead(Object o, DynamicObject dO, Map fields) {
if (o != null)
if (dO != null) {
if (debug)
printStructure("setOptAllDyn", fields);
setOptAllDyn(dO, fields);
} else {
setOptAll(o, fields);
}
else for (String field : keys(fields))
dO.fieldValues.put(field.intern(), fields.get(field));
if (o != null)
pcallOpt_noArgs(o, "_doneLoading");
}
void parseSet(final Set set, final unstructure_Receiver out) {
parseList(new unstructure_Receiver() {
void set(Object o) {
set.addAll((List) o);
out.set(set);
}
});
}
void parseLisp(final unstructure_Receiver out) {
consume("l");
consume("(");
final ArrayList list = new ArrayList();
stack.add(new Runnable() { public void run() { try {
if (eq(t(), ")")) {
consume(")");
out.set(newObject("main$Lisp", (String) list.get(0), subList(list, 1)));
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
list.add(o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \")\")) {\r\n consume(\")\");\r\n out.set(newObject(\"main$..."; }});
}
void parseBitSet(final unstructure_Receiver out) {
consume("bitset");
consume("{");
final BitSet bs = new BitSet();
stack.add(new Runnable() { public void run() { try {
if (eq(t(), "}")) {
consume("}");
out.set(bs);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
bs.set((Integer) o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n } ..."; }});
}
void parseList(final unstructure_Receiver out) {
consume("[");
final ArrayList list = new ArrayList();
stack.add(new Runnable() { public void run() { try {
if (eq(t(), "]")) {
consume("]");
out.set(list);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
//if (debug) print("List element type: " + getClassName(o));
list.add(o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"]\")) {\r\n consume(\"]\");\r\n out.set(list);\r\n ..."; }});
}
void parseArray(final unstructure_Receiver out) {
final String type = tpp();
consume("{");
final List list = new ArrayList();
stack.add(new Runnable() { public void run() { try {
if (eq(t(), "}")) {
consume("}");
out.set(type.equals("intarray") ? toIntArray(list) : list.toArray());
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
list.add(o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(type.equals(\"int..."; }});
}
Object parseClass() {
consume("class");
consume("(");
String name = unquote(tpp());
consume(")");
name = dropPrefix("main$", name);
Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : 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 = tpp();
if (eq(val, "-"))
val = "-" + tpp();
consume(")");
return new BigInteger(val);
}
Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tpp());
consume(")");
return Double.parseDouble(val);
}
Object parseFloat() {
consume("fl");
String val;
if (eq(t(), "(")) {
consume("(");
val = unquote(tpp());
consume(")");
} else {
val = unquote(tpp());
}
return Float.parseFloat(val);
}
void parseHashSet(unstructure_Receiver out) {
consume("hashset");
parseSet(new HashSet(), out);
}
void parseTreeSet(unstructure_Receiver out) {
consume("treeset");
parseSet(new TreeSet(), out);
}
void parseMap(unstructure_Receiver out) {
parseMap(new TreeMap(), out);
}
Object parseJava() {
String j = unquote(tpp());
Matches m = new Matches();
if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
else {
warn("Unknown Java object: " + j);
return null;
}
}
void parseMap(final Map map, final unstructure_Receiver out) {
consume("{");
stack.add(new Runnable() {
boolean v;
Object key;
public void run() {
if (v) {
v = false;
stack.add(this);
consume("=");
parse(new unstructure_Receiver() {
void set(Object value) {
map.put(key, value);
if (debug)
print("parseMap: Got value " + getClassName(value) + ", next token: " + quote(t()));
if (eq(t(), ",")) consume();
}
});
} else {
if (eq(t(), "}")) {
consume("}");
out.set(map);
} else {
v = true;
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
key = o;
}
});
}
} // if v else
} // run()
});
}
/*void parseSub(unstructure_Receiver out) {
int n = l(stack);
parse(out);
while (l(stack) > n)
stack
}*/
void consume() { curT = tok.next(); ++i; }
void consume(String s) {
if (!eq(t(), s)) {
/*S prevToken = i-1 >= 0 ? tok.get(i-1) : "";
S nextTokens = join(tok.subList(i, Math.min(i+2, tok.size())));
fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");*/
throw fail(quote(s) + " expected, got " + quote(t()));
}
consume();
}
void parse_x(unstructure_Receiver out) {
consume(); // get first token
parse(out);
while (nempty(stack))
popLast(stack).run();
}
}
final Var v = new Var();
X x = new X();
x.parse_x(new unstructure_Receiver() {
void set(Object o) { v.set(o); }
});
unstructure_tokrefs = x.tokrefs.size();
return v.get();
}
static boolean unstructure_debug;
static JTable sexyTableWithoutDrag() {
final JTable table = tableWithToolTips();
tablePopupMenu(table, new Object() { void get(JPopupMenu menu, final int row) { try {
final String item = first(getTableLine(table, row));
MouseEvent e = tablePopupMenu_mouseEvent.get();
final int col = table.columnAtPoint(e.getPoint());
final Object value = table.getModel().getValueAt(row, col);
//print("Cell type: " + getClassName(value));
if (value instanceof ImageIcon) {
addMenuItem(menu, "Copy image to clipboard", new Runnable() { public void run() { try {
copyImageToClipboard(((ImageIcon) value).getImage());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyImageToClipboard(((ImageIcon) value).getImage());"; }});
} else {
final String text = str(value);
addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(text);
print("Copied text to clipboard: " + quote(text));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(text);\r\n print(\"Copied text to clipboard: \" + quote(t..."; }});
}
addMenuItem(menu, "Set row height...", new Runnable() { public void run() { try {
final JTextField tf = jTextField(table.getRowHeight());
showTitledForm("Set row height",
"Pixels", tf, new Runnable() { public void run() { try {
table.setRowHeight(parseInt(trim(tf.getText())))
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "table.setRowHeight(parseInt(trim(tf.getText())))"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tf = jTextField(table.getRowHeight());\r\n showTitledForm(\"S..."; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final S item = first(getTableLine(table, row));\r\n MouseEvent e = tablePopupMe..."; }});
// Disable Ctrl+PageUp and Ctrl+PageDown
table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
//table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, InputEvent.CTRL_MASK), "none");
/*table.registerKeyboardAction(
null,
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
);*/
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_FOCUSED)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
((InputMap) UIManager.get("Table.ancestorInputMap")).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
return table;
}
static String postPage(String url, Object... params) {
return doPost(litmap(params), url);
}
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }
static String hideCredentials(String url) {
return url.replaceAll("([&?])_pass=[^&\\s\"]*", "$1_pass=");
}
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 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().contains(..."; }});
}
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 HashMap getDeclaredFields_cache = new HashMap();
static Field[] getDeclaredFields_cached(Class c) {
Field[] fields;
synchronized(getDeclaredFields_cache) {
fields = getDeclaredFields_cache.get(c);
if (fields == null) {
getDeclaredFields_cache.put(c, fields = c.getDeclaredFields());
for (Field f : fields)
f.setAccessible(true);
}
}
return fields;
}
static Set setMinus(Set set, Object... stuff) {
Set s2 = cloneSet(set);
for (Object o : stuff)
s2.remove(o);
return s2;
}
static boolean loadBufferedImage_useImageCache = true;
static BufferedImage loadBufferedImage(String snippetIDOrURL) { try {
if (snippetIDOrURL == null) return null;
if (isURL(snippetIDOrURL))
return ImageIO.read(new URL(snippetIDOrURL));
if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
String snippetID = "" + parseSnippetID(snippetIDOrURL);
try {
File dir = getCacheProgramDir("Image-Snippets");
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
try {
return ImageIO.read(file);
} catch (Throwable e) {
e.printStackTrace();
// fall back to loading from sourceforge
}
}
String imageURL = snippetImageURL(snippetID);
System.err.println("Loading image: " + imageURL);
BufferedImage image = ImageIO.read(new URL(imageURL));
if (loadBufferedImage_useImageCache) {
File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
ImageIO.write(image, "png", tempFile);
tempFile.renameTo(new File(dir, snippetID + ".png"));
//Log.info("Cached image.");
}
//Log.info("Loaded image.");
return image;
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage loadBufferedImage(File file) { try {
return file.isFile() ? ImageIO.read(file) : null;
} catch (Exception __e) { throw rethrow(__e); } }
static void lockOrFail(Lock lock, long timeout) { try {
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) ( lock);
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
} catch (Exception __e) { throw rethrow(__e); } }
static JScrollPane jscroll(final Component c) {
return swing(new F0() { JScrollPane get() { try { return new JScrollPane(c) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "new JScrollPane(c)"; }});
}
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len*2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs+i]);
stringBuilder.append(s.substring(s.length()-2, s.length()));
}
return stringBuilder.toString();
}
static void makeTableUneditable(JTable table) {
for (int c = 0; c < table.getColumnCount(); c++) {
Class> col_class = table.getColumnClass(c);
//O ed = table.getDefaultEditor(col_class);
//print("Column " + c + " class: " + col_class + " editor: " + ed);
table.setDefaultEditor(col_class, null); // remove editor
}
}
static void dataToTable_dynSet(List l, int i, Object 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 : keysWithoutHidden(m)) {
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, dataToTable_wrapValue(value));
}
return row;
}
return litlist(structureOrText(x));
}
static Object dataToTable_wrapValue(Object o) {
if (o instanceof BufferedImage) return o;
if (o instanceof RGBImage) return o;
if (o instanceof Boolean) return o;
return structureOrText(o);
}
static String or2(String a, String b) {
return nempty(a) ? a : b;
}
static void revalidate(final Component c) {
if (c == null || !c.isShowing()) return;
{ swing(new Runnable() { public void run() { try {
// magic combo to actually relayout and repaint
c.revalidate();
c.repaint();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "// magic combo to actually relayout and repaint\r\n c.revalidate();\r\n c.repa..."; }}); }
}
static File loadDataSnippetToFile(String snippetID) { try {
snippetID = fsI(snippetID);
File f = DiskSnippetCache_file(parseSnippetID(snippetID));
try {
URL url = new URL(dataSnippetLink(snippetID));
print("Loading library: " + hideCredentials(url));
try {
loadBinaryPageToFile(openConnection(url), f);
if (fileSize(f) == 0) throw fail();
} catch (Throwable _e) {
url = 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);
throw fail("Binary snippet " + snippetID + " not found or not public");
}
return f;
} catch (Exception __e) { throw rethrow(__e); } }
public static File mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) // is null if file is in current dir
dir.mkdirs();
return file;
}
static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static File newFile(String name) {
return name == null ? null : new File(name);
}
static void standardTitlePopupMenu(final JFrame frame) {
// standard right-click behavior on titles
if (isSubstanceLAF())
titlePopupMenu(frame,
new Object() { void get(JPopupMenu menu) { try {
boolean alwaysOnTop = frame.isAlwaysOnTop();
menu.add(jmenuItem("Restart Program", "restart"));
menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram"));
menu.add(jmenuItem("Show Console", "showConsole"));
menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() { public void run() { try {
toggleAlwaysOnTop(frame) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "toggleAlwaysOnTop(frame)"; }}));
menu.add(jMenuItem("Shoot Window", new Runnable() { public void run() { try { shootWindowGUI_external(frame, 500) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "shootWindowGUI_external(frame, 500)"; }}));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n menu.add(jmenuItem(\"Restart P..."; }});
}
static File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
static ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static boolean possibleGlobalID(String s) {
return l(s) == 16 && allLowerCaseCharacters(s);
}
static String structureOrText(Object o) {
return o instanceof String ? (String) o : structure(o);
}
static String makeResponder_callAnswerMethod(Object bot, String s, List history) {
String answer = (String) callOpt(bot, "answer", s, history);
if (answer == null)
answer = (String) callOpt(bot, "answer", s);
return answer;
}
static Responder makeResponder(final Object bot) {
if (bot instanceof Responder) return (Responder) bot;
if (bot instanceof String) {
String f = (String) ( bot);
return new Responder() {
String answer(String s, List history) {
String answer = (String) callOptMC((String) bot, s, history);
if (answer == null)
answer = (String) callOptMC((String) bot, s);
return answer;
}
};
}
return new Responder() {
String answer(String s, List history) {
return makeResponder_callAnswerMethod(bot, s, history);
}
};
}
static Object componentAtMouse_gen() {
return swing(new Object() { Object get() { try {
Point p = MouseInfo.getPointerInfo().getLocation();
Window window = locationToWindow(p);
if (window == null) return null;
SwingUtilities.convertPointFromScreen(p, window);
return SwingUtilities.getDeepestComponentAt(window, p.x, p.y);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Point p = MouseInfo.getPointerInfo().getLocation();\r\n Window window = locatio..."; }});
}
static String toStringOpt(Object o) {
return o instanceof String ? ((String) o) : null;
}
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("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
+ parseSnippetID(snippetID) + "&contentType=application/binary");
System.err.println("Loading library: " + url);
try {
data = loadBinaryPage(url.openConnection());
} catch (RuntimeException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL("http://data.tinybrain.de/blobs/"
+ parseSnippetID(snippetID));
System.err.println("Loading library: " + url);
data = loadBinaryPage(url.openConnection());
}
System.err.println("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
static List splitAtSpace(String s) {
return asList(s.split("\\s+"));
}
static URLConnection setURLConnectionTimeouts(URLConnection con, int timeout) {
con.setConnectTimeout(timeout);
con.setReadTimeout(timeout);
if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
print("Warning: Timeouts not set by JDK.");
return con;
}
static void setOpt_raw(Object o, String field, Object value) {
if (o == null) return;
if (o instanceof Class) setOpt_raw((Class) o, field, value);
else try {
Field f = setOpt_raw_findField(o.getClass(), field);
if (f != null)
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void setOpt_raw(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = setOpt_raw_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_raw_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Field setOpt_raw_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 String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
static A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
static int packFrame_minw = 150, packFrame_minh = 50;
static A packFrame(final A c) {
{ swing(new Runnable() { public void run() { try {
JFrame frame = getFrame(c);
if (frame != null) {
frame.pack();
int maxW = getScreenWidth()-50, maxH = getScreenHeight()-50;
frame.setSize(
min(maxW, max(frame.getWidth(), packFrame_minw)),
min(maxH, max(frame.getHeight(), packFrame_minh)));
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFrame frame = getFrame(c);\r\n if (frame != null) {\r\n frame.pack();\r\n ..."; }}); }
return c;
}
static JFrame packFrame(ButtonGroup g) {
return packFrame(getFrame(g));
}
static String standardCredentialsUser() {
return trim(loadTextFile(new File(userHome(), ".tinybrain/username")));
}
static String doPost(Map urlParameters, String url) {
return doPost(makePostData(urlParameters), url);
}
static String doPost(String urlParameters, String url) { try {
URL _url = new URL(url);
return doPost(urlParameters, _url.openConnection(), _url);
} catch (Exception __e) { throw rethrow(__e); } }
static String doPost(String urlParameters, URLConnection conn, URL url) { try {
setHeaders(conn);
int l = lUtf8(urlParameters);
print("Sending POST request: " + url + " (" + l + " bytes)");
// connect and do POST
((HttpURLConnection) conn).setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", str(l));
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
writer.write(urlParameters);
writer.flush();
String contents = loadPage(conn, url, false);
writer.close();
return contents;
} catch (Exception __e) { throw rethrow(__e); } }
static String shortenClassName(String name) {
if (name == null) return null;
int i = lastIndexOf(name, "$");
if (i < 0) i = lastIndexOf(name, ".");
return i < 0 ? name : substring(name, i+1);
}
static byte[] toPNG(BufferedImage img) {
return convertToPNG(img);
}
static boolean showTable_searcher = true;
static JTable showTable(Object data) {
return dataToTable_uneditable(data);
}
static JTable showTable(Object data, String title) {
return dataToTable_uneditable(data, title);
}
static JTable showTable(JTable table, Object data) {
return showTable(table, data, autoFrameTitle());
}
static JTable showTable(Object data, JTable table) {
return showTable(table, data);
}
static JTable showTable(JTable table, Object data, String title) {
if (table == null)
table = showTable(data, title);
else {
setFrameTitle(table, title);
dataToTable_uneditable(table, data);
}
return table;
}
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) {
JTable tbl = sexyTable();
fillTableWithStrings(tbl, rows, cols);
showFrame(title, tbl);
return tbl;
}
public static void copyFile(File src, File dest) { try {
mkdirsForFile(dest);
FileInputStream inputStream = new FileInputStream(src.getPath());
FileOutputStream outputStream = newFileOutputStream(dest.getPath());
try {
copyStream(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
} catch (Exception __e) { throw rethrow(__e); } }
static String conceptToNameOpt(String s) {
AIConcept c = aiConceptsMap_cached().get(s);
return c == null ? null : unnull(c.name);
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static A callPostProcessor(Object f, A a) {
return f == null ? a : (A) callF(f, a);
}
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 File javaxCachesDir_dir; // can be set to work on different base dir
static File javaxCachesDir() {
return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
static Map hippoSingulars() {
return pairsToMap((List>) scanStructureLog("#1011041", "singulars"));
}
static List getClasses(Object[] array) {
List l = new ArrayList();
for (Object o : array) l.add(_getClass(o));
return l;
}
static int iround(double d) {
return (int) Math.round(d);
}
static List javaTokC(String s) {
if (s == null) return null;
int l = s.length();
ArrayList tok = new ArrayList();
int i = 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;
}
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// 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 (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;
tok.add(quickSubstring(s, i, j));
i = j;
}
return tok;
}
static boolean isConceptFieldIndexed(Class extends Concept> c, String field) {
return mainConcepts.getFieldIndex(c, field) != null;
}
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { printStackTrace2(__e); }
return null;
}
static final boolean loadPageThroughProxy_enabled = false;
static String loadPageThroughProxy(String url) {
return null;
}
static void hotwire_copyOver(Class c) {
synchronized(StringBuffer.class) {
for (String field : litlist("print_log", "print_silent", "androidContext")) {
Object o = getOpt(mc(), field);
if (o != null)
setOpt(c, field, o);
}
Object mainBot = getMainBot();
if (mainBot != null)
setOpt(c, "mainBot", mainBot);
setOpt(c, "creator_class", new WeakReference(mc()));
}
}
static BufferedImage toBufferedImageOpt(Object o) {
if (o instanceof BufferedImage) return (BufferedImage) o;
String c = getClassName(o);
if (eqOneOf(c, "main$BWImage", "main$RGBImage"))
return (BufferedImage) call(o, "getBufferedImage");
if (eq(c, "main$PNGFile"))
return (BufferedImage) call(o, "getImage");
return null;
}
static void activateFrame(final Component c) {
{ swing(new Runnable() { public void run() { try {
JFrame f = getFrame(c);
if (f == null) return;
if (!f.isVisible()) f.setVisible(true);
if (f.getState() == Frame.ICONIFIED)
f.setState(Frame.NORMAL);
// My glorious Windows hack
// See: https://stackoverflow.com/questions/309023/how-to-bring-a-window-to-the-front
if (isWindows()) {
boolean fullscreen = f.getExtendedState() == Frame.MAXIMIZED_BOTH;
f.setExtendedState(JFrame.ICONIFIED);
f.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL);
}
f.toFront();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JFrame f = getFrame(c);\r\n if (f == null) return;\r\n if (!f.isVisible()) f.s..."; }}); }
}
// 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 long fileSize(String path) { return getFileSize(path); }
static long fileSize(File f) { return getFileSize(f); }
static int tableRows(JTable table) {
return table.getRowCount();
}
static void setAddAll(List a, Collection b) {
for (A x : b)
setAdd(a, x);
}
static Object callOpt(Object o) {
if (o == null) return null;
return callF(o);
}
static Object callOpt(Object o, String method, Object... args) {
try {
if (o == null) return null;
if (o instanceof Class) {
Method m = callOpt_findStaticMethod((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = callOpt_findMethod(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
//fail(e.getMessage() + " | Method: " + method + ", receiver: " + className(o) + ", args: (" + join(", ", map(f className, args) + ")");
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() & java.lang.reflect.Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static Collection values(MultiMap mm) {
return mm == null ? emptyList() : concatLists(values(mm.data));
}
static void assertFalse(Object o) {
assertEquals(false, o);
}
static boolean assertFalse(boolean b) {
if (b) throw fail("oops");
return b;
}
static boolean assertFalse(String msg, boolean b) {
if (b) throw fail(msg);
return b;
}
static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
static JLabel jlabel() {
return jlabel(" ");
}
// returns null if program not running, answer otherwise
static String activateFramesOf(String progID) {
return sendToLocalBotOpt(fsI(progID) + " Frames.", "activate frames");
}
static long parseLongOpt(String s) {
return isInteger(s) ? parseLong(s) : 0;
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static void readLocally(String progID, String varNames) {
readLocally2(mc(), progID, varNames);
}
static void readLocally(String varNames) {
readLocally2(mc(), programID(), varNames);
}
static void readLocally2(Object obj, String varNames) {
readLocally2(obj, programID(), varNames);
}
static int readLocally_stringLength;
static ThreadLocal readLocally2_allDynamic = new ThreadLocal();
// read a string variable from standard storage
// does not overwrite variable contents if there is no file
static void readLocally2(Object obj, String progID, String varNames) { try {
boolean allDynamic = isTrue(getAndClearThreadLocal(readLocally2_allDynamic));
for (String variableName : javaTokC(varNames)) {
File textFile = new File(programDir(progID), variableName + ".text");
String value = loadTextFile(textFile);
if (value != null)
set(main.class, variableName, value);
else {
File structureFile = new File(programDir(progID), variableName + ".structure");
value = loadTextFile(structureFile);
if (value == null) {
File structureGZFile = new File(programDir(progID), variableName + ".structure.gz");
if (!structureGZFile.isFile()) return;
//value = loadGZTextFile(structureGZFile);
InputStream fis = new FileInputStream(structureGZFile);
try {
GZIPInputStream gis = new GZIPInputStream(fis);
InputStreamReader reader = new InputStreamReader(gis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
//O o = unstructure_reader(bufferedReader);
Object o = unstructure_tok(javaTokC_noMLS_onReader(bufferedReader), allDynamic, null);
readLocally_set(obj, variableName, o);
} finally {
fis.close();
}
return;
}
readLocally_stringLength = l(value);
if (nempty(value))
readLocally_set(obj, variableName, allDynamic ? safeUnstructure(value) : unstructure(value));
}
}
} catch (Exception __e) { throw rethrow(__e); } }
static void readLocally_set(Object c, String varName, Object value) {
Object oldValue = get(c, varName);
if (oldValue instanceof List && !(oldValue instanceof ArrayList) && value != null) {
// Assume it's a synchroList.
value = synchroList((List) value);
}
set(c, varName, value);
}
static JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
for (Object o : parts)
panel.add(wrapForSmartAdd(o), layout);
return panel;
}
static JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
return smartAddWithLayout(panel, layout, asList(parts));
}
static Class hotwireOnce(String programID) {
return hotwireCached(programID, false);
}
static void revalidateFrame(Component c) {
revalidate(getFrame(c));
}
static String standardCredentialsPass() {
return trim(loadTextFile(new File(userHome(), ".tinybrain/userpass")));
}
static int isAndroid_flag;
static boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, char c) {
return nempty(a) && a.charAt(0) == c;
}
static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
m.m = new String[] {substring(a, l(b))};
return true;
}
static boolean startsWith(List a, List b) {
if (a == null || l(b) > l(a)) return false;
for (int i = 0; i < l(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static boolean isRunnableX(Object o) {
if (o == null) return false;
if (o instanceof String) return hasMethod(mc(), (String) o);
return o instanceof Runnable || hasMethod(o, "get");
}
static List record_list = synchroList();
static void record(Object o) {
record_list.add(o);
}
static TreeMap hotwireCached_cache = new TreeMap();
static Lock hotwireCached_lock = lock();
static Class hotwireCached(String programID) {
return hotwireCached(programID, true);
}
static Class hotwireCached(String programID, boolean runMain) {
Lock _lock_523 = hotwireCached_lock; lock(_lock_523); try {
programID = formatSnippetID(programID);
Class c = hotwireCached_cache.get(programID);
if (c == null) {
c = hotwire(programID);
if (runMain)
callMain(c);
hotwireCached_cache.put(programID, c);
}
return c;
} finally { _lock_523.unlock(); } }
public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}
static boolean isLowerHexString(String s) {
for (int i = 0; i < l(s); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
// ok
} else
return false;
}
return true;
}
static byte[] hexToBytes(String s) {
int n = l(s) / 2;
byte[] bytes = new byte[n];
for (int i = 0; i < n; i++) {
String hex = substring(s, i*2, i*2+2);
try {
bytes[i] = (byte) parseHexByte(hex);
} catch (Throwable _e) {
throw fail("Bad hex byte: " + quote(hex) + " at " + i*2 + "/" + l(s));
}
}
return bytes;
}
static HashMap nuEmptyObject_cache = new HashMap();
static A nuEmptyObject(Class c) { try {
Constructor ctr;
synchronized(nuEmptyObject_cache) {
ctr = nuEmptyObject_cache.get(c);
if (ctr == null) {
nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
ctr.setAccessible(true);
}
}
return (A) ctr.newInstance();
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuEmptyObject_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors())
if (m.getParameterTypes().length == 0)
return m;
throw fail("No default constructor declared in " + c.getName());
}
static Lock saveLock_lock = fairLock();
static Lock saveLock() {
return saveLock_lock;
}
static String quickSubstring(String s, int i, int j) {
if (i == j) return "";
return s.substring(i, j);
}
static boolean structure_isMarker(String s, int i, int j) {
if (i >= j) return false;
if (s.charAt(i) != 'm') return false;
++i;
while (i < j) {
char c = s.charAt(i);
if (c < '0' || c > '9') return false;
++i;
}
return true;
}
static Object newObject(Class c, Object... args) {
return nuObject(c, args);
}
static Object newObject(String className, Object... args) {
return nuObject(className, args);
}
// menuMaker = voidfunc(JPopupMenu)
static void titlePopupMenu(final Component c, final Object menuMaker) {
swingNowOrLater(new Runnable() { public void run() { try {
if (!isSubstanceLAF())
print("Can't add title right click!");
else {
JComponent titleBar = getTitlePaneComponent(getFrame(c));
componentPopupMenu(titleBar, menuMaker);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!isSubstanceLAF())\r\n print(\"Can't add title right click!\");\r\n else {..."; }});
}
static void duplicateThisProgram() {
nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs"))));
}
static void set(Object o, String field, Object value) {
if (o instanceof Class) set((Class) o, field, value);
else try {
Field f = set_findField(o.getClass(), field);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void set(Class c, String field, Object value) {
try {
Field f = set_findStaticField(c, field);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static String copyTextToClipboard(String text) {
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
return text;
}
// match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens)
static String[] match2(List pat, List tok) {
// standard case (no ...)
int i = pat.indexOf("...");
if (i < 0) return match2_match(pat, tok);
pat = new ArrayList(pat); // We're modifying it, so copy first
pat.set(i, "*");
while (pat.size() < tok.size()) {
pat.add(i, "*");
pat.add(i+1, ""); // doesn't matter
}
return match2_match(pat, tok);
}
static String[] match2_match(List pat, List tok) {
List result = new ArrayList();
if (pat.size() != tok.size()) {
return null;
}
for (int i = 1; i < pat.size(); i += 2) {
String p = pat.get(i), t = tok.get(i);
if (eq(p, "*"))
result.add(t);
else if (!equalsIgnoreCase(unquote(p), unquote(t))) // bold change - match quoted and unquoted now
return null;
}
return result.toArray(new String[result.size()]);
}
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 instanceOf(Object o, Class c) {
if (c == null) return false;
return c.isInstance(o);
}
static boolean jmatch(String pat, String s) {
return jmatch(pat, s, null);
}
static boolean jmatch(String pat, String s, Matches matches) {
if (s == null) return false;
return jmatch(pat, javaTok(s), matches);
}
static boolean jmatch(String pat, List toks) {
return jmatch(pat, toks, null);
}
static boolean jmatch(String pat, List toks, Matches matches) {
List tokpat = javaTok(pat);
String[] m = match2(tokpat, toks);
//print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
if (m == null)
return false;
else {
if (matches != null) matches.m = m;
return true;
}
}
static Class javax() {
return getJavaX();
}
static String lispForwardRawOrSame(String relation, String argument) {
return or(lispForwardRaw(relation, argument), argument);
}
static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
/** writes safely (to temp file, then rename) */
public static void saveBinaryFile(String fileName, byte[] contents) throws IOException {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
FileOutputStream fileOutputStream = newFileOutputStream(tempFileName);
fileOutputStream.write(contents);
fileOutputStream.close();
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
}
static void saveBinaryFile(File fileName, byte[] contents) {
try {
saveBinaryFile(fileName.getPath(), contents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
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 AtomicInteger dialogServer_clients = new AtomicInteger();
static boolean dialogServer_printConnects;
static ThreadLocal startDialogServer_quiet = new ThreadLocal();
static Set dialogServer_knownClients = synchroTreeSet();
static int startDialogServerOnPortAbove(int port, DialogHandler handler) {
while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler))
++port;
return port;
}
static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) {
while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler, true))
++port;
return port;
}
static void startDialogServer(int port, DialogHandler handler) {
if (!startDialogServerIfPortAvailable(port, handler))
throw fail("Can't start dialog server on port " + port);
}
static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) {
return startDialogServerIfPortAvailable(port, handler, false);
}
static ServerSocket startDialogServer_serverSocket;
static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
// probably the port number is used - let's assume there already is a chat server.
return false;
}
final ServerSocket _serverSocket = serverSocket;
startDialogServer_serverSocket = serverSocket;
Thread thread = new Thread("Socket accept port " + port) { public void run() {
try {
while (true) {
try {
final Socket s = _serverSocket.accept();
String client = s.getInetAddress().toString();
if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) {
print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet());
dialogServer_knownClients.add(client);
}
String threadName = "Handling client " + s.getInetAddress();
Thread t2 = new Thread(threadName) {
public void run() {
try {
final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
final BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream(), "UTF-8"));
DialogIO io = new DialogIO() {
// This should be the same as #1001076 (talkTo)
boolean isLocalConnection() {
return s.getInetAddress().isLoopbackAddress();
}
boolean isStillConnected() {
return !(eos || s.isClosed());
}
void sendLine(String line) { try {
w.write(line + "\n");
w.flush();
} catch (Exception __e) { throw rethrow(__e); } }
String readLineImpl() { try {
return in.readLine();
} catch (Exception __e) { throw rethrow(__e); } }
void close() {
try {
s.close();
} catch (IOException e) {
// whatever
}
}
Socket getSocket() {
return s;
}
};
try {
handler.run(io);
} finally {
s.close();
}
} catch (IOException e) {
print("[internal] " + e);
} finally {
//print("client disconnect - " + dialogServer_clients.decrementAndGet() + " remaining");
}
}
}; // Thread t2
t2.setDaemon(true); // ?
t2.start();
} catch (SocketTimeoutException e) {
}
}
} catch (IOException e) {
print("[internal] " + e);
}
}};
if (daemon) thread.setDaemon(true);
thread.start();
if (!isTrue(getAndClearThreadLocal(startDialogServer_quiet)))
print("Dialog server on port " + port + " started.");
return true;
}
static Method findMethod(Object o, String method, Object... args) {
try {
if (o == null) return null;
if (o instanceof Class) {
Method m = findMethod_static((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m;
} else {
Method m = findMethod_instance(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Method findMethod_static(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 || !findMethod_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method findMethod_instance(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) && findMethod_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
static boolean findMethod_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 String unquote(String s) {
if (s == null) return null;
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.startsWith("\'")) && s.length() > 1) {
int l = s.endsWith(substring(s, 0, 1)) ? s.length()-1 : s.length();
StringBuilder sb = new StringBuilder(l-1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.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 >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + s.charAt(i + 2) + s.charAt(i + 3)
+ s.charAt(i + 4) + s.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();
}
return s; // not quoted - return original
}
static String clUnparse(Lisp l) {
if (l == null) return "";
return join(" ", (List) concatLists(ll(conceptQuote(l.head)), map("clUnparse_sub", l)));
}
static String clUnparse_sub(Lisp l) {
return l.empty() ? clUnparse(l) : "(" + clUnparse(l) + ")";
}
static List clUnparse(List l) {
return map("clUnparse", l);
}
static void setOptAll(Object o, Map fields) {
if (fields == null) return;
for (String field : keys(fields))
setOpt(o, field, fields.get(field));
}
static void setOptAll(Object o, Object... values) {
//values = expandParams(c.getClass(), values);
warnIfOddCount(values);
for (int i = 0; i+1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i+1];
setOpt(o, field, value);
}
}
static Set joinSets(Set ... l) {
TreeSet set = new TreeSet();
for (Set o : l)
if (o != null)
set.addAll(o);
return set;
}
static Producer javaTokC_noMLS_onReader(final BufferedReader r) {
final class X implements Producer {
StringBuilder buf = new StringBuilder(); // stores from "i"
char c, d, e = 'x'; // just not '\0'
X() {
// fill c, d and e
nc();
nc();
nc();
}
// get next character(s) into c, d and e
void nc() { try {
c = d;
d = e;
if (e == '\0') return;
int i = r.read();
e = i < 0 ? '\0' : (char) i;
} catch (Exception __e) { throw rethrow(__e); } }
void ncSave() {
if (c != '\0') {
buf.append(c);
nc();
}
}
public String next() {
// scan for whitespace
while (c != '\0') {
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
nc();
else if (c == '/' && d == '*') {
do nc(); while (c != '\0' && !(c == '*' && d == '/'));
nc(); nc();
} else if (c == '/' && d == '/') {
do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
} else
break;
}
if (c == '\0') return null;
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
ncSave();
while (c != '\0') {
if (c == opener || c == '\n') { // end at \n to not propagate unclosed string literal errors
ncSave();
break;
} else if (c == '\\') {
ncSave();
ncSave();
} else
ncSave();
}
} else if (Character.isJavaIdentifierStart(c))
do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\''); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ncSave(); while (Character.isDigit(c));
if (c == 'L') ncSave(); // Long constants like 1L
} else
ncSave();
String t = buf.toString();
buf.setLength(0);
return t;
}
}
return new X();
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static String dataSnippetLink(String snippetID) {
long id = parseSnippetID(snippetID);
if (id >= 1200000 && id < 1300000) {
String pw = muricaPassword();
if (empty(pw)) throw fail("Please set 'murica password by running #1008829");
return "http://ai1.lol/1008823/raw/" + id + "?_pass=" + pw; // XXX, although it typically gets hidden when printing
} else
return "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
+ id + "&contentType=application/binary";
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
// TODO: does not detect set type (hash/tree) when it's synchronized
static Set cloneSet(Set set) {
// assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does.
synchronized(set) {
return set instanceof TreeSet ? new TreeSet(set) : new HashSet(set);
}
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
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));
}
static String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static void sleepInCleanUp(long ms) { try {
if (ms < 0) return;
Thread.sleep(ms);
} catch (Exception __e) { throw rethrow(__e); } }
static boolean isSubstanceLAF() {
return substanceLookAndFeelEnabled();
}
static WeakAssoc, Map> lispStatements_cache = new WeakAssoc("statementsToLisp");
static Map lispStatements_global;
static Map lispStatements_cached() {
ThoughtSpace ts = thoughtSpace();
if (ts != null) return ts.statements;
if (lispStatements_global != null) return lispStatements_global;
return lispStatements_cache.get(loadTruth_cached());
}
static JTextArea jtextarea() {
return jTextArea();
}
static JTextArea jtextarea(String text) {
return jTextArea(text);
}
static List _registerWeakMap_preList;
static A _registerWeakMap(A map) {
if (javax() == null) {
// We're in class init
if (_registerWeakMap_preList == null) _registerWeakMap_preList = synchroList();
_registerWeakMap_preList.add(map);
return map;
}
try {
call(javax(), "_registerWeakMap", map);
} catch (Throwable e) {
printException(e);
print("Upgrade JavaX!!");
}
return map;
}
static void _onLoad_registerWeakMap() {
assertNotNull(javax());
if (_registerWeakMap_preList == null) return;
for (Object o : _registerWeakMap_preList)
_registerWeakMap(o);
_registerWeakMap_preList = null;
}
static TableWithTooltips tableWithToolTips() {
return tableWithTooltips();
}
static boolean endsWithIgnoreCase(String a, String b) {
return a != null && l(a) >= l(b) && a.regionMatches(true, l(a)-l(b), b, 0, l(b));
}
static String myJavaSource_code;
static String myJavaSource() {
return myJavaSource_code;
}
static int getScreenWidth() {
return getScreenSize().width;
}
static String parse3_cached_s;
static List parse3_cached_l;
static synchronized List parse3_cached(String s) {
if (neq(s, parse3_cached_s))
parse3_cached_l = parse3(parse3_cached_s = s);
return parse3_cached_l;
}
static boolean isLongConstant(String s) {
if (!s.endsWith("L")) return false;
s = s.substring(0, l(s)-1);
return isInteger(s);
}
static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static float max(float[] c) {
if (c.length == 0) return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static void loadBinaryPageToFile(String url, File file) { try {
print("Loading " + url);
loadBinaryPageToFile(openConnection(new URL(url)), file);
} catch (Exception __e) { throw rethrow(__e); } }
static void loadBinaryPageToFile(URLConnection con, File file) { try {
setHeaders(con);
loadBinaryPageToFile_noHeaders(con, file);
} catch (Exception __e) { throw rethrow(__e); } }
static void loadBinaryPageToFile_noHeaders(URLConnection con, File file) { try {
File ftemp = new File(f2s(file) + "_temp");
FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
InputStream inputStream = con.getInputStream();
try {
long len = 0;
try { len = con.getContentLengthLong(); } catch (Throwable e) { printStackTrace(e); }
int n = 0;
while (true) {
int ch = inputStream.read();
if (ch < 0)
break;
buf.write(ch);
if (++n % 100000 == 0)
println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
}
buf.close();
buf = null;
file.delete();
ftemp.renameTo(file);
inputStream.close();
} finally {
if (buf != null) buf.close();
}
} catch (Exception __e) { throw rethrow(__e); } }
static List scanStructureLog(String progID, String fileName) {
return scanStructureLog(getProgramFile(progID, fileName));
}
static List scanStructureLog(String fileName) {
return scanStructureLog(getProgramFile(fileName));
}
static List scanStructureLog(File file) {
List l = new ArrayList();
for (String s : scanLog(file)) try {
l.add(unstructure(s));
} catch (Throwable __e) { printStackTrace2(__e); }
return l;
}
static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked);
mi.addActionListener(actionListener(r));
return mi;
}
static boolean publicCommOn() {
return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
}
static String wordAroundIndex(String s, int i) {
if (!(i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i)))) return "";
int j = i;
while (i > 0 && isLetterOrDigit(s.charAt(i-1))) --i;
while (j < l(s) && isLetterOrDigit(s.charAt(j))) ++j;
return substring(s, i, j);
}
static int[] toIntArray(List l) {
int[] a = new int[l(l)];
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
return a;
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static String formatXYZ_appendRest(String pattern, List