Warning : session_start(): open(/var/lib/php/sessions/sess_esqn6lcfk0j6oltcnn6rnfigbk, 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.StringSelection;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.datatransfer.*;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import java.awt.geom.*;
import java.text.NumberFormat;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.nio.file.Path;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import java.text.*;
import java.util.TimeZone;
class main {
static boolean SimpleCRUD_searcher = true;
static class SimpleCRUD_v2 extends JConceptsTable {
JPanel buttons, panel;
String hID = "ID"; // Column header for concept 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;
int formFixer = 12; // stupid value to make submit button appear
boolean showBackRefs = false;
int maxRefsToShow = 3;
SimpleCRUD_v2(Class conceptClass) { super(conceptClass); }
SimpleCRUD_v2(Concepts concepts, Class conceptClass) { super(concepts, conceptClass); }
SimpleCRUD_v2 show(String frameTitle) {
make();
showFrame(frameTitle, panel);
return this;
}
SimpleCRUD_v2 show() {
return show(plural(shortClassName(conceptClass)));
}
SimpleCRUD_v2 showMaximized() { show(); maximizeFrame(panel); return this; }
JPanel makePanel() { return make(); }
JPanel make() {
db();
framesBot();
return make_dontStartBots();
}
transient IF1 > itemToMap_inner;
Map itemToMap_inner(A a) { return itemToMap_inner != null ? itemToMap_inner.get(a) : itemToMap_inner_base(a); }
final Map itemToMap_inner_fallback(IF1> _f, A a) { return _f != null ? _f.get(a) : itemToMap_inner_base(a); }
Map itemToMap_inner_base(A a) {
return super.itemToMap_base(a);
}
Map itemToMap_base(A a) {
Map map = itemToMap_inner(a);
if (map == null) return null;
return putAll(putAll(specialFieldsForItem(a), map), moreSpecialFieldsForItem(a));
}
// shown on the left (usually)
transient IF1> specialFieldsForItem;
Map specialFieldsForItem(A a) { return specialFieldsForItem != null ? specialFieldsForItem.get(a) : specialFieldsForItem_base(a); }
final Map specialFieldsForItem_fallback(IF1> _f, A a) { return _f != null ? _f.get(a) : specialFieldsForItem_base(a); }
Map specialFieldsForItem_base(A a) {
Map map = litorderedmap(hID, str(a.id));
mapPut(map, "Java Class", javaClassDescForItem(a));
return map;
}
// shown on the right (usually)
transient IF1> moreSpecialFieldsForItem;
Map moreSpecialFieldsForItem(A a) { return moreSpecialFieldsForItem != null ? moreSpecialFieldsForItem.get(a) : moreSpecialFieldsForItem_base(a); }
final Map moreSpecialFieldsForItem_fallback(IF1> _f, A a) { return _f != null ? _f.get(a) : moreSpecialFieldsForItem_base(a); }
Map moreSpecialFieldsForItem_base(A a) {
Map map = litorderedmap();
if (showBackRefs) {
Collection refs = allBackRefs(a);
if (nempty(refs)) {
refs = sortedByConceptID(refs);
int more = l(refs)-maxRefsToShow;
map.put("Referenced by",
joinWithComma(takeFirst(maxRefsToShow, refs))
+ (more > 0 ? ", " + more + " more" : ""));
}
}
return map;
}
String javaClassDescForItem(A a) {
String className = dynShortClassName(a);
if (neq(className, shortClassName(conceptClass))) {
String text = className;
String realClass = shortClassName(a);
if (neq(className, realClass))
text += " as " + realClass;
return text;
}
return null;
}
JPanel make_dontStartBots() {
dropFields = asList(unshownFields);
makeTable();
{ 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();
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 "final List l = selectedConcepts();\r\n withDBLock(concepts, r { for..."; }})),
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(getItem(row))
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "editConcept(getItem(row))"; }};
tablePopupMenuItem(table, "Edit...", fEdit);
onDoubleClick(table, fEdit);
tablePopupMenuFirst(table, (menu, row) -> {
Concept c = getItem(row);
if (c != null)
addMenuItem(menu, "Delete " + quote(shorten(str(c))), runnableThread(new Runnable() { public void run() { try {
deleteConcept(c);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "deleteConcept(c);"; }}));
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "buttons = jRightAlignedLine(\r\n jbutton(\"Add...\", r { newConcept() }),\r..."; }}); } // end of swing
return panel;
}
void newConcept() {
duplicateConcept(null);
}
void duplicateConcept(A oldConcept) {
final A c = unlisted(conceptClass);
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 __1 = tempSetMCOpt("formLayouter1_fixer2" , formFixer); try {
showFormTitled2("New " + shortClassName(conceptClass), arrayPlus(mapToObjectArray(map), r));
} finally { _close(__1); }}
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 __2 = tempSetMCOpt("formLayouter1_fixer2" , formFixer); try {
showFormTitled2("Edit " + shortClassName(conceptClass) + " #" + c.id, arrayPlus(mapToObjectArray(map), r));
} finally { _close(__2); }}
A selectedConcept() {
return (A) concepts.getConcept(toLong(selectedTableCell(table, 0)));
}
A selected() { return selectedConcept(); }
A getItem(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() {
int[] rows = table.getSelectedRows();
List l = new ArrayList();
for (int row : rows)
l.add(getItem(row));
return l;
}
Map makeComponents(A c) {
Map map = litorderedmap();
makeComponents(c, map);
return map;
}
JComponent fieldComponent(A c, String field) {
Class type = getFieldType(conceptClass, 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(structureOrText_crud(value), new TreeSet(map("structureOrText_crud",collect(list(concepts, conceptClass), field))));
} catch (Throwable e) {
printException(e);
return jTextField(structureOrText_crud(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)), conceptClass, 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, conceptClass, 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(conceptClass) , new F1() { public Boolean get(String field) { try { return fieldType(conceptClass, field) != Concept.Ref.class; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "fieldType(conceptClass, 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());
}
}
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 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);
}
static Map putAll(Map a, Map extends A,? extends B> b) {
if (a != null && b != null) a.putAll(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 void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null) map.put(key, value);
}
static void mapPut(Map map, Pair p) {
if (map != null && p != null) map.put(p.a, p.b);
}
static List allBackRefs(Concept c) {
IdentityHashMap l = new IdentityHashMap();
if (c != null && c.backRefs != null) for (Concept.Ref r : cloneList(c.backRefs))
l.put(r.concept(), true);
return keysList(l);
}
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 List sortedByConceptID(Collection c) {
return sortedByCalculatedField("conceptID",c);
}
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 String joinWithComma(Collection c) {
return join(", ", c);
}
static String joinWithComma(String... c) {
return join(", ", c);
}
static String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
static List takeFirst(int n, List l) {
return takeFirst(l, n);
}
static String takeFirst(int n, String s) { return substring(s, 0, n); }
static String takeFirst(String s, int n) { return substring(s, 0, n); }
static CharSequence takeFirst(int n, CharSequence s) { return subCharSequence(s, 0, n); }
static List takeFirst(int n, Iterable i) {
if (i == null) return null;
List l = new ArrayList();
Iterator it = i.iterator();
for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) { if (it.hasNext()) l.add(it.next()); else break; }
return l;
}
static int[] takeFirst(int n, int[] a) {
return takeFirstOfIntArray(n, a);
}
static String dynShortClassName(Object o) {
return shortDynamicClassName(o);
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
// 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(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 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 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 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..."; }}); }
}
// menuMaker = voidfunc(JPopupMenu, int row)
static void tablePopupMenuFirst(JTable table, final Object menuMaker) {
tablePopupMenu_first.set(true);
tablePopupMenu(table, menuMaker);
}
static void tablePopupMenuFirst(JTable table, IVF2 menuMaker) {
tablePopupMenuFirst(table, (Object) menuMaker);
}
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 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 int shorten_default = 100;
static String shorten(CharSequence s) { return shorten(s, shorten_default); }
static String shorten(CharSequence s, int max) {
return shorten(s, max, "...");
}
static String shorten(CharSequence s, int max, String shortener) {
if (s == null) return "";
if (max < 0) return str(s);
return s.length() <= max ? str(s) : subCharSequence(s, 0, min(s.length(), max-l(shortener))) + shortener;
}
static String shorten(int max, CharSequence s) { return shorten(s, max); }
static Runnable runnableThread(final Runnable r) {
return new Runnable() { public void run() { try { startThread(r) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "startThread(r)"; }};
}
static void deleteConcept(long id) {
db_mainConcepts().deleteConcept(id);
}
static void deleteConcept(Concepts concepts, long id) {
concepts.deleteConcept(id);
}
static void deleteConcept(Concept c) {
if (c != null) c.delete();
}
static void deleteConcept(Concept.Ref ref) {
if (ref != null) deleteConcept(ref.get());
}
// 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 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 long toLong(Object o) {
if (o instanceof Number)
return ((Number) o).longValue();
if (o instanceof String)
return parseLong((String) o);
return 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 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 ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(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 int tableRowCount(JTable table) {
return tableRows(table);
}
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)
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)
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)
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)
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()) {
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);
}
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 : unnull(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 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(final 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(final 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 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 long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
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("printStackTrace2"));
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)
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());
}
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 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 List keysList(Map map) {
return cloneListSynchronizingOn(keys(map), map);
}
static List keysList(MultiSet ms) {
return ms == null ? null : keysList(ms.map);
}
// f: A -> Comparable
static List sortedByCalculatedField(Iterable c, Object f) {
return sortByCalculatedField(c, f);
}
static List sortedByCalculatedField(Object f, Iterable c) {
return sortedByCalculatedField(c, f);
}
static List sortedByCalculatedField(IF1 f, Iterable c) {
return sortedByCalculatedField(c, f);
}
static List sortedByCalculatedField(Iterable c, IF1 f) {
List l = cloneList(c);
sort(l, new Comparator () {
public int compare(A a, A b) {
return stdcompare(f.get(a), f.get(b));
}
});
return l;
}
static long conceptID(Concept c) {
return c == null ? 0 : c.id;
}
static int iteratorCount_int_close(Iterator i) { try {
int n = 0;
if (i != null) while (i.hasNext()) { i.next(); ++n; }
if (i instanceof AutoCloseable) ((AutoCloseable) i).close();
return n;
} catch (Exception __e) { throw rethrow(__e); } }
static Object call(Object o) {
return callF(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
//ret call_cached(o, method, args);
return call_withVarargs(o, method, args);
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1) return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
static List newSubListOrSame(List l, int startIndex, int endIndex) {
if (l == null) return null;
int n = l(l);
startIndex = max(0, startIndex);
endIndex = min(n, endIndex);
if (startIndex >= endIndex) return ll();
if (startIndex == 0 && endIndex == n) return l;
return cloneList(l.subList(startIndex, endIndex));
}
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, l(l));
}
static CharSequence subCharSequence(CharSequence s, int x) {
return subCharSequence(s, x, s == null ? 0 : s.length());
}
static CharSequence subCharSequence(CharSequence s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
if (x >= s.length()) return "";
if (y < x) y = x;
if (y > s.length()) y = s.length();
return s.subSequence(x, y);
}
static int[] takeFirstOfIntArray(int[] b, int n) {
return subIntArray(b, 0, n);
}
static int[] takeFirstOfIntArray(int n, int[] b) {
return takeFirstOfIntArray(b, n);
}
static String shortDynamicClassName(Object o) {
if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
return ((DynamicObject) o).className;
return shortClassName(o);
}
static boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
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 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 List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
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 void lock(Lock lock) { try {
ping();
if (lock == null) return;
try {
lock.lockInterruptibly();
} 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 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(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;
}
static void unlock(Lock lock, String msg) {
if (lock == null) return;
lock.unlock();
print("Unlocked: " + msg); // print afterwards to make sure the lock is always unlocked
}
static void unlock(Lock lock) {
if (lock == null) return;
lock.unlock();
}
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 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;
}
public static JComponent withLabel(String label, JComponent component) {
return westAndCenter(jlabel(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(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 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 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 B pcallF(IF1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static boolean jmenuItem_newThreads = false;
static JMenuItem jmenuItem(final String text) {
return jMenuItem(text, null);
}
static JMenuItem jmenuItem(final String text, final Object r) {
return swing(new F0() { public JMenuItem get() { try {
Pair p = jmenu_autoMnemonic(dropPrefix("[disabled] ", text));
JMenuItem mi = new JMenuItem(p.a);
if (startsWith(text, "[disabled] ")) disableMenuItem(mi);
if (p.b != 0) mi.setMnemonic(p.b);
mi.addActionListener(jmenuItem_newThreads
? actionListenerInNewThread(r)
: actionListener(r));
return mi;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Pair p = jmenu_autoMnemonic(dropPrefix(\"[disabled] \", text));\r\n JM..."; }});
}
static MenuItem menuItem(String text, final Object r) {
MenuItem mi = new MenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x) x = d;
return x;
}
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 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
pref.height = totalPreferredHeight(l)+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 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 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 int tableColumnViewIndex(final JTable t, final String colName) {
return swing(new F0() { public Integer get() { try {
return t.convertColumnIndexToView(t.getColumn(colName).getModelIndex());
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret t.convertColumnIndexToView(t.getColumn(colName).getModelIndex());"; }});
}
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 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 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 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 Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
/*if (o instanceof S)
ret getOpt(getBot((S) o), field);*/
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
if (o instanceof DynamicObject)
return mapGet2(((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 RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
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 setFont(jTextArea(text), typeWriterFont());
}
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;
}
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 Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static long unnull(Long l) { return l == null ? 0L : 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 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) {
// TODO: keep ref if it exists
c.fieldValues = syncMapPut2_createLinkedHashMap(c.fieldValues, assertIdentifier(field), value instanceof Concept ? c.new Ref((Concept) value) : value);
c.change();
} 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(__22 -> derefRef(__22),(List) value));
c.change(); return true;
} else {
Object old = f.get(c);
if (neq(value, old)) {
f.set(c, value);
if (!isTransient(f)) 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);
} 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);
}
// magic cast
static A cget(Object c, String field) {
Object o = getOpt(c, field);
if (o instanceof Concept.Ref) return (A) ((Concept.Ref) o).get();
return (A) o;
}
static A cget(String field, Object c) {
return cget(c, field);
}
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 Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
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) a.putAll(b);
return a;
}
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 String programTitle() {
return getProgramName();
}
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 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 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 if (swingable instanceof Swingable) c = componentToJComponent(((Swingable) swingable).visualize());
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 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();
}
//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() {
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 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((endsWithLetterOrDigit(s) ? s + ": " : 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 Collections.synchronizedList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
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 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();
java.util.regex.Pattern pat = regexp("^(.*)\\.backup(20\\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);
long time = timestampFromYMDH(year, month, day, hour);
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 getDBProgramID_id;
static String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
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 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 Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
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 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() + ".";
}
static Object collectionMutex(List l) {
return l;
}
static Object collectionMutex(Object o) {
if (o instanceof List) return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
static ArrayList cloneListSynchronizingOn(Collection l, Object mutex) {
if (l == null) return new ArrayList();
synchronized(mutex) {
return new ArrayList (l);
}
}
// f: A -> Comparable
static List sortByCalculatedField(Iterable c, final Object f) {
List l = cloneList(c);
sort(l, new Comparator () {
public int compare(A a, A b) {
return stdcompare(callF(f, a), callF(f, b));
}
});
return l;
}
static void sort(T[] a, Comparator super T> c) {
if (a != null) Arrays.sort(a, c);
}
static void sort(T[] a) {
if (a != null) Arrays.sort(a);
}
static void sort(int[] a) { if (a != null) Arrays.sort(a); }
static void sort(List a, Comparator super T> c) {
if (a != null) Collections.sort(a, c);
}
static void sort(List a) {
if (a != null) Collections.sort(a);
}
static int stdcompare(Number a, Number b) {
return cmp(a, b);
}
static int stdcompare(String a, String b) {
return cmp(a, b);
}
static int stdcompare(long a, long b) {
return a < b ? -1 : a > b ? 1 : 0;
}
static int stdcompare(Object a, Object b) {
return cmp(a, b);
}
static Object call_withVarargs(Object o, String method, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
{ if (!(isStaticMethod(m))) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) { throw rethrow(__e); } }
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 int strL(String s) {
return s == null ? 0 : s.length();
}
static int[] subIntArray(int[] b, int start) {
return subIntArray(b, start, l(b));
}
static int[] subIntArray(int[] b, int start, int end) {
start = max(start, 0); end = min(end, l(b));
if (start == 0 && end == l(b)) return b;
if (start >= end) return new int[0];
int[] x = new int[end-start];
System.arraycopy(b, start, x, 0, end-start);
return x;
}
static Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() { public void run() { try { _inheritThreadInfo(info); callF(r);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_inheritThreadInfo(info); callF(r);"; }};
}
static Object[] asArray(List l) {
return toObjectArray(l);
}
static A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () { public A get() { try { return nuObject(c, args); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret nuObject(c, args);"; }});
}
static Class javax() {
return getJavaX();
}
static Concepts newConceptsWithClassFinder(String progID) {
Concepts cc = new Concepts(progID);
cc.classFinder = _defaultClassFinder();
return cc;
}
static Map vm_threadInterruptionReasonsMap() {
return vm_generalWeakSubMap("Thread interruption reasons");
}
static Thread currentThread() {
return Thread.currentThread();
}
static String strOr(Object o, String ifNull) {
return o == null ? ifNull : str(o);
}
static void lockOrFail(Lock lock, long timeout) { try {
ping();
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
ping();
} catch (Exception __e) { throw rethrow(__e); } }
static ReentrantLock fairLock() {
return new ReentrantLock(true);
}
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 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 Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
// convenience shortcut for values_gen
static Collection values(Object map) {
return values((Map) map);
}
static Map rawTableLineAsMap(JTable tbl, int row) {
if (row >= 0 && row < tbl.getModel().getRowCount()) {
Map map = litorderedmap(); // keep order of columns
for (int i = 0; i < tbl.getModel().getColumnCount(); i++)
mapPut(map, tbl.getModel().getColumnName(i),
tbl.getModel().getValueAt(row, i));
return map;
}
return null;
}
static boolean showTable_searcher = true;
static JTable showTable(Object data) {
return dataToTable_uneditable(data);
}
static JTable showTable(String title, Object data) {
return showTable(data, title);
}
static JTable showTable(Object data, String title) {
return dataToTable_uneditable(data, title);
}
static JTable showTable(JTable table, Object data) {
return showTable(table, data, autoFrameTitle());
}
static JTable showTable(Object data, JTable table) {
return showTable(table, data);
}
static JTable showTable(JTable table, Object data, String title) {
if (table == null)
table = showTable(data, title);
else {
setFrameTitle(table, title);
dataToTable_uneditable(table, data);
}
return table;
}
static JTable showTable() {
return showTable(new ArrayList