Warning : session_start(): open(/var/lib/php/sessions/sess_5g3n2rl4muehhks0orq7u51irj, 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.*;
import javax.swing.undo.UndoManager;
import java.awt.datatransfer.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import java.awt.datatransfer.StringSelection;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import java.awt.geom.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import static x30_pkg.x30_util.DynamicObject;
import java.nio.file.Path;
import java.text.*;
import java.util.TimeZone;
class main {
static boolean SimpleCRUD_searcher = true;
static class SimpleCRUD {
Concepts concepts;
Class cc;
JTable table;
JPanel buttons, panel;
Object renderer; // optional, func(A) -> Map
Object sorter; // optional, func(Cl) -> Cl
String hID = "ID";
Set unshownFields; // not shown in table or form
Set excludeFieldsFromEditing;
String modifiedField; // field to hold last-modified timestamp
TableSearcher tableSearcher;
Set multiLineFields; // string fields that should be shown as text areas
Set dontDuplicateFields;
boolean latestFirst = false;
int formFixer = 12; // stupid value to make submit button appear
boolean editOnDoubleClick = true;
boolean ensureIndexed = false;
boolean showValuesAsStruct = false; // BREAKING CHANGE - used to be true
SimpleCRUD(Class cc) { this(db_mainConcepts(), cc); }
SimpleCRUD(Concepts concepts, Class cc) {
this.cc = cc;
this.concepts = concepts;}
SimpleCRUD show(String frameTitle) {
make();
showFrame(frameTitle, panel);
return this;
}
SimpleCRUD show() {
return show(plural(shortClassName(cc)));
}
SimpleCRUD showMaximized() { show(); maximizeFrame(panel); return this; }
JPanel makePanel() { return make(); }
JPanel make() {
db();
framesBot();
return make_dontStartBots();
}
JPanel make_dontStartBots() {
printVars("SimpleCRUD.make_dontStartBots", "concepts", concepts, "cc", cc, "count" , countConcepts(cc));
if (ensureIndexed)
indexConceptClass(concepts, cc);
// next line not in swing part to allow passing arguments
// from outside like showConceptsTable_afterUpdate
AutoCloseable __1 = tempSetTL(showConceptsTable_concepts, concepts); try {
AutoCloseable __2 = tempSetTL(showConceptsTable_latestFirst, latestFirst); try {
AutoCloseable __3 = tempSetTL(showConceptsTable_sorter, sorter); try {
AutoCloseable __4 = tempSetTL(showConceptsTable_dropFields, asList(unshownFields)); try {
AutoCloseable __5 = tempSetTL(dataToTable_useStruct, showValuesAsStruct); try {
table = makeConceptsTable(cc, wrapRenderer(renderer));
{ swing(new Runnable() { public void run() { try {
buttons = jRightAlignedLine(
jbutton("Add...", new Runnable() { public void run() { try { newConcept() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "newConcept()"; }}),
tableDependButton(table, jbutton("Edit", new Runnable() { public void run() { try {
editConcept(selectedConcept())
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "editConcept(selectedConcept())"; }})),
tableDependButton(table, jbutton("Delete", new Runnable() { public void run() { try {
final List l = selectedConcepts();
startThread("Delete concepts", new Runnable() { public void run() { try {
withDBLock(concepts, new Runnable() { public void run() { try { for (A c : l) c.delete() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "for (A c : l) c.delete()"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "withDBLock(concepts, new Runnable() { public void run() { try { for (A c : ..."; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final List l = selectedConcepts();\r\n thread \"Delete concepts\" {\r\n..."; }})),
tableDependButton(table, jbutton("Duplicate...", new Runnable() { public void run() { try {
duplicateConcept(selectedConcept())
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "duplicateConcept(selectedConcept())"; }})));
if (SimpleCRUD_searcher) {
tableSearcher = tableWithSearcher2(table, "withMargin" , true);
panel = centerAndSouthWithMargin(tableSearcher.panel, withBottomMargin(buttons));
} else
panel = centerAndSouthWithMargin(table, withBottomMargin(buttons));
Object fEdit = new VF1() { public void get(Integer row) { try { editConcept(conceptForRow(row)) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "editConcept(conceptForRow(row))"; }};
tablePopupMenuItem(table, "Edit...", fEdit);
if (editOnDoubleClick)
onDoubleClick(table, fEdit);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "buttons = jRightAlignedLine(\r\n jbutton(\"Add...\", r { newConcept() }),\r..."; }}); }
return panel;
} finally { _close(__5); }} finally { _close(__4); }} finally { _close(__3); }} finally { _close(__2); }} finally { _close(__1); }}
Object wrapRenderer(final Object renderer) {
return renderer == null ? null : new F1() { public Object get(A a) { try {
return putAll(litorderedmap(hID, str(a.id)), (Map) callF(renderer, a));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "putAll(litorderedmap(hID, str(a.id)), (Map) callF(renderer, a))"; }};
}
void newConcept() {
duplicateConcept(null);
}
void duplicateConcept(A oldConcept) {
final A c = unlisted(cc);
ccopyFieldsExcept(oldConcept, c, dontDuplicateFields);
final Map map = makeComponents(c);
Runnable r = new Runnable() { public void run() { try {
concepts.register(c);
saveData(c, map);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "concepts.register(c);\r\n saveData(c, map);"; }};
AutoCloseable __6 = tempSetMCOpt("formLayouter1_fixer2" , formFixer); try {
showFormTitled2("New " + shortClassName(cc), arrayPlus(mapToObjectArray(map), r));
} finally { _close(__6); }}
void editConcept(final A c) {
if (c == null) return;
final Map map = makeComponents(c);
Runnable r = new Runnable() { public void run() { try { saveData(c, map) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "saveData(c, map)"; }};
AutoCloseable __7 = tempSetMCOpt("formLayouter1_fixer2" , formFixer); try {
showFormTitled2("Edit " + shortClassName(cc) + " #" + c.id, arrayPlus(mapToObjectArray(map), r));
} finally { _close(__7); }}
A selectedConcept() { return selected(); }
A selected() {
return conceptForRow(selectedRow(table));
}
A conceptForRow(int row) {
return (A) concepts.getConcept(toLong(getTableCell(table, row, 0)));
}
int indexOfConcept(final A c) {
if (c == null) return -1;
return swing(new F0() { public Integer get() { try {
int n = tableRowCount(table);
for (int row = 0; row < n; row++)
if (toLong(getTableCell(table, row, 0)) == c.id)
return row;
return -1;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "int n = tableRowCount(table);\r\n for row to n:\r\n if (toLong(getTab..."; }});
}
List selectedConcepts() {
return swing(() -> {
int[] rows = table == null ? null : table.getSelectedRows();
List l = new ArrayList();
for (int row : unnullForIteration(rows))
l.add(conceptForRow(row));
return l;
});
}
Map makeComponents(A c) {
Map map = litorderedmap();
makeComponents(c, map);
return map;
}
JComponent fieldComponent(A c, String field) {
Class type = getFieldType(cc, field);
Object value = getOpt(c, field);
//print("Field type: " + field + " => " + type);
if (type == boolean.class)
return jCenteredCheckBox(isTrue(value));
else if (contains(multiLineFields, field) || containsNewLines(optCast(String.class, value)))
return typeWriterTextArea((String) value);
else if (isSubtype(type, Concept.class))
return jcomboboxFromConcepts_str(concepts, type, (Concept) value);
else try {
return autoComboBox(valueToString(value), new TreeSet(map(__29 -> valueToString(__29), collect(list(concepts, cc), field))));
} catch (Throwable e) {
printException(e);
return jTextField(valueToString(value));
}
}
void saveComponent(A c, String field, JComponent comp) {
comp = unwrap(comp);
Class type = fieldType(c, field);
if (comp instanceof JTextComponent)
cset(c, field, convertToField(trimIf(!(comp instanceof JTextArea), getText((JTextComponent) comp)), cc, field));
else if (comp instanceof JComboBox) {
String text = getTextTrim((JComboBox) comp);
if (isSubtype(type, Concept.class))
cset(c, field, getConcept(concepts, parseFirstLong(text)));
else
cset(c, field, convertToField(text, cc, field));
} else if (comp instanceof JCheckBox)
cset(c, field, isChecked((JCheckBox) comp));
}
List fields() {
if (excludeFieldsFromEditing != null && modifiedField != null) excludeFieldsFromEditing.add(modifiedField);
return listWithoutSet(filter(conceptFieldsInOrder(cc) , new F1() { public Boolean get(String field) { try { return fieldType(cc, field) != Concept.Ref.class; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "fieldType(cc, field) != Concept.Ref.class"; }}),
joinSets(excludeFieldsFromEditing, unshownFields));
}
void excludeFieldsFromEditing(String... fields) {
excludeFieldsFromEditing = setPlus(excludeFieldsFromEditing, fields);
}
// override the following two methods to customize edit window
void makeComponents(A c, Map map) {
for (String field : fields())
map.put(field, fieldComponent(c, field));
}
void saveData(A c, Map components) {
for (String field : keys(components))
saveComponent(c, field, components.get(field));
if (modifiedField != null) cset(c, modifiedField, now());
}
JTable table() { return table; }
transient IF1 valueToString;
String valueToString(Object o) { return valueToString != null ? valueToString.get(o) : valueToString_base(o); }
final String valueToString_fallback(IF1 _f, Object o) { return _f != null ? _f.get(o) : valueToString_base(o); }
String valueToString_base(Object o) {
return showValuesAsStruct
? structureOrText_crud(o)
: strOrNull(o);
}
}
static volatile Concepts mainConcepts; // Where we create new concepts
static Concepts db_mainConcepts() {
if (mainConcepts == null)
mainConcepts = newConceptsWithClassFinder(getDBProgramID());
return mainConcepts;
}
static void cleanMeUp_concepts() {
if (db_mainConcepts() != null) db_mainConcepts().cleanMeUp();
// mainConcepts = null; // TODO
}
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 f) {
if (f != null) { swing(new Runnable() { public void run() { try {
if (frameTooSmall(f)) frameStandardSize(f);
if (!f.isVisible()) f.setVisible(true); // XXX
if (f.getState() == Frame.ICONIFIED) f.setState(Frame.NORMAL);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (frameTooSmall(f)) frameStandardSize(f);\r\n if (!f.isVisible()) f.setVis..."; }}); }
return f;
}
// 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 String plural(String s) {
return getPlural(s);
}
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);
}
static A maximizeFrame(A c) {
JFrame f = swing(new F0() { public JFrame get() { try {
JFrame f = getFrame(c);
if (f != null)
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JFrame f = getFrame(c);\r\n if (f != null)\r\n f.setExtendedState(JFrame...."; }});
// wait until frame is actually maximized so
// we can add components based on correct size
if (f != null && !isAWTThread()) {
Dimension d = maximumWindowBounds().getSize();
long start = sysNow();
while (licensed()) { try {
if (f.getWidth() >= d.getWidth()-100 && f.getHeight() >= d.getHeight()-100) break;
if (sysNow() >= start+100) { warn("maximizeFrame timeout"); break; }
} catch (Throwable __e) { _handleException(__e); } sleep(1); }
}
return c;
}
static void db() {
conceptsAndBot();
}
// use -10000 for 10 seconds plus slowdown logic
static void db(Integer autoSaveInterval) {
conceptsAndBot(autoSaveInterval);
}
static volatile boolean framesBot_has = false;
static Android3 framesBot() {
if (framesBot_has) return null;
framesBot_has = true;
Android3 android = new Android3();
android.greeting = programIDPlusHome() + " 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 act..."; }});
return "OK, activating " + programName();
}
return null;
}
};
return makeBot(android);
}
// Use like this: printVars(+x, +y);
// Or: printVars("bla", +x);
// Or: printVars bla(, +x);
static void printVars(Object... params) {
printVars_str(params);
}
static int countConcepts(Concepts concepts, Class c, Object... params) {
return concepts.countConcepts(c, params);
}
static int countConcepts(Class c, Object... params) {
return db_mainConcepts().countConcepts(c, params);
}
static int countConcepts() {
return db_mainConcepts().countConcepts();
}
static int countConcepts(String className) {
return db_mainConcepts().countConcepts(className);
}
static int countConcepts(Concepts concepts, String className) {
return concepts.countConcepts(className);
}
static int countConcepts(Concepts concepts) {
return concepts.countConcepts();
}
static void indexConceptClass(Class extends Concept> c) { indexConceptClass(db_mainConcepts(), c); }
static void indexConceptClass(Concepts cc, Class extends Concept> c) {
ensureConceptClassIsIndexed(cc, c);
}
static AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static AutoCloseable tempSetTL(x30_pkg.x30_util.BetterThreadLocal tl, A a) {
return tempSetThreadLocalIfNecessary(tl, a);
}
// unclear semantics as to whether return null on null
static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static ArrayList asList(int[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(long[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static ArrayList asList(float[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static ArrayList asList(double[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static ArrayList asList(Iterator it) {
ArrayList l = new ArrayList();
if (it != null)
while (it.hasNext())
l.add(it.next());
return l;
}
// disambiguation
static ArrayList asList(IterableIterator s) {
return asList((Iterator) s);
}
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(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null) while ((a = p.next()) != null)
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 List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
// 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 ThreadLocal showConceptsTable_concepts = new ThreadLocal();
static ThreadLocal showConceptsTable_latestFirst = new ThreadLocal();
static ThreadLocal showConceptsTable_sorter = new ThreadLocal(); // func(Cl) -> Cl
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 Concepts concepts = optParam(showConceptsTable_concepts, db_mainConcepts());
final boolean latestFirst = boolParam(showConceptsTable_latestFirst);
Object sorter = optParam(showConceptsTable_sorter);
final List fields = listMinusList(concatLists(ll("id"), conceptFieldsInOrder(c)), dropFields);
final JTable table = sexyTable();
tablePopupMenu(table, new VF2() { public void get(JPopupMenu menu, final Integer row) { try {
addMenuItem(menu, "Delete", new Runnable() { public void run() { try {
final long id = toLong(getTableCell(table, row, 0));
deleteConcept_sync(concepts, id);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final long id = toLong(getTableCell(table, row, 0));\r\n deleteConcept_syn..."; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "addMenuItem(menu, \"Delete\", r {\r\n final long id = toLong(getTableCell(ta..."; }});
AutoCloseable __1 = tempSetTL(awtOnConceptChanges_concepts, concepts); try {
awtOnConceptChanges(table, new Runnable() { public void run() { try {
//print("Updating concept table");
List data = new ArrayList();
Collection extends Concept> l = list(concepts, c);
if (sorter != null) l = (Collection) callF(sorter, l);
for (Concept cc : l)
data.add(map(new F1() { public 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));
if (latestFirst) reverseInPlace(data);
data = (List) postProcess(pp, data);
fillTableWithData(table, data, map(__30 -> humanizeFormLabel(__30), 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 Collection<..."; }}, true);
return table;
} finally { _close(__1); }}
// renderer takes a concept and makes a map for display
static JTable makeConceptsTable(final Class cClass, final Object renderer) {
if (renderer == null) return makeConceptsTable(cClass);
final Object pp = optParam(showConceptsTable_postProcess);
final Object afterUpdate = optParam(showConceptsTable_afterUpdate);
final Concepts concepts = optParam(showConceptsTable_concepts, db_mainConcepts());
final boolean latestFirst = boolParam(showConceptsTable_latestFirst);
Object sorter = optParam(showConceptsTable_sorter);
boolean useStruct = boolParam(dataToTable_useStruct);
final JTable table = sexyTable();
AutoCloseable __2 = tempSetTL(awtOnConceptChanges_concepts, concepts); try {
awtOnConceptChanges(table, 1000, new Runnable() { public void run() { try {
List data = new ArrayList();
Collection l = list(concepts, cClass);
if (sorter != null) l = (Collection) callF(sorter, l);
for (A c : l)
addIfNotNull(data, (Map) pcallF(renderer, c));
if (latestFirst) reverseInPlace(data);
data = (List) postProcess(pp, data);
AutoCloseable __3 = tempSetTL(dataToTable_useStruct, useStruct); try {
dataToTable_uneditable(data, table);
pcallF(afterUpdate, table);
} finally { _close(__3); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "new List data;\r\n Collection l = list(concepts, cClass);\r\n if (s..."; }});
return table;
} finally { _close(__2); }}
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 Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static A swing(IF0 f) {
return (A) swingAndWait(f);
}
static JPanel jRightAlignedLine(Component... components) {
return jrightAlignedLine(components);
}
static JPanel jRightAlignedLine(List extends Component> components) {
return jrightAlignedLine(components);
}
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, O action) {
ret setButtonImage(img, jbutton("", action));
}*/
static JButton jbutton(Action action) {
return swingNu(JButton.class, action);
}
static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
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 A selectedConcept(JTable table, Class cc) {
return (A) getConcept(toLong(selectedTableCell(table, 0)));
}
static Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static Object withDBLock(Object r) {
Lock __0 = db_mainConcepts().lock; lock(__0); try {
return callF(r);
} finally { unlock(__0); } }
static A withDBLock(F0 r) {
return (A) withDBLock((Object) r);
}
static Object withDBLock(Concepts concepts, Object r) {
Lock __1 = concepts.lock; lock(__1); try {
return callF(r);
} finally { unlock(__1); } }
static A withDBLock(Concepts concepts, F0 r) {
return (A) withDBLock(concepts, (Object) r);
}
static A withDBLock(Concept concept, IF0 r) {
return (A) withDBLock(concept._concepts, r);
}
static class TableSearcher {
JTable table;
JTextField tfInput;
JComponent searchPanel, panel;
F2 rowTester;
List rowIndices;
String input() { return gtt(tfInput); }
}
static TableSearcher tableWithSearcher2(final JTable t, Object... __) {
final TableSearcher s = new TableSearcher();
final boolean precise = true;
s.table = t;
s.tfInput = jtextfield();
s.rowTester = new F2() { public Boolean get(String pat, Map row) { try { return anyValueContainsIgnoreCase(row, pat); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "anyValueContainsIgnoreCase(row, pat)"; }};
onUpdate(s.tfInput, new Runnable() {
List lastFiltered, lastOriginal;
public void run() {
String pat = s.input();
List> data = rawTableData(t);
if (eq(lastFiltered, data))
data = lastOriginal;
//print("Searching " + n(l(data), "entry"));
List data2 = new ArrayList();
List rowIndices = new ArrayList();
for (int i = 0; i < l(data); i++) {
Map map = data.get(i);
if (isTrue(callF(s.rowTester, pat, map))) {
data2.add(map);
rowIndices.add(i);
}
}
//print("Found " + n(l(data2), "entry"));
lastFiltered = data2;
lastOriginal = data;
dataToTable(t, data2);
if (precise) lastFiltered = rawTableData(t);
s.rowIndices = rowIndices;
}
});
s.searchPanel = withLabel("Search:", s.tfInput);
JComponent top = s.searchPanel;
s.panel = boolOptPar(__, "withMargin") ? northAndCenterWithMargin(top, t) : northAndCenter(top, t);
return s;
}
static JPanel centerAndSouthWithMargin(Component c, Component s) {
return centerAndSouth(c, withTopMargin(s));
}
static JPanel centerAndSouthWithMargin(int margin, Component c, Component s) {
return centerAndSouth(c, withTopMargin(margin, s));
}
static int withBottomMargin_defaultWidth = 6;
static JPanel withBottomMargin(Component c) {
return withBottomMargin(withBottomMargin_defaultWidth, c);
}
static JPanel withBottomMargin(final int w, final Component c) {
return swing(new F0() { public JPanel get() { try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(0, 0, w, 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.creat..."; }});
}
// action: voidfunc(int row)
static void tablePopupMenuItem(JTable table, String name, Object action) {
tablePopupMenu(table, new VF2() { public void get(JPopupMenu menu, final Integer row) { try {
addMenuItem(menu, name, new Runnable() { public void run() { try { pcallF(action, row) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, row)"; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "addMenuItem(menu, name, r { pcallF(action, row) });"; }});
}
static void tablePopupMenuItem(JTable table, String name, IVF1 action) {
tablePopupMenuItem(table, name, (Object) action);
}
// runnable can be a func(O o) {} receving the selected item
static JList onDoubleClick(final JList list, final Object runnable) {
{ swing(new Runnable() { public void run() { try {
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);
}
}
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "list.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(Mous..."; }}); }
return list;
}
// runnable can be a func(O o) {} receving the selected row index
static JTable onDoubleClick(final JTable table, final Object runnable) {
{ swing(new Runnable() { public void run() { try {
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);
}
}
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "table.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(Mou..."; }}); }
return table;
}
// other components get the pointer position
// only reacts on left button
static void onDoubleClick(final JComponent c, final Object runnable) {
{ swing(new Runnable() { public void run() { try {
c.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getButton() == 1 && evt.getClickCount() == 2)
callF(runnable, evt.getPoint());
}
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(MouseEv..."; }}); }
}
static void _close(AutoCloseable c) {
if (c != null) try {
c.close();
} catch (Throwable e) {
// Some classes stupidly throw an exception on double-closing
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else throw rethrow(e);
}
}
static Map putAll(Map a, Map extends A,? extends B> b) {
if (a != null && b != null) a.putAll(b);
return a;
}
static Map putAll(Map a, Object... b) {
if (a != null)
litmap_impl(a, b);
return a;
}
static LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static Map> callF_cache = newDangerousWeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static A callF(IF0 f) {
return f == null ? null : f.get();
}
static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Runnable r) { { if (r != null) r.run(); } return null; }
static Object callF(Object f, Object... args) {
if (f instanceof String)
return callMCWithVarArgs((String) f, args); // possible SLOWDOWN over callMC
return safeCallF(f, args);
}
static Object safeCallF(Object f, Object... 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 invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
}
// 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")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
// make concept instance that is not connected to DB
static A unlisted(Class c, Object... args) {
concepts_unlisted.set(true);
try {
return nuObject(c, args);
} finally {
concepts_unlisted.set(null);
}
}
static Concept unlisted(String name, Object... args) {
Class extends Concept> cc = findClass(name);
concepts_unlisted.set(true);
try {
return cc != null ? nuObject(cc) : new Concept(name);
} finally {
concepts_unlisted.set(null);
}
}
static A ccopyFieldsExcept(Concept x, A y, Set dontCopyFields) {
if (x == null || y == null) return y;
return ccopyFields2(x, y, setMinusSet(conceptFields(x), dontCopyFields));
}
static AutoCloseable tempSetMCOpt(final String field, Object value) {
final Object oldValue = getMCOpt(field);
setMCOpt(field, value);
return new AutoCloseable() { public String toString() { return "setMCOpt(field, oldValue);"; } public void close() throws Exception { setMCOpt(field, oldValue); }};
}
static JPanel showFormTitled2(String title, Object... parts) {
return showFormTitled_customLayout(formLayouter1(), title, parts);
}
// one array plus more elements
static Object[] arrayPlus(Object[] a1, Object... a2) {
return concatArrays(a1, a2);
}
static Object[] mapToObjectArray(Map map) {
List l = new ArrayList();
for (Object o : keys(map)) {
l.add(o);
l.add(map.get(o));
}
return toObjectArray(l);
}
static Object[] mapToObjectArray(Object f, Collection l) {
int n = l(l);
Object[] array = new Object[n];
if (n != 0) {
Iterator it = iterator(l);
for (int i = 0; i < n; i++)
array[i] = callF(f, it.next());
}
return array;
}
static Object[] mapToObjectArray(Object f, Object[] l) {
int n = l(l);
Object[] array = new Object[n];
for (int i = 0; i < n; i++)
array[i] = callF(f, l[i]);
return array;
}
static Object[] mapToObjectArray(Collection l, IF1 f) {
return mapToObjectArray(f, l);
}
static Object[] mapToObjectArray(A[] l, IF1 f) {
return mapToObjectArray(f, l);
}
static Object[] mapToObjectArray(IF1 f, A[] l) {
int n = l(l);
Object[] array = new Object[n];
for (int i = 0; i < n; i++)
array[i] = f.get(l[i]);
return array;
}
static int selectedRow(JTable t) {
return selectedTableRow(t);
}
static long toLong(Object o) {
if (o instanceof Number)
return ((Number) o).longValue();
if (o instanceof String)
return parseLong((String) o);
return 0;
}
static Object getTableCell(JTable tbl, int row, int col) {
if (row >= 0 && row < tbl.getModel().getRowCount())
return tbl.getModel().getValueAt(row, col);
return null;
}
// 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 == null) return null;
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) {
makeAccessible(f);
return f.get(o);
}
if (o instanceof DynamicObject)
return getOptDynOnly(((DynamicObject) o), field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static Object get_raw(Object o, String field) { try {
if (o == null) return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
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 Object get(String field, Object o) {
return get(o, field);
}
static boolean get(BitSet bs, int idx) {
return bs != null && bs.get(idx);
}
static int tableRowCount(JTable table) {
return tableRows(table);
}
static String unnullForIteration(String s) {
return s == null ? "" : s;
}
static Collection unnullForIteration(Collection l) {
return l == null ? immutableEmptyList() : l;
}
static List unnullForIteration(List l) { return l == null ? immutableEmptyList() : l; }
static int[] unnullForIteration(int[] l) { return l == null ? emptyIntArray() : l; }
static char[] unnullForIteration(char[] l) { return l == null ? emptyCharArray() : l; }
static double[] unnullForIteration(double[] l) { return l == null ? emptyDoubleArray() : l; }
static short[] unnullForIteration(short[] l) { return l == null ? emptyShortArray() : l; }
static Map unnullForIteration(Map l) {
return l == null ? immutableEmptyMap() : l;
}
static Iterable unnullForIteration(Iterable i) {
return i == null ? immutableEmptyList() : i;
}
static A[] unnullForIteration(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static BitSet unnullForIteration(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnullForIteration(Pt p) {
return p == null ? new Pt() : p;
}
//ifclass Symbol
static Symbol unnullForIteration(Symbol s) {
return s == null ? emptySymbol() : s;
}
//endif
static Pair unnullForIteration(Pair p) {
return p != null ? p : new Pair(null, null);
}
static long unnullForIteration(Long l) { return l == null ? 0L : l; }
static Class getFieldType(Object o, String field) {
return fieldType(o, field);
}
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt(String field, Object o) {
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;
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__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;
makeAccessible(f);
return f.get(null);
} catch (Exception __e) { throw rethrow(__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 JCheckBox jCenteredCheckBox() {
return centerCheckBox(new JCheckBox());
}
static JCheckBox jCenteredCheckBox(boolean checked) {
return centerCheckBox(new JCheckBox("", checked));
}
static JCheckBox jCenteredCheckBox(String text, boolean checked) {
return centerCheckBox(new JCheckBox(text, checked));
}
static JCheckBox jCenteredCheckBox(String text) {
return centerCheckBox(new JCheckBox(text));
}
static JCheckBox jCenteredCheckBox(String text, boolean checked, final Object onChange) {
return centerCheckBox(jCheckBox(text, checked, onChange));
}
// onChange can be a Runnable or a voidfunc(bool)
static JCheckBox jCenteredCheckBox(boolean checked, final Object onChange) {
return centerCheckBox(jCheckBox(checked, onChange));
}
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
if (o instanceof ThreadLocal) // TODO: remove this
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static boolean isTrue(Boolean b) {
return b != null && b.booleanValue();
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static boolean contains(Producer p, A a) {
if (p != null && a != null) while (true) {
A x = p.next();
if (x == null) break;
if (eq(x, a)) return true;
}
return false;
}
static boolean containsNewLines(String s) {
return containsNewLine(s);
}
static A optCast(Class c, Object o) {
return isInstance(c, o) ? (A) o : null;
}
static JTextArea typeWriterTextArea() {
return newTypeWriterTextArea();
}
static JTextArea typeWriterTextArea(String text) {
return newTypeWriterTextArea(text);
}
static boolean isSubtype(Class a, Class b) {
return isSubclass(a, b);
}
static JComboBox jcomboboxFromConcepts_str(Class extends Concept> cc) {
return jcomboboxFromConcepts_str(db_mainConcepts(), cc);
}
static JComboBox jcomboboxFromConcepts_str(Concepts concepts, Class extends Concept> cc) { return jcomboboxFromConcepts_str(concepts, cc, null); }
static JComboBox jcomboboxFromConcepts_str(Concepts concepts, Class extends Concept> cc, Concept selected) {
List items = ll("");
String selectedItem = null;
for (Concept c : list(concepts, cc)) {
String item = c.id + " - " + c;
if (c == selected) selectedItem = item;
items.add(item);
}
return jcombobox(items, selectedItem);
}
static JPasswordField jpassword() {
return jpassword("");
}
static JPasswordField jpassword(final String pw) {
return swing(new F0() { public JPasswordField get() { try { return new JPasswordField(pw); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret new JPasswordField(pw);"; }});
}
static String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static A getVar(IF0 v) {
return v == null ? null : v.get();
}
static AutoComboBox autoComboBox() {
return autoComboBox(new ArrayList());
}
static AutoComboBox autoComboBox(final Collection items) {
return swing(new F0() { public AutoComboBox get() { try {
AutoComboBox cb = new AutoComboBox();
cb.setKeyWord(items);
return cb;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "new AutoComboBox cb;\r\n cb.setKeyWord(items);\r\n ret cb;"; }});
}
static AutoComboBox autoComboBox(String value, Collection items) {
return setText(autoComboBox(items), value);
}
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)
{ ping(); x.add(callF(f, o)); }
return x;
}
static List map(Iterable l, F1 f) { return map(f, l); }
static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null) for (A o : l)
{ ping(); x.add(callF(f, o)); }
return x;
}
static List map(IF1 f, Iterable l) { return map(l, f); }
static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
{ ping(); x.add(f.get(o)); }
return x;
}
static List map(IF1 f, A[] l) { return map(l, f); }
static List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
{ ping(); x.add(f.get(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);
}
// map: func(key, value) -> list element
static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null) for (Object _e : map.entrySet()) { ping();
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static List map(Map map, IF2 f) {
return map(map, (Object) f);
}
// new magic alias for mapLL - does it conflict?
static List map(IF1 f, A data1, A... moreData) {
List x = emptyList(l(moreData)+1);
x.add(f.get(data1));
if (moreData != null) for (A o : moreData)
{ ping(); x.add(f.get(o)); }
return x;
}
static List collect(Iterable c, String field) {
return collectField(c, field);
}
static List collect(String field, Iterable c) {
return collectField(c, field);
}
/*ifclass Concept
static L collect(Class c, S field) {
ret collect(list(c), field);
}
endif
TODO: make translator ignore stuff in ifclass until resolved
*/
static List list(Class type) {
return db_mainConcepts().list(type);
}
static List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static List list(String type) {
return db_mainConcepts().list(type);
}
static List list(Concepts concepts, String type) {
return concepts.list(type);
}
static A printException(A e) {
printStackTrace(e);
return e;
}
static JTextField jTextField() {
return jTextField("");
}
static JTextField jTextField(final String text) {
return swing(new F0() { public JTextField get() { try {
JTextField tf = new JTextField(unnull(text));
standardTextFieldPopupMenu(tf);
jenableUndoRedo(tf);
tf.selectAll();
return tf;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JTextField tf = new JTextField(unnull(text));\r\n standardTextFieldPopupMenu..."; }});
}
static JTextField jTextField(Object o) {
return jTextField(strOrEmpty(o));
}
static JComponent unwrap(JComponent c) {
return c instanceof JScrollPane ? unwrapScrollPane((JScrollPane) c) : c;
}
static Class fieldType(Object o, String field) {
Field f = getField(o, field);
return f == null ? null : f.getType();
}
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);
}
// returns number of changes
static int cset(Concept c, Object... values) { try {
if (c == null) return 0;
warnIfOddCount(values = expandParams(c.getClass(), values));
int changes = 0;
for (int i = 0; i+1 < l(values); i += 2)
if (_csetField(c, (String) values[i], values[i+1])) ++changes;
return changes;
} catch (Exception __e) { throw rethrow(__e); } }
static int cset(Iterable extends Concept> l, Object... values) {
int changes = 0;
for (Concept c : unnullForIteration(l))
changes += cset(c, values);
return changes;
}
static int cset(Concept.Ref c, Object... values) {
return cset(getVar(c), values);
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(Iterable c) { return c == null || !c.iterator().hasNext(); }
static boolean empty(CharSequence 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);
if (o instanceof byte[]) return empty((byte[]) o);
if (o == null) return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(Iterator i) { return i == null || !i.hasNext(); }
static boolean empty(double[] a) { return a == null || a.length == 0; }
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 empty(byte[] a) { return a == null || a.length == 0; }
static boolean empty(short[] a) { return a == null || a.length == 0; }
static boolean empty(MultiSet ms) { return ms == null || ms.isEmpty(); }
static boolean empty(File f) { return getFileSize(f) == 0; }
static boolean empty(Rect r) { return !(r != null && r.w != 0 && r.h != 0); }
static Object convertToField(Object o, Class c, String field) {
Field f = setOpt_findField(c, field);
if (f == null) return o;
Class t = f.getType();
if (t == Long.class || t == long.class)
return toLong(o);
else if (t == Integer.class || t == int.class)
return toInt(o);
else if (t == Float.class || t == float.class)
return toFloat(o);
else if (t == Double.class || t == double.class)
return toDouble(o);
else if (t == String.class)
return o instanceof String ? (String) o : str(o);
else if (t == File.class) {
if (o instanceof String) return new File((String) o).getAbsoluteFile();
}
return o;
}
static String trimIf(boolean b, String s) {
return b ? trim(s) : s;
}
static String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret c.getText();"; }});
}
static String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret c.getText();"; }});
}
static String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() { public Object get() { try { return l.getText(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret l.getText();"; }});
}
// returns the contents of text field for editable combo box
static String getText(final JComboBox cb) {
if (cb == null) return null;
if (isEditableComboBox(cb))
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
static Concept getConcept(long id) {
return db_mainConcepts().getConcept(id);
}
static Concept getConcept(Concepts concepts, long id) {
return concepts.getConcept(id);
}
static A getConcept(Class cc, long id) {
return getConcept(db_mainConcepts(), cc, id);
}
static A getConcept(Concepts concepts, Class cc, long id) {
Concept c = concepts.getConcept(id);
if (c == null) return null;
if (!isInstance(cc, c))
throw fail("Can't convert concept: " + getClassName(c) + " -> " + getClassName(cc) + " (" + id + ")");
return (A) c;
}
static long parseFirstLong(String s) {
return parseLong(jextract("", s));
}
static boolean isChecked(JCheckBox checkBox) {
return checkBox != null && (boolean) swing(new F0() { public Boolean get() { try { return checkBox.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret checkBox.isSelected();"; }});
}
static boolean isChecked(JCheckBoxMenuItem mi) {
return mi != null && (boolean) swing(new F0() { public Boolean get() { try { return mi.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret mi.isSelected();"; }});
}
static boolean isChecked(JRadioButton rb) {
return rb != null && (boolean) swing(() -> rb.isSelected());
}
static void cUpdatePNGFile(Concept c, String field, BufferedImage image, boolean deleteOldFile) {
PNGFile png = (PNGFile) (cget(c, field));
if (image == null && png != null)
cset(c, field, null);
else if (image != null &&
(png == null || !imagesIdentical(png.getImage(), image))) {
if (png != null && deleteOldFile) png.delete();
cset(c, field, new PNGFile(image));
}
}
static Set fields(Object c) {
return listFields(c);
}
static List listWithoutSet(Collection l, Collection stuff) {
return listMinusSet(l, stuff);
}
static List filter(Iterable c, Object pred) {
if (pred instanceof F1) return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null) for (Object o : c)
if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
static List filter(Object pred, Iterable c) {
return filter(c, pred);
}
static List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null) for (B o : c)
if (pred.get(o))
x.add(o);
return x;
}
static List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
//ifclass IF1
static List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null) for (B o : c)
if (pred.get(o))
x.add(o);
return x;
}
static List filter(B[] c, IF1 pred) {
List x = new ArrayList();
if (c != null) for (B o : c)
if (pred.get(o))
x.add(o);
return x;
}
static List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
//endif
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;
}
static Set joinSets(Collection ... l) {
Set set = similarEmptySet(first(l));
for (Collection o : l)
if (o != null)
set.addAll(o);
return set;
}
static Set setPlus(Collection l, A... more) {
Set set = similarEmptySet(l);
addAll(set, l);
for (A a : more) set.add(a);
return set;
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
// convenience shortcut for keys_gen
static Set keys(Object map) {
return keys((Map) map);
}
static Set keys(MultiSet ms) {
return ms.keySet();
}
static Set keys(MultiSetMap mm) {
return mm.keySet();
}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static String structureOrText_crud(Object o) {
if (o == null) return "";
if (o instanceof Long) return str(o); // avoid the "L"
if (o instanceof File) return ((File) o).getAbsolutePath();
return str(o);
}
static String strOrNull(Object o) {
return o == null ? null : str(o);
}
static Concepts newConceptsWithClassFinder(String progID) {
Concepts cc = new Concepts(progID);
cc.classFinder = _defaultClassFinder();
return cc;
}
static String getDBProgramID_id;
static String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
static String makeFrame_defaultIcon;
static boolean makeFrame_hideConsole = false;
static ThreadLocal> makeFrame_post = new ThreadLocal();
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) {
final VF1 post = optParam(makeFrame_post);
return swing(new F0() { public JFrame get() { try {
if (getFrame(content) != null)
return getFrame(setFrameTitle((Component) content, title));
final JFrame frame = new JFrame(title);
if (makeFrame_defaultIcon != null)
setFrameIconLater(frame, makeFrame_defaultIcon);
_initFrame(frame);
Component wrapped = wrap(content);
if (wrapped != null)
frame.getContentPane().add(wrapped);
frame.setBounds(defaultNewFrameBounds());
callF(post, frame);
if (showIt)
frame.setVisible(true);
//callOpt(content, "requestFocus");
//exitOnFrameClose(frame);
if (showIt && makeFrame_hideConsole) {
hideConsole();
makeFrame_hideConsole = false;
}
return frame;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (getFrame(content) != null)\r\n ret getFrame(setFrameTitle((Component) ..."; }});
}
static boolean frameTooSmall(JFrame frame) {
return frame.getWidth() < 100 || frame.getHeight() < 50;
}
static void frameStandardSize(JFrame frame) {
frame.setBounds(300, 100, 500, 400);
}
static void setFrameContents(final Component c, final Object contents) { swing(new Runnable() { public void run() { try {
JFrame frame = getFrame(c);
if (frame == null) return;
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 if (frame == null) return;\r\n frame.getContent..."; }}); }
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 (ewicOneOf(s, "ss", "ch")) return s + "es";
if (ewic(s, "s")) return s;
return s + "s";
}
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 JFrame getFrame(final Object _o) {
return swing(new F0() { public 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((Button..."; }});
}
// 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 Rectangle maximumWindowBounds() {
return maxWindowBounds();
}
static long sysNow() {
ping();
return System.nanoTime()/1000000;
}
static volatile boolean licensed_yes = true;
static boolean licensed() {
if (!licensed_yes) return false;
ping_okInCleanUp();
return true;
}
static void licensed_off() {
licensed_yes = false;
}
static boolean warn_on = true;
static ThreadLocal> warn_warnings = new ThreadLocal();
static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
addToCollection(warn_warnings.get(), s);
}
static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll((IVF1) (__1 -> printStackTrace2(__1))));
static boolean _handleException_showThreadCancellations = false;
static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException) {
if (_handleException_showThreadCancellations)
System.out.println(getStackTrace_noRecord(e2));
return;
}
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
try {
printStackTrace2(e3); // not using pcall here - it could lead to endless loops
} catch (Throwable e4) {
System.out.println(getStackTrace(e3));
System.out.println(getStackTrace(e4));
}
}
}
static volatile boolean sleep_noSleep = false;
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); } }
volatile static boolean conceptsAndBot_running = false;
static boolean conceptsAndBot_thinOnStart = true;
static void conceptsAndBot() {
conceptsAndBot(null);
}
static void conceptsAndBot(Integer autoSaveInterval) {
if (conceptsAndBot_running) return;
conceptsAndBot_running = true;
Concepts cc = db_mainConcepts();
try {
if (cc.useFileLock) {
if (!cc.fileLock().tryToLock()) {
ensureDBNotRunning(dbBotStandardName());
cc.fileLock().forceLock();
}
} else
ensureDBNotRunning(dbBotStandardName());
} catch (Throwable _e) {
cc.dontSave = true; // SAFETY
throw rethrow(_e); }
cc.persist(autoSaveInterval);
dbBot(false);
if (conceptsAndBot_thinOnStart) { try {
thinAProgramsBackups(getDBProgramID(), true);
} catch (Throwable __e) { _handleException(__e); }}
}
static String programIDPlusHome() {
return programIDPlusHome(programID(), userHomeIfNotActual());
}
static String programIDPlusHome(String programID, File home) {
return programIDPlusHome(programID, f2s(home));
}
static String programIDPlusHome(String programID, String home) {
if (home != null)
programID += " " + quote(home);
return programID;
}
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 boolean match(String pat, List toks, Matches matches) {
return match3(pat, toks, matches);
}
static void swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
timer.setRepeats(false);
timer.start();
}
static void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
static 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 String programName() {
return getProgramName();
}
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(defaultBotName());
}
// Use like this: printVars_str(+x, +y);
// Or: printVars("bla", +x);
// Or: printVars bla(+x);
static void printVars_str(Object... params) {
print(renderVars_str(params));
}
static void ensureConceptClassIsIndexed(Class extends Concept> c) { ensureConceptClassIsIndexed(db_mainConcepts(), c); }
static void ensureConceptClassIsIndexed(Concepts cc, Class extends Concept> c) {
if (cc != null && c != null && !isConceptClassIndexed(cc, c))
indexRandomConceptField(cc, c);
}
static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null) return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}
static AutoCloseable tempSetThreadLocalIfNecessary(ThreadLocal tl, A a) {
if (tl == null) return null;
A prev = tl.get();
if (eq(prev, a)) return null;
tl.set(a);
return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}
static AutoCloseable tempSetThreadLocalIfNecessary(x30_pkg.x30_util.BetterThreadLocal tl, A a) {
if (tl == null) return null;
A prev = tl.get();
if (eq(prev, a)) return null;
tl.set(a);
return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}
static ArrayList emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
// Try to match capacity
static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
// get correct type at once
static ArrayList emptyList(Class c) {
return new ArrayList();
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
static A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
static A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static A optParam(ThreadLocal tl) {
return optPar(tl);
}
static Object optParam(String name, Map params) {
return mapGet(params, name);
}
// now also takes a map as single array entry
static A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt))) throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2)
if (eq(opt[i], name))
return (A) opt[i+1];
return defaultValue;
}
static Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
static Object optParam(String name, Object[] params) {
return optParam(params, name);
}
static boolean boolParam(ThreadLocal tl) {
return boolOptParam(tl);
}
// defaults to false
static boolean boolParam(Object[] __, String name) {
return boolOptParam(__, name);
}
static boolean boolParam(String name, Object[] __) {
return boolOptParam(name, __);
}
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 List concatLists(Iterable ... lists) {
List l = new ArrayList();
if (lists != null) for (Iterable list : lists)
addAll(l, list);
return l;
}
static List concatLists(Collection extends Iterable > lists) {
List l = new ArrayList();
if (lists != null) for (Iterable list : lists)
addAll(l, list);
return l;
}
static boolean sexyTable_drag = false;
static JTable sexyTable() {
final JTable table = sexyTableWithoutDrag();
if (sexyTable_drag)
tableEnableTextDrag(table); // TODO: seems to interfere with double clicks
return table;
}
static class tablePopupMenu_Maker {
List menuMakers = new ArrayList();
}
static Map tablePopupMenu_map = newWeakHashMap();
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));
{ swing(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()) return;
JPopupMenu menu = new JPopupMenu();
int row = table.rowAtPoint(e.getPoint());
if (table.getSelectedRowCount() < 2)
table.setRowSelectionInterval(row, row);
int modelRow = convertTableRowToModel(table, row);
int emptyCount = menu.getComponentCount();
tablePopupMenu_mouseEvent.set(e);
for (Object menuMaker : _maker.menuMakers)
pcallF(menuMaker, menu, modelRow);
vmBus_send("showingPopupMenu", table, menu);
// 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 ==..."; }}); }
}
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(Menu menu, String text, Object action) {
menu.add(menuItem(text, action));
}
static void addMenuItem(JMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static void addMenuItem(JMenuBar menuBar, String text, Runnable action) {
addMenuItem(menuBar, jmenuItem(text, action));
}
static void addMenuItem(JMenuBar menuBar, JMenuItem menuItem) {
addDirectMenuItem(menuBar, menuItem);
}
static void deleteConcept_sync(long id) {
deleteConcept_sync(db_mainConcepts(), id);
}
static void deleteConcept_sync(Concepts concepts, long id) {
withDBLock(concepts, new Runnable() { public void run() { try { concepts.deleteConcept(id) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "concepts.deleteConcept(id)"; }});
}
static void deleteConcept_sync(Concept c) {
if (c != null) withDBLock(c._concepts, new Runnable() { public void run() { try { c.delete() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.delete()"; }});
}
static void deleteConcept_sync(Concept.Ref ref) {
if (ref != null) deleteConcept_sync(ref.get());
}
static int awtOnConceptChanges_defaultDelay = 500;
static ThreadLocal awtOnConceptChanges_concepts = new ThreadLocal();
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 = false;
static void awtOnConceptChanges(JComponent component, int delay, int firstDelay, final Object runnable, final boolean runOnFirstTime) {
final Concepts concepts = or(awtOnConceptChanges_concepts.get(), db_mainConcepts());
installTimer(component, delay, firstDelay, new Runnable() {
long c = runOnFirstTime ? -1 : concepts.changes;
boolean skip = false;
public void run() {
long _c = concepts.changes;
if (awtOnConceptChanges_debug)
print("awtOnConceptChanges: " + _c + " / " + c);
if (skip) skip = false;
else if (_c != c) {
c = _c;
call(runnable);
skip = true;
}
}
});
}
static Object renderForTable(Object o) {
{ Object __1= toBufferedImageOpt(o); if (__1 != null) return __1; }
if (o instanceof String && containsNewLine((String) o))
return escapeNewLines((String) o);
return o;
}
static Object cget(Object c, String field) {
c = derefRef(c);
Object o = getOpt(c, field);
return derefRef(o);
}
static Object cget(String field, Object c) {
return cget(c, field);
}
static List reverseInPlace(List l) {
return reverseList(l);
}
static A postProcess(Object f, A a) {
return callPostProcessor(f, a);
}
static A postProcess(IF1 f, A a) {
return callPostProcessor(f, 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);
// TODO: keep model if columns identical?
setTableModel(table, model);
}
static DefaultTableModel fillTableWithData_makeModel(List rows, String... colNames) {
Pair p = fillTableWithData_makeData(rows, colNames);
return new DefaultTableModel(p.a, p.b) {
public Class getColumnClass(int column) {
return or(_getClass(getValueAt(0, column)), String.class);
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
};
}
static Map humanizeFormLabel_replacements = litmap("id" , "ID", "md5" , "MD5");
static String humanizeFormLabel(String s) {
if (containsSpace(s)) return s;
return firstToUpper(
joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID")
);
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static A pcallF(F0 f) { try {
return f == null ? null : f.get();
} catch (Throwable __e) { return null; } }
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static void pcallF(VF1 f, A a) {
try {
{ if (f != null) f.get(a); }
} catch (Throwable __e) { _handleException(__e); }
}
static A pcallF(IF0 f) { try {
return f == null ? null : f.get();
} catch (Throwable __e) { return null; } }
static B pcallF(IF1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static boolean addIfNotNull(Collection l, A a) {
return a != null && l != null & l.add(a);
}
static void addIfNotNull(MultiSet ms, A a) {
if (a != null && ms != null) ms.add(a);
}
static JTable dataToTable_uneditable(Object data, final JTable table) {
return dataToTable_uneditable(table, data);
}
static JTable dataToTable_uneditable(final JTable table, final Object data) {
if (table != null) { 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 A setFrameTitle(A c, final String title) {
final Frame f = getAWTFrame(c);
if (f != null) { swing(new Runnable() { public void run() { try { f.setTitle(title);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.setTitle(title);"; }}); }
return c;
}
static A setFrameTitle(String title, A c) {
return setFrameTitle(c, title);
}
// magically find a field called "frame" in main class :-)
static JFrame setFrameTitle(String title) {
Object f = getOpt(mc(), "frame");
if (f instanceof JFrame)
return setFrameTitle((JFrame) f, title);
return null;
}
static void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(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 JPanel jrightAlignedLine(final Component... components) {
return swing(new F0() { public RightAlignedLine get() { try { return new RightAlignedLine(components); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret RightAlignedLine(components);"; }});
}
static JPanel jrightAlignedLine(List extends Component> components) {
return jrightAlignedLine(asArray(Component.class, components));
}
static boolean newButton_autoToolTip = true;
// action can be Runnable or a function name
static JButton newButton(final String text, final Object action) {
return swing(new F0() { public JButton get() { try {
String text2 = dropPrefix("[disabled] ", text);
final JButton btn = new JButton(text2);
if (l(text2) < l(text)) btn.setEnabled(false);
if (newButton_autoToolTip) {
btn.setToolTipText(btn.getText());
//onChangeAndNow(btn, r { btn.setToolTipText(btn.getText()) });
}
// submitButtonOnEnter(btn); // test this first
if (action != null)
btn.addActionListener(actionListener(action, btn));
return btn;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "S text2 = dropPrefix(\"[disabled] \", text);\r\n final JButton btn = new JButt..."; }});
}
static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
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 Object selectedTableCell(JTable t, int col) {
return getTableCell(t, selectedTableRow(t), col);
}
static Object selectedTableCell(final JTable t) {
return swing(new F0() { public Object get() { try { return selectedTableCell(t, t.getSelectedColumn()); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret selectedTableCell(t, t.getSelectedColumn());"; }});
}
static Object selectedTableCell(final JTable t, final String colName) {
return swing(new F0() { public Object get() { try { return selectedTableCell(t, tableColumnViewIndex(t, colName)); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret selectedTableCell(t, tableColumnViewIndex(t, colName));"; }});
}
static String defaultThreadName_name;
static String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static Runnable wrapAsActivity(Object r) {
if (r == null) return null;
Runnable r2 = toRunnable(r);
Object mod = dm_current_generic();
if (mod == null) return r2;
return new Runnable() { public void run() { try {
AutoCloseable c = (AutoCloseable) (rcall("enter", mod));
AutoCloseable __1 = c; try {
r2.run();
} finally { _close(__1); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable c = (AutoCloseable) (rcall enter(mod));\r\n temp c;\r\n r2.r..."; }};
}
// runnable = Runnable or String (method name)
static Thread newThread(Object runnable) {
return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)));
}
static Thread newThread(Object runnable, String name) {
if (name == null) name = defaultThreadName();
return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static Thread newThread(String name, Object runnable) {
return newThread(runnable, 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 Map _registerThread_threads;
static Object _onRegisterThread; // voidfunc(Thread)
static Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static void _registerThread() {
_registerThread(Thread.currentThread());
}
static void lock(Lock lock) { try {
ping();
if (lock == null) return;
try {
vmBus_send("locking", lock, "thread" , currentThread());
lock.lockInterruptibly();
vmBus_send("locked", lock, "thread" , currentThread());
} catch (InterruptedException e) {
Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
printStackTrace(e);
rethrow(e);
}
// NO call to ping here! Make sure lock is always released.
} 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 void unlock(Lock lock, String msg) {
if (lock == null) return;
lock.unlock();
vmBus_send("unlocked", lock, "thread" , currentThread());
print("Unlocked: " + msg); // print afterwards to make sure the lock is always unlocked
}
static void unlock(Lock lock) {
if (lock == null) return;
lock.unlock();
vmBus_send("unlocked", lock, "thread" , currentThread());
}
static String gtt(JTextComponent c) {
return getTextTrim(c);
}
static String gtt(JComboBox cb) {
return getTextTrim(cb);
}
static JTextField jtextfield() {
return jTextField();
}
static JTextField jtextfield(String text) {
return jTextField(text);
}
static JTextField jtextfield(Object o) {
return jTextField(o);
}
static boolean anyValueContainsIgnoreCase(Map map, String pat) {
for (Object val : values(map))
if (val instanceof String && containsIgnoreCase((String) val, pat))
return true;
return false;
}
// 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 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 boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
// a little kludge for stuff like eq(symbol, "$X")
static boolean eq(Symbol a, String b) {
return eq(str(a), b);
}
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(short[] a) { return a == null ? 0 : a.length; }
static int l(long[] 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(double[] 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(Iterator i) { return iteratorCount_int_close(i); } // consumes the iterator && closes it if possible
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 == null ? 0
: o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: o instanceof Collection ? l((Collection) o)
: o instanceof Object[] ? l((Object[]) o)
: o instanceof boolean[] ? l((boolean[]) o)
: o instanceof byte[] ? l((byte[]) o)
: o instanceof char[] ? l((char[]) o)
: o instanceof short[] ? l((short[]) o)
: o instanceof int[] ? l((int[]) o)
: o instanceof float[] ? l((float[]) o)
: o instanceof double[] ? l((double[]) o)
: o instanceof long[] ? l((long[]) o)
: (Integer) call(o, "size");
}
static int l(MultiSet ms) { return ms == null ? 0 : ms.size(); }
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);
}
// "now" is ignored now
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) { _handleException(__e); }}
} else if (data instanceof Map) {
Map map = (Map) data;
for (Object key : map.keySet()) {
Object value = map.get(key);
rows.add(litlist(structureOrTextForUser(key), structureOrTextForUser(value)));
}
} else if (data != null)
print("Unknown data type: " + data);
fillTableWithData(table, rows, cols);
return table;
}
static JComponent withLabel(String label, JComponent component) {
return westAndCenter(jlabel(label + " "), component);
}
static JComponent withLabel(JComponent label, JComponent component) {
return westAndCenterWithMargin(label, component);
}
static boolean boolOptPar(ThreadLocal tl) {
return boolOptParam(tl);
}
// defaults to false
static boolean boolOptPar(Object[] __, String name) {
return boolOptParam(__, name);
}
static boolean boolOptPar(String name, Object[] __) {
return boolOptParam(__, name);
}
static JPanel northAndCenterWithMargin(int margin, Component n, Component c) {
return northAndCenter(withBottomMargin(margin, n), c);
}
static JPanel northAndCenterWithMargin(Component n, Component c) {
return northAndCenter(withBottomMargin(n), c);
}
static JPanel northAndCenter(Component n, Component c) {
return centerAndNorth(c, n);
}
static JPanel centerAndSouth(final Component c, final Component s) {
return swing(new F0() { public JPanel get() { try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
if (s != null) panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT..."; }});
}
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() { public 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.creat..."; }});
}
static HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static void litmap_impl(Map map, Object... x) {
if (x != null) for (int i = 0; i < x.length-1; i += 2)
if (x[i+1] != null)
map.put(x[i], x[i+1]);
}
static Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
static Object callMCWithVarArgs(String method, Object... args) {
return call_withVarargs(mc(), method, args);
}
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(Object... objects) { throw new Fail(objects); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static Object invokeMethod(Method m, Object o, Object... args) { try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) { throw rethrow(__e); } }
static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive()
: isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
// Note: The error reporting only works with Java VM option --illegal-access=deny
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static Object nuObject(String className, Object... args) { try {
return nuObject(classForName(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 {
if (args.length == 0) return nuObjectWithoutArguments(c); // cached!
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
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 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 A ccopyFields2(Concept x, A y, Iterable fields) {
if (x == null || y == null) return y;
for (String field : unnull(fields)) {
Object o = cget(x, field);
if (o != null)
cset(y, field, o);
}
return y;
}
static Set setMinusSet(Set l, Collection stuff) {
if (empty(stuff)) return l;
Set set = asSet(stuff);
Set l2 = similarEmptySet(l);
for (A a : l) if (!set.contains(a)) l2.add(a);
return l2;
}
static Set setMinusSet(Collection l, Collection stuff) {
return setMinusSet(asSet(l), stuff);
}
static String[] conceptFields_drop = {"className", "fieldValues", "id", "created", "_modified", "refs", "backRefs", "_concepts"};
static Set conceptFields(Concept c) {
return setMinus(mergeSets(allNonStaticNonTransientFields(c), keys(c.fieldValues)), conceptFields_drop);
}
static Set conceptFields(Class extends Concept> c) {
return setMinus(allNonStaticNonTransientFields(c), conceptFields_drop);
}
static Object getMCOpt(String field) {
return getOptMC(field);
}
static void setMCOpt(String field, Object value) {
setOptMC(field, value);
}
static JPanel showFormTitled_customLayout(final F1 layouter, final String title, final Object... parts) {
return showFormTitled_customArrangement(false, new F1, JPanel>() { public JPanel get(List components) { try {
return customLayoutPanel(layouter, components); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "customLayoutPanel(layouter, components)"; }}, title, parts);
}
static int formLayouter1_yPlus = 5; // make higher (bug fixing)
static int formLayouter1_fixer2 = 0;
static F1 formLayouter1() {
final int yplus = formLayouter1_yPlus, fixer2 = formLayouter1_fixer2;
return new F1() { public Dimension get(Container parent) { try {
List l = getComponents(parent);
BitSet bigOnes = new BitSet();
for (int i = 0; i < l(l); i++)
if (containsATextArea(l.get(i))) add(bigOnes, i);
int nBigOnes = bigOnes.cardinality();
int mandatoryHeight = totalPreferredHeight(listWithoutIndicesInBitSet(l, bigOnes));
int gap = 4, outerSpacing = 5;
Dimension size = parent.getSize();
int gapsAndMargins = outerSpacing*2-(l(l)-1)*gap;
int totalSpace = size.height-gapsAndMargins-fixer2;
int liberalSpace = totalSpace-mandatoryHeight;
double perBigOne = doubleRatio(liberalSpace, nBigOnes);
double y = outerSpacing;
for (int i = 0; i < l(l); i++) {
Component c = l.get(i);
boolean big = contains(bigOnes, i);
double h = big ? perBigOne : c.getPreferredSize().height;
int actualY = iround(y);
c.setBounds(10, actualY, size.width-outerSpacing*2, iround(y+h)-actualY);
y += h+gap;
}
// return preferred size
Dimension pref = componentsBoundingSize(parent, outerSpacing);
if (parent.getHeight() <= 0) { // pre-showing - maybe we should always do this
int tph = totalPreferredHeight(l);
pref.height = tph+gapsAndMargins+yplus;
}
return pref;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "L l = getComponents(parent);\r\n new BitSet bigOnes;\r\n for i o..."; }};
}
static Object[] concatArrays(Object[]... arrays) {
int l = 0;
for (Object[] a : arrays) l += l(a);
Object[] x = new Object[l];
int i = 0;
for (Object[] a : arrays) if (a != null) {
System.arraycopy(a, 0, x, i, l(a));
i += l(a);
}
return x;
}
static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static int selectedTableRow(final JTable t) {
return t == null ? -1 : swing(new F0() { public Integer get() { try { return t.getSelectedRow(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret t.getSelectedRow();"; }});
}
static long parseLong(String s) {
if (empty(s)) return 0;
return Long.parseLong(dropSuffix("L", s));
}
static long parseLong(Object s) {
return Long.parseLong((String) s);
}
static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Object getOptDynOnly(DynamicObject o, String field) {
if (o == null || o.fieldValues == null) return null;
return o.fieldValues.get(field);
}
static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static int tableRows(JTable table) {
return (int) swingCall(table, "getRowCount");
}
static List immutableEmptyList() {
return Collections.emptyList();
}
static int[] emptyIntArray_a = new int[0];
static int[] emptyIntArray() { return emptyIntArray_a; }
static char[] emptyCharArray = new char[0];
static char[] emptyCharArray() { return emptyCharArray; }
static double[] emptyDoubleArray = new double[0];
static double[] emptyDoubleArray() { return emptyDoubleArray; }
static short[] emptyShortArray = new short[0];
static short[] emptyShortArray() { return emptyShortArray; }
static Map immutableEmptyMap() {
return Collections.emptyMap();
}
static Object[] emptyObjectArray_a = new Object[0];
static Object[] emptyObjectArray() { return emptyObjectArray_a; }
static Symbol emptySymbol_value;
static Symbol emptySymbol() {
if (emptySymbol_value == null) emptySymbol_value = symbol("");
return emptySymbol_value;
}
//static final Map> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init);
static class getOpt_Map extends WeakHashMap {
getOpt_Map() {
if (getOpt_special == null) getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
//print("getOpt clear");
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
//static final Map> getOpt_cache = _registerWeakMap(synchroMap(new getOpt_Map));
static HashMap getOpt_special; // just a marker
/*static void getOpt_special_init(Map map) {
map.put(Class.class, getOpt_special);
map.put(S.class, getOpt_special);
}*/
static Map getOpt_getFieldMap(Object o) {
Class c = _getClass(o);
HashMap map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
return map;
}
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Map map = getOpt_getFieldMap(o);
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 syncMapGet2(((DynamicObject) o).fieldValues, 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();
if (!reflection_classesNotToScan().contains(c.getName())) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
makeAccessible(f);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
}
if (getOpt_cache != null) getOpt_cache.put(c, map);
return map;
}
static JCheckBox centerCheckBox(JCheckBox cb) {
return setHorizontalAlignment(SwingConstants.CENTER, cb);
}
static JCheckBox jCheckBox() {
return swingNu(JCheckBox.class);
}
static JCheckBox jCheckBox(boolean checked) {
return swingNu(JCheckBox.class, "", checked);
}
static JCheckBox jCheckBox(String text, boolean checked) {
return swingNu(JCheckBox.class, text, checked);
}
static JCheckBox jCheckBox(String text) {
return swingNu(JCheckBox.class, 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 boolean containsNewLine(String s) {
return contains(s, '\n'); // screw \r, nobody needs it
}
static boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
static JTextArea newTypeWriterTextArea() {
return newTypeWriterTextArea("");
}
static JTextArea newTypeWriterTextArea(String text) {
return withTypeWriterFont(jTextArea(text));
}
static boolean isSubclass(Class a, Class b) {
return a != null && b != null && b.isAssignableFrom(a);
}
static JComboBox jcombobox(final String... items) {
return swing(new F0() { public JComboBox get() { try { return new JComboBox(items); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret new JComboBox(items);"; }});
}
static JComboBox jcombobox(Collection items) {
return jcombobox(toStringArray(items));
}
static JComboBox jcombobox(Collection items, String selectedItem) {
return selectItem(selectedItem, jcombobox(items));
}
static boolean setText_opt = true; // optimize by calling getText first
static A setText(A c, Object text) {
setText((JComponent) c, text);
return c;
}
static A setText(final A c, Object text) {
// only for editable combo boxes at this point
final String s = strUnnull(text);
{ swing(new Runnable() { public void run() { try {
c.getEditor().setItem(s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.getEditor().setItem(s);"; }}); }
return c;
}
static void setText(JLabel c, Object text) {
setText((JComponent) c, text);
}
static JButton setText(JButton c, Object text) {
setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text)));
return c;
}
static A setText(final A c, Object text) {
if (c == null) return null;
final String s = strUnnull(text);
{ swing(new Runnable() { public void run() { try {
if (!setText_opt || neq(callOpt(c, "getText"), s))
call(c, "setText", s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n call(c, \"setText\", s);"; }}); }
return c;
}
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll = false;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions = false;
static Map ping_actions = newWeakHashMap();
static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
// always returns true
static boolean ping() {
//ifdef useNewPing
newPing();
//endifdef
if (ping_pauseAll || ping_anyActions) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized(ping_actions) {
if (!ping_actions.isEmpty()) {
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 List collectField(Iterable c, String field) {
List l = new ArrayList();
if (c != null) for (Object a : c)
l.add(getOpt(a, field));
return l;
}
static List collectField(String field, Iterable c) {
return collectField(c, field);
}
static A printStackTrace(A 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(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static String unnull(String s) {
return s == null ? "" : s;
}
static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static List unnull(List l) { return l == null ? emptyList() : l; }
static int[] unnull(int[] l) { return l == null ? emptyIntArray() : l; }
static char[] unnull(char[] l) { return l == null ? emptyCharArray() : l; }
static double[] unnull(double[] l) { return l == null ? emptyDoubleArray() : l; }
static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
//ifclass Symbol
static Symbol unnull(Symbol s) {
return s == null ? emptySymbol() : s;
}
//endif
static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static int unnull(Integer i) { return i == null ? 0 : i; }
static long unnull(Long l) { return l == null ? 0L : l; }
static double unnull(Double l) { return l == null ? 0.0 : l; }
static JTextField standardTextFieldPopupMenu(final JTextField tf) {
final WeakReference ref = weakRef(tf);
componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(ref.get().getText())
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(ref.get().getText())"; }});
componentPopupMenuItem(tf, "Paste", new Runnable() { public void run() { try { ref.get().paste() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ref.get().paste()"; }});
return tf;
}
static A jenableUndoRedo(final A textcomp) {
{ swing(new Runnable() { public void run() { try {
final UndoManager undo = new UndoManager();
vm_generalWeakSet("Undo Managers").add(undo);
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");
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new UndoManager undo;\r\n vm_generalWeakSet(\"Undo Managers\").add(undo)..."; }}); }
return textcomp;
}
static JComponent unwrapScrollPane(JScrollPane sp) {
return sp == null ? null : (JComponent) sp.getViewport().getView();
}
static Field getField(Object o, String field) {
if (o == null) return null;
return setOpt_findField(_getClass(o), field);
}
static Object getField(Field field, Object o) {
return fieldGet(field, o);
}
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 void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
static Object[] expandParams(Class c, Object[] params) {
if (l(params) == 1)
params = new Object[] { singleFieldName(c), params[0] };
else
warnIfOddCount(params);
return params;
}
// returns true if change
static boolean _csetField(Concept c, String field, Object value) { try {
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 = intern((String) value);
if (f == null) {
// dynamic field (undeclared)
assertIdentifier(field);
Object oldVal = mapGet(c.fieldValues, field);
if (value instanceof Concept) {
if (oldVal instanceof Concept.Ref)
// change existing reference
return ((Concept.Ref) oldVal).set((Concept) value);
else {
// overwrite non-reference value if any,
// create new reference
dynamicObject_setRawFieldValue(c, field, c.new Ref((Concept) value));
c.change(); return true;
}
} else {
// value is not a concept
// if it was a reference, cleanly delete it
if (oldVal instanceof Concept.Ref) ((Concept.Ref) oldVal).unindexAndDrop();
if (eq(oldVal, value)) return false;
if (isConceptList(value) && nempty(((List) value))) {
// TODO: clean-up etc
dynamicObject_setRawFieldValue(c, field, c.new RefL(((List) value)));
c.change(); return true;
}
if (value == null) {
// delete field
dynamicObject_dropRawField(c, field);
} else {
// update or create field
if (!isPersistable(value))
throw fail("Can't persist: " + c + "." + field + " = "+ value);
dynamicObject_setRawFieldValue(c, field, value);
}
c.change(); return true;
}
} else if (isSubtypeOf(f.getType(), Concept.Ref.class)) {
// Concept.Ref magic
((Concept.Ref) f.get(c)).set((Concept) derefRef(value));
c.change(); return true;
} else if (isSubtypeOf(f.getType(), Concept.RefL.class)) {
// Concept.RefL magic
((Concept.RefL) f.get(c)).replaceWithList(lmap(__31 -> derefRef(__31), (List) value));
c.change(); return true;
} else {
Object old = f.get(c);
if (neq(value, old)) {
boolean isTransient = isTransient(f);
if (!isTransient && !isPersistable(value))
throw fail("Can't persist: " + c + "." + field + " = "+ value);
f.set(c, value);
if (!isTransient) c.change();
return true;
}
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static String getType(Object o) {
return getClassName(o);
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
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;
if (getOpt_cache == null)
map = getOpt_makeCache(c); // in class init
else 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); return; } // possible improvement: skip setAccessible
if (o instanceof DynamicObject)
{ setDyn(((DynamicObject) o), field, value); return; }
if (o instanceof IMeta)
setDyn(((IMeta) o), field, value);
} 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); // TODO: optimize
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) {
makeAccessible(f);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
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);
if (o instanceof Boolean)
return boolToInt((Boolean) 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 float toFloat(Object o) {
if (o == null) return 0f;
if (o instanceof Number) return ((Number) o).floatValue();
if (o instanceof Boolean) return ((Boolean) o).booleanValue() ? 1f : 0f;
throw fail("Not convertible to float: " + _getClass(o));
}
static double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o instanceof String)
return parseDouble((String) o);
if (o == null) return 0.0;
throw fail(o);
}
static boolean isEditableComboBox(final JComboBox cb) {
return cb != null && swing(new F0() { public Boolean get() { try { return cb.isEditable(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret cb.isEditable();"; }});
}
// returns from C to C
static String jextract(String pat, String s) {
return jextract(pat, javaTok(s));
}
static String jextract(String pat, List tok) {
List tokpat = javaTok(pat);
jfind_preprocess(tokpat);
int i = jfind(tok, tokpat);
if (i < 0) return null;
int j = i + l(tokpat) - 2;
return joinSubList(tok, i, j);
}
static boolean imagesIdentical(BufferedImage img1, BufferedImage img2) {
if (img1 == null) return img2 == null;
if (img2 == null) return false;
int w = img1.getWidth(), h = img1.getHeight();
if (w != img2.getWidth() || h != img2.getHeight()) return false;
for (int y = 0; y < h; y++) for (int x = 0; x < w; x++)
if (img1.getRGB(x, y) != img2.getRGB(x, y)) return false;
return true;
}
// This is for main classes that are all static.
// (We don't go to base classes.)
static Set listFields(Object c) {
TreeSet fields = new TreeSet();
for (Field f : _getClass(c).getDeclaredFields())
fields.add(f.getName());
return fields;
}
static List listMinusSet(Iterable l, Collection extends A> stuff) {
if (l == null) return null;
if (empty(stuff)) return asList(l);
Set extends A> set = asSet(stuff);
List l2 = new ArrayList();
for (A a : l) if (!set.contains(a)) l2.add(a);
return l2;
}
static List listMinusSet(Iterable l, Collection stuff, Collection extends A> stuff2) {
return listMinusSet(listMinusSet(l, stuff), stuff2);
}
static String toStringOpt(Object o) {
return o instanceof String ? ((String) o) : null;
}
static TreeSet asTreeSet(Collection set) {
return set == null ? null : set instanceof TreeSet ? (TreeSet) set : new TreeSet(set);
}
static List splitAtSpace(String s) {
return empty(s) ? emptyList() : asList(s.split("\\s+"));
}
static void setAddAll(Collection a, Collection b) {
for (A x : b)
setAdd(a, x);
}
static Set similarEmptySet(Iterable m) {
if (m instanceof TreeSet) return new TreeSet(((TreeSet) m).comparator());
if (m instanceof LinkedHashSet) return new LinkedHashSet();
return new HashSet();
}
static Set similarEmptySet(Map m) {
if (m instanceof TreeMap) return new TreeSet(((TreeMap) m).comparator());
if (m instanceof LinkedHashMap) return new LinkedHashSet();
return new HashSet();
}
static Object first(Object list) {
return first((Iterable) list);
}
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(IterableIterator i) {
return first((Iterator ) i);
}
static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
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 Character first(CharSequence s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static A first(T3 t) {
return t == null ? null : t.a;
}
static Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static void addAll(Collection c, Iterable b) {
if (c != null && b != null) for (A a : b) c.add(a);
}
static boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static boolean addAll(Collection c, B... b) {
return c != null && b != null && c.addAll(Arrays.asList(b));
}
static Map addAll(Map a, Map extends A,? extends B> b) {
if (a != null && b != null) a.putAll(b);
return a;
}
static Object _defaultClassFinder_value = defaultDefaultClassFinder();
static Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
static boolean nempty(Collection c) {
return !empty(c);
}
static boolean nempty(CharSequence s) {
return !empty(s);
}
static boolean nempty(Object[] o) { return !empty(o); }
static boolean nempty(byte[] o) { return !empty(o); }
static boolean nempty(int[] o) { return !empty(o); }
static boolean nempty(Map m) {
return !empty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean nempty(Object o) { return !empty(o); }
static boolean nempty(Rect r) { return r != null && r.w != 0 && r.h != 0; }
static String programIDWithCase() {
return nempty(caseID())
? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID())
: programID();
}
static String programTitle() {
return getProgramName();
}
static JFrame setFrameIconLater(Component c, final String imageID) {
final JFrame frame = getFrame(c);
if (frame != null)
startThread("Loading Icon", new Runnable() { public void run() { try {
final Image i = imageIcon(or2(imageID, "#1005557")).getImage();
swingLater(new Runnable() { public void run() { try {
frame.setIconImage(i);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setIconImage(i);"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n swingL..."; }});
return frame;
}
static void _initFrame(JFrame f) {
myFrames_list.put(f, Boolean.TRUE);
standardTitlePopupMenu(f);
}
// c = Component or something implementing swing()
static JComponent wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
static JComponent wrap_2(Object swingable) {
if (swingable == null) return null;
JComponent c;
if (swingable instanceof Component) c = componentToJComponent((Component) swingable);
else c = componentToJComponent((Component) 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 == null ? jlabel(str(swingable)) : c;
}
static Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400);
static Rectangle defaultNewFrameBounds() {
return swing(new F0() { public Rectangle get() { try {
defaultNewFrameBounds_r.translate(60, 20);
if (!screenRectangle().contains(defaultNewFrameBounds_r))
defaultNewFrameBounds_r.setLocation(30+random(30), 20+random(20));
return new Rectangle(defaultNewFrameBounds_r);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "defaultNewFrameBounds_r.translate(60, 20);\r\n if (!screenRectangle().contai..."; }});
}
static void hideConsole() {
final JFrame frame = consoleFrame();
if (frame != null) {
autoVMExit();
swingLater(new Runnable() { public void run() { try {
frame.setVisible(false);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setVisible(false);"; }});
}
}
static A revalidate(final A c) {
if (c == null || !c.isShowing()) return c;
{ 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.r..."; }}); }
return c;
}
static void revalidate(JFrame f) { revalidate((Component) f); }
static void revalidate(JInternalFrame f) { revalidate((Component) f); }
static boolean containsIgnoreCase(Collection l, String s) {
if (l != null) for (String x : l)
if (eqic(x, s))
return true;
return false;
}
static boolean containsIgnoreCase(String[] l, String s) {
if (l != null) 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 boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static String dropSuffixIgnoreCase(String suffix, String s) {
return ewic(s, suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static boolean ewicOneOf(String s, String... l) {
if (s != null) for (String x : l) if (ewic(s, x)) return true; return false;
}
static int lastIndexOf(String a, String b) {
return a == null || b == null ? -1 : a.lastIndexOf(b);
}
static int lastIndexOf(String a, char b) {
return a == null ? -1 : a.lastIndexOf(b);
}
// starts searching from i-1
static int lastIndexOf(List l, int i, A a) {
if (l == null) return -1;
for (i = min(l(l), i)-1; i >= 0; i--)
if (eq(l.get(i), a))
return i;
return -1;
}
static int lastIndexOf(List l, A a) {
if (l == null) return -1;
for (int i = l(l)-1; i >= 0; i--)
if (eq(l.get(i), a))
return i;
return -1;
}
static String substring(String s, int x) {
return substring(s, x, strL(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
int n = s.length();
if (y < x) y = x;
if (y > n) y = n;
if (x >= y) return "";
return s.substring(x, y);
}
// convenience method for quickly dropping a prefix
static String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
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 isHeadless_cache;
static boolean isHeadless() {
if (isHeadless_cache != null) return isHeadless_cache;
if (isAndroid()) return isHeadless_cache = true;
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 Rectangle maxWindowBounds() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
}
static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile Appendable 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 boolean print_silent = false; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal print_byThread; // special handling by thread - prefers F1
static volatile Object print_allThreads;
static volatile Object print_preprocess;
static void print() {
print("");
}
static A print(String s, A o) {
print(combinePrintParameters(s, o));
return o;
}
// slightly overblown signature to return original object...
static A print(A o) {
ping_okInCleanUp();
if (print_silent) return o;
String s = o + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
try {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null) f = print_allThreads;
if (f != null)
// We do need the general callF machinery here as print_byThread is sometimes shared between modules
if (isFalse(
f instanceof F1 ? ((F1) f).get(s) :
callF(f, s))) return;
} catch (Throwable e) {
System.out.println(getStackTrace(e));
}
print_raw(s);
}
static void print_raw(String s) {
if (print_preprocess != null) s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable 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);
vmBus_send("printed", mc(), s);
}
static void print_autoRotate() {
}
static boolean addToCollection(Collection c, A a) {
return c != null && c.add(a);
}
static List synchroList() {
return synchroList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
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 PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static ArrayList cloneList(Collection l) {
if (l == null) return new ArrayList();
synchronized(collectionMutex(l)) {
return new ArrayList (l);
}
}
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 void ensureDBNotRunning(String name) {
if (hasBot(name)) {
try {
String framesBot = dropSuffix(".", name) + " Frames";
print("Trying to activate frames of running DB: " + framesBot);
if (isOK(sendOpt(framesBot, "activate frames")) && isMainProgram())
cleanKill();
} catch (Throwable __e) { _handleException(__e); }
throw fail("Already running: " + name);
}
}
static void ensureDBNotRunning() {
ensureDBNotRunning(dbBotStandardName());
}
static String dbBotStandardName() {
String home = userHome();
String name = dbBotName(getDBProgramID());
if (neq(home, actualUserHome()))
name += " " + quote(home);
return name + ".";
}
static volatile Android3 dbBot_instance;
static Android3 dbBot() { return dbBot(true); }
static Android3 dbBot(boolean ensureNotRunning) {
return dbBot(dbBotStandardName(), ensureNotRunning);
}
static Android3 dbBot(String name) { return dbBot(name, true); }
static Android3 dbBot(String name, boolean ensureNotRunning) {
if (ensureNotRunning)
ensureDBNotRunning(name);
return dbBot_instance = methodsBot2(name, assertNotNull(db_mainConcepts()), db_standardExposedMethods(), db_mainConcepts().lock);
}
static void thinAProgramsBackups(String progID, boolean doIt) {
List files = new ArrayList();
Map ageMap = new HashMap();
// minutes (last group) are optional
java.util.regex.Pattern pat = regexp("^(.*)\\.backup(20\\d\\d)(\\d\\d)(\\d\\d)-(\\d\\d)(\\d*)$");
//print("Processing backups of program " + progID);
File dir = programDir(progID);
for (File f : listFilesNotDirs(dir, newFile(dir, "backups"))) {
String s = f.getName();
java.util.regex.Matcher matcher = pat.matcher(s);
{ if (!(matcher.find())) continue; }
String originalName = matcher.group(1);
{ if (!(eq(originalName, "concepts.structure.gz"))) continue; }
//print("Found backup: " + sfu(matcherGroups(matcher)));
int year = matcherInt(matcher, 2);
int month = matcherInt(matcher, 3);
int day = matcherInt(matcher, 4);
int hour = matcherInt(matcher, 5);
int minute = matcherInt(matcher, 6);
long time = timestampFromYMDHM(year, month, day, hour, minute);
double age = ((now()-time)/1000.0/60/60/24);
//print("Age: " + age + " days");
ageMap.put(f, age);
files.add(f);
}
int numDeleted = 0;
sortByMap_inPlace(files, ageMap);
double lastAge = -1;
for (File f : files) {
double age = ageMap.get(f);
if (!thinAProgramsBackups_shouldKeep(age, lastAge)) {
//print("Deleting: " + f);
++numDeleted;
if (doIt) {
print("Deleting: " + f);
f.delete();
}
} else {
//print("Keeping: " + f);
lastAge = age;
}
}
if (numDeleted != 0)
print((doIt ? "Deleted: " : "Would delete: ") + n(numDeleted, "file"));
}
// age = age in days
static boolean thinAProgramsBackups_shouldKeep(double age, double lastAge) {
return defaultAgeBasedBackupRetentionStrategy_shouldKeep(age, lastAge);
}
static String programID() {
return getProgramID();
}
static String programID(Object o) {
return getProgramID(o);
}
static String userHomeIfNotActual() {
String home = userHome();
return eq(home, actualUserHome()) ? null : home;
}
static String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static String f2s(String s) { return f2s(newFile(s)); }
static String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
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 if (c == '\t')
out.append("\\t");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
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_cachedInput(s), matches);
}
static boolean match3(String pat, List toks, Matches matches) {
List tokpat = parse3_cachedPattern(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;
}
static ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
static ActionListener actionListener(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
final Object info = _threadInfo();
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
_threadInheritInfo(info);
AutoCloseable __1 = holdInstance(instanceToHold); try {
callF(runnable);
} finally { _close(__1); }} catch (Throwable __e) { messageBox(__e); }}};
}
static Map myFrames_list = weakHashMap();
static List myFrames() {
return swing(new F0>() { public List get() { try { return keysList(myFrames_list); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret keysList(myFrames_list);"; }});
}
static boolean activateFrame(final Component c, Object... __) {
return swing(new F0() { public Boolean get() { try {
Frame f = getAWTFrame(c);
if (f == null) return false;
if (!f.isVisible()) f.setVisible(true);
boolean windowsHack = optPar("windowsHack", __, true);
boolean iconified = f.getState() == Frame.ICONIFIED;
boolean maximize = boolPar("maximize", __);
if (iconified)
f.setState(maximize ? Frame.MAXIMIZED_BOTH : Frame.NORMAL);
// My glorious Windows hack
// See: https://stackoverflow.com/questions/309023/how-to-bring-a-window-to-the-front
if (windowsHack && !iconified && isWindows()) {
boolean fullscreen = f.getExtendedState() == Frame.MAXIMIZED_BOTH;
f.setExtendedState(JFrame.ICONIFIED);
f.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL);
}
f.toFront();
return true;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Frame f = getAWTFrame(c);\r\n if (f == null) false;\r\n if (!f.isVisible())..."; }});
}
static String getProgramName_cache;
static String getProgramName() {
Lock __0 = downloadLock(); lock(__0); try {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitleOpt(programID());
return getProgramName_cache;
} finally { unlock(__0); } }
static void _onLoad_getProgramName() {
{ startThread(new Runnable() { public void run() { try { getProgramName();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getProgramName();"; }}); }
}
// An "Android" is a program that accepts text questions (on console or TCP) and outputs one response text per question
//please include function myJavaSource. // for getting my known commands
static boolean makeAndroid3_disable = false; // disable all android making
static class Android3 implements AutoCloseable {
String greeting;
boolean publicOverride = false; // optionally set this in client
int startPort = 5000; // optionally set this in client
Responder responder;
boolean console = true;
boolean quiet = false; // no messages on console
boolean daemon = false;
boolean incomingSilent = false;
int incomingPrintLimit = 200;
boolean useMultiPort = true;
boolean recordHistory = false;
boolean verbose = false;
int answerPrintLimit = 500;
boolean newLineAboveAnswer, newLineBelowAnswer;
// set by system
int port;
long vport;
DialogHandler handler;
ServerSocket server;
Android3(String greeting) {
this.greeting = greeting;}
Android3() {}
public void close() { dispose(); }
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) { _handleException(__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 && (readLine_noReadLine || makeAndroid3_consoleInUse()))
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.");
{ startThread(new Runnable() { 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 (Exception __e) { throw rethrow(__e); } } public String toString() { return "List history = new ArrayList();\r\n while (licensed()) {\r\n Stri..."; }}); }
}
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() {
if (isTrue(vm_generalMap_get("consoleInUse"))) return true;
for (Object o : record_list)
if (o instanceof Android3 && ((Android3) o).console)
return true;
return false;
}
static Responder makeAndroid3_verboseResponder(final Android3 a) {
return new Responder() {
String answer(String s, List history) {
if (a.verbose)
print("> " + shorten(s, a.incomingPrintLimit));
String answer = a.responder.answer(s, history);
if (a.verbose)
print("< " + shorten(answer, a.incomingPrintLimit));
return answer;
}
};
}
static ThreadLocal makeAndroid3_io = new ThreadLocal();
static Android3 makeAndroid3() {
return makeAndroid3(getProgramTitle() + ".");
}
static String 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 String defaultBotName() {
return getProgramTitle() + ".";
}
// Use like this: renderVars(+x, +y)
static String renderVars_str(Object... params) {
List l = new ArrayList();
int i = 0;
if (odd(l(params))) {
l.add(strOrNull(first(params)));
++i;
}
for (; i+1 < l(params); i += 2)
l.add(params[i] + "=" + params[i+1]);
return trim(joinWithComma(l));
}
static boolean isConceptClassIndexed(Class c) {
return isConceptClassIndexed(db_mainConcepts(), c);
}
static boolean isConceptClassIndexed(Concepts concepts, Class c) {
return concepts.conceptCounterForClass(c) != null;
}
static void indexRandomConceptField(Class extends Concept> c) { indexRandomConceptField(db_mainConcepts(), c); }
static void indexRandomConceptField(Concepts cc, Class extends Concept> c) {
String field = or(first(conceptFields(c)), "_dummy");
print("Indexing " + c + "." + field);
indexConceptField(cc, c, field);
assertTrue("Concept class indexed", isConceptClassIndexed(cc, c));
{ long _startTime_0 = sysNow(); try { print("Got " + nConcepts(countConcepts(cc, c))); } finally { _startTime_0 = sysNow()-_startTime_0; saveTiming(_startTime_0); } }
}
static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null) return null;
A old = tl.get();
tl.set(value);
return old;
}
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 int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x) x = d;
return x;
}
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 Object optPar(Object[] params, String name) {
return optParam(params, name);
}
static Object optPar(String name, Object[] params) {
return optParam(params, name);
}
static Object optPar(String name, Map params) {
return optParam(name, params);
}
static A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
static A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
static B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
static B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
static boolean even(int i) {
return (i & 1) == 0;
}
static boolean even(long i) {
return (i & 1) == 0;
}
static boolean even(BigInteger n) {
return even(n.intValue());
}
static boolean boolOptParam(ThreadLocal tl) {
return isTrue(optPar(tl));
}
// defaults to false
static boolean boolOptParam(Object[] __, String name) {
return isTrue(optParam(__, name));
}
static boolean boolOptParam(String name, Object[] __) {
return boolOptParam(__, name);
}
static boolean boolOptParam(String name, Map __) {
return isTrue(optPar(name, __));
}
static JTable sexyTableWithoutDrag() {
final JTable table = tableWithToolTips();
tablePopupMenu(table, sexyTableWithoutDrag_popupMenuMaker(table));
// 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 VF2 sexyTableWithoutDrag_popupMenuMaker(JTable t) {
final WeakReference