import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import org.pushingpixels.substance.api.*;
import org.pushingpixels.substance.api.skin.*;
public class main {
public static void main(final String[] args) throws Exception { { swingAndWait(new Runnable() { public void run() { try { substance();
final JTable table = showTable(ll(
litorderedmap("Hello" , "World", "How" , "Good"),
litorderedmap("Hello" , "Boys", "How" , "Whatever")));
TransferHandler th = new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {
return COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
print("Row/Column: " + table.getSelectedRow() + " / " + table.getSelectedColumn());
Object o = selectedTableCell(table);
print("Value: " + o);
return new StringSelection(str(o));
}
};
tableEnableDrag(table, th);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "substance();\n final JTable table = showTable(ll(\n litorderedmap(\"Hello\" , \"World\", \"How\" , \"Good\"),\n litorderedmap(\"Hello\" , \"Boys\", \"How\" , \"Whatever\")));\n \n TransferHandler th = new TransferHandler {\n @Override\n public int getSourceActions(JComponent c) {\n return COPY;\n }\n\n @Override\n protected Transferable createTransferable(JComponent c) {\n print(\"Row/Column: \" + table.getSelectedRow() + \" / \" + table.getSelectedColumn());\n Object o = selectedTableCell(table);\n print(\"Value: \" + o);\n return new StringSelection(str(o));\n }\n };\n \n tableEnableDrag(table, th);"; }}); }}
static void tableEnableDrag(final JTable table, TransferHandler th) {
table.setDragEnabled(true);
table.setTransferHandler(th);
table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
table.getTransferHandler().exportAsDrag(table, e, TransferHandler.COPY);
}
});
}
static List ll(A... a) {
return litlist(a);
}
static Object selectedTableCell(JTable t, int col) {
return getTableCell(t, t.getSelectedRow(), col);
}
static Object selectedTableCell(JTable t) {
return selectedTableCell(t, t.getSelectedColumn());
}
static String str(Object o) {
return String.valueOf(o);
}
static String str(char[] c) {
return new String(c);
}
static LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
//static int print_maxLineLength = 0; // 0 = unset
static boolean print_silent; // total mute if set
static volatile ThreadLocal print_byThread; // special handling by thread
static void print() {
print("");
}
// slightly overblown signature to return original object...
static A print(A o) {
ping();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
if (print_byThread != null) {
Object f = print_byThread.get();
if (f != null)
if (isFalse(callF(f, s))) return;
}
print_raw(s);
}
static void print_raw(String s) {
s = fixNewLines(s);
// TODO if (print_maxLineLength != 0)
StringBuffer loc = local_log;
StringBuffer buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static void print(long l) {
print(String.valueOf(l));
}
static void print(char c) {
print(String.valueOf(c));
}
static void print_append(StringBuffer buf, String s, int max) {
synchronized(buf) {
buf.append(s);
max /= 2;
if (buf.length() > max) try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
}
}
static boolean showTable_searcher = true;
static JTable showTable(Object data) {
return dataToTable_uneditable(data);
}
static JTable showTable(Object data, String title) {
return dataToTable_uneditable(data, title);
}
static JTable showTable(JTable table, Object data) {
return showTable(table, data, autoFrameTitle());
}
static JTable showTable(Object data, JTable table) {
return showTable(table, data);
}
static JTable showTable(JTable table, Object data, String title) {
if (table == null)
table = showTable(data, title);
else {
setFrameTitle(table, title);
dataToTable_uneditable(table, data);
}
return table;
}
static JTable showTable() {
return showTable(new ArrayList>(), new ArrayList());
}
static JTable showTable(String title) {
return showTable(new ArrayList>(), new ArrayList(), title);
}
static JTable showTable(List> rows, List cols) {
return showTable(rows, cols, autoFrameTitle());
}
static JTable showTable(List> rows, List cols, String title) {
JTable tbl = sexyTable();
fillTableWithStrings(tbl, rows, cols);
showFrame(title, tbl);
return tbl;
}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
static Object getTableCell(JTable tbl, int row, int col) {
if (row >= 0 && row < tbl.getModel().getRowCount())
return tbl.getModel().getValueAt(row, col);
return null;
}
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = synchroMap(new WeakHashMap());
// returns true if it did anything
static boolean ping() { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
Object action;
synchronized(mc()) {
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 (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static Object callF(Object f, Object... args) {
return callFunction(f, args);
}
static A setFrameTitle(A c, String title) {
JFrame f = getFrame(c);
if (f == null)
showFrame(title, c);
else
f.setTitle(title);
return c;
}
static A setFrameTitle(String title, A c) {
return setFrameTitle(c, title);
}
// magically find a field called "frame" in main class :-)
static JFrame setFrameTitle(String title) {
Object f = getOpt(mc(), "frame");
if (f instanceof JFrame)
return setFrameTitle((JFrame) f, title);
return null;
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static JTable dataToTable_uneditable(Object data, final JTable table) {
return dataToTable_uneditable(table, data);
}
static JTable dataToTable_uneditable(final JTable table, final Object data) {
{ swingAndWait(new Runnable() { public void run() { try {
dataToTable(table, data, true);
makeTableUneditable(table);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "dataToTable(table, data, true);\r\n makeTableUneditable(table);"; }}); }
return table;
}
static JTable dataToTable_uneditable(final Object data) {
return dataToTable_uneditable(showTable(), data);
}
static JTable dataToTable_uneditable(Object data, String title) {
return dataToTable_uneditable(showTable(title), data);
}
static void fillTableWithStrings(final JTable table, List> rows, List colNames) {
fillTableWithStrings(table, rows, toStringArray(colNames));
}
// thread-safe
static void fillTableWithStrings(final JTable table, List> rows, String... colNames) {
final DefaultTableModel model = fillTableWithStrings_makeModel(rows, colNames);
swingNowOrLater(new Runnable() { public void run() { try {
setTableModel(table, model);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "setTableModel(table, model);"; }});
}
static DefaultTableModel fillTableWithStrings_makeModel(List> rows, String... colNames) {
Object[][] data = new Object[rows.size()][];
int w = 0;
for (int i = 0; i < rows.size(); i++) {
List l = rows.get(i);
Object[] r = new Object[l.size()];
for (int j = 0; j < l.size(); j++)
r[j] = l.get(j);
data[i] = r;
w = Math.max(w, l.size());
}
Object[] columnNames = new Object[w];
for (int i = 0; i < w; i++)
columnNames[i] = i < l(colNames) ? colNames[i] : "?";
return new DefaultTableModel(data, columnNames);
}
static JTable sexyTable() {
final JTable table = tableWithToolTips();
tablePopupMenu(table, new Object() { void get(JPopupMenu menu, final int row) { try {
final String item = first(getTableLine(table, row));
MouseEvent e = tablePopupMenu_mouseEvent.get();
final int col = table.columnAtPoint(e.getPoint());
final Object value = table.getModel().getValueAt(row, col);
//print("Cell type: " + getClassName(value));
if (value instanceof ImageIcon) {
addMenuItem(menu, "Copy image to clipboard", new Runnable() { public void run() { try {
copyImageToClipboard(((ImageIcon) value).getImage());
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "copyImageToClipboard(((ImageIcon) value).getImage());"; }});
} else {
final String text = str(value);
addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(text);
print("Copied text to clipboard: " + quote(text));
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "copyTextToClipboard(text);\r\n print(\"Copied text to clipboard: \" + quote(text));"; }});
}
addMenuItem(menu, "Set row height...", new Runnable() { public void run() { try {
final JTextField tf = jTextField(table.getRowHeight());
showTitledForm("Set row height",
"Pixels", tf, new Runnable() { public void run() { try {
table.setRowHeight(parseInt(trim(tf.getText())))
;
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "table.setRowHeight(parseInt(trim(tf.getText())))"; }});
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "final JTextField tf = jTextField(table.getRowHeight());\r\n showTitledForm(\"Set row height\",\r\n \"Pixels\", tf, r {\r\n table.setRowHeight(parseInt(trim(tf.getText())))\r\n });"; }});
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "final S item = first(getTableLine(table, row));\r\n MouseEvent e = tablePopupMenu_mouseEvent.get();\r\n final int col = table.columnAtPoint(e.getPoint());\r\n final O value = table.getModel().getValueAt(row, col);\r\n //print(\"Cell type: \" + getClassName(value));\r\n\r\n if (value instanceof ImageIcon) {\r\n addMenuItem(menu, \"Copy image to clipboard\", r {\r\n copyImageToClipboard(((ImageIcon) value).getImage());\r\n });\r\n } else {\r\n final S text = str(value);\r\n addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(text);\r\n print(\"Copied text to clipboard: \" + quote(text));\r\n });\r\n }\r\n \r\n addMenuItem(menu, \"Set row height...\", r {\r\n final JTextField tf = jTextField(table.getRowHeight());\r\n showTitledForm(\"Set row height\",\r\n \"Pixels\", tf, r {\r\n table.setRowHeight(parseInt(trim(tf.getText())))\r\n });\r\n });"; }});
// Disable Ctrl+PageUp and Ctrl+PageDown
table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
//table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, InputEvent.CTRL_MASK), "none");
/*table.registerKeyboardAction(
null,
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
);*/
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_FOCUSED)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
((InputMap) UIManager.get("Table.ancestorInputMap")).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
return table;
}
static ArrayList litlist(A... a) {
return new ArrayList(Arrays.asList(a));
}
static String autoFrameTitle() {
return getProgramTitle();
}
static void autoFrameTitle(Component c) {
setFrameTitle(getFrame(c), autoFrameTitle());
}
static JFrame showFrame() {
return makeFrame();
}
static JFrame showFrame(Object content) {
return makeFrame(content);
}
static JFrame showFrame(String title) {
return makeFrame(title);
}
static JFrame showFrame(String title, Object content) {
return makeFrame(title, content);
}
static JFrame showFrame(final JFrame frame) {
if (frame != null) { swingAndWait(new Runnable() { public void run() { try {
if (frameTooSmall(frame)) frameStandardSize(frame);
frame.setVisible(true);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "if (frameTooSmall(frame)) frameStandardSize(frame);\r\n frame.setVisible(true);"; }}); }
return frame;
}
// make or update frame
static JFrame showFrame(String title, Object content, JFrame frame) {
if (frame == null)
return showFrame(title, content);
else {
frame.setTitle(title);
setFrameContents(frame, content);
return frame;
}
}
static Map litmap(Object... x) {
TreeMap map = new TreeMap();
litmap_impl(map, x);
return map;
}
static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length-1; i += 2)
if (x[i+1] != null)
map.put(x[i], x[i+1]);
}
static boolean frameTooSmall(JFrame frame) {
return frame.getWidth() < 100 || frame.getHeight() < 50;
}
static JFrame makeFrame() {
return makeFrame((Component) null);
}
static JFrame makeFrame(Object content) {
return makeFrame(programTitle(), content);
}
static JFrame makeFrame(String title) {
return makeFrame(title, null);
}
static JFrame makeFrame(String title, Object content) {
return makeFrame(title, content, true);
}
static JFrame makeFrame(final String title, final Object content, final boolean showIt) {
return (JFrame) swing(new Object() { Object get() { try {
if (getFrame(content) != null)
return setFrameTitle((Component) content, title);
final JFrame frame = new JFrame(title);
if (content != null)
frame.getContentPane().add(wrap(content));
frame.setBounds(300, 100, 500, 400);
if (showIt)
frame.setVisible(true);
//callOpt(content, "requestFocus");
//exitOnFrameClose(frame);
// standard right-click behavior on titles
if (isSubstanceLAF())
titlePopupMenu(frame,
new Object() { void get(JPopupMenu menu) { try {
boolean alwaysOnTop = frame.isAlwaysOnTop();
menu.add(jmenuItem("Restart Program", "restart"));
menu.add(jmenuItem("Show Console", "showConsole"));
menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() { public void run() { try {
toggleAlwaysOnTop(frame) ;
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "toggleAlwaysOnTop(frame)"; }}));
menu.add(jMenuItem("Shoot Window", new Runnable() { public void run() { try { shootWindowGUI_external(frame, 500) ;
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "shootWindowGUI_external(frame, 500)"; }}));
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n menu.add(jmenuItem(\"Restart Program\", f restart));\r\n menu.add(jmenuItem(\"Show Console\", f showConsole));\r\n menu.add(jCheckBoxMenuItem(\"Always On Top\", alwaysOnTop, r {\r\n toggleAlwaysOnTop(frame) }));\r\n menu.add(jMenuItem(\"Shoot Window\", r { shootWindowGUI_external(frame, 500) }));"; }});
return frame;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "if (getFrame(content) != null)\r\n ret setFrameTitle((Component) content, title);\r\n final JFrame frame = new JFrame(title);\r\n if (content != null)\r\n frame.getContentPane().add(wrap(content));\r\n frame.setBounds(300, 100, 500, 400);\r\n if (showIt)\r\n frame.setVisible(true);\r\n //callOpt(content, \"requestFocus\");\r\n //exitOnFrameClose(frame);\r\n \r\n // standard right-click behavior on titles\r\n if (isSubstanceLAF())\r\n titlePopupMenu(frame,\r\n new O { void get(JPopupMenu menu) { try {\n \r\n bool alwaysOnTop = frame.isAlwaysOnTop();\r\n menu.add(jmenuItem(\"Restart Program\", f restart));\r\n menu.add(jmenuItem(\"Show Console\", f showConsole));\r\n menu.add(jCheckBoxMenuItem(\"Always On Top\", alwaysOnTop, r {\r\n toggleAlwaysOnTop(frame) }));\r\n menu.add(jMenuItem(\"Shoot Window\", r { shootWindowGUI_external(frame, 500) }));\r\n \n} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}\n public S toString() { ret \"bool alwaysOnTop = frame.isAlwaysOnTop();\\r\\n menu.add(jmenuItem(\\\"Restart Program\\\", f restart));\\r\\n menu.add(jmenuItem(\\\"Show Console\\\", f showConsole));\\r\\n menu.add(jCheckBoxMenuItem(\\\"Always On Top\\\", alwaysOnTop, r {\\r\\n toggleAlwaysOnTop(frame) }));\\r\\n menu.add(jMenuItem(\\\"Shoot Window\\\", r { shootWindowGUI_external(frame, 500) }));\"; }});\r\n ret frame;"; }});
}
static Object callFunction(Object f, Object... args) {
if (f == null) return null;
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
} else if (f instanceof String)
return call(mc(), (String) f, args);
else
return call(f, "get", args);
//else throw fail("Can't call a " + getClassName(f));
}
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();
quote_impl(s, out);
return out.toString();
}
static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else
out.append(c);
}
out.append('"');
}
static String 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 makeTableUneditable(JTable table) {
for (int c = 0; c < table.getColumnCount(); c++) {
Class> col_class = table.getColumnClass(c);
//O ed = table.getDefaultEditor(col_class);
//print("Column " + c + " class: " + col_class + " editor: " + ed);
table.setDefaultEditor(col_class, null); // remove editor
}
}
static Object mc() {
return getMainClass();
}
static void setFrameContents(JFrame frame, Object contents) {
frame.getContentPane().removeAll();
frame.getContentPane().add(wrap(contents));
revalidate(frame);
}
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isTrue(callOpt(getClass("javax.swing.SwingUtilities"), "isEventDispatchThread"));
}
static String getProgramTitle() {
return getProgramName();
}
static JTextField jTextField() {
return new JTextField();
}
static JTextField jTextField(String text) {
JTextField tf = new JTextField(unnull(text));
tf.selectAll();
return tf;
}
static JTextField jTextField(Object o) {
return jTextField(strOrEmpty(o));
}
static Thread currentThread() {
return Thread.currentThread();
}
static boolean eq(Object a, Object b) {
if (a == null) return b == null;
if (a.equals(b)) return true;
if (a instanceof BigInteger) {
if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b));
if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b));
}
return false;
}
static class tablePopupMenu_Maker {
List menuMakers = new ArrayList();
}
static Map tablePopupMenu_map = new WeakHashMap();
static ThreadLocal tablePopupMenu_mouseEvent = new ThreadLocal();
static ThreadLocal tablePopupMenu_first = new ThreadLocal();
// menuMaker = voidfunc(JPopupMenu, int row)
static void tablePopupMenu(final JTable table, final Object menuMaker) {
final boolean first = isTrue(getAndClearThreadLocal(tablePopupMenu_first));
swingNowOrLater(new Runnable() { public void run() { try {
tablePopupMenu_Maker maker = tablePopupMenu_map.get(table);
if (maker == null) {
tablePopupMenu_map.put(table, maker = new tablePopupMenu_Maker());
final tablePopupMenu_Maker _maker = maker;
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) { displayMenu(e); }
public void mouseReleased(MouseEvent e) { displayMenu(e); }
void displayMenu(MouseEvent e) {
if (e.isPopupTrigger()) {
JPopupMenu menu = new JPopupMenu();
int row = table.rowAtPoint(e.getPoint());
table.setRowSelectionInterval(row, row);
int emptyCount = menu.getComponentCount();
tablePopupMenu_mouseEvent.set(e);
for (Object menuMaker : _maker.menuMakers)
pcallF(menuMaker, menu, row);
// show menu if any items in it
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
if (first)
maker.menuMakers.add(0, menuMaker);
else
maker.menuMakers.add(menuMaker);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "tablePopupMenu_Maker maker = tablePopupMenu_map.get(table);\n if (maker == null) {\n tablePopupMenu_map.put(table, maker = new tablePopupMenu_Maker);\n final tablePopupMenu_Maker _maker = maker;\n table.addMouseListener(new MouseAdapter {\n public void mousePressed(MouseEvent e) { displayMenu(e); }\n public void mouseReleased(MouseEvent e) { displayMenu(e); }\n \n void displayMenu(MouseEvent e) {\n if (e.isPopupTrigger()) {\n new JPopupMenu menu;\n int row = table.rowAtPoint(e.getPoint());\n table.setRowSelectionInterval(row, row);\n int emptyCount = menu.getComponentCount();\n \n tablePopupMenu_mouseEvent.set(e);\n for (Object menuMaker : _maker.menuMakers)\n pcallF(menuMaker, menu, row);\n \n // show menu if any items in it\n if (menu.getComponentCount() != emptyCount)\n menu.show(e.getComponent(), e.getX(), e.getY());\n }\n }\n });\n }\n if (first)\n maker.menuMakers.add(0, menuMaker);\n else\n maker.menuMakers.add(menuMaker);"; }});
}
static RuntimeException fail() {
throw new RuntimeException("fail");
}
static RuntimeException fail(Throwable e) {
throw asRuntimeException(e);
}
static RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static RuntimeException fail(String msg) {
throw new RuntimeException(unnull(msg));
}
static RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
// disabled for now to shorten some programs
/*static RuntimeException fail(S msg, O... args) {
throw new RuntimeException(format(msg, args));
}*/
static void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static TableWithTooltips tableWithToolTips() {
return tableWithTooltips();
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static void setTableModel(JTable table, TableModel model) {
int i = table.getSelectedRow();
table.setModel(model);
if (i >= 0 && i < model.getRowCount())
table.setRowSelectionInterval(i, i);
}
static JFrame getFrame(Object 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;
}
static JTable dataToTable(Object data) {
return dataToTable(showTable(), data);
}
static JTable dataToTable(Object data, String title) {
return dataToTable(showTable(title), data);
}
static JTable dataToTable(JTable table, Object data) {
return dataToTable(table, data, false);
}
static JTable dataToTable(JTable table, Object data, boolean now) {
List rows = new ArrayList();
List cols = new ArrayList();
if (data instanceof List) {
for (Object x : (List) data) try {
rows.add(dataToTable_makeRow(x, cols));
} catch (Throwable __e) { printStackTrace(__e); }
} else if (data instanceof Map) {
Map map = (Map) ( data);
for (Object key : map.keySet()) {
Object value = map.get(key);
rows.add(litlist(structureOrText(key), structureOrText(value)));
}
} else
print("Unknown data type: " + data);
if (now)
table.setModel(fillTableWithData_makeModel(rows, toStringArray(cols)));
else
fillTableWithData(table, rows, cols);
return table;
}
static void copyImageToClipboard(Image img) {
TransferableImage trans = new TransferableImage(img);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents( trans, null);
print("Copied image to clipboard (" + img.getWidth(null) + "*" + img.getHeight(null) + " px)");
}
static List getTableLine(JTable tbl, int row) {
if (row >= 0 && row < tbl.getModel().getRowCount()) {
List l = new ArrayList();
for (int i = 0; i < tbl.getModel().getColumnCount(); i++)
l.add(String.valueOf(tbl.getModel().getValueAt(row, i)));
return l;
}
return null;
}
static JComponent showTitledForm(String title, Object... _parts) {
return showFormTitled(title, _parts);
}
static void frameStandardSize(JFrame frame) {
frame.setBounds(300, 100, 500, 400);
}
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: " + structure(o));
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); } static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o instanceof String ? l((String) o)
: l((Collection) o); // incomplete
}
static int l(MultiSet ms) { return ms == null ? 0 : ms.size(); }
static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object getOpt(Class c, String field) {
try {
if (c == null) return null;
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
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 String copyTextToClipboard(String text) {
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
return text;
}
static Object first(Object list) {
return empty((List) list) ? null : ((List) list).get(0);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static Class getClass(Object realm, String name) { try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void fillTableWithData(final JTable table, List rows, List colNames) {
fillTableWithData(table, rows, toStringArray(colNames));
}
// thread-safe
static void fillTableWithData(final JTable table, List rows, String... colNames) {
final DefaultTableModel model = fillTableWithData_makeModel(rows, colNames);
swingNowOrLater(new Runnable() { public void run() { try {
setTableModel(table, model);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "setTableModel(table, model);"; }});
}
static DefaultTableModel fillTableWithData_makeModel(List rows, String... colNames) {
Object[][] data = new Object[rows.size()][];
int w = 0;
for (int i = 0; i < rows.size(); i++) {
List l = rows.get(i);
Object[] r = new Object[l.size()];
for (int j = 0; j < l.size(); j++) {
Object o = l.get(j);
if (o instanceof BufferedImage) o = imageIcon((BufferedImage) o);
if (o instanceof RGBImage) o = imageIcon((RGBImage) o);
r[j] = o;
}
data[i] = r;
w = Math.max(w, l.size());
}
Object[] columnNames = new Object[w];
for (int i = 0; i < w; i++)
columnNames[i] = i < l(colNames) ? colNames[i] : "?";
return new DefaultTableModel(data, columnNames) {
public Class getColumnClass(int column) {
return or(_getClass(getValueAt(0, column)), String.class);
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
};
}
static Boolean isHeadless_cache;
static boolean isHeadless() {
if (isHeadless_cache != null) return isHeadless_cache;
if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true;
// Also check if AWT actually works.
// If DISPLAY variable is set but no X server up, this will notice.
try {
callOpt(getClass("javax.swing.SwingUtilities"), "isEventDispatchThread");
return isHeadless_cache = false;
} catch (Throwable e) { return isHeadless_cache = true; }
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
static boolean empty(Collection c) {
return isEmpty(c);
}
static boolean empty(String s) {
return isEmpty(s);
}
static boolean empty(Map map) {
return map == null || map.isEmpty();
}
static boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(float[] a) { return a == null || a.length == 0; }
static JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
JCheckBoxMenuItem mi = new JCheckBoxMenuItem(text, checked);
mi.addActionListener(actionListener(r));
return mi;
}
static RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static void dataToTable_dynSet(List l, int i, Object s) {
while (i >= l.size()) l.add("");
l.set(i, s);
}
static List dataToTable_makeRow(Object x, List cols) {
if (instanceOf(x, "DynamicObject"))
x = get_raw(x, "fieldValues");
if (x instanceof Map) {
Map m = (Map) ( x);
List row = new ArrayList();
for (Object _field : keysWithoutHidden(m)) {
String field = (String) ( _field);
Object value = m.get(field);
int col = cols.indexOf(field);
if (col < 0) {
cols.add(field);
col = cols.size()-1;
}
dataToTable_dynSet(row, col, dataToTable_wrapValue(value));
}
return row;
}
return litlist(structureOrText(x));
}
static Object dataToTable_wrapValue(Object o) {
if (o instanceof BufferedImage) return o;
if (o instanceof RGBImage) return o;
if (o instanceof Boolean) return o;
return structureOrText(o);
}
static boolean isSubstanceLAF() {
return substanceLookAndFeelEnabled();
}
static JMenuItem jmenuItem(String text, final Object r) {
JMenuItem mi = new JMenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
static TableWithTooltips tableWithTooltips() {
return (TableWithTooltips) swing(new Object() { Object get() { try {
return new TableWithTooltips() ;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public String toString() { return "new TableWithTooltips"; }});
}
static class TableWithTooltips extends JTable {
public String getToolTipText(MouseEvent e) {
String tip = null;
Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
try {
return str(getValueAt(rowIndex, colIndex));
} catch (Throwable _e) {
return null;
}
}
}
static JMenuItem jMenuItem(String text, Object r) {
return jmenuItem(text, r);
}
static void revalidate(Component c) {
if (c == null || !c.isShowing()) return;
// magic combo to actually relayout and repaint
c.revalidate();
c.repaint();
}
static Object callOpt(Object o) {
if (o == null) return null;
return callF(o);
}
static Object callOpt(Object o, String method, Object... args) {
try {
if (o == null) return null;
if (o instanceof Class) {
Method m = callOpt_findStaticMethod((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = callOpt_findMethod(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (!m.getName().equals(method)) {
if (debug) System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static String unnull(String s) {
return s == null ? "" : s;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static Object[] unnull(Object[] a) {
return a == null ? new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static void toggleAlwaysOnTop(JFrame frame) {
frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
}
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
static final WeakHashMap> getOpt_cache = new WeakHashMap();
static final HashMap getOpt_special = new HashMap(); // just a marker
static {
getOpt_cache.put(Class.class, getOpt_special);
getOpt_cache.put(String.class, getOpt_special);
}
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
if (o instanceof String)
return getOpt(getBot((String) o), field);
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
return null;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
f.setAccessible(true);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
getOpt_cache.put(c, map);
return map;
}
// menuMaker = voidfunc(JPopupMenu)
static void titlePopupMenu(final Component c, final Object menuMaker) {
swingNowOrLater(new Runnable() { public void run() { try {
if (!isSubstanceLAF())
print("Can't add title right click!");
else {
JComponent titleBar = getTitlePaneComponent(getFrame(c));
componentPopupMenu(titleBar, menuMaker);
}
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "if (!isSubstanceLAF())\n print(\"Can't add title right click!\");\n else {\n JComponent titleBar = getTitlePaneComponent(getFrame(c));\n componentPopupMenu(titleBar, menuMaker);\n }"; }});
}
//please include function withMargin.
static int showForm_defaultGap = 4;
static JPanel showFormTitled(String title, Object... _parts) {
final Var frame = new Var();
JPanel panel = showForm_makePanel(frame, _parts);
frame.set(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400));
return panel;
}
static JPanel showForm_makePanel(final Var frame, Object... _parts) {
List l = new ArrayList();
List parts = asList(_parts);
Runnable submit = null;
for (int i = 0; i < l(parts); i++) {
final Object o = parts.get(i), next = get(parts, i+1);
if (o instanceof Component || o instanceof String || next instanceof Component) { // smartAdd accepts strings
l.add(ll(o == null ? new JPanel() : o, next));
if (next instanceof JButton && submit == null)
submit = new Runnable() { public void run() { try { ((JButton) next).doClick() ;
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "((JButton) next).doClick()"; }};
i++;
} else if (isRunnable(o))
l.add(ll(null, jbutton(showFormSubmitButtonName(), submit = new Runnable() { public void run() { try {
Object result = call(o);
if (neq(Boolean.FALSE, result))
disposeFrame(frame.get());
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } public String toString() { return "Object result = call(o);\r\n if (neq(Boolean.FALSE, result))\r\n disposeFrame(frame.get());"; }})));
else print("showForm: Unknown element type: " + getClassName(o));
}
JPanel panel = hvgrid((List) l, showForm_defaultGap);
if (submit != null)
for (JTextField textField : childrenOfType(panel, JTextField.class))
onEnter(textField, submit);
return panel;
}
static void shootWindowGUI_external(JFrame frame) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame);
}
static void shootWindowGUI_external(final JFrame frame, int delay) {
call(hotwireOnce("#1007178"), "shootWindowGUI", frame, delay);
}
static Class getMainClass() {
return main.class;
}
static Class getMainClass(Object o) { try {
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
structure_Data d = new structure_Data();
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack))
popLast(d.stack).run();
}
static void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static int structure_shareStringsLongerThan = 20;
static class structure_Data {
PrintWriter out;
int stringSizeLimit;
IdentityHashMap