Warning : session_start(): open(/var/lib/php/sessions/sess_lr5lgade3rs8v3ude2q8k7ncbe, 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 java.util.function.*;
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 java.awt.geom.*;
import javax.imageio.*;
import java.math.*;
import java.time.Duration;
import java.lang.invoke.VarHandle;
import java.lang.invoke.MethodHandles;
import javax.swing.undo.UndoManager;
import javax.swing.border.*;
import java.awt.geom.*;
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.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import static x30_pkg.x30_util.DynamicObject;
import javax.swing.Icon;
import java.nio.file.Path;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import java.text.*;
import java.text.NumberFormat;
import java.util.TimeZone;
class main {
static class SimpleCRUD_v2 extends JConceptsTable {
JPanel buttons, panel;
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;
boolean showClassNameSelectors = false;
boolean allowNewFields = false;
int newFieldsToShow = 3;
boolean emptyStringsToNull = false; // convert all empty string values to nulls (also means dropping the field if it's dynamic)
int formLabelsWidth = 100; // just another bug fixer
final public SimpleCRUD_v2 setShowSearchBar(boolean showSearchBar){ return showSearchBar(showSearchBar); }
public SimpleCRUD_v2 showSearchBar(boolean showSearchBar) { this.showSearchBar = showSearchBar; return this; } final public boolean getShowSearchBar(){ return showSearchBar(); }
public boolean showSearchBar() { return showSearchBar; }
boolean showSearchBar = true;
final public SimpleCRUD_v2 setShowAddButton(boolean showAddButton){ return showAddButton(showAddButton); }
public SimpleCRUD_v2 showAddButton(boolean showAddButton) { this.showAddButton = showAddButton; return this; } final public boolean getShowAddButton(){ return showAddButton(); }
public boolean showAddButton() { return showAddButton; }
boolean showAddButton = true;
final public SimpleCRUD_v2 setShowEditButton(boolean showEditButton){ return showEditButton(showEditButton); }
public SimpleCRUD_v2 showEditButton(boolean showEditButton) { this.showEditButton = showEditButton; return this; } final public boolean getShowEditButton(){ return showEditButton(); }
public boolean showEditButton() { return showEditButton; }
boolean showEditButton = true;
final public SimpleCRUD_v2 setShowDeleteButton(boolean showDeleteButton){ return showDeleteButton(showDeleteButton); }
public SimpleCRUD_v2 showDeleteButton(boolean showDeleteButton) { this.showDeleteButton = showDeleteButton; return this; } final public boolean getShowDeleteButton(){ return showDeleteButton(); }
public boolean showDeleteButton() { return showDeleteButton; }
boolean showDeleteButton = true;
final public SimpleCRUD_v2 setShowDuplicateButton(boolean showDuplicateButton){ return showDuplicateButton(showDuplicateButton); }
public SimpleCRUD_v2 showDuplicateButton(boolean showDuplicateButton) { this.showDuplicateButton = showDuplicateButton; return this; } final public boolean getShowDuplicateButton(){ return showDuplicateButton(); }
public boolean showDuplicateButton() { return showDuplicateButton; }
boolean showDuplicateButton = true;
final public SimpleCRUD_v2 setIconButtons(boolean iconButtons){ return iconButtons(iconButtons); }
public SimpleCRUD_v2 iconButtons(boolean iconButtons) { this.iconButtons = iconButtons; return this; } final public boolean getIconButtons(){ return iconButtons(); }
public boolean iconButtons() { return iconButtons; }
boolean iconButtons = false;
final public SimpleCRUD_v2 setEditWindowScrollable(boolean editWindowScrollable){ return editWindowScrollable(editWindowScrollable); }
public SimpleCRUD_v2 editWindowScrollable(boolean editWindowScrollable) { this.editWindowScrollable = editWindowScrollable; return this; } final public boolean getEditWindowScrollable(){ return editWindowScrollable(); }
public boolean editWindowScrollable() { return editWindowScrollable; }
boolean editWindowScrollable = false;
final public SimpleCRUD_v2 setScrollableButtons(boolean scrollableButtons){ return scrollableButtons(scrollableButtons); }
public SimpleCRUD_v2 scrollableButtons(boolean scrollableButtons) { this.scrollableButtons = scrollableButtons; return this; } final public boolean getScrollableButtons(){ return scrollableButtons(); }
public boolean scrollableButtons() { return scrollableButtons; }
boolean scrollableButtons = false; // if you have a lot of them
// put a component in here to fill the space left of the buttons
SingleComponentPanel scpButtonFiller;
JComponent wrappedButtonBar;
// After user has submitted edit/create window
transient Set> onConceptSaved;
public SimpleCRUD_v2 onConceptSaved(IVF1 f) { onConceptSaved = createOrAddToSyncLinkedHashSet(onConceptSaved, f); return this; }
public SimpleCRUD_v2 removeConceptSavedListener(IVF1 f) { main.remove(onConceptSaved, f); return this; }
public void conceptSaved(A concept) { if (onConceptSaved != null) for (var listener : onConceptSaved) pcallF_typed(listener, concept); }
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(entityNamePlural());
}
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(map, moreSpecialFieldsForItem(a));
}
// 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;
}
public JPanel make_dontStartBots() { return (JPanel) visualize(); }
public transient JComponent visualize_cache;
public JComponent visualize() { if (visualize_cache == null) visualize_cache = visualize_load(); return visualize_cache;}
public JComponent visualize_load() { return markVisualizer(this, visualize_impl()); }
JComponent visualize_impl() {
dropFields = asList(unshownFields);
makeTable();
{ swing(() -> {
JButton deleteButton = !showDeleteButton ? null
: tableDependButton(table, makeDeleteButton(new Runnable() { public void run() { try {
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 "List l = selectedConcepts();\r\n withDBLock(concepts, r { for (A c ..."; }}));
buttons = jRightAlignedLine(flattenToList(
!showAddButton ? null : makeAddButton(new Runnable() { public void run() { try { newConcept();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "newConcept();"; }}),
!showEditButton || !showDuplicateButton ? null : tableDependButton(table, makeDuplicateButton(new Runnable() { public void run() { try {
duplicateConcept(selectedConcept())
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "duplicateConcept(selectedConcept())"; }})),
!showEditButton ? null : tableDependButton(table, makeEditButton(new Runnable() { public void run() { try {
editConcept(selectedConcept())
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "editConcept(selectedConcept())"; }})),
deleteButton));
wrappedButtonBar = wrapButtonBar(centerAndEastWithMargin(scpButtonFiller = singleComponentPanel(), buttons));
if (showSearchBar) {
tableSearcher = tableWithSearcher2(table, "withMargin" , true);
panel = centerAndSouthWithMargin(tableSearcher.panel, wrappedButtonBar);
} else
panel = centerAndSouthWithMargin(table, wrappedButtonBar);
var 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);"; }}));
});
}); } // end of swing
return panel;
}
transient IF1 wrapButtonBar;
JComponent wrapButtonBar(JComponent buttonBar) { return wrapButtonBar != null ? wrapButtonBar.get(buttonBar) : wrapButtonBar_base(buttonBar); }
final JComponent wrapButtonBar_fallback(IF1 _f, JComponent buttonBar) { return _f != null ? _f.get(buttonBar) : wrapButtonBar_base(buttonBar); }
JComponent wrapButtonBar_base(JComponent buttonBar) {
if (scrollableButtons)
return jBorderlessHigherHorizontalScrollPane(vstack(buttonBar));
return buttonBar;
}
transient Runnable newConcept;
void newConcept() { if (newConcept != null) newConcept.run(); else newConcept_base(); }
final void newConcept_fallback(Runnable _f) { if (_f != null) _f.run(); else newConcept_base(); }
void newConcept_base() {
duplicateConcept(null);
}
transient IF1 createDuplicate;
A createDuplicate(A c) { return createDuplicate != null ? createDuplicate.get(c) : createDuplicate_base(c); }
final A createDuplicate_fallback(IF1 _f, A c) { return _f != null ? _f.get(c) : createDuplicate_base(c); }
A createDuplicate_base(A c) {
A clone = (A) unlisted(_getClass(c));
ccopyFieldsExcept(c, clone, dontDuplicateFields);
return clone;
}
void duplicateConcept(A oldConcept) {
EditWindow ew = new EditWindow();
if (oldConcept == null)
ew.item = unlisted(conceptClass);
else
ew.item = createDuplicate(oldConcept);
csetAll(ew.item, filters);
makeComponents(ew);
// save action
F0 r = new F0() { public Boolean get() { try {
try {
selectAfterUpdate(ew.item);
concepts.register(ew.item);
saveData(ew);
} catch (Throwable e) { printStackTrace(e);
infoBox(e);
return false;
}
return true;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "try {\r\n selectAfterUpdate(ew.item);\r\n concepts.register(ew.item..."; }};
AutoCloseable __2 = tempSetMCOpt("formLayouter1_fixer2" , formFixer); try {
String title = "New " + entityName();
title += appendBracketed(javaClassDescForItem(ew.item));
renameSubmitButton("Create", showAForm(title,
toObjectArray(listPlus(ew.matrix, r))));
} finally { _close(__2); }}
void editConcept(A c) {
if (c == null) return;
EditWindow ew = new EditWindow();
ew.item = c;
makeComponents(ew);
F0 r = new F0() { public Boolean get() { try {
try {
// concept class was changed, replace object
if (ew.item != c) {
print("Replacing object: " + c + " => " + ew.item);
replaceConceptAndUpdateRefs(c, ew.item);
}
saveData(ew);
} catch (Throwable e) { printStackTrace(e);
infoBox(e);
return false;
}
return true;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "try {\r\n // concept class was changed, replace object\r\n if (ew.i..."; }};
AutoCloseable __3 = tempSetMCOpt("formLayouter1_fixer2" , formFixer); try {
renameSubmitButton("Save", showAForm("Edit " + entityName() + " #" + c.id,
toObjectArray(listPlus(ew.matrix, r))));
} finally { _close(__3); }}
JComponent fieldComponent(A c, String field) {
Class type = getFieldType(c.getClass(), field);
Type genericType = genericFieldType(conceptClass, field);
if (type == Concept.Ref.class)
type = getTypeArgumentAsClass(genericType);
Object value = cget(c, field);
if (type == null) type = _getClass(value);
print("Field type: " + field + " => " + type);
if (type == boolean.class)
return jCenteredCheckBox(isTrue(value));
else if (contains(multiLineFields, field) || containsNewLines(optCast(String.class, value)))
return makeTextArea((String) value);
else if (isSubtype(type, Concept.class))
return jcomboboxFromConcepts_str(concepts, type, (Concept) value);
else if (isUneditableFieldType(type))
return jlabel(structureOrText_crud(value));
else try {
return autoComboBox(structureOrText_crud(value), new TreeSet(map(__28 -> structureOrText_crud(__28), 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);
Type genericType = genericFieldType(conceptClass, field);
if (type == Concept.Ref.class)
type = getTypeArgumentAsClass(genericType);
if (comp instanceof JTextComponent) {
String text = trimIf(!(comp instanceof JTextArea), getText((JTextComponent) comp));
Object value = postProcessValue(text);
Object converted = convertToField(value, c.getClass(), field);
cset(c, field, converted);
}
else if (comp instanceof JComboBox) {
String text = getTextTrim((JComboBox) comp);
if (isSubtype(type, Concept.class))
cset(c, field, getConcept(concepts, parseFirstLong(text)));
else {
Object value = postProcessValue(text);
cset(c, field, convertToField(value, c.getClass(), field));
}
} else if (comp instanceof JCheckBox)
cset(c, field, isChecked((JCheckBox) comp));
}
transient IF1> editableFieldsForItem;
Collection editableFieldsForItem(A c) { return editableFieldsForItem != null ? editableFieldsForItem.get(c) : editableFieldsForItem_base(c); }
final Collection editableFieldsForItem_fallback(IF1> _f, A c) { return _f != null ? _f.get(c) : editableFieldsForItem_base(c); }
Collection editableFieldsForItem_base(A c) {
if (excludeFieldsFromEditing != null && modifiedField != null) excludeFieldsFromEditing.add(modifiedField);
return listWithoutSet(
conceptFieldsInOrder(c),
joinSets(excludeFieldsFromEditing, unshownFields, keys(filters)));
}
void excludeFieldsFromEditing(String... fields) {
excludeFieldsFromEditing = setPlus(excludeFieldsFromEditing, fields);
}
Collection> possibleClasses() {
return (Collection) moveItemFirst(conceptClass, dropTypeParameter(sortClassesByNameIC(myNonAbstractClassesImplementing(conceptClass))));
}
JComboBox> classSelectorComponent(A c) {
return setComboBoxRenderer(jTypedComboBox(possibleClasses(), _getClass(c)),
customToStringListCellRenderer(__29 -> shortClassName(__29)));
}
class NewField {
JTextField tfName = jtextfield();
JTextField tfValue = jtextfield();
JComboBox cbRef = jcomboboxFromConcepts_str(concepts, conceptClass);
JComboBox cbType = jcombobox("String", "Reference");
SingleComponentPanel scpValue = singleComponentPanel();
JPanel panel() {
onChangeAndNow(cbType, new Runnable() { public void run() { try { updateSCP();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "updateSCP();"; }});
return jhgridWithSpacing(
withToolTip("Name for new field", withLabel("Name", tfName)),
withLabel("Value", westAndCenterWithMargin(cbType, scpValue)));
}
String typeStr() { return getText(cbType); }
void updateSCP() {
scpValue.setComponent(eqic(typeStr(), "Reference")
? cbRef
: withToolTip("Contents of new field", tfValue));
}
String field() { return gtt(tfName); }
Object value() {
return eqic(typeStr(), "Reference")
? getConcept(concepts, parseFirstLong(getText(cbRef)))
: gtt(tfValue);
}
}
class EditWindow {
A item;
Map componentsByField = litorderedmap();
List matrix = new ArrayList(); // label, component, label, component, ...
JComboBox> classSelector;
List newFields = new ArrayList();
}
// override the following two methods to customize edit window
void makeComponents(EditWindow ew) {
// class selector
if (showClassNameSelectors) {
addAll(ew.matrix, makeLabel("Java Class"), ew.classSelector = classSelectorComponent(ew.item));
onChange(ew.classSelector, new Runnable() { public void run() { try {
Class extends A> oldClass = _getClass(ew.item);
Class extends A> newClass = getSelectedItem_typed(ew.classSelector);
if (oldClass == newClass) return;
A oldItem = ew.item;
ew.item = unlisted(newClass);
ccopyFields(oldItem, ew.item);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Class extends A> oldClass = _getClass(ew.item);\r\n Class extends A>..."; }});
}
// regular fields
for (String field : editableFieldsForItem(ew.item)) {
JComponent c = fieldComponent(ew.item, field);
ew.componentsByField.put(field, c);
addAll(ew.matrix, makeLabel(field), c);
}
// new fields
if (allowNewFields && newFieldsToShow > 0) {
addAll(ew.matrix, " ", jlabel()); // spacing
for (int i = 0; i < newFieldsToShow; i++) {
NewField nf = new NewField();
ew.newFields.add(nf);
addAll(ew.matrix, makeLabel(""/*"New field"*/), nf.panel());
}
}
}
void saveData(EditWindow ew) {
// save regular fields
for (Map.Entry extends String, ? extends JComponent> __0 : _entrySet( ew.componentsByField))
{ String field = __0.getKey(); JComponent component = __0.getValue(); if (isIdentifier(field))
saveComponent(ew.item, field, component); }
// save new fields
for (NewField nf : ew.newFields) {
String field = nf.field();
Object value = nf.value();
if (nempty(field) && notNullOrEmptyString(value))
cset(ew.item, field, value);
}
if (modifiedField != null) cset(ew.item, modifiedField, now());
conceptSaved(ew.item);
}
Object postProcessValue(Object o) {
if (emptyStringsToNull && eq(o, "")) return null;
return o;
}
// labels on left hand side of form
JComponent makeLabel(String label) {
return jMinWidthAtLeast(formLabelsWidth, jlabel(label));
}
transient IF2 showAForm;
JComponent showAForm(String title, Object... parts) { return showAForm != null ? showAForm.get(title, parts) : showAForm_base(title, parts); }
final JComponent showAForm_fallback(IF2 _f, String title, Object... parts) { return _f != null ? _f.get(title, parts) : showAForm_base(title, parts); }
JComponent showAForm_base(String title, Object... parts) {
JForm form = new JForm(parts).disposeFrameOnSubmit();
var panel = form.visualize();
showFrame(title, editWindowScrollable ? jscroll_vertical(panel) : panel);
return panel;
}
boolean isUneditableFieldType(Class type) {
return isSubclassOfAny(type, Map.class, Collection.class, Pair.class);
}
void hideField(String field) { hideFields(field); }
void hideFields(String... fields) {
unshownFields = createOrAddToSet(unshownFields, fields);
}
transient IF0 entityName;
String entityName() { return entityName != null ? entityName.get() : entityName_base(); }
final String entityName_fallback(IF0 _f) { return _f != null ? _f.get() : entityName_base(); }
String entityName_base() { return shortClassName(conceptClass); }
transient IF0 entityNamePlural;
String entityNamePlural() { return entityNamePlural != null ? entityNamePlural.get() : entityNamePlural_base(); }
final String entityNamePlural_fallback(IF0 _f) { return _f != null ? _f.get() : entityNamePlural_base(); }
String entityNamePlural_base() { return plural(entityName()); }
transient IF0 entityNameLower;
String entityNameLower() { return entityNameLower != null ? entityNameLower.get() : entityNameLower_base(); }
final String entityNameLower_fallback(IF0 _f) { return _f != null ? _f.get() : entityNameLower_base(); }
String entityNameLower_base() { return firstToLower(entityName()); }
transient IF0 entityNamePluralLower;
String entityNamePluralLower() { return entityNamePluralLower != null ? entityNamePluralLower.get() : entityNamePluralLower_base(); }
final String entityNamePluralLower_fallback(IF0 _f) { return _f != null ? _f.get() : entityNamePluralLower_base(); }
String entityNamePluralLower_base() { return firstToLower(entityNamePlural()); }
JPanel buttons() { visualize(); return buttons; }
void addButtonInFront(String text, Runnable r) {
addButtonInFront(jbutton(text, r));
}
void addButton(String text, Runnable r) {
addButton(jbutton(text, r));
}
void addButton(JComponent c) {
buttons().add(c);
}
void addButtonInFront(JComponent c) {
addComponentInFront(buttons(), c);
}
JButton makeAddButton(Runnable r) { return makeButton(
"Add...", "Create a new " + entityNameLower(), "#1103069", r); }
JButton makeDeleteButton(Runnable r) { return makeButton(
"Delete", "Delete selected " + entityNamePluralLower(), "#1103067", r); }
JButton makeEditButton(Runnable r) { return makeButton(
"Edit...", "Edit selected " + entityNameLower(), "#1103068", r); }
JButton makeDuplicateButton(Runnable r) { return makeButton(
"Duplicate...", "Duplicate selected " + entityNameLower(), "#1103070", r); }
JButton makeButton(String text, String iconID, Runnable r) { return makeButton(text, null, iconID, r); }
JButton makeButton(String text, String toolTip, String iconID, Runnable r) {
if (iconButtons)
return toolTip(or2(toolTip, text), jimageButtonScaledToWidth(16, iconID, text, r));
else
return toolTip(toolTip, jbutton(text, r));
}
void multiLineField(String field) {
multiLineFields = addOrCreate(multiLineFields, field);
}
transient IF1 makeTextArea;
JComponent makeTextArea(String text) { return makeTextArea != null ? makeTextArea.get(text) : makeTextArea_base(text); }
final JComponent makeTextArea_fallback(IF1 _f, String text) { return _f != null ? _f.get(text) : makeTextArea_base(text); }
JComponent makeTextArea_base(String text) {
return typeWriterTextArea(text);
}
void setButtonFiller(JComponent c) {
scpButtonFiller.set(c);
}
TableSearcher tableSearcher() {
visualize();
return tableSearcher;
}
}
static Set createOrAddToSyncLinkedHashSet(Set set, A a) {
if (set == null) set = syncLinkedHashSet();
set.add(a);
return set;
}
static void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
static void remove(Collection l, A a) {
if (l != null) l.remove(a);
}
static B remove(Map map, Object a) {
return map == null ? null : map.remove(a);
}
static void remove(BitSet bs, int i) {
bs.clear(i);
}
static A pcallF_typed(F0 f) {
try { return f == null ? null : f.get(); } catch (Throwable __e) { pcallFail(__e); } return null;
}
static B pcallF_typed(F1 f, A a) {
try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__e); } return null;
}
static void pcallF_typed(VF1 f, A a) {
try {
{ if (f != null) f.get(a); }
} catch (Throwable __e) { pcallFail(__e); }
}
static void pcallF_typed(IVF1 f, A a) {
try {
{ if (f != null) f.get(a); }
} catch (Throwable __e) { pcallFail(__e); }
}
static void pcallF_typed(IVF2 f, A a, B b) {
try {
{ if (f != null) f.get(a, b); }
} catch (Throwable __e) { pcallFail(__e); }
}
static Object pcallF_typed(Runnable r) {
try { { if (r != null) r.run(); } } catch (Throwable __e) { pcallFail(__e); } return null;
}
static A pcallF_typed(IF0 f) {
try { return f == null ? null : f.get(); } catch (Throwable __e) { pcallFail(__e); } return null;
}
static B pcallF_typed(IF1 f, A a) {
try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__e); } return null;
}
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(() -> {
if (frameTooSmall(f)) frameStandardSize(f);
if (!f.isVisible()) f.setVisible(true); // XXX
if (f.getState() == Frame.ICONIFIED) f.setState(Frame.NORMAL);
}); }
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 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) { pcallFail(__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() {
public 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 MultiMap putAll(MultiMap a, Map extends A,? extends B> b) {
if (a != null) a.putAll((Map) b);
return a;
}
static Map putAll(Map a, Object... b) {
if (a != null)
litmap_impl(a, b);
return a;
}
static LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static 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(BitSet bs) { return !empty(bs); }
static boolean nempty(Map m) {
return !empty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean nempty(IMultiMap mm) { return mm != null && mm.size() != 0; }
static boolean nempty(Object o) { return !empty(o); }
static boolean nempty(IntBuffer b) { return b != null && !b.isEmpty(); }
static boolean nempty(Rect r) { return r != null && r.w != 0 && r.h != 0; }
static boolean nempty(MultiSet ms) { return ms != null && !ms.isEmpty(); }
static List sortedByConceptID(Collection c) {
return sortedByCalculatedField(__30 -> conceptID(__30), 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(MultiSet ms) { return ms == null ? 0 : ms.size(); }
static int l(IMultiMap mm) { return mm == null ? 0 : mm.size(); }
static int l(IntBuffer b) { return b == null ? 0 : b.size(); }
static int l(IntSize o) { return o == null ? 0 : o.size(); }
static String joinWithComma(Collection c) {
return join(", ", c);
}
static String joinWithComma(Object... 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, Iterator it) {
if (it == null) return null;
List l = new ArrayList();
for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) { if (it.hasNext()) l.add(it.next()); else break; }
return l;
}
static List takeFirst(int n, Iterable i) {
if (i == null) return null;
return i == null ? null : takeFirst(n, i.iterator());
}
static List takeFirst(int n, IterableIterator i) {
return takeFirst(n, (Iterator ) i);
}
static int[] takeFirst(int n, int[] a) { return takeFirstOfIntArray(n, a); }
static short[] takeFirst(int n, short[] a) { return takeFirstOfShortArray(n, a); }
static byte[] takeFirst(int n, byte[] a) { return takeFirstOfByteArray(n, a); }
static byte[] takeFirst(byte[] a, int n) { return takeFirstOfByteArray(n, a); }
static double[] takeFirst(int n, double[] a) { return takeFirstOfDoubleArray(n, a); }
static double[] takeFirst(double[] a, int n) { return takeFirstOfDoubleArray(n, a); }
static A markVisualizer(Object visualizer, A a) {
return setMetaSrc(a, visualizer);
}
// 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(char[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
static ArrayList asList(byte[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
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(short[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (short i : a) l.add(i);
return l;
}
static ArrayList asList(Iterator it) {
ArrayList l = new ArrayList();
if (it != null)
while (it.hasNext())
l.add(it.next());
return l;
}
// disambiguation
static ArrayList asList(IterableIterator s) {
return asList((Iterator) s);
}
static ArrayList asList(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null) while ((a = p.next()) != null)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
static ArrayList asList(ReverseChain c) {
return c == null ? emptyList() : c.toList();
}
static List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static Object swing(Object f) {
return swingAndWait(f);
}
static void swing(Runnable f) {
swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static A swing(IF0 f) {
return (A) swingAndWait(f);
}
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 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 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 JPanel jRightAlignedLine(Component... components) {
return jrightAlignedLine(components);
}
static JPanel jRightAlignedLine(List extends Component> components) {
return jrightAlignedLine(components);
}
static List flattenToList(Object... l) {
Flattener f = new Flattener();
f.add(l);
return f.toList();
}
static A selectedConcept(JTable table, Class cc) {
return (A) getConcept(toLong(selectedTableCell(table, 0)));
}
static JPanel centerAndEastWithMargin(Swingable c, Swingable e) { return centerAndEastWithMargin(c, toComponent(e)); }
static JPanel centerAndEastWithMargin(Swingable c, Component e) { return centerAndEastWithMargin(toComponent(c), e); }
static JPanel centerAndEastWithMargin(Component c, Swingable e) { return centerAndEastWithMargin(c, toComponent(e)); }
static JPanel centerAndEastWithMargin(Component c, Component e) {
return centerAndEastWithMarginInbetween(c, e);
}
static SingleComponentPanel singleComponentPanel() {
return singleComponentPanel(null);
}
static SingleComponentPanel singleComponentPanel(final Component c) {
return swing(new F0() { public SingleComponentPanel get() { try {
return new SingleComponentPanel(c);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "return new SingleComponentPanel(c);"; }});
}
static class TableSearcher {
JTable table;
JTextField tfInput;
JComponent searchPanel, panel;
F2 rowTester;
List rowIndices;
SingleComponentPanel scpRightOfSearchPanel = scp();
List lastFiltered, lastOriginal;
String input() { return gtt(tfInput); }
void clearSearchField() { setText(tfInput, ""); }
}
static TableSearcher tableWithSearcher2(JTable t, Object... __) {
TableSearcher s = new TableSearcher();
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() {
public void run() {
String pat = s.input();
List> data = rawTableData(t);
if (eq(s.lastFiltered, data))
data = s.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"));
s.lastFiltered = data2;
s.lastOriginal = data;
dataToTable(t, data2);
if (precise) s.lastFiltered = rawTableData(t);
s.rowIndices = rowIndices;
}
});
s.searchPanel = centerAndEast(withLabel(" Search:", s.tfInput), s.scpRightOfSearchPanel);
JComponent top = s.searchPanel;
s.panel = boolOptPar(__, "withMargin") ? northAndCenterWithMargin(top, t) : northAndCenter(top, t);
return s;
}
static JPanel centerAndSouthWithMargin(Swingable c, Swingable s) { return centerAndSouthWithMargin(c, toComponent(s)); }
static JPanel centerAndSouthWithMargin(Swingable c, Component s) { return centerAndSouthWithMargin(toComponent(c), s); }
static JPanel centerAndSouthWithMargin(Component c, Swingable s) { return centerAndSouthWithMargin(c, toComponent(s)); }
static JPanel centerAndSouthWithMargin(Component c, Component s) {
return centerAndSouth(c, withTopMargin(s));
}
static JPanel centerAndSouthWithMargin(int margin, Swingable c, Swingable s) { return centerAndSouthWithMargin(margin, c, toComponent(s)); }
static JPanel centerAndSouthWithMargin(int margin, Swingable c, Component s) { return centerAndSouthWithMargin(margin, toComponent(c), s); }
static JPanel centerAndSouthWithMargin(int margin, Component c, Swingable s) { return centerAndSouthWithMargin(margin, c, toComponent(s)); }
static JPanel centerAndSouthWithMargin(int margin, Component c, Component s) {
return centerAndSouth(c, withTopMargin(margin, s));
}
// 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(() -> {
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);
}
}
});
}); }
return list;
}
// runnable can be a func(O o) {} receving the selected row index
static JTable onDoubleClick(final JTable table, final Object runnable) {
{ swing(() -> {
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);
}
}
});
}); }
return table;
}
// other components get the pointer position
// only reacts on left button
static void onDoubleClick(final JComponent c, final Object runnable) {
{ swing(() -> {
c.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getButton() == 1 && evt.getClickCount() == 2)
callF(runnable, evt.getPoint());
}
});
}); }
}
// 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) {
if (menu != null && menuItem != null)
menu.add(menuItem);
}
static void addMenuItem(JMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(Menu menu, String text, Object action) {
menu.add(menuItem(text, action));
}
static void addMenuItem(JMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static void addMenuItem(JMenuBar menuBar, String text, Runnable action) {
addMenuItem(menuBar, jmenuItem(text, action));
}
static void addMenuItem(JMenuBar menuBar, JMenuItem menuItem) {
addDirectMenuItem(menuBar, menuItem);
}
static 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 String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return c == null ? "null" : new String(c);
}
static String str(char[] c, int offset, int count) {
return new String(c, offset, count);
}
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());
}
static JScrollPane jBorderlessHigherHorizontalScrollPane(JComponent c) {
var sp = borderlessScrollPane(jHigherScrollPane(c));
sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
return sp;
}
static JPanel vstack(Object... parts) {
return vstack2(parts);
}
static JPanel vstack(List parts) {
return vstack(toObjectArray(parts));
}
// 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 Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static Class _getClass(Object o) {
return o == null ? null
: o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) {
try {
return classLoaderForObject(realm).loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
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 int csetAll(Concept c, Object... values) {
return cset(c, values);
}
static int csetAll(Iterable extends Concept> l, Object... values) {
int n = 0;
for (Concept c : unnullForIteration(l))
n += cset(c, values);
return n;
}
static int csetAll(Concept c, Map values) {
int n = 0;
for (Map.Entry extends String, ? extends Object> __0 : _entrySet( values))
{ String field = __0.getKey(); Object value = __0.getValue(); n += cset(c, field, value); }
return n;
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o == null) return null;
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
return f.get(o);
}
if (o instanceof DynamicObject)
return getOptDynOnly(((DynamicObject) o), field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static Object get_raw(Object o, String field) { try {
if (o == null) return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static Object get(String field, Object o) {
return get(o, field);
}
static boolean get(BitSet bs, int idx) {
return bs != null && bs.get(idx);
}
static A printStackTrace(A e) {
// we go to system.out now - system.err is nonsense
if (e != null) 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 JWindow infoBox(Object text) {
return infoMessage(strOrNull(text));
}
static JWindow infoBox(String text) {
return infoMessage(text);
}
static JWindow infoBox(String text, double seconds) {
return infoMessage(text, seconds);
}
static JWindow infoBox(Throwable e) {
return infoMessage(e);
}
static 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 String appendBracketed(Object o) {
String b = strOrNull(o);
return empty(b) ? "" : "" + " (" + b + ")";
}
static String appendBracketed(String a, String b) {
return a + appendBracketed(b);
}
static A renameSubmitButton(A form, String newName) {
renameButton(form, showFormSubmitButtonName(), newName);
return form;
}
static A renameSubmitButton(String newName, A form) {
return renameSubmitButton(form, newName);
}
// binary legacy signature
static Object[] toObjectArray(Collection c) {
return toObjectArray((Iterable) c);
}
static Object[] toObjectArray(Iterable c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static List listPlus(Collection l, A... more) {
return concatLists(l, asList(more));
}
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 volatile StringBuffer local_log = new StringBuffer(); // not redirected
static boolean printAlsoToSystemOut = true;
static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
static boolean print_silent = false; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal print_byThread; // special handling by thread - prefers F1
static volatile Object print_allThreads;
static volatile Object print_preprocess;
static void print() {
print("");
}
static A print(String s, A o) {
print(combinePrintParameters(s, o));
return o;
}
// slightly overblown signature to return original object...
static A print(A o) {
ping_okInCleanUp();
if (print_silent) return o;
String s = o + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
try {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null) f = print_allThreads;
if (f != null)
// We do need the general callF machinery here as print_byThread is sometimes shared between modules
if (isFalse(
f instanceof F1 ? ((F1) f).get(s) :
callF(f, s))) return;
} catch (Throwable e) {
System.out.println(getStackTrace(e));
}
print_raw(s);
}
static void print_raw(String s) {
if (print_preprocess != null) s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
if (printAlsoToSystemOut)
System.out.print(s);
vmBus_send("printed", mc(), s);
}
static void print_autoRotate() {
}
static A replaceConceptAndUpdateRefs(Concept a, A b) {
assertTrue("object to replace with must be unlisted", isUnlisted(b));
Concepts cc = a.concepts();
assertTrue("object to replace must be listed", cc != null);
List refs = allBackRefObjects(a);
b.id = a.id;
deleteConcept(a);
cc.register_phase2(b);
cset(a, "meta_migratedTo" , b); // for objects that may have had direct pointers
for (Concept.Ref ref : refs)
ref.set(b);
return b;
}
static Class getFieldType(Object o, String field) {
return fieldType(o, field);
}
static Type genericFieldType(Object o, String field) {
Field f = getField(o, field);
return f == null ? null : f.getGenericType();
}
static Class getTypeArgumentAsClass(Type type) {
if (type instanceof ParameterizedType)
return typeToClass(first(((ParameterizedType) type).getActualTypeArguments()));
return null;
}
static Object cget(Object c, String field) {
c = derefRef(c);
Object o = getOpt(c, field);
return derefRef(o);
}
static Object cget(String field, Object c) {
return cget(c, field);
}
static 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(Iterable it, Object a) {
if (it != null)
for (Object o : it)
if (eq(a, o))
return true;
return false;
}
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 contains(Rect r, Pt p) { return rectContains(r, p); }
static boolean containsNewLines(String s) {
return containsNewLine(s);
}
static A optCast(Class c, Object o) {
return isInstance(c, o) ? (A) o : null;
}
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 "return 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 A getVar(Optional v) {
return v == null ? null : v.orElse(null);
}
static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
static JLabel jlabel() {
return jlabel(" ");
}
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 AutoComboBox autoComboBox() {
return autoComboBox(new ArrayList());
}
static AutoComboBox autoComboBox(final Collection items) {
return swing(new F0() { public AutoComboBox get() { try {
AutoComboBox cb = new AutoComboBox();
cb.setKeyWord(items);
return cb;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "new AutoComboBox cb;\r\n cb.setKeyWord(items);\r\n ret cb;"; }});
}
static AutoComboBox autoComboBox(String value, Collection items) {
return setText(autoComboBox(items), value);
}
static List map(Iterable l, Object f) { return map(f, l); }
static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null) for (Object o : l)
{ ping(); x.add(callF(f, o)); }
return x;
}
// map: func(key, value) -> list element
static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null) for (Object _e : map.entrySet()) { ping();
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }
static List map(Object f, Map map) {
return map(map, f);
}
static List map(Iterable l, F1 f) { return map(f, l); }
static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null) for (A o : l)
{ ping(); x.add(callF(f, o)); }
return x;
}
static List map(IF1 f, Iterable l) { return map(l, f); }
static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null) {
var it = l.iterator();
if (it.hasNext()) {
var pingSource = pingSource();
do {
ping(pingSource);
x.add(f.get(it.next()));
} while (it.hasNext());
}
}
return x;
}
static List map(IF1 f, A[] l) { return map(l, f); }
static List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
{ ping(); x.add(f.get(o)); }
return x;
}
static List map(Map map, IF2 f) {
List x = new ArrayList();
if (map != null) for (Map.Entry e : map.entrySet()) { ping();
x.add(f.get(e.getKey(), e.getValue()));
}
return x;
}
// new magic alias for mapLL - does it conflict?
static List map(IF1 f, A data1, A... moreData) {
List x = emptyList(l(moreData)+1);
x.add(f.get(data1));
if (moreData != null) for (A o : moreData)
{ ping(); x.add(f.get(o)); }
return x;
}
static List collect(Iterable c, String field) {
return collectField(c, field);
}
static List collect(String field, Iterable c) {
return collectField(c, field);
}
/*ifclass Concept
static L collect(Class c, S field) {
ret collect(list(c), field);
}
endif
TODO: make translator ignore stuff in ifclass until resolved
*/
static List list(Class type) { return list(type, db_mainConcepts()); }
static List list(Class type, Concepts cc) {
return cc.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 List list(Concepts concepts) {
return asList(concepts.allConcepts());
}
static A printException(A e) {
printStackTrace(e);
return e;
}
static JTextField jTextField() {
return jTextField("");
}
static JTextField jTextField(final String text) {
return swing(new F0() { public JTextField get() { try {
JTextField tf = new JTextField(unnull(text));
standardTextFieldPopupMenu(tf);
jenableUndoRedo(tf);
tf.selectAll();
return tf;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JTextField tf = new JTextField(unnull(text));\r\n standardTextFieldPopupMenu..."; }});
}
static JTextField jTextField(Object o) {
return jTextField(strOrEmpty(o));
}
static JComponent unwrap(JComponent c) {
return c instanceof JScrollPane ? unwrapScrollPane((JScrollPane) c) : c;
}
static Class fieldType(Object o, String field) {
Field f = getField(o, field);
return f == null ? null : f.getType();
}
static String getTextTrim(JTextComponent c) {
return trim(getText(c));
}
// tested for editable combo box - returns the contents of text field
static String getTextTrim(JComboBox cb) {
return trim(getText(cb));
}
static String getTextTrim(JComponent c) {
if (c instanceof JLabel) return trim(((JLabel) c).getText());
if (c instanceof JComboBox) return getTextTrim((JComboBox) c);
return getTextTrim((JTextComponent) c);
}
// returns number of changes
static int cset(Concept c, Object... values) { try {
if (c == null) return 0;
warnIfOddCount(values = expandParams(c.getClass(), values));
int changes = 0;
for (int i = 0; i+1 < l(values); i += 2)
if (_csetField(c, (String) values[i], values[i+1])) ++changes;
return changes;
} catch (Exception __e) { throw rethrow(__e); } }
static int cset(Iterable extends Concept> l, Object... values) {
int changes = 0;
for (Concept c : unnullForIteration(l))
changes += cset(c, values);
return changes;
}
static int cset(Concept.Ref c, Object... values) {
return cset(getVar(c), values);
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(Iterable c) { return c == null || !c.iterator().hasNext(); }
static boolean empty(CharSequence s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(BitSet bs) { return bs == null || bs.isEmpty(); }
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
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(IMultiMap mm) { return mm == null || mm.size() == 0; }
static boolean empty(File f) { return getFileSize(f) == 0; }
static boolean empty(IntBuffer b) { return b == null || b.isEmpty(); }
static boolean empty(Rect r) { return !(r != null && r.w != 0 && r.h != 0); }
static boolean empty(Chain c) { return c == null; }
static boolean empty(AppendableChain c) { return c == null; }
static boolean empty(IntSize l) { return l == null || l.size() == 0; }
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 "return 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 "return 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 "return 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 strOrNull(cb.getSelectedItem());
}
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();
} else if (t == Pt.class) {
if (o instanceof String) return parsePt((String) o);
} else if (t == Rect.class) {
if (o instanceof String) return parseRect((String) o);
}
return o;
}
static Concept getConcept(long id) {
return db_mainConcepts().getConcept(id);
}
static Concept getConcept(Concepts concepts, long id) {
return concepts.getConcept(id);
}
static A getConcept(Class cc, long id) {
return getConcept(db_mainConcepts(), cc, id);
}
static A getConcept(Concepts concepts, Class cc, long id) {
Concept c = concepts.getConcept(id);
if (c == null) return null;
if (!isInstance(cc, c))
throw fail("Can't convert concept: " + getClassName(c) + " -> " + getClassName(cc) + " (" + id + ")");
return (A) c;
}
static long parseFirstLong(String s) {
return parseLong(jextract("", s));
}
static boolean isChecked(JCheckBox checkBox) {
return checkBox != null && (boolean) swing(new F0() { public Boolean get() { try { return checkBox.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "return checkBox.isSelected();"; }});
}
static boolean isChecked(JCheckBoxMenuItem mi) {
return mi != null && (boolean) swing(new F0() { public Boolean get() { try { return mi.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "return mi.isSelected();"; }});
}
static boolean isChecked(JRadioButton rb) {
return rb != null && (boolean) swing(() -> rb.isSelected());
}
static void cUpdatePNGFile(Concept c, String field, BufferedImage image, boolean deleteOldFile) {
PNGFile png = (PNGFile) (cget(c, field));
if (image == null && png != null)
cset(c, field, null);
else if (image != null &&
(png == null || !imagesIdentical(png.getImage(), image))) {
if (png != null && deleteOldFile) png.delete();
cset(c, field, new PNGFile(image));
}
}
static List listWithoutSet(Collection l, Collection stuff) {
return listMinusSet(l, stuff);
}
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 = listIntersectSet(splitAtSpace(order), set);
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 keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
// convenience shortcut for keys_gen
static Set keys(Object map) {
return keys((Map) map);
}
static Set keys(MultiSet ms) {
return ms.keySet();
}
static Set keys(IMultiMap mm) {
return mm.keySet();
}
static Set setPlus(Collection l, A... more) {
Set set = similarEmptySet(l);
addAll(set, l);
for (A a : more) set.add(a);
return set;
}
static List moveItemFirst(A item, Collection l) {
if (!contains(l, item)) return asList(l);
List out = emptyList(l(l));
out.add(item);
for (A a : l)
if (!eq(a, item))
out.add(a);
return out;
}
static List dropTypeParameter(List l) { return l; }
static Collection dropTypeParameter(Collection l) { return l; }
static List> sortClassesByNameIC(Collection> l) {
return sortedByCalculatedFieldIC(__31 -> shortClassName(__31), l);
}
static List> myNonAbstractClassesImplementing(Class base) {
List> l = new ArrayList();
for (String name : myInnerClasses()) {
Class c = _getClass(mcName() + "$" + name);
if (c != null && !isAbstract(c) && isSubtypeOf(c, base))
l.add(c);
}
return l;
}
static JComboBox setComboBoxRenderer(JComboBox cb, ListCellRenderer renderer) {
if (cb != null) { swing(() -> { cb.setRenderer(renderer); }); }
return cb;
}
static JComboBox jTypedComboBox(Collection items) {
return swing(() -> new JComboBox (toVector(items)));
}
static JComboBox jTypedComboBox(Collection items, A selectedItem) {
return selectItem(selectedItem, jTypedComboBox(items));
}
static ListCellRenderer customToStringListCellRenderer(IF1 toString) {
return (ListCellRenderer) new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
return super.getListCellRendererComponent(list, toString.get((A) value), index, isSelected, cellHasFocus);
}
};
}
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 JTextField jtextfield() {
return jTextField();
}
static JTextField jtextfield(String text) {
return jTextField(text);
}
static JTextField jtextfield(Object o) {
return jTextField(o);
}
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 "return 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 JComboBox jcombobox(String selectedItem, Collection items) {
return jcombobox(items, selectedItem);
}
// action = runnable or method name
static void onChangeAndNow(JComponent c, Object r) {
onUpdateAndNow(c, r);
}
static void onChangeAndNow(List extends JComponent> l, Object r) {
onUpdateAndNow(l, r);
}
static void onChangeAndNow(JTextComponent c, IVF1 r) {
onUpdateAndNow(c, r);
}
static JComboBox onChangeAndNow(JComboBox cb, IVF1 f) {
onChange(cb, f);
{ if (f != null) f.get(getSelectedItem_typed(cb)); }
return cb;
}
static A onChangeAndNow(A tabs, Runnable r) {
if (r != null) {
onChange(tabs, r);
r.run();
}
return tabs;
}
static JSlider onChangeAndNow(JSlider s, Runnable f) {
if (s != null && f != null) {
onChange(s, f);
f.run();
}
return s;
}
static JPanel jhgridWithSpacing(Object... parts) {
return hgridWithSpacing(parts);
}
static A withToolTip(A c, final Object toolTip) {
return setToolTipText(c, toolTip);
}
static A withToolTip(Object toolTip, A c) {
return setToolTipText(toolTip, c);
}
static JComponent withLabel(String label, JComponent component) {
return westAndCenter(jlabel(label + " "), component);
}
static JComponent withLabel(JComponent label, JComponent component) {
return westAndCenterWithMargin(label, component);
}
static JPanel westAndCenterWithMargin(Component w, Component c) {
return westAndCenter(withRightMargin(w), c);
}
static JPanel westAndCenterWithMargin(int margin, Component w, Component c) {
return westAndCenter(withRightMargin(margin, w), c);
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
static boolean eqic(Symbol a, Symbol b) {
return eq(a, b);
}
static boolean eqic(Symbol a, String b) {
return eqic(asString(a), b);
}
static boolean eqic(char a, char b) {
if (a == b) return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2) return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static String gtt(JTextComponent c) {
return getTextTrim(c);
}
static String gtt(JComboBox cb) {
return getTextTrim(cb);
}
static void addAll(Collection c, Iterable b) {
if (c != null && b != null) for (A a : b) c.add(a);
}
static boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static boolean addAll(Collection c, B... b) {
return c != null && b != null && c.addAll(Arrays.asList(b));
}
static Map addAll(Map a, Map extends A,? extends B> b) {
if (a != null && b != null) a.putAll(b);
return a;
}
static A addAll(A c, Collection extends Component> components) {
return addComponents(c, components);
}
static A addAll(A c, Component... components) {
return addComponents(c, components);
}
static A onChange(A spinner, Object r) {
return onChange(spinner, toRunnable(r));
}
static A onChange(A spinner, Runnable r) {
if (r != null)
{ swing(() -> { spinner.addChangeListener(changeListener(r)); }); }
return spinner;
}
static A onChange(A b, Object r) {
{ swing(() -> { b.addItemListener(itemListener(r)); }); }
return b;
}
static A onChange(A b, Runnable r) {
{ swing(() -> { b.addItemListener(itemListener(r)); }); }
return b;
}
static void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
static void onChange(JTextComponent tc, Runnable r) {
onUpdate(tc, r);
}
static A onChange(A slider, Runnable r) {
return onChange(slider, (Object) r);
}
static A onChange(A slider, Object r) {
{ swing(() -> { slider.addChangeListener(changeListener(r)); }); }
return slider;
}
static JComboBox onChange(JComboBox cb, Runnable r) {
addActionListener(cb, r);
return cb;
}
static JComboBox onChange(JComboBox cb, IVF1 f) {
if (f != null) addActionListener(cb, () -> f.get(getSelectedItem_typed(cb)));
return cb;
}
static JComboBox onChange(Object r, JComboBox cb) {
return onChange(cb, r);
}
static JComboBox onChange(JComboBox cb, final Object r) {
if (isEditableComboBox(cb))
onChange(textFieldFromComboBox(cb), r);
else
onSelectedItem(cb, new VF1() { public void get(String s) { try { callF(r) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callF(r)"; }});
return cb;
}
static A onChange(A tabs, Runnable r) {
{ swing(() -> { tabs.addChangeListener(changeListener(r)); }); }
return tabs;
}
static A onChange(Runnable r, A cc) {
if (cc != null && r != null) { swing(() -> {
cc.getSelectionModel().addChangeListener(changeListener(r));
}); }
return cc;
}
static void onChange(IHasChangeListeners a, ChangeTriggerable b) {
if (a != null && b != null) a.onChange(new ChangeTrigger(b));
}
static void onChange(IHasChangeListeners a, Runnable r) {
if (a != null && r != null) a.onChange(r);
}
static A getSelectedItem_typed(JList l) {
return swing(() -> l.getSelectedValue());
}
static A getSelectedItem_typed(JComboBox cb) {
return swing(() -> (A) cb.getSelectedItem());
}
static A ccopyFields(Concept x, A y, String... fields) {
if (x == null || y == null) return y;
if (empty(fields)) { // assume we should copy all fields
for (String field : conceptFields(x))
cset(y, field, cget(x, field));
} else
for (String field : fields) {
Object o = cget(x, field);
if (o != null)
cset(y, field, o);
}
return y;
}
static Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static boolean notNullOrEmptyString(Object o) {
return o != null && !eq(o, "");
}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
// a little kludge for stuff like eq(symbol, "$X")
static boolean eq(Symbol a, String b) {
return eq(str(a), b);
}
static A jMinWidthAtLeast(int w, final A c) {
if (c == null) return null;
return swing(new F0 () { public A get() { try {
Dimension size = c.getMinimumSize();
Dimension d = new Dimension(max(w, size.width), size.height);
c.setMinimumSize(d);
return jPreferWidth(d.width, c);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Dimension size = c.getMinimumSize();\r\n Dimension d = new Dimension(max(w, ..."; }});
}
static JScrollPane jscroll_vertical(JComponent c) {
return jscroll_trackWidth(c);
}
static JScrollPane jscroll_vertical(Swingable c) {
return jscroll_trackWidth(c);
}
static boolean isSubclassOfAny(Class a, Collection b) {
return any(b, x -> isSubclass(a, x));
}
static boolean isSubclassOfAny(Class a, Class... b) {
return any(b, x -> isSubclass(a, x));
}
static Set createOrAddToSet(Set set, A a) {
if (set == null) set = new HashSet();
set.add(a);
return set;
}
static Set createOrAddToSet(Set set, A... l) {
for (A a : unnullForIteration(l)) set = createOrAddToSet(set, a);
return set;
}
static String plural(String s) {
return getPlural(s);
}
static String firstToLower(String s) {
if (empty(s)) return s;
return Character.toLowerCase(s.charAt(0)) + s.substring(1);
}
static JButton jbutton(String text, Runnable action) {
return newButton(text, action);
}
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 void addComponentInFront(Container c, Component... l) {
containerAddFirst(c, l);
}
static A toolTip(A c, final Object toolTip) {
return setToolTipText(c, toolTip);
}
static A toolTip(Object toolTip, A c) {
return setToolTipText(toolTip, c);
}
static String or2(String a, String b) {
return nempty(a) ? a : b;
}
static String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
static JButton jimageButtonScaledToWidth(int w, String imageID, Runnable action) { return jimageButtonScaledToWidth(w, imageID, "", action); }
static JButton jimageButtonScaledToWidth(int w, String imageID, String toolTip, Runnable action) {
return jimageButton(scaleImageToWidth(w, imageID), toolTip, action);
}
static Collection addOrCreate(Collection l, A a) {
return addDyn(l, a);
}
static List addOrCreate(List l, A a) {
return addDyn(l, a);
}
static Set addOrCreate(Set l, A a) {
return createOrAddToSet(l, a);
}
static JTextArea typeWriterTextArea() {
return newTypeWriterTextArea();
}
static JTextArea typeWriterTextArea(String text) {
return newTypeWriterTextArea(text);
}
static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static Set syncLinkedHashSet() {
return synchroLinkedHashSet();
}
static void pcallFail(Throwable e) {
pcallPolicyForThread().handlePcallFail(e);
}
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(() -> {
JFrame frame = getFrame(c);
if (frame == null) return;
frame.getContentPane().removeAll();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrap(contents));
revalidate(frame);
}); }
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 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();
cc.programID = getDBProgramID();
try {
if (cc.useFileLock) {
if (!cc.fileLock().tryToLock()) {
ensureDBNotRunning(dbBotStandardName());
cc.fileLock().forceLock();
}
} else
ensureDBNotRunning(dbBotStandardName());
} catch (Throwable e) { printStackTrace(e);
cc.dontSave = true; // SAFETY
throw rethrow(e); }
cc.persist(autoSaveInterval);
dbBot(false);
if (conceptsAndBot_thinOnStart) { try {
thinAProgramsBackups(getDBProgramID(), true);
} catch (Throwable __e) { pcallFail(__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) {
var runnable = toRunnable(r);
executingSwingCode(runnable);
SwingUtilities.invokeLater(runnable);
}
static List activateMyFrames() {
final List l = myFrames();
{ swing(() -> {
for (JFrame f : l)
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 long conceptID(Concept.Ref ref) {
return conceptID(cDeref(ref));
}
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); } }
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1) return strOrEmpty(first((Collection) strings));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(strOrEmpty(i.next()));
while (i.hasNext())
buf.append(glue).append(strOrEmpty(i.next()));
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(String glue, Object... 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, lCharSequence(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 short[] takeFirstOfShortArray(short[] b, int n) {
return subShortArray(b, 0, n);
}
static short[] takeFirstOfShortArray(int n, short[] b) {
return takeFirstOfShortArray(b, n);
}
static byte[] takeFirstOfByteArray(byte[] b, int n) {
return subByteArray(b, 0, n);
}
static byte[] takeFirstOfByteArray(int n, byte[] b) {
return takeFirstOfByteArray(b, n);
}
static double[] takeFirstOfDoubleArray(double[] b, int n) {
return subDoubleArray(b, 0, n);
}
static double[] takeFirstOfDoubleArray(int n, double[] b) {
return takeFirstOfDoubleArray(b, n);
}
static A setMetaSrc(A a, Object src) {
setMetaAndVerify(a, "src", src);
return a;
}
static A setMetaSrc(A a, Object src) {
setMetaAndVerify(a, "src", src);
return a;
}
static ArrayList emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
// Try to match capacity
static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
// get correct type at once
static ArrayList emptyList(Class c) {
return new ArrayList();
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
static void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else {
r = addThreadInfoToRunnable(r);
executingSwingCode(r);
EventQueue.invokeAndWait(r);
}
} catch (Exception __e) { throw rethrow(__e); } }
static Object swingAndWait(Object f) {
if (isAWTThread())
return callF(f);
else {
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 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 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 {
vmBus_send("locking", lock, "thread" , currentThread());
lock.lockInterruptibly();
vmBus_send("locked", lock, "thread" , currentThread());
} catch (InterruptedException e) {
Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
printStackTrace(e);
rethrow(e);
}
// NO call to ping here! Make sure lock is always released.
} catch (Exception __e) { throw rethrow(__e); } }
static void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static ReentrantLock lock() {
return fairLock();
}
static 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 B callF(A a, IF1 f) {
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 void callF(A a, IVF1 f) {
if (f != null) f.get(a);
}
static void callF(IVF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Runnable r) { { if (r != null) r.run(); } return null; }
static Object callF(Object f, Object... args) {
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) {
if (f instanceof String)
throw fail("Legacy call: " + f);
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();
vmBus_send("unlocked", lock, "thread" , currentThread());
print("Unlocked: " + msg); // print afterwards to make sure the lock is always unlocked
}
static void unlock(Lock lock) {
if (lock == null) return;
lock.unlock();
vmBus_send("unlocked", lock, "thread" , currentThread());
}
static void _handleError(Error e) {
//call(javax(), '_handleError, e);
}
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 "return RightAlignedLine(components);"; }});
}
static JPanel jrightAlignedLine(List extends Component> components) {
return jrightAlignedLine(asArray(Component.class, components));
}
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 "return 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 "return selectedTableCell(t, tableColumnViewIndex(t, colName));"; }});
}
static A toComponent(A c) {
return c;
}
static Component toComponent(Swingable c) {
return c == null ? null : c.visualize();
}
static JPanel centerAndEastWithMarginInbetween(Component c, final Component e) {
return centerAndEast(c, withLeftMargin(e));
}
static SingleComponentPanel scp() {
return singleComponentPanel();
}
static SingleComponentPanel scp(Component c) {
return singleComponentPanel(c);
}
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(() -> {
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(() -> {
if (!setText_opt || neq(callOpt(c, "getText"), s))
call(c, "setText", s);
}); }
return c;
}
static boolean anyValueContainsIgnoreCase(Map map, String pat) {
for (Object val : values(map))
if (val instanceof String && containsIgnoreCase((String) val, pat))
return true;
return false;
}
static void onUpdate(JComponent c, Runnable r) {
onUpdate(c, (Object) r);
}
static void onUpdate(JTextComponent c, IVF1 r) {
if (c == null || r == null) return;
c.getDocument().addDocumentListener(runnableToDocumentListener(() -> r.get(c.getText())));
}
// legacy signature
static void onUpdate(JComponent c, Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(runnableToDocumentListener(toRunnable(r)));
else if (c instanceof ItemSelectable) // JCheckBox and others
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pcallF(r);
}
});
else if (c instanceof JSpinner)
onChange(((JSpinner) c), 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 ContentsIndexedList();
if (data instanceof List) {
for (Object x : (List) data) { try {
rows.add(dataToTable_makeRow(x, cols));
} catch (Throwable __e) { pcallFail(__e); }}
} else if (data instanceof Map) {
Map map = (Map) data;
for (Object key : map.keySet()) {
Object value = map.get(key);
rows.add(litlist(structureOrTextForUser(key), structureOrTextForUser(value)));
}
} else if (data != null)
print("Unknown data type: " + data);
fillTableWithData(table, rows, cols);
return table;
}
static JPanel centerAndEast(final Component c, final Component e) {
return swing(new F0() { public JPanel get() { try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.EAST, wrap(e));
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 boolean boolOptPar(ThreadLocal tl) {
return boolOptParam(tl);
}
// defaults to false
static boolean boolOptPar(Object[] __, String name) {
return boolOptParam(__, name);
}
static boolean boolOptPar(String name, Object[] __) {
return boolOptParam(__, name);
}
static JPanel northAndCenterWithMargin(int margin, Swingable n, Swingable c) { return northAndCenterWithMargin(margin, n, toComponent(c)); }
static JPanel northAndCenterWithMargin(int margin, Swingable n, Component c) { return northAndCenterWithMargin(margin, toComponent(n), c); }
static JPanel northAndCenterWithMargin(int margin, Component n, Swingable c) { return northAndCenterWithMargin(margin, n, toComponent(c)); }
static JPanel northAndCenterWithMargin(int margin, Component n, Component c) {
return northAndCenter(withBottomMargin(margin, n), c);
}
static JPanel northAndCenterWithMargin(Swingable n, Swingable c) { return northAndCenterWithMargin(n, toComponent(c)); }
static JPanel northAndCenterWithMargin(Swingable n, Component c) { return northAndCenterWithMargin(toComponent(n), c); }
static JPanel northAndCenterWithMargin(Component n, Swingable c) { return northAndCenterWithMargin(n, toComponent(c)); }
static JPanel northAndCenterWithMargin(Component n, Component c) {
return northAndCenter(withBottomMargin(n), c);
}
static JPanel northAndCenter(Component n, Component c) {
return centerAndNorth(c, n);
}
static JPanel centerAndSouth(final Component c, final Component s) {
return swing(new F0() { public JPanel get() { try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
if (s != null) panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT..."; }});
}
static int withTopMargin_defaultWidth = 6;
static JPanel withTopMargin(Component c) {
return withTopMargin(withTopMargin_defaultWidth, c);
}
static JPanel withTopMargin(final int w, final Component c) {
return swing(new F0() { public JPanel get() { try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0));
p.add(c);
return p;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat..."; }});
}
static 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(() -> {
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);
}); }
}
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) { pcallFail(__e); } return null;
}
static B pcallF(F1 f, A a) {
try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__e); } return null;
}
static void pcallF(VF1 f, A a) {
try {
{ if (f != null) f.get(a); }
} catch (Throwable __e) { pcallFail(__e); }
}
static Object pcallF(Runnable r) {
try { { if (r != null) r.run(); } } catch (Throwable __e) { pcallFail(__e); } return null;
}
static A pcallF(IF0 f) {
try { return f == null ? null : f.get(); } catch (Throwable __e) { pcallFail(__e); } return null;
}
static B pcallF(IF1 f, A a) {
try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__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 void addDirectMenuItem(JMenuBar mb, String text, Object action) {
if (mb != null) { swing(() -> {
addDirectMenuItem(mb, directJMenuItem(text, action));
}); }
}
static void addDirectMenuItem(Component c, String text, Object action) {
addDirectMenuItem(addMenuBar(c), text, action);
}
static void addDirectMenuItem(JMenuBar mb, JMenuItem menuItem) {
if (mb != null) { swing(() -> {
mb.add(menuItem);
revalidate(mb);
}); }
}
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, Runnable runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(runnable, name));
}
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 JScrollPane borderlessScrollPane(JScrollPane sp) {
return setBorder(null, withoutViewportBorder(sp));
}
static JScrollPane jHigherScrollPane(final JComponent c) {
return swing(() -> new JScrollPane(c) {
public Dimension getPreferredSize() {
Component view = getViewport().getView();
if (view == null) return super.getPreferredSize();
int pref_width = view.getPreferredSize().width;
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
Dimension dim = new Dimension(pref_width, super.getPreferredSize().height + getHorizontalScrollBar().getSize().height);
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
return dim;
}
});
}
static JPanel vstack2(final Object... parts) {
return swing(new F0() { public JPanel get() { try {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
smartAddWithLayout(panel, gbc, parts);
//gbc = (GridBagConstraints) gbc.clone();
//gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
panel.add(jrigid(), gbc);
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new GridBagLayout);\r\n new GridBagConstraints gbc..."; }});
}
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 == null || 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 : getDeclaredConstructors_cached(c)) {
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 ClassLoader classLoaderForObject(Object o) {
if (o instanceof ClassLoader) return ((ClassLoader) o);
if (o == null) return null;
return _getClass(o).getClassLoader();
}
// Note: This is actually broken. Inner classes must stay with a $ separator
static String classNameToVM(String name) {
return name.replace(".", "$");
}
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 String unnullForIteration(String s) {
return s == null ? "" : s;
}
static Collection unnullForIteration(Collection l) {
return l == null ? immutableEmptyList() : l;
}
static List unnullForIteration(List l) { return l == null ? immutableEmptyList() : l; }
static byte[] unnullForIteration(byte[] l) { return l == null ? emptyByteArray() : l; }
static int[] unnullForIteration(int[] l) { return l == null ? emptyIntArray() : l; }
static char[] unnullForIteration(char[] l) { return l == null ? emptyCharArray() : l; }
static double[] unnullForIteration(double[] l) { return l == null ? emptyDoubleArray() : l; }
static short[] unnullForIteration(short[] l) { return l == null ? emptyShortArray() : l; }
static Map unnullForIteration(Map l) {
return l == null ? immutableEmptyMap() : l;
}
static Iterable unnullForIteration(Iterable i) {
return i == null ? immutableEmptyList() : i;
}
static A[] unnullForIteration(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static BitSet unnullForIteration(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnullForIteration(Pt p) {
return p == null ? new Pt() : p;
}
//ifclass Symbol
static Symbol unnullForIteration(Symbol s) {
return s == null ? emptySymbol() : s;
}
//endif
static Pair unnullForIteration(Pair p) {
return p != null ? p : new Pair(null, null);
}
static long unnullForIteration(Long l) { return l == null ? 0L : l; }
static 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 Object getOptDynOnly(DynamicObject o, String field) {
if (o == null || o.fieldValues == null) return null;
return o.fieldValues.get(field);
}
static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static 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 String getStackTrace(String msg) {
return getStackTrace_noRecord(new Throwable(msg));
}
static boolean infoMessage_alwaysOnTop = true;
static double infoMessage_defaultTime = 5.0;
// automatically switches to AWT thread for you
static JWindow infoMessage(String text) {
return infoMessage(text, infoMessage_defaultTime);
}
static JWindow infoMessage(final String text, final double seconds) {
printHidingCredentials(text);
return infoMessage_noprint(text, seconds);
}
static JWindow infoMessage_noprint(String text) {
return infoMessage_noprint(text, infoMessage_defaultTime);
}
static JWindow infoMessage_noprint(final String _text, final double seconds) {
final String text = hideCredentials(_text);
if (empty(text)) return null;
logQuotedWithDate(infoBoxesLogFile(), text);
if (isHeadless()) return null;
return (JWindow) swingAndWait(new F0() { public Object get() { try {
JWindow window = makeWindow(infoMessage_makePanel(text));
window.setSize(300, 150);
moveToTopRightCorner(window);
if (infoMessage_alwaysOnTop)
window.setAlwaysOnTop(true);
if (vmBus_noObjections("shouldShowInfoBox", window, text))
window.setVisible(true);
if (seconds != 0)
disposeWindowAfter(iround(seconds*1000), window);
return window;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JWindow window = makeWindow(infoMessage_makePanel(text));\r\n window.setSize..."; }});
}
static JWindow infoMessage(Throwable e) {
//showConsole();
printStackTrace(e);
return infoMessage(exceptionToStringShort(e));
}
static String strOrNull(Object o) {
return o == null ? null : str(o);
}
static Object getMCOpt(String field) {
return getOptMC(field);
}
static void setMCOpt(String field, Object value) {
setOptMC(field, value);
}
static JButton renameButton(JComponent c, String name) {
JButton b = first(childrenOfType(c, JButton.class));
if (b != null)
b.setText(name);
return b;
}
static JButton renameButton(JComponent c, String oldName, String newName) {
JButton b = findButton(c, oldName);
if (b != null) b.setText(newName);
return b;
}
static String showFormSubmitButtonName() {
return "Submit";
}
static List concatLists(Iterable ... lists) {
List l = new ArrayList();
if (lists != null) for (Iterable list : lists)
addAll(l, list);
return l;
}
static List concatLists(Collection extends Iterable > lists) {
List l = new ArrayList();
if (lists != null) for (Iterable list : lists)
addAll(l, list);
return l;
}
static String combinePrintParameters(String s, Object o) {
return (endsWithLetterOrDigit(s) ? s + ": " : s) + o;
}
static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
// this syntax should be removed...
static Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0) return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i+1 < l && s.charAt(i+1) == '\n') ++i;
}
}
return out.toString();
}
static void print_append(Appendable buf, String s, int max) { try {
synchronized(buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) { throw rethrow(__e); } }
static void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg);
pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static Class mc() {
return main.class;
}
static void assertTrue(Object o) {
if (!(eq(o, true) /*|| isTrue(pcallF(o))*/))
throw fail(str(o));
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static boolean assertTrue(Scorer scorer, boolean b) {
scorer.add(b);
return b;
}
static boolean isUnlisted(Concept c) {
return c != null && c.concepts() == null;
}
static List allBackRefObjects(Concept c) {
return cloneList(c == null ? null : c.backRefs);
}
static Field getField(Object o, String field) {
if (o == null) return null;
return setOpt_findField(_getClass(o), field);
}
static Object getField(Field field, Object o) {
return fieldGet(field, o);
}
static Class typeToClass(Type type) {
if (type == null) return null;
if (type instanceof Class) return ((Class) type);
if (type instanceof ParameterizedType) return optCast(Class.class, ((ParameterizedType) type).getRawType());
if (type instanceof GenericArrayType)
return typeToClass(((GenericArrayType) type).getGenericComponentType()).arrayType();
return null;
}
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 Pair first(Map map) {
return mapEntryToPair(first(entrySet(map)));
}
static Pair first(MultiMap mm) {
if (mm == null) return null;
var e = first(mm.data.entrySet());
if (e == null) return null;
return pair(e.getKey(), first(e.getValue()));
}
static A first(IterableIterator i) {
return first((Iterator ) i);
}
static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static Character first(CharSequence s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static A first(T3 t) {
return t == null ? null : t.a;
}
static Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static int first(IntBuffer buf) {
return buf.get(0);
}
static A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static A first(AppendableChain a) {
return a == null ? null : a.element;
}
static Object derefRef(Object o) {
if (o instanceof Concept.Ref) o = ((Concept.Ref) o).get();
return o;
}
static A derefRef(Concept.Ref r) {
return r == null ? null : r.get();
}
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 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, Object onChange) {
JCheckBox cb = jCheckBox(text, checked);
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 JCheckBox jCheckBox(boolean checked, String text, IVF1 onChangeAndNow) {
var cb = jCheckBox(text, checked);
onChangeAndNow(cb, new Runnable() { public void run() { try { onChangeAndNow.get(isChecked(cb));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "onChangeAndNow.get(isChecked(cb));"; }});
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(Object... objects) { throw new Fail(objects); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static boolean rectContains(int x1, int y1, int w, int h, Pt p) {
return p.x >= x1 && p.y >= y1 && p.x < x1+w && p.y < y1+h;
}
static boolean rectContains(Rect a, Rect b) {
return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2();
}
static boolean rectContains(Rect a, Rectangle b) {
return rectContains(a, toRect(b));
}
static boolean rectContains(Rect a, int x, int y) {
return a != null && a.contains(x, y);
}
static boolean rectContains(Rect a, Pt p) {
return a != null && p != null && a.contains(p);
}
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 boolean isSubclass(Class a, Class b) {
return a != null && b != null && b.isAssignableFrom(a);
}
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 "return nuObject(c, args);"; }});
}
// legacy mode
//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();
// ignore pingSource if not PingV3
static boolean ping(PingSource pingSource) { return ping(); }
// always returns true
static boolean ping() {
//ifdef useNewPing
newPing();
//endifdef
if (ping_pauseAll || ping_anyActions) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized(ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
// assumptions:
// -pingSource() stays constant within a stack frame (so you can cache it)
// -all changes happen with tempSetPingSource
// -multiple threads can share a PingSource
static PingSource pingSource() {
return pingSource_tl().get();
}
static PingSource pingSource(Thread thread) {
return pingSource_tl().get(thread);
}
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 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 float[] unnull(float[] l) { return l == null ? emptyFloatArray() : l; }
static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
//ifclass Symbol
static Symbol unnull(Symbol s) {
return s == null ? emptySymbol() : s;
}
//endif
static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static int unnull(Integer i) { return i == null ? 0 : i; }
static long unnull(Long l) { return l == null ? 0L : l; }
static double unnull(Double l) { return l == null ? 0.0 : l; }
static JTextField standardTextFieldPopupMenu(final JTextField tf) {
final WeakReference ref = weakRef(tf);
componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(ref.get().getText())
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(ref.get().getText())"; }});
componentPopupMenuItem(tf, "Paste", new Runnable() { public void run() { try { ref.get().paste() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ref.get().paste()"; }});
return tf;
}
static A jenableUndoRedo(A textcomp) {
{ swing(() -> {
UndoManager undo = new UndoManager();
vm_generalWeakSet("Undo Managers").add(undo);
setMeta(textcomp, "UndoManager", 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");
}); }
return textcomp;
}
static JComponent unwrapScrollPane(JScrollPane sp) {
return sp == null ? null : (JComponent) sp.getViewport().getView();
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
static Object[] expandParams(Class c, Object[] params) {
if (l(params) == 1)
params = new Object[] { singleFieldName(c), params[0] };
else
warnIfOddCount(params);
return params;
}
// returns true if change
static boolean _csetField(Concept c, String field, Object value) { try {
Field f = setOpt_findField(c.getClass(), field);
//print("cset: " + c.id + " " + field + " " + struct(value) + " " + f);
if (value instanceof RC) value = c._concepts.getConcept((RC) value);
value = deref(value);
if (value instanceof String && l((String) value) >= concepts_internStringsLongerThan) value = intern((String) value);
if (f == null) {
// dynamic field (undeclared)
assertIdentifier(field);
Object oldVal = mapGet(c.fieldValues, field);
if (value instanceof Concept) {
if (oldVal instanceof Concept.Ref)
// change existing reference
return ((Concept.Ref) oldVal).set((Concept) value);
else {
// overwrite non-reference value if any,
// create new reference
dynamicObject_setRawFieldValue(c, field, c.new Ref((Concept) value));
c.change(); return true;
}
} else {
// value is not a concept
// if it was a reference, cleanly delete it
if (oldVal instanceof Concept.Ref) ((Concept.Ref) oldVal).unindexAndDrop();
if (eq(oldVal, value)) return false;
if (isConceptList(value) && nempty(((List) value))) {
// TODO: clean-up etc
dynamicObject_setRawFieldValue(c, field, c.new RefL(((List) value)));
c.change(); return true;
}
if (value == null) {
// delete field
dynamicObject_dropRawField(c, field);
} else {
// update or create field
if (!isPersistable(value))
throw fail("Can't persist: " + c + "." + field + " = "+ value);
dynamicObject_setRawFieldValue(c, field, value);
}
c.change(); return true;
}
} else if (isSubtypeOf(f.getType(), Concept.Ref.class)) {
// Concept.Ref magic
((Concept.Ref) f.get(c)).set((Concept) derefRef(value));
c.change(); return true;
} else if (isSubtypeOf(f.getType(), Concept.RefL.class)) {
// Concept.RefL magic
((Concept.RefL) f.get(c)).replaceWithList(lmap(__32 -> derefRef(__32), (List) value));
c.change(); return true;
} else {
Object old = f.get(c);
if (neq(value, old)) {
boolean isTransient = isTransient(f);
if (!isTransient && !isPersistable(value))
throw fail("Can't persist: " + c + "." + field + " = "+ value);
f.set(c, value);
if (!isTransient) c.change();
return true;
}
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static String getType(Object o) {
return getClassName(o);
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static 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 "return cb.isEditable();"; }});
}
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. TODO: huh?
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null)
{ smartSet(f, o, value); return; } // possible improvement: skip setAccessible
if (o instanceof DynamicObject)
{ setDyn(((DynamicObject) o), field, value); return; }
if (o instanceof IMeta)
setDyn(((IMeta) o), field, value);
} catch (Exception __e) { throw rethrow(__e); } }
static void setOpt(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = setOpt_findStaticField(c, field); // TODO: optimize
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
makeAccessible(f);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static int toInt(Object o) {
if (o == null) return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt((String) o);
if (o instanceof Boolean)
return boolToInt((Boolean) o);
throw fail("woot not int: " + getClassName(o));
}
static int toInt(long l) {
if (l != (int) l) throw fail("Too large for int: " + l);
return (int) l;
}
static float toFloat(Object o) {
if (o == null) return 0f;
if (o instanceof Number) return ((Number) o).floatValue();
if (o instanceof Boolean) return ((Boolean) o).booleanValue() ? 1f : 0f;
throw fail("Not convertible to float: " + _getClass(o));
}
static double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o instanceof String)
return parseDouble((String) o);
if (o == null) return 0.0;
throw fail(o);
}
static Pt parsePt(String s) {
var l = parseInts(splitAtComma_trim(s));
return empty(l) ? null : pt(first(l), second(l));
}
static Rect parseRect(String s) {
List tok = javaTokC(s);
assertEquals(7, l(tok));
return new Rect(parseInt(tok.get(0)), parseInt(tok.get(2)),
parseInt(tok.get(4)), parseInt(tok.get(6)));
}
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);
}
// returns from C to C
static String jextract(String pat, String s) {
return jextract(pat, javaTok(s));
}
static String jextract(String pat, List tok) {
List tokpat = javaTok(pat);
jfind_preprocess(tokpat);
int i = jfind(tok, tokpat);
if (i < 0) return null;
int j = i + l(tokpat) - 2;
return joinSubList(tok, i, j);
}
static boolean imagesIdentical(BufferedImage img1, BufferedImage img2) {
if (img1 == img2) return true;
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;
var gp1 = grabbableIntPixels_fastOrSlow(img1);
var gp2 = grabbableIntPixels_fastOrSlow(img2);
int[] pixels1 = gp1.data, pixels2 = gp2.data;
int scanlineExtra1 = gp1.scanlineStride-w;
int scanlineExtra2 = gp2.scanlineStride-w;
int i1 = gp1.offset, i2 = gp2.offset;
var ping = pingSource();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++)
if (pixels1[i1++] != pixels2[i2++])
return false;
i1 += scanlineExtra1;
i2 += scanlineExtra2;
{ if (ping != null) ping.get(); }
}
return true;
}
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 listIntersectSet(Collection a, Collection b) {
return listSetIntersection(a, b);
}
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();
}
// f: A -> S
static List sortedByCalculatedFieldIC(Iterable c, Object f) {
return sortByCalculatedFieldIC(c, f);
}
static List sortedByCalculatedFieldIC(Object f, Iterable c) {
return sortedByCalculatedFieldIC(c, f);
}
static List sortedByCalculatedFieldIC(IF1 f, Iterable c) {
return sortedByCalculatedFieldIC((Object) f, c);
}
static List sortedByCalculatedFieldIC(Iterable c, IF1 f) {
return sortedByCalculatedFieldIC((Object) f, c);
}
static List myInnerClasses_list=litlist(
null, "Meta", "MultiSetMap", "Var", "DefunctClassLoader", "Scorer", "ITokCondition", "talkToThisVM_IO", "PingSource", "PopupMenuMaker", "IFieldIndex", "CountingOutputStream", "AppendableChain", "ConceptChange", "JForm", "CompactAbstractMap", "SingleComponentPanel", "CompactLinkedHashSet", "FixedRateTimer", "Fail", "Rect", "Pt", "ISetter", "AbstractLayoutManager", "BufferedImageWithMeta", "IterableIterator", "betterCIComparator_C", "RemoteDB", "MakesBufferedImage", "ScannedBot", "PCallPolicy", "Concepts", "RC", "XRef", "Hasher", "PNGFile", "CloseableIterableIterator", "getOpt_Map", "IFieldsToList", "IResponder", "IntBuffer", "structure_Data", "IVar", "IIntPred", "Chain", "Matches", "CompactHashMap", "TableWithTooltips", "ThreadPool", "IDialogHandler", "Timestamp", "AWTOnConceptChanges", "Complex", "MultiMap", "IHasChangeListeners", "CriticalAction", "IResourceLoader", "WeakHasherMap", "RestartableCountdown", "TransientObject", "MultiSet", "T3", "IResourceHolder", "JMenuScroller", "DialogIO", "mapI_if1_It", "IConceptCounter", "IAutoCloseableF0", "UnsynchronizedCompactHashSet", "BetterLabel", "componentPopupMenu_Adapter", "MRUCache", "ISleeper_v2", "AWTOnConceptChangesByClass", "PersistableThrowable", "talkToSubBot_IO", "IDoublePt", "RGBImage", "WidthAndHeight", "HasIndex", "SmartTimerTask", "Responder", "VF1", "VF2", "TableSearcher", "IMultiSet", "SimpleCRUD_v2", "ConceptsChange", "FullChange", "TokCondition", "IntegerIterator", "RightAlignedLine", "ConceptDelete", "findCodeTokens_Matcher", "Unstructurer", "IntSize", "MultiSleeper", "unstructure_Handler", "IMultiMap", "Concept", "IRGBImage", "AutoComboBox", "JConceptsTable", "PtInComponent", "ProgramScan", "IRef", "F0", "F1", "F2", "RandomAccessAbstractList", "TreeMultiMap", "RGB", "Flag", "unstructure_Receiver", "ContentsIndexedList", "WidthAndHeightFinal", "IF0", "BaseXRef", "IContentsIndexedList2", "IF2", "Producer", "FormLayout1", "IF1", "Value", "tablePopupMenu_Maker", "IVF1", "IVF2", "Cache", "_MethodCache", "talkTo_IO", "IConcept", "PingSourceCancelledException", "structure_ClassInfo", "FileBasedLock", "Symbol", "IMeta", "BetterThread", "IContentsIndexedList", "LetterLayout", "BetterThreadLocal", "DialogHandler", "proxy_InvocationHandler", "ChangeTrigger", "Pair", "Swingable", "MinimalChain", "Flattener", "ChangeTriggerable", "GrabbableIntPixels", "TransferableImage", "Sleeping", "IConceptIndex", "ReverseChain", "ConceptCreate", "Seconds", "Android3");
static List myInnerClasses() {
return myInnerClasses_list;
}
static String mcName() {
return mc().getName();
}
static boolean isAbstract(Class c) {
return (c.getModifiers() & Modifier.ABSTRACT) != 0;
}
static boolean isAbstract(Method m) {
return (m.getModifiers() & Modifier.ABSTRACT) != 0;
}
static boolean isSubtypeOf(Class a, Class b) {
return a != null && b != null && b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static Vector toVector(A[] array) {
return new Vector(toList(array));
}
static Vector toVector(Collection l) {
return l == null ? null : new Vector(l);
}
static JComboBox selectItem(A item, JComboBox cb) {
if (cb != null) { swing(() -> { cb.setSelectedItem(item); }); }
return cb;
}
static JComboBox selectItem(JComboBox cb, A item) {
return selectItem(item, cb);
}
static JList selectItem(JList list, A item) {
{ swing(() -> { selectRow(list, jlist_indexOf(list, item)); }); }
return list;
}
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 String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++)
a[i] = it.next();
return a;
}
static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
// action = runnable or method name (old)
static void onUpdateAndNow(JComponent c, final Object r) {
onUpdate(c, r);
callF(r);
}
static void onUpdateAndNow(JTextComponent c, IVF1 r) { swing(() -> {
if (c == null) return;
onUpdate(c, r);
callF(r, c.getText());
}); }
static void onUpdateAndNow(List extends JComponent> l, Object r) {
for (JComponent c : l)
onUpdate(c, r);
callF(r);
}
static JPanel hgridWithSpacing(Object... _parts) {
return swing(() -> {
int spacing = 6;
Object[] parts = _parts;
if (first(parts) instanceof Integer) {
spacing = (Integer) first(parts);
parts = dropFirst(parts);
}
JPanel panel = hgrid(parts);
GridLayout gl = (GridLayout) (panel.getLayout());
gl.setHgap(spacing);
gl.setVgap(spacing);
return panel;
});
}
static A setToolTipText(final A c, final Object toolTip) {
if (c == null) return null;
{ swing(() -> {
String s = str_nullIfEmpty(toolTip);
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
}); }
return c;
}
static A setToolTipText(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
static JPanel westAndCenter(final Component w, final Component c) {
return swing(new F0() { public JPanel get() { try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.WEST, wrap(w));
panel.add(BorderLayout.CENTER, wrap(c));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST..."; }});
}
static int withRightMargin_defaultWidth = 6;
static JPanel withRightMargin(Component c) {
return withRightMargin(withRightMargin_defaultWidth, c);
}
static JPanel withRightMargin(final int w, final Component c) {
return swing(new F0() { public JPanel get() { try {
JPanel p = marginPanel();
p.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, w));
p.add(c);
return p;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel p = marginPanel();\r\n p.setBorder(BorderFactory.createEmptyBorder(0,..."; }});
}
static String asString(Object o) {
return o == null ? null : o.toString();
}
static A addComponents(A c, Collection extends Component> components) {
if (nempty(components)) { swing(() -> {
for (Component comp : components)
if (comp != null)
c.add(comp);
revalidate(c);
}); }
return c;
}
static A addComponents(A c, Component... components) {
return addComponents(c, asList(components));
}
static Runnable toRunnable(final Object o) {
if (o == null) return null;
if (o instanceof Runnable) return (Runnable) o;
if (o instanceof String) throw fail("callF_legacy");
return new Runnable() { public void run() { try { callF(o) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; }};
}
static ChangeListener changeListener(final Object r) {
return new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(r);
}
};
}
static ItemListener itemListener(final Object r) {
return new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pcallF(r);
}
};
}
static void addActionListener(JTextField tf, final Runnable action) {
onEnter(tf, action);
}
static void addActionListener(final JComboBox cb, final Runnable action) {
if (cb != null) { swing(() -> {
cb.addActionListener(actionListener(action));
}); }
}
static void addActionListener(final AbstractButton b, final Runnable action) {
if (b != null) { swing(() -> {
b.addActionListener(actionListener(action));
}); }
}
static JTextField textFieldFromComboBox(JComboBox cb) {
return (JTextField) cb.getEditor().getEditorComponent();
}
static JComboBox onSelectedItem(final JComboBox cb, final VF1 f) {
addActionListener(cb, new Runnable() { public void run() { try {
pcallF(f, selectedItem(cb))
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(f, selectedItem(cb))"; }});
return cb;
}
static JComboBox onSelectedItem(final JComboBox cb, IVF1 f) {
addActionListener(cb, new Runnable() { public void run() { try {
pcallF(f, selectedItem(cb))
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(f, selectedItem(cb))"; }});
return cb;
}
static boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++)
if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static 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 > A max (Iterable l) {
A max = null;
var it = iterator(l);
if (it.hasNext()) {
max = it.next();
while (it.hasNext()) {
A a = it.next();
if (cmp(a, max) > 0)
max = a;
}
}
return max;
}
/*Nah.
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
ret x;
}*/
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static float max(float[] c) {
if (c.length == 0) return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x) x = d;
return x;
}
static > A max(A a, A b) {
return cmp(a, b) >= 0 ? a : b;
}
static A jPreferWidth(int w, A c) {
{ swing(() -> {
Dimension size = c.getPreferredSize();
c.setPreferredSize(new Dimension(/*max(w, size.width) ??? */w, size.height));
}); }
return c;
}
static A jPreferWidth(A c, int w) {
return jPreferWidth(w, c);
}
static JScrollPane jscroll_trackWidth(JComponent c) {
return jscroll(scrollable_trackWidth(c));
}
static JScrollPane jscroll_trackWidth(Swingable c) {
return jscroll_trackWidth(c.visualize());
}
static boolean any(Object pred, Iterable l) {
if (l != null) for (A a : l)
if (isTrue(callF(pred, a)))
return true;
return false;
}
static boolean any(IF1 pred, Iterable l) {
if (l != null) for (A a : l)
if (pred.get(a))
return true;
return false;
}
static boolean any(Iterable l, IF1 pred) {
return any(pred, l);
}
static boolean any(A[] l, IF1 pred) {
if (l != null) for (A a : l)
if (pred.get(a))
return true;
return false;
}
static boolean any(Iterable l) {
if (l != null) for (Boolean a : l)
if (isTrue(a))
return true;
return false;
}
static Set getPlural_specials = litciset("sheep", "fish");
static String getPlural(String s) {
if (contains(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 boolean newButton_autoToolTip = true;
static boolean newButton_autoToolTip() { return newButton_autoToolTip; }
// 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);
JButton btn = basicJButton(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 JButton btn = basicJButton(te..."; }});
}
static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static void containerAddFirst(Container c, Component... l) {
if (c != null) { swing(() -> {
for (int i = 0; i < l(l); i++)
c.add(l[i], i);
revalidate(c);
}); }
}
static JButton jimageButton(String imageID, Object action) {
JButton btn = jbutton("", action);
btn.setIcon(imageIcon(imageID));
return btn;
}
// button without action
static JButton jimageButton(String imageID) {
return jimageButton(imageID, null);
}
static JButton jimageButton(Image img) {
return jimageButton(img, null, null);
}
static JButton jimageButton(String imageID, String toolTip, Runnable action) {
return jimageButton(imageIcon(imageID), toolTip, action);
}
static JButton jimageButton(Image img, String toolTip, Runnable action) {
var btn = jbutton("", action);
setButtonImage(btn, img);
return setToolTip(toolTip, btn);
}
static JButton jimageButton(ImageIcon img, String toolTip, Runnable action) {
var btn = jbutton("", action);
setButtonImage(btn, img);
return setToolTip(toolTip, btn);
}
static BufferedImage scaleImageToWidth(BufferedImage img, int newW) {
return resizeImage(img, newW);
}
static BufferedImage scaleImageToWidth(int newW, BufferedImage img) {
return scaleImageToWidth(img, newW);
}
static BufferedImage scaleImageToWidth(int newW, String imageID) {
return scaleImageToWidth(newW, loadImage2(imageID));
}
static Collection addDyn(Collection l, A a) {
if (l == null) l = new ArrayList();
l.add(a);
return l;
}
static List addDyn(List l, A a) {
if (l == null) l = new ArrayList();
l.add(a);
return l;
}
static JTextArea newTypeWriterTextArea() {
return newTypeWriterTextArea("");
}
static JTextArea newTypeWriterTextArea(String text) {
return withTypeWriterFont(jTextArea(text));
}
//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 HashMap getOpt_special; // just a marker
/*static void getOpt_special_init(Map map) {
map.put(Class.class, getOpt_special);
map.put(S.class, getOpt_special);
}*/
static Map getOpt_getFieldMap(Object o) {
Class c = _getClass(o);
HashMap map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
return map;
}
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Map map = getOpt_getFieldMap(o);
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
/*if (o instanceof S)
ret getOpt(getBot((S) o), field);*/
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
if (o instanceof DynamicObject)
return syncMapGet2(((DynamicObject) o).fieldValues, field);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
if (!reflection_classesNotToScan().contains(c.getName())) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
makeAccessible(f);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
}
if (getOpt_cache != null) getOpt_cache.put(c, map);
return map;
}
static