Warning : session_start(): open(/var/lib/php/sessions/sess_p6nadkq77g39mccg24t7vdcd90, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import java.awt.geom.*;
import java.awt.font.GlyphVector;
import java.text.*;
import javax.swing.undo.UndoManager;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import java.awt.geom.AffineTransform;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.datatransfer.StringSelection;
import java.util.TimeZone;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import net.coobird.thumbnailator.Thumbnailator;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
class main {
static class GrabbedImage {
BWImage image;
String md5;
BWImage visualizedSplit;
List rects = new ArrayList();
List characters = new ArrayList();
List characterMD5s = new ArrayList();
List groupedRecognition;
String recognition;
}
static class OCRRecognizeAndTeach {
BufferedImage img;
ImageSurface is; // can pre-set this to reuse image surface
List rects; // use these if not null, otherwise auto-segment
List texts;
ReliableSingleThread rst = new ReliableSingleThread(new Runnable() { public void run() { try { reRecognize() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "reRecognize()"; }});
OCRRecognizeAndTeach() {}
OCRRecognizeAndTeach(ImageSurface is) {
this.is = is; go(is.getImage()); }
OCRRecognizeAndTeach(BufferedImage img) { go(img); }
void go(BufferedImage img, List rects) {
this.rects = rects;
go(img);
}
void go(BufferedImage img) {
print("Recognizing");
this.img = img;
texts = rec();
is = showImageWithRecognizedTexts(img, is, texts);
showImageWithRecognizedTexts_makeTeachable2(img, is, texts, simpleRecognizer(), rTrigger(rst));
}
List rec() {
return time("OCR", () ->
rects != null
? ocr_recognizeMultiLine_scored(new BWImage(img), simpleRecognizer(), rects)
: ocr_recognizeMultiLine_scored(img));
}
void reRecognize() {
print("Re-recognizing...");
AutoCloseable __3 = tempDisposeWindow(smallLoadingAnim()); try {
replaceCollection(texts, rec());
is.repaint();
print("Done");
} finally { _close(__3); }}
void cleanMeUp() {
if (rst != null) rst.cancel();
disposeWindow(is);
is = null;
}
}
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 volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
static boolean print_silent = false; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal print_byThread; // special handling by thread - prefers F1
static volatile Object print_allThreads;
static volatile Object print_preprocess;
static void print() {
print("");
}
static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
// slightly overblown signature to return original object...
static A print(A o) {
ping_okInCleanUp();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
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;
print_raw(s);
}
static void print_raw(String s) {
if (print_preprocess != null) s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static void print_autoRotate() {
}
static float showImageWithSelections_darkening = 0.75f;
static ImageSurface showImageWithRecognizedTexts(BufferedImage img, ImageSurface _is, final List rects) {
final ImageSurface is = showImage(img, _is);
is.specialPurposed = true;
final Var highlighted = new Var();
showImageWithSelections_highlighted = highlighted;
is.overlay = new VF1() { public void get(Graphics2D g) { try {
fillRect(g, 0, 0, is.getWidth(), is.getHeight(), colorWithAlpha(Color.black, showImageWithSelections_darkening));
antiAliasOn(g);
AutoCloseable __1 = tempGraphicsTransform(g); try {
g.scale(is.zoomX, is.zoomY);
Font font = g.getFont().deriveFont(12);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
for (RecognizedText r : cloneList(rects)) {
is.drawSelectionRect(g, r.r.getRectangle(), Color.blue, blendColor(Color.black, Color.white, /*ocr_minScoreAdjust*/(r.score())), 1, 1);
String text = r.text.get();
if (nempty(text) && neq(text, ocr_unknownCharacterPlaceholder())) {
Pt p = centerTextInRect(fm, r.text.get(), r.r);
// Pt p = pt(r.r.x+2, r.r.y+2);
drawTextWithOutline(g, r.text.get(), p.x, p.y, Color.white, Color.black);
}
}
if (highlighted.has())
fillRect(g, scaleRect(highlighted.get(), is.getZoomX(), is.getZoomY()), new Color(0, 0, 0, 0x30)); // semi-transparent black
} finally { _close(__1); }} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "fillRect(g, 0, 0, is.getWidth(), is.getHeight(), colorWithAlpha(Color.black, ..."; }};
imageSurfaceOnMouseMove(is, new VF1() { public void get(Pt p) { try {
/*repaintIf(is,*/ setVarIfNeq(highlighted, smallestRectContaining(collect(rects, "r"), p))/*)*/;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "/*repaintIf(is,*/ setVarIfNeq(highlighted, smallestRectContaining(collect(rec..."; }});
imageSurfacePopupMenuOnSelection_top(is, new VF2() { public void get(JPopupMenu menu, final Rect selection) { try {
addMenuItem(menu, "Export selected texts", new Runnable() { public void run() { try {
showText("Selected recognized texts",
lines(allToStruct(recognizedTextsFullyContainedIn(rects, selection))))
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showText(\"Selected recognized texts\",\r\n lines(allToStruct(recognizedTe..."; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "addMenuItem(menu, \"Export selected texts\", r {\r\n showText(\"Selected reco..."; }});
return repaint(is);
}
static void showImageWithRecognizedTexts_makeTeachable2(final BufferedImage img, final ImageSurface is, final List lines, final SimpleRecognizer sr, final Runnable reRecognize) {
//final File extraFile = optParam(showImageWithRecognizedTexts_makeTeachable2_extraFile);
onImageSurfaceHighlightChange(is, new VF1() { public void get(Rect r) { try {
RecognizedText rec = findByField(lines, "r", r);
setToolTip(is, rec == null ? null : str(ocr_minScoreAdjust(rec.text)));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "RecognizedText rec = findByField(lines, +r);\r\n setToolTip(is, rec == null ..."; }});
imageSurfacePopupMenuWhenHighlighted_top(is, new VF2() { public void get(JPopupMenu menu, final Rect r) { try {
RecognizedText rec = findByField(lines, "r", r);
{ if (rec == null) return; }
int score = toIntPercent(ocr_minScoreAdjust(rec.text.score));
addPopupMenuItem(menu, score + "%. Teach... (" + r.w + "*" + r.h + ")", new Runnable() { public void run() { try {
assertNotASubclassOfConcept(GrabbedImage.class);
GrabbedImage gi = new GrabbedImage();
gi.image = new BWImage(clipBufferedImage(img, rec.r));
ocr_teachPhraseForm(gi, sr, new VF1() { public void get(String groupedText) { try {
rec.text = scored(groupedText, 1);
is.repaint();
pcallF(reRecognize);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "rec.text = scored(groupedText, 1);\r\n is.repaint();\r\n pcallF(reR..."; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "assertNotASubclassOfConcept(GrabbedImage);\r\n new GrabbedImage gi;\r\n ..."; }});
addSeparator(menu);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "RecognizedText rec = findByField(lines, +r);\r\n ret if rec == null;\r\n in..."; }});
}
static SimpleRecognizer simpleRecognizer() {
return filledSimpleRecognizer_cached();
}
static Runnable rTrigger(final ReliableSingleThread rst) {
return new Runnable() { public void run() { try { rst.trigger() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "rst.trigger()"; }};
}
static Object time(Object f) {
long time = sysNow();
Object o = callF(f);
done2_always(str(f), time);
return o;
}
static A time(F0 f) {
return (A) time((Object) f);
}
static A time(IF0 f) {
return (A) time((Object) f);
}
static A time(String msg, IF0 f) {
long time = sysNow();
A o = f.get();
done2_always(msg, time);
return o;
}
static int ocr_recognizeMultiLine_scored_maxPixels = 100000;
static boolean ocr_recognizeMultiLine_scored_filterByMinScore = false;
static int ocr_recognizeMultiLine_scored_g = 3;
static List ocr_recognizeMultiLine_scored(RGBImage img) {
BWImage bw = new BWImage(img); img = null; return ocr_recognizeMultiLine_scored(bw);
}
static List ocr_recognizeMultiLine_scored(BufferedImage img) {
BWImage bw = new BWImage(img); img = null; return ocr_recognizeMultiLine_scored(bw);
}
static List ocr_recognizeMultiLine_scored(BWImage bw) {
SimpleRecognizer sr = filledSimpleRecognizer_cached();
enableFullSearchInSimpleRecognizer(sr);
return ocr_recognizeMultiLine_scored(bw, sr);
}
static List ocr_recognizeMultiLine_scored(final BWImage bw, final SimpleRecognizer sr) {
return ocr_recognizeMultiLine_scored(bw, sr, autoSegment(bw, ocr_recognizeMultiLine_scored_g));
}
static List ocr_recognizeMultiLine_scored(final BWImage bw, List _rects) {
return ocr_recognizeMultiLine_scored(bw, simpleRecognizer(), _rects);
}
static List ocr_recognizeMultiLine_scored(final RGBImage rgb, List _rects) {
return ocr_recognizeMultiLine_scored(new BWImage(rgb), _rects);
}
static List ocr_recognizeMultiLine_scored(BufferedImage img, List _rects) {
return ocr_recognizeMultiLine_scored(new BWImage(img), _rects);
}
static List ocr_recognizeMultiLine_scored(final BWImage bw, final SimpleRecognizer sr, List _rects) {
final List rects = dropRectsLargerThan(ocr_recognizeMultiLine_scored_maxPixels, _rects);
/*new L lines;
for (Rect r : rects)
lines.add(RecognizedText(r, sr.recognizeScored(bw.clip(r))));
ret lines;*/
List l = parallelMap2(rects, new F1() { public RecognizedText get(Rect r) { try {
//print(sysNow() + " " + currentThreadID() + rectPixels(r));
return new RecognizedText(r, sr.recognizeScored(bw.clip(r)));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "//print(sysNow() + \" \" + currentThreadID() + rectPixels(r));\r\n ret Recogni..."; }});
if (ocr_recognizeMultiLine_scored_filterByMinScore)
l = ocr_filterByMinScore(l);
else
ocr_clearLinesBelowMinScore(l);
return l;
}
static AutoCloseable tempDisposeWindow(final Window w) {
return new AutoCloseable() {
public void close() {
disposeWindow(w);
}
};
}
static JWindow smallLoadingAnim(String text) {
return miniLoadingAnim(text);
}
static JWindow smallLoadingAnim() {
return miniLoadingAnim();
}
static void replaceCollection(Collection dest, Collection src) {
if (dest == src) return;
dest.clear();
dest.addAll(src);
}
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 void disposeWindow(final Window window) {
if (window != null) { swing(new Runnable() { public void run() { try {
window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); // call listeners
myFrames_list.remove(window);
window.dispose();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //..."; }}); }
}
static void disposeWindow(final Component c) {
disposeWindow(getWindow(c));
}
static void disposeWindow(Object o) {
if (o != null) disposeWindow(((Component) o));
}
static void disposeWindow() {
disposeWindow(heldInstance(Component.class));
}
static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static ImageSurface showImageWithSelections(MakesBufferedImage img, final Collection rects) {
return showImageWithSelections(img.getBufferedImage(), rects);
}
static ImageSurface showImageWithSelections(String title, BufferedImage img, Collection rects) {
return frameTitle(title, showImageWithSelections(img, rects));
}
static ImageSurface showImageWithSelections(BufferedImage img, Collection rects) {
return showImageWithSelections(img, null, rects);
}
// for callers to use
static Var showImageWithSelections_highlighted;
static ImageSurface showImageWithSelections(BufferedImage img, ImageSurface _is, final Collection _rects) {
final ImageSurface is = showImage(img, _is);
final List rects = sortRectsBySize(_rects);
final Var highlighted = new Var();
showImageWithSelections_highlighted = highlighted;
is.overlay = new VF1() { public void get(Graphics2D g) { try {
for (Rect r : rects)
is.drawSelectionRect(g, r.getRectangle(), Color.blue, Color.white);
if (highlighted.has())
fillRect(g, scaleRect(highlighted.get(), is.getZoomX(), is.getZoomY()), new Color(0, 0, 0, 0x30)); // semi-transparent black
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "for (Rect r : rects)\r\n is.drawSelectionRect(g, r.getRectangle(), Color.b..."; }};
imageSurfaceOnMouseMove(is, new VF1() { public void get(Pt p) { try {
repaintIf(is, setVarIfNeq(highlighted, smallestRectContaining(rects, p)));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "repaintIf(is, setVarIfNeq(highlighted, smallestRectContaining(rects, p)));"; }});
is.repaint();
return is;
}
static Map myFrames_list = weakHashMap();
static List myFrames() {
return swing(new F0>() { public List get() { try { return keysList(myFrames_list); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret keysList(myFrames_list);"; }});
}
static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1));
}
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 Map> callF_cache = newDangerousWeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static A callF(IF0 f) {
return f == null ? null : f.get();
}
static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Object f, Object... args) { try {
if (f instanceof String)
return callMCWithVarArgs((String) f, args); // possible SLOWDOWN over callMC
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1) return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
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 String showImage_defaultIcon = "#1004230"; // "#1004227";
static ImageSurface showImage(String snippetIDOrURL, String title) {
return showImage(loadImage(snippetIDOrURL), title);
}
static ImageSurface showImage(String title, BufferedImage img) {
return showImage(img, title);
}
static ImageSurface showImage(final BufferedImage img, final String title) {
return (ImageSurface) swing(new F0() { public Object get() { try {
ImageSurface is = showImage(img);
getFrame(is).setTitle(title);
return is;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ImageSurface is = showImage(img);\r\n getFrame(is).setTitle(title);\r\n ret..."; }});
}
static ImageSurface showImage(final BufferedImage img) {
return (ImageSurface) swing(new F0() { public Object get() { try {
ImageSurface is = new ImageSurface(img);
JFrame frame = showPackedFrame(new JScrollPane(is));
moveToTopRightCorner(frame);
frameIcon(frame, showImage_defaultIcon);
return is;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ImageSurface is = new ImageSurface(img);\r\n JFrame frame = showPackedFrame(..."; }});
}
static ImageSurface showImage(String imageID) {
return showImage(loadImage2(imageID));
}
static ImageSurface showImage(ImageSurface surface, BufferedImage img) {
return showImage(img, surface);
}
static ImageSurface showImage(ImageSurface surface, String title, BufferedImage img) {
return showImage(surface, img, title);
}
static ImageSurface showImage(ImageSurface surface, BufferedImage img, String title) {
return setFrameTitle(showImage(img, surface), title);
}
static ImageSurface showImage(BufferedImage img, ImageSurface surface) {
if (surface == null)
return showImage(img);
else {
surface.setImage(img);
return surface;
}
}
static ImageSurface showImage(String title, MakesBufferedImage img) {
return showImage(title, img.getBufferedImage());
}
static ImageSurface showImage(ImageSurface is, MakesBufferedImage img) {
return showImage(is, img.getBufferedImage());
}
static ImageSurface showImage(RGBImage img) {
return showImage(img.getBufferedImage());
}
static ImageSurface showImage(RGBImage img, String title) {
ImageSurface is = showImage(img.getBufferedImage());
getFrame(is).setTitle(title);
return is;
}
static ImageSurface showImage(ImageSurface surface, RGBImage img) {
return showImage(img, surface);
}
static ImageSurface showImage(RGBImage img, ImageSurface surface) {
if (surface == null)
return showImage(img);
else {
surface.setImage(img);
return surface;
}
}
static ImageSurface showImage(ImageSurface surface, String title, RGBImage img) {
return showImage(surface, img, title);
}
static ImageSurface showImage(ImageSurface surface, RGBImage img, String title) {
return setFrameTitle(showImage(img, surface), title);
}
static ImageSurface showImage(MakesBufferedImage img) {
return showImage(img.getBufferedImage());
}
static ImageSurface showImage() {
return showImage(currentImage());
}
static ImageSurface showImage(File f) {
return showImage(f2s(f), loadImage2(f)).setFile(f);
}
static void fillRect(BufferedImage image, int x, int y, int w, int h, Color color) {
Graphics2D g = imageGraphics(image);
fillRect(g, x, y, w, h, color);
g.dispose();
}
static void fillRect(Graphics/*2D*/ g, int x, int y, int w, int h, Color color) {
g.setColor(color);
g.fillRect(x, y, w, h);
}
// draw on currentImage()
static void fillRect(int x, int y, int w, int h, Color color) {
fillRect(currentImage(), x, y, w, h, color);
}
static void fillRect(Rect r, Color color) {
fillRect(r.x, r.y, r.w, r.h, color);
}
static void fillRect(BufferedImage image, Rect r, Color c) {
if (r != null) fillRect(image, r.x, r.y, r.w, r.h, c);
}
static void fillRect(Graphics/*2D*/ g, Rect r, Color c) {
if (r != null) fillRect(g, r.x, r.y, r.w, r.h, c);
}
static Color colorWithAlpha(Color c, double alpha) {
return new Color(c.getRed()/255f, c.getGreen()/255f, c.getBlue()/255f,
(float) alpha);
}
static Color colorWithAlpha(double alpha, Color c) {
return colorWithAlpha(c, alpha);
}
static Graphics2D antiAliasOn(Graphics2D g) {
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
return g;
}
static AutoCloseable tempGraphicsTransform(final Graphics2D g) {
final AffineTransform t = g.getTransform();
return new AutoCloseable() {
public void close() {
g.setTransform(t);
}
};
}
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 Color blendColor(Color a, Color b, double bish) {
return blendColors(a, b, bish);
}
static boolean nempty(Collection c) {
return !empty(c);
}
static boolean nempty(CharSequence s) {
return !empty(s);
}
static boolean nempty(Object[] o) { return !empty(o); }
static boolean nempty(byte[] o) { return !empty(o); }
static boolean nempty(int[] o) { return !empty(o); }
static boolean nempty(Map m) {
return !empty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean nempty(Object o) { return !empty(o); }
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static String ocr_unknownCharacterPlaceholder() {
return diamond();
}
static Pt centerTextInRect(FontMetrics fm, String s, Rect r) {
int tw = fm.stringWidth(s), th = fm.getHeight();
return pt(r.x + (r.w-tw)/2, r.y + (r.h-th)/2 + fm.getAscent());
}
static void drawTextWithOutline(Graphics2D g2, String text, float x, float y, Color fillColor, Color outlineColor) {
BasicStroke outlineStroke = new BasicStroke(2.0f);
g2.translate(x, y);
// remember original settings
Stroke originalStroke = g2.getStroke();
RenderingHints originalHints = g2.getRenderingHints();
// create a glyph vector from your text
GlyphVector glyphVector = g2.getFont().createGlyphVector(g2.getFontRenderContext(), text);
// get the shape object
Shape textShape = glyphVector.getOutline();
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setColor(outlineColor);
g2.setStroke(outlineStroke);
g2.draw(textShape); // draw outline
g2.setColor(fillColor);
g2.fill(textShape); // fill the shape
// reset to original settings after painting
g2.setStroke(originalStroke);
g2.setRenderingHints(originalHints);
g2.translate(-x, -y);
}
static Rect scaleRect(Rect r, double factorX, double factorY) {
return new Rect(iround(r.x*factorX), iround(r.y*factorY), iround(r.w*factorX), iround(r.h*factorY));
}
static Rect scaleRect(Rect r, double factor) {
return scaleRect(r, factor, factor);
}
static Rect scaleRect(double factor, Rect r) {
return scaleRect(r, factor);
}
// f : voidfunc(Pt) - point can be null, then mouse has exited
static void imageSurfaceOnMouseMove(final ImageSurface is, final Object f) {
{ swing(new Runnable() { public void run() { try {
MouseAdapter ma = new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
pcallF(f, is.pointFromEvent(e));
}
public void mouseEntered(MouseEvent e) {
pcallF(f, is.pointFromEvent(e));
}
public void mouseExited(MouseEvent e) {
pcallF(f, (Pt) null);
}
};
is.addMouseMotionListener(ma);
is.addMouseListener(ma);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "MouseAdapter ma = new MouseAdapter {\r\n public void mouseMoved(MouseEvent..."; }}); }
}
static boolean setVarIfNeq(Var v, A value) {
if (v == null || eq(v.get(), value)) return false;
v.set(value);
return true;
}
static Rect smallestRectContaining(List l, final Pt p) {
if (p == null) return null;
Lowest b = new Lowest();
for (Rect r : l)
if (r.contains(p))
b.put(r, rectPixels(r));
return b.get();
}
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 void imageSurfacePopupMenuOnSelection_top(final ImageSurface is, final VF2 f) {
componentPopupMenu_top(is, new VF1() { public void get(JPopupMenu menu) { try {
if (is.selection != null)
pcallF(f, menu, toRect(is.selection));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (is.selection != null)\r\n pcallF(f, menu, toRect(is.selection));"; }});
}
static void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static void addMenuItem(JMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(Menu menu, String text, Object action) {
menu.add(menuItem(text, action));
}
static void addMenuItem(JMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static JTextArea showText(final String title, Object text) {
return showText(null, title, text);
}
static JTextArea showText(JTextArea ta, final String title, Object text) {
final String _text = str(text);
if (ta != null)
return activateFrameAndReturnComponent(setFrameTitle(title, setText(ta, _text)));
return swing(new F0() { public JTextArea get() { try {
JTextArea textArea = newTypeWriterTextArea(_text);
makeFrame(title, new JScrollPane(textArea));
return textArea;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JTextArea textArea = newTypeWriterTextArea(_text);\r\n makeFrame(title, new ..."; }});
}
static JTextArea showText(Object text) {
return showText(str(text));
}
static JTextArea showText(String text) {
return showText(autoFrameTitle(), text);
}
static JTextArea showText() {
return showText("");
}
static String lines(Iterable lines) { return fromLines(lines); }
static String lines(Object[] lines) { return fromLines(asList(lines)); }
static List lines(String s) { return toLines(s); }
static List allToStruct(Collection l) {
return lmap(__27 -> struct(__27),l);
}
static List recognizedTextsFullyContainedIn(Iterable l, final Rect r) {
return filter(unnull(l) , new F1() { public Boolean get(RecognizedText t) { try { return rectContains(r, t.r); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "rectContains(r, t.r)"; }});
}
static A repaint(A c) {
if (c != null) c.repaint();
return c;
}
static void onImageSurfaceHighlightChange(final ImageSurface is, final VF1 f) {
final Var highlighted = showImageWithSelections_highlighted;
imageSurfaceOnMouseMove(is, new Runnable() {
Rect last;
public void run() {
if (eq(highlighted.get(), last)) return;
last = highlighted.get();
pcallF(f, last);
}
});
}
static A findByField(Collection c, String field, Object value) {
for (A a : c)
if (eq(getOpt(a, field), value))
return a;
return null;
}
static A setToolTip(A c, Object toolTip) {
return setToolTipText(c, toolTip);
}
static A setToolTip(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
static void setToolTip(TrayIcon trayIcon, String toolTip) {
setTrayIconToolTip(trayIcon, toolTip);
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static double ocr_minScoreAdjust(double rawScore) {
return max(0, min(1, adjustDouble(rawScore, ocr_minScore(), 1, 0, 1)));
}
static float ocr_minScoreAdjust(float rawScore) {
return (float) ocr_minScoreAdjust((double) rawScore);
}
static Scored ocr_minScoreAdjust(Scored s) {
return s == null ? null : new Scored(s.get(), ocr_minScoreAdjust(s.score()));
}
static void imageSurfacePopupMenuWhenHighlighted_top(final ImageSurface is, final VF2 f) {
final Var highlighted = showImageWithSelections_highlighted;
componentPopupMenu_top(is, new VF1() { public void get(JPopupMenu menu) { try {
Rect r = highlighted.get();
if (r != null)
pcallF(f, menu, r);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Rect r = highlighted!;\r\n if (r != null)\r\n pcallF(f, menu, r);"; }});
}
static int toIntPercent(double ratio) {
return roundToInt(ratio*100);
}
// when used with map function
static int toIntPercent(float ratio) {
return toIntPercent((double) ratio);
}
static void addPopupMenuItem(JPopupMenu menu, String text, Object action) {
addMenuItem(menu, text, action);
}
static void addPopupMenuItem(JPopupMenu menu, JMenuItem menuItem) {
addMenuItem(menu, menuItem);
}
static void assertNotASubclassOfConcept(Class c) {
assertFalse(isSubclassOf(c, classForNameOpt("main$Concept")));
}
static BufferedImage clipBufferedImage(BufferedImage src, Rectangle clip) {
return clipBufferedImage(src, new Rect(clip));
}
static BufferedImage clipBufferedImage(BufferedImage src, Rect r) {
if (src == null || r == null) return null;
// fixClipRect
r = intersectRects(r, new Rect(0, 0, src.getWidth(), src.getHeight()));
if (rectEmpty(r)) return null; // can't make zero-sized BufferedImage
return src.getSubimage(r.x, r.y, r.w, r.h);
}
static BufferedImage clipBufferedImage(BufferedImage src, int x, int y, int w, int h) {
return clipBufferedImage(src, new Rect(x, y, w, h));
}
static void ocr_teachPhraseForm(final GrabbedImage gi, final SimpleRecognizer sr, final VF1 onTaught) {
analyzeGrabbedImage(gi, sr);
// make form
final JTextField tf = jTypeWriterTextField(ocr_joinAsGrouped(gi.groupedRecognition));
final JCheckBox grouped = jCheckBox("grouped (" + ocrCharGroupingHelpText() + ")", true);
final JButton btnSubmit = jbutton("Submit", new Runnable() { public void run() { try {
String s = trim(tf.getText());
boolean group = isChecked(grouped);
List rects = gi.rects;
if (group) { rects = ocr_groupRects(rects, s); s = ocr_unmerge(s); }
saveScreenClip(gi.image);
List characterMD5s = md5OfBWImageParts(gi.image, rects);
if (sr.fullSearchMap != null)
for (int i = 0; i < l(rects); i++)
sr.fullSearchMap.put(gi.image.clip(rects.get(i)), characterMD5s.get(i));
String line = "The images " + quote(join(" ", characterMD5s)) + " are the " + (group ? "grouped " : "") + "characters " + quote(s) + ".";
print(">> " + line);
String imageMD5 = ocrMD5OfBWImage(gi.image);
logQuoted(glyphTeachLog(), "[" + localDateWithSeconds() + "] Image " + imageMD5 + ": " + line);
saveTextFile(newFile(screenClipsDir(), imageMD5 + ".line"), line);
sr.load(line);
disposePossiblyInternalFrame(tf);
pcallF(onTaught, s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = trim(tf.getText());\r\n boolean group = isChecked(grouped);\r\n ..."; }});
onUpdateAndNow(ll(tf, grouped), new Runnable() { public void run() { try {
String s = trim(tf.getText());
btnSubmit.setEnabled((isChecked(grouped) ? ocr_glyphCount(s) : l(dropSpaces(s))) == l(gi.characters));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = trim(tf.getText());\r\n btnSubmit.setEnabled((isChecked(grouped) ..."; }});
// show form
growFrameSouth(50, showFormTitled("Teach",
"Image:" , jscroll_minHeight(75, zoomedImageSurface(2, gi.image.getBufferedImage())),
"Split:" , jscroll_minHeight(75, zoomedImageSurface(2, gi.visualizedSplit.getBufferedImage())),
"Meaning:", tf,
"", grouped,
"", btnSubmit));
selectAllLater(tf, 100);
}
static Scored scored(A a, float score) {
return new Scored(a, score);
}
static Scored scored(A a, double score) {
return new Scored(a, (float) score);
}
static Scored scored(A a, Scored scored) {
return new Scored(a, getScore(scored));
}
static Scored scored(double score, A a) {
return scored(a, score);
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static A pcallF(F0 f) { try {
return f == null ? null : f.get();
} catch (Throwable __e) { return null; } }
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static void pcallF(VF1 f, A a) {
try {
if (f != null) f.get(a);
} catch (Throwable __e) { _handleException(__e); }
}
static void addSeparator(JMenu menu) {
menu.addSeparator();
}
static void addSeparator(JPopupMenu menu) {
menu.addSeparator();
}
static volatile SimpleRecognizer filledSimpleRecognizer_cached_object;
static SimpleRecognizer filledSimpleRecognizer_cached() {
if (filledSimpleRecognizer_cached_object != null)
return filledSimpleRecognizer_cached_object;
SimpleRecognizer sr = filledSimpleRecognizer();
enableFullSearchInSimpleRecognizer(sr);
return filledSimpleRecognizer_cached_object = sr;
}
static long sysNow() {
ping();
return System.nanoTime()/1000000;
}
static long done2_always(long startTime, String desc) {
long time = sysNow()-startTime;
// BREAKING CHANGE: Now stores result for lastTiming()
saveTiming_noPrint(time);
print(desc + " [" + time + " ms]");
return time;
}
static long done2_always(String desc, long startTime) {
return done2_always(startTime, desc);
}
static long done2_always(long startTime) {
return done2_always(startTime, "");
}
static void enableFullSearchInSimpleRecognizer(SimpleRecognizer sr) {
if (sr.fullSearchMap == null)
sr.fullSearchMap = synchroMap(ocr_slimFullSearchMap(reverseMap(getLearnedCharacters2())));
}
static int autoSegment_g = 3;
// g = grid size - typical values are 3 or 4
static List autoSegment(BWImage img, int g) {
AutoSegmenter as = new AutoSegmenter();
as.g = g;
return as.go(img);
}
static List autoSegment(BWImage img) {
return autoSegment(img, autoSegment_g);
}
static List autoSegment(BufferedImage img) {
return autoSegment(new BWImage(img));
}
static List autoSegment(BufferedImage img, int g) {
return autoSegment(new BWImage(img), g);
}
static List autoSegment(RGBImage img) {
return autoSegment(new BWImage(img));
}
static List dropRectsLargerThan(int maxPixels, Collection l) {
List l2 = emptyList(l(l));
for (Rect r : unnull(l))
if (rectPixels(r) <= maxPixels)
l2.add(r);
return l2;
}
static boolean parallelMap2_debug = false;
static List parallelMap2(Collection l, F1 f) {
return parallelMap2(iterator(l), l(l), f);
}
static List parallelMap2(Iterator it, final int count, final F1 f) { try {
final List> out = new ArrayList();
int poolSize = coresToUse_fixed(), queueSize = 500;
NotifyingBlockingThreadPoolExecutor e = new NotifyingBlockingThreadPoolExecutor(poolSize, queueSize, 15, TimeUnit.SECONDS);
if (parallelMap2_debug)
print("parallelMap2: " + count + " elements, " + poolSize + " threads");
// TODO: if poolSize == 1, do it in this thread
long time = sysNow();
try {
int i = 0;
for (final A o : iterable(it)) {
++i;
final int _i = i;
e.execute(new Runnable() { public void run() { try { try {
B x = callF(f, o);
synchronized(out) {
out.add(pair(x, _i));
}
} catch (Throwable __e) { _handleException(__e); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall {\r\n B x = callF(f, o);\r\n synchronized(out) {\r\n o..."; }});
}
/*if (parallelMap2_debug)
print("parallelMap2: scheduling done after " + (sysNow()-time));*/
e.shutdown();
e.awaitTermination(1, TimeUnit.DAYS);
} finally {
e.shutdown();
}
if (parallelMap2_debug)
print("parallelMap2: main done after " + (sysNow()-time));
return firstOfPairs(sortBySecondOfPairs_inPlace(out));
} catch (Exception __e) { throw rethrow(__e); } }
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o == null) return null;
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static Object get_raw(Object o, String field) { try {
if (o == null) return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static Object get(String field, Object o) {
return get(o, field);
}
static List ocr_filterByMinScore(List l) {
return filter(l , new F1() { public Boolean get(RecognizedText r) { try { return r.text.score() >= ocr_minScore(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "r.text.score() >= ocr_minScore()"; }});
}
static List ocr_clearLinesBelowMinScore(List l) {
for (RecognizedText r : l)
if (r.text.score() < ocr_minScore())
r.text = new Scored(ocr_unknownCharacterPlaceholder(), 0);
return l;
}
static JWindow miniLoadingAnim(String text) {
return miniLoadingAnim(); // text is ignored
}
static JWindow miniLoadingAnim() {
return showAnimationInTopRightCorner("#1009613");
}
static Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static A swing(IF0 f) {
return (A) swingAndWait(f);
}
static Window getWindow(Object o) {
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof Window) return (Window) c;
c = c.getParent();
}
return null;
}
static A heldInstance(Class c) {
List l = holdInstance_l.get();
for (int i = l(l)-1; i >= 0; i--) {
Object o = l.get(i);
if (isInstanceOf(o, c))
return (A) o;
}
throw fail("No instance of " + className(c) + " held");
}
static ThreadLocal> holdInstance_l = new ThreadLocal();
static AutoCloseable holdInstance(Object o) {
if (o == null) return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
static ThreadLocal print_byThread() {
synchronized(print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
// f can return false to suppress regular printing
// call print_raw within f to actually print something
static AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static A frameTitle(A c, String title) {
return setFrameTitle(c, title);
}
static A frameTitle(String title, A c) {
return setFrameTitle(c, title);
}
static String frameTitle(Component c) {
return getFrameTitle(c);
}
static List sortRectsBySize(Collection l) {
return sortByCalculatedField(l, "rectPixels");
}
static void repaintIf(Component c, boolean b) {
if (b) c.repaint();
}
static Map weakHashMap() {
return newWeakHashMap();
}
static List keysList(Map map) {
return cloneListSynchronizingOn(keys(map), map);
}
static Object call(Object o) {
return callF(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
//ret call_cached(o, method, args);
return call_withVarargs(o, method, args);
}
static Class javax() {
return getJavaX();
}
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll = false;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions = false;
static Map ping_actions = newWeakHashMap();
static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized(ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static 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 A or(A a, A b) {
return a != null ? a : b;
}
static boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
static Object callMCWithVarArgs(String method, Object... args) {
return call_withVarargs(mc(), method, args);
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(short[] a) { return a == null ? 0 : a.length; }
static int l(long[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(double[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Iterator i) { return iteratorCount_int_close(i); } // consumes the iterator && closes it if possible
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); }
static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o == null ? 0
: o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: o instanceof Collection ? l((Collection) o)
: o instanceof Object[] ? l((Object[]) o)
: o instanceof boolean[] ? l((boolean[]) o)
: o instanceof byte[] ? l((byte[]) o)
: o instanceof char[] ? l((char[]) o)
: o instanceof short[] ? l((short[]) o)
: o instanceof int[] ? l((int[]) o)
: o instanceof float[] ? l((float[]) o)
: o instanceof double[] ? l((double[]) o)
: o instanceof long[] ? l((long[]) o)
: (Integer) call(o, "size");
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static Object invokeMethod(Method m, Object o, Object... args) { try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) { throw rethrow(__e); } }
static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive()
: isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
// Note: The error reporting only works with Java VM option --illegal-access=deny
vmBus_send("makeAccessible_error",e, f);
}
return f;
}
static Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error",e, m);
}
return m;
}
static Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error",e, c);
}
return c;
}
static int indexOf(List l, A a, int startIndex) {
if (l == null) return -1;
int n = l(l);
for (int i = startIndex; i < n; i++)
if (eq(l.get(i), a))
return i;
return -1;
}
static int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
static int indexOf(List l, A a) {
if (l == null) return -1;
return l.indexOf(a);
}
static int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(A[] x, A a) {
int n = l(x);
for (int i = 0; i < n; i++)
if (eq(x[i], a))
return i;
return -1;
}
static void rotateStringBuffer(StringBuffer buf, int max) { try {
if (buf == null) return;
synchronized(buf) {
if (buf.length() <= max) return;
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);
}
buf.trimToSize();
}
} catch (Exception __e) { throw rethrow(__e); } }
static void rotateStringBuilder(StringBuilder buf, int max) { try {
if (buf == null) return;
synchronized(buf) {
if (buf.length() <= max) return;
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);
}
buf.trimToSize();
}
} catch (Exception __e) { throw rethrow(__e); } }
static RGBImage loadImage(String snippetIDOrURL) {
return new RGBImage(loadBufferedImage(snippetIDOrURL));
}
static RGBImage loadImage(File f) {
return new RGBImage(loadBufferedImage(f));
}
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..."; }});
}
static JFrame showPackedFrame(String title, Component contents) {
return packFrame(showFrame(title, contents));
}
static JFrame showPackedFrame(Component contents) {
return packFrame(showFrame(contents));
}
static int moveToTopRightCorner_inset = 20;
static A moveToTopRightCorner(A a) {
return moveToTopRightCorner(moveToTopRightCorner_inset, moveToTopRightCorner_inset, a);
}
static A moveToTopRightCorner(int insetX, int insetY, A a) {
Window w = getWindow(a);
if (w != null)
w.setLocation(getScreenSize().width-w.getWidth()-insetX, insetY);
return a;
}
static Component frameIcon(Component c, String imageID) {
setFrameIconLater(c, imageID);
return c;
}
static Component frameIcon(String imageID, Component c) {
setFrameIconLater(c, imageID);
return c;
}
static BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
static A setFrameTitle(A c, final String title) {
final Frame f = getAWTFrame(c);
if (f != null) { swing(new Runnable() { public void run() { try { f.setTitle(title);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.setTitle(title);"; }}); }
return c;
}
static A setFrameTitle(String title, A c) {
return setFrameTitle(c, title);
}
// magically find a field called "frame" in main class :-)
static JFrame setFrameTitle(String title) {
Object f = getOpt(mc(), "frame");
if (f instanceof JFrame)
return setFrameTitle((JFrame) f, title);
return null;
}
static ThreadLocal currentImage_var = new ThreadLocal();
static BufferedImage currentImage() {
return currentImage_var.get();
}
static void currentImage(BufferedImage img) {
currentImage_var.set(img);
}
static String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static String f2s(String s) { return f2s(newFile(s)); }
static String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static ThreadLocal imageGraphics_antiAlias = new ThreadLocal();
static Graphics2D imageGraphics(BufferedImage img) {
return !isFalse(imageGraphics_antiAlias.get()) ? antiAliasGraphics(img) : createGraphics(img);
}
// unclear semantics as to whether return null on null
static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static ArrayList asList(int[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(float[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static ArrayList asList(double[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static ArrayList asList(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
static Object collectionMutex(List l) {
return l;
}
static Object collectionMutex(Object o) {
if (o instanceof List) return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
static Color blendColors(Color a, Color b, double bish) {
bish = normalizeTo0to1(bish);
return new Color(
(float) blend(a.getRed()/255.0, b.getRed()/255.0, bish),
(float) blend(a.getGreen()/255.0, b.getGreen()/255.0, bish),
(float) blend(a.getBlue()/255.0, b.getBlue()/255.0, bish));
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(CharSequence s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
if (o instanceof byte[]) return empty((byte[]) o);
if (o == null) return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(Iterator i) { return i == null || !i.hasNext(); }
static boolean empty(double[] a) { return a == null || a.length == 0; }
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static boolean empty(byte[] a) { return a == null || a.length == 0; }
static boolean empty(short[] a) { return a == null || a.length == 0; }
static boolean empty(File f) { return getFileSize(f) == 0; }
static String diamond() {
return "\u2666"; // diamond suit symbol
}
static Pt pt(int x, int y) {
return new Pt(x, y);
}
static Pt pt(int x) {
return new Pt(x, x);
}
static int iround(double d) {
return (int) Math.round(d);
}
static int iround(Number n) {
return iround(toDouble(n));
}
static long rectPixels(Rect r) {
return r.w*r.h;
}
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 void componentPopupMenu_top(final JComponent component, final VF1 menuMaker) {
if (component != null && menuMaker != null) { swing(new Runnable() { public void run() { try {
Object adapter = componentPopupMenu_initForComponent(component);
((List) get(adapter, "maker")).add(0, menuMaker);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object adapter = componentPopupMenu_initForComponent(component);\r\n ((List)..."; }}); }
}
static Rect toRect(Rectangle r) {
return r == null ? null : new Rect(r);
}
static Rect toRect(RectangularShape r) {
return r == null ? null : toRect(r.getBounds());
}
static Rect toRect(Rect r) { return r; }
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 A activateFrameAndReturnComponent(A c) {
activateFrame(c);
return 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(new Runnable() { public void run() { try {
c.getEditor().setItem(s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.getEditor().setItem(s);"; }}); }
return c;
}
static void setText(JLabel c, Object text) {
setText((JComponent) c, text);
}
static JButton setText(JButton c, Object text) {
setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text)));
return c;
}
static A setText(final A c, Object text) {
if (c == null) return null;
final String s = strUnnull(text);
{ swing(new Runnable() { public void run() { try {
if (!setText_opt || neq(callOpt(c, "getText"), s))
call(c, "setText", s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n call(c, \"setText\", s);"; }}); }
return c;
}
static JTextArea newTypeWriterTextArea() {
return newTypeWriterTextArea("");
}
static JTextArea newTypeWriterTextArea(String text) {
return setFont(jTextArea(text), typeWriterFont());
}
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 String autoFrameTitle_value;
static String autoFrameTitle() {
return autoFrameTitle_value != null ? autoFrameTitle_value : getProgramTitle();
}
static void autoFrameTitle(Component c) {
setFrameTitle(getFrame(c), autoFrameTitle());
}
// usually L
static String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines)
buf.append(str(line)).append('\n');
return buf.toString();
}
static String fromLines(String... lines) {
return fromLines(asList(lines));
}
static IterableIterator toLines(File f) {
return linesFromFile(f);
}
static List toLines(String s) {
List lines = new ArrayList();
if (s == null) return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start) lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
static int toLines_nextLineBreak(String s, int start) {
int n = s.length();
for (int i = start; i < n; i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static List lmap(IF1 f, Iterable l) {
return lambdaMap(f, l);
}
static List lmap(IF1 f, A[] l) {
return lambdaMap(f, l);
}
static String struct(Object o) {
return structure(o);
}
static String struct(Object o, structure_Data data) {
return structure(o, data);
}
static List filter(Iterable c, Object pred) {
if (pred instanceof F1) return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null) for (Object o : c)
if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
static List filter(Object pred, Iterable c) {
return filter(c, pred);
}
static List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null) for (B o : c)
if (pred.get(o))
x.add(o);
return x;
}
static List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
//ifclass IF1
static List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null) for (B o : c)
if (pred.get(o))
x.add(o);
return x;
}
static List filter(B[] c, IF1 pred) {
List x = new ArrayList();
if (c != null) for (B o : c)
if (pred.get(o))
x.add(o);
return x;
}
static List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
//endif
static 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 Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
//ifclass Symbol
static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static 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, int x, int y) {
return a != null && a.contains(x, y);
}
static A setToolTipText(final A c, final Object toolTip) {
if (c == null) return null;
{ swing(new Runnable() { public void run() { try {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ..."; }}); }
return c;
}
static A setToolTipText(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
static void setTrayIconToolTip(TrayIcon trayIcon, String toolTip) {
if (trayIcon != null) trayIcon.setToolTip(toolTip);
}
static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static float max(float[] c) {
if (c.length == 0) return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x) x = d;
return x;
}
static int 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 double adjustDouble(double x, double a1, double b1, double a2, double b2) {
return (x-a1)/(b1-a1)*(b2-a2)+a2;
}
static double ocr_minScore() {
return 0.8;
}
static int roundToInt(double d) {
return (int) Math.round(d);
}
static void assertFalse(Object o) {
if (!(eq(o, false) /*|| isFalse(pcallF(o))*/))
throw fail(str(o));
}
static boolean assertFalse(boolean b) {
if (b) throw fail("oops");
return b;
}
static boolean assertFalse(String msg, boolean b) {
if (b) throw fail(msg);
return b;
}
static boolean isSubclassOf(Class a, Class b) {
return isSubclass(a, b);
}
static Map classForNameOpt_cache = synchroHashMap();
static Class classForNameOpt(String name) { try {
if (classForNameOpt_cache.containsKey(name))
return classForNameOpt_cache.get(name);
Class c = null;
try { c = Class.forName(name); } catch (Throwable _e) {}
classForNameOpt_cache.put(name, c);
return c;
} catch (Exception __e) { throw rethrow(__e); } }
static Rect intersectRects(Rect a, Rect b) {
int x = max(a.x, b.x), y = max(a.y, b.y);
int x2 = min(a.x+a.w, b.x+b.w), y2 = min(a.y+a.h, b.y+b.h);
return new Rect(x, y, x2-x, y2-y);
}
static boolean rectEmpty(Rect r) {
return r == null || r.w <= 0 || r.h <= 0;
}
static void analyzeGrabbedImage(GrabbedImage gi, SimpleRecognizer sr) {
if (gi.visualizedSplit == null) {
List rects = horizontalAutoSplit2ThenAutoCrop(gi.image);
gi.visualizedSplit = new BWImage(mergeImagePartsHorizontally(gi.image.toRGB(), rects));
for (Rect r : rects) {
BWImage cImg = gi.image.clip(r);
gi.rects.add(r);
gi.characters.add(cImg);
gi.characterMD5s.add(md5OfBWImage(cImg));
}
}
gi.groupedRecognition = sr.recognizeGrouped(gi.image);
gi.recognition = ocr_unescape(ocr_joinGroups(gi.groupedRecognition));
}
static JTextField jTypeWriterTextField() {
JTextField tf = jTextField();
tf.setFont(typeWriterFont());
return tf;
}
static JTextField jTypeWriterTextField(String text) {
return setTextAndSelectAll(jTypeWriterTextField(), text);
}
static String ocr_joinAsGrouped(List l) {
StringBuilder buf = new StringBuilder();
for (String s : l)
if (l(s) == 1 || l(s) == 2 && s.charAt(0) == '\\')
buf.append(s);
else
buf.append("[").append(s).append("]");
return str(buf);
}
static JCheckBox jCheckBox() {
return swingNu(JCheckBox.class);
}
static JCheckBox jCheckBox(boolean checked) {
return swingNu(JCheckBox.class, "", checked);
}
static JCheckBox jCheckBox(String text, boolean checked) {
return swingNu(JCheckBox.class, text, checked);
}
static JCheckBox jCheckBox(String text) {
return swingNu(JCheckBox.class, text);
}
static JCheckBox jCheckBox(String text, boolean checked, final Object onChange) {
JCheckBox cb = jCheckBox(checked, onChange);
cb.setText(text);
return cb;
}
// onChange can be a Runnable or a voidfunc(bool)
static JCheckBox jCheckBox(boolean checked, final Object onChange) {
final JCheckBox cb = jCheckBox(checked);
cb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(onChange, cb.isSelected());
}
});
return cb;
}
static String ocrCharGroupingHelpText() {
return "[ab] to split a glyph, a_ to merge glyphs, \\ to escape, {sym} for symbols";
}
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 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 boolean isChecked(final JCheckBox checkBox) {
return checkBox != null && (boolean) swing(new F0() { public Boolean get() { try { return checkBox.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret checkBox.isSelected();"; }});
}
static boolean isChecked(final JCheckBoxMenuItem mi) {
return mi != null && (boolean) swing(new F0() { public Boolean get() { try { return mi.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret mi.isSelected();"; }});
}
static List ocr_groupRects(List rects, String s) {
List l = ocr_parseGlyphs(dropSpaces(s));
assertEquals(l(rects), l(l));
List rects2 = new ArrayList();
for (int i = 0; i < l(l); ) {
int j = i+1;
while (j < l(l) && eq(l.get(j), "_")) ++j;
rects2.add(mergeRects(subList(rects, i, j)));
i = j;
}
return rects2;
}
static String ocr_unmerge(String s) {
return s.replace("_", "");
}
static void saveScreenClip(BWImage img) {
String md5 = ocrMD5OfBWImage(img);
File f = screenClipFileForMD5(md5);
if (!f.exists()) {
BufferedImage bufferedImage = img.getBufferedImage();
assertBWImagesIdentical(img, new BWImage(bufferedImage));
// verify 1
//assertEquals("BufferedImage md5", md5, ocrMD5OfBufferedImage(bufferedImage));
savePNG(f, bufferedImage);
//bufferedImage = loadBufferedImage(f);
// verify 2
//assertEquals("loaded", md5, ocrMD5OfBufferedImage(bufferedImage));
}
}
static List md5OfBWImageParts(BWImage img, List rects) {
List md5s = new ArrayList();
for (Rect r : rects)
md5s.add(md5OfBWImage(img.clip(r)));
return md5s;
}
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 == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1) return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static String ocrMD5OfBWImage(BWImage img) {
return rgbMD5(img.toRGB());
}
static void logQuoted(String logFile, String line) {
logQuoted(getProgramFile(logFile), line);
}
static void logQuoted(File logFile, String line) {
appendToFile(logFile, quote(line) + "\n");
}
static File glyphTeachLog() {
return javaxDataDir("Image Recognition/glyph-teaching.txt");
}
static String localDateWithSeconds(long time) {
SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss");
return format.format(time);
}
static String localDateWithSeconds() {
return localDateWithSeconds(now());
}
/** writes safely (to temp file, then rename) */
static File saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
File file = new File(fileName);
mkdirsForFile(file);
String tempFileName = fileName + "_temp";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists()) try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) { printStackTrace(e); }
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
vmBus_send("wroteFile", file);
return file;
} finally {
action.done();
}
}
static File saveTextFile(File fileName, String contents) { try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) { throw rethrow(__e); } }
static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static File newFile(String name) {
return name == null ? null : new File(name);
}
static File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static File screenClipsDir() {
return newFile(javaxDataDir(), "Screen Clips");
}
static void disposePossiblyInternalFrame(Component c) {
Container f = (Container) (getPossiblyInternalFrame(c));
if (f instanceof JInternalFrame) disposeInternalFrame((JInternalFrame) f);
else if (f instanceof Window) disposeWindow(f);
}
// action = runnable or method name
static void onUpdateAndNow(JComponent c, final Object r) {
onUpdate(c, r);
callF(r);
}
static void onUpdateAndNow(List extends JComponent> l, Object r) {
for (JComponent c : l)
onUpdate(c, r);
callF(r);
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
static int ocr_glyphCount(String s) {
return l(ocr_parseGlyphs(dropSpaces(s)));
}
static String dropSpaces(String s) {
return unnull(s).replace(" ", "");
}
static void growFrameSouth(Component c, final int howMuch) {
growWindowSouth(c, howMuch);
}
static void growFrameSouth(int howMuch, Component c) {
growFrameSouth(c, howMuch);
}
static int showForm_defaultGap = 4;
static int showForm_gapBetweenColumns = 10;
static JPanel showFormTitled(final String title, final Object... _parts) {
JDesktopPane desktop = mainDesktopPane();
if (desktop != null) return showInternalFrameFormTitled(desktop, title, _parts);
return swing(new F0() { public JPanel get() { try {
final Var frame = new Var();
JPanel panel = showForm_makePanel(false, _parts);
frame.set(showForm_makeFrame(title, panel));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final new Var frame;\r\n JPanel panel = showForm_makePanel(false, _p..."; }});
}
static JPanel showForm_makePanel(Boolean internalFrame, Object... _parts) {
List out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts));
return vstackWithSpacing(out, showForm_defaultGap);
}
static JScrollPane jscroll_minHeight(int h, Component c) {
return jMinHeight(h, jscroll(c));
}
static ImageSurface zoomedImageSurface(final BufferedImage image, final double zoom) {
return swing(new F0() { public ImageSurface get() { try {
ImageSurface is = new ImageSurface(image);
is.setZoom(zoom);
return is;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ImageSurface is = new(image);\r\n is.setZoom(zoom);\r\n ret is;"; }});
}
static ImageSurface zoomedImageSurface(double zoom, BufferedImage image) {
return zoomedImageSurface(image, zoom);
}
static void selectAllLater(int delay, final JTextField tf) {
awtLater(tf, delay, new Runnable() { public void run() { try { tf.selectAll() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tf.selectAll()"; }});
}
static void selectAllLater(JTextField tf, int delay) {
selectAllLater(delay, tf);
}
static float getScore(Scored s) {
return s == null ? 0 : s.score;
}
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
return null;
}
static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));
static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3); // not using pcall here - it could lead to endless loops
}
}
static SimpleRecognizer filledSimpleRecognizer() {
SimpleRecognizer sr = new SimpleRecognizer();
for (String s : scanLog_iterator(glyphTeachLog()))
sr.load(afterSquareBracketStuff(s));
return sr;
}
static ThreadLocal saveTiming_last = new ThreadLocal();
static void saveTiming(long ms) {
print(ms + " ms");
saveTiming_noPrint(ms);
}
static void saveTiming_noPrint(long ms) {
saveTiming_last.set(ms);
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static int ocr_slimFullSearchMap_maxPixels = 1000;
static Map ocr_slimFullSearchMap(Map map) {
if (ocr_slimFullSearchMap_maxPixels <= 0) return map;
for (BWImage img : cloneKeys(map)) {
int pix = bwImagePixels(img);
{ if (pix <= ocr_slimFullSearchMap_maxPixels) continue; }
BWImage img2 = new BWImage(scaleBufferedImageToMaxPixels(ocr_slimFullSearchMap_maxPixels, img.getBufferedImage()));
//print("Shrunk image to " + img2.getWidth() + "*" + img2.getHeight());
String md5 = map.get(img);
map.remove(img);
map.put(img2, md5);
}
return map;
}
static Map reverseMap(Map map) {
Map rmap = new HashMap();
for (A key : keys(map))
rmap.put(map.get(key), key);
return rmap;
}
// keys are md5s
static Map getLearnedCharacters2() {
Set md5s = requiredPhraseImageMD5s();
HashMap md5ToImage = new HashMap();
int nFound = 0;
{ final Map __0 = screenClipFilesContainedInMD5Set(md5s); for (String md5 : keys( __0)) { File f = __0.get(md5);
++nFound;
BWImage img = loadBWImage(f);
//md5ToImage.put(md5, img);
for (BWImage cImg : horizontalAutoSplitToImages(img)) {
String cMD5 = ocrMD5OfBWImage(cImg);
md5ToImage.put(cMD5, cImg);
}
}}
print("Loaded phrase images: " + nFound + "/" + l(md5s));
return md5ToImage;
}
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 Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static int coresToUse_fixed() {
return max(1, coresToUse());
}
static Iterable iterable(final Iterator i) {
return new Iterable () {
public Iterator iterator() {
return i;
}
};
}
static Pair pair(A a, B b) {
return new Pair(a, b);
}
static Pair pair(A a) {
return new Pair(a, a);
}
static List firstOfPairs(Collection> l) {
List out = new ArrayList();
for (Pair p : unnull(l)) out.add(firstOfPair(p));
return out;
}
static List> sortBySecondOfPairs_inPlace(List> l) {
sort(l, new Comparator>() {
public int compare(Pair a, Pair b) {
return stdcompare(a.b, b.b);
}
});
return 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 RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static boolean showAnimationInTopRightCorner_alwaysOnTop = true;
static boolean showAnimationInTopRightCorner_on = true;
// automatically switches to AWT thread for you
// text is optional text below image
static JWindow showAnimationInTopRightCorner(String imageID, String text) {
if (isHeadless() || !showAnimationInTopRightCorner_on) return null;
return showAnimationInTopRightCorner(imageIcon(imageID), text);
}
static JWindow showAnimationInTopRightCorner(final Image image, final String text) {
if (image == null || isHeadless() || !showAnimationInTopRightCorner_on) return null;
return showAnimationInTopRightCorner(imageIcon(image), text);
}
static JWindow showAnimationInTopRightCorner(final ImageIcon imageIcon, final String text) {
if (isHeadless() || !showAnimationInTopRightCorner_on) return null;
return (JWindow) swingAndWait(new F0() { public Object get() { try {
JLabel label = new JLabel(imageIcon);
if (nempty(text)) {
label.setText(text);
label.setVerticalTextPosition(SwingConstants.BOTTOM);
label.setHorizontalTextPosition(SwingConstants.CENTER);
}
final JWindow window = showInTopRightCorner(label);
onClick(label, new Runnable() { public void run() { try { window.dispose() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "window.dispose()"; }});
if (showAnimationInTopRightCorner_alwaysOnTop)
window.setAlwaysOnTop(true);
return window;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JLabel label = new JLabel(imageIcon);\r\n if (nempty(text)) {\r\n label.s..."; }});
}
static JWindow showAnimationInTopRightCorner(final String imageID) {
return showAnimationInTopRightCorner(imageID, "");
}
static JWindow showAnimationInTopRightCorner(String imageID, double seconds) {
return showAnimationInTopRightCorner(imageID, "", seconds);
}
static JWindow showAnimationInTopRightCorner(String imageID, String text, double seconds) {
if (isHeadless()) return null;
return disposeWindowAfter(iround(seconds*1000), showAnimationInTopRightCorner(imageID, text));
}
static JWindow showAnimationInTopRightCorner(BufferedImage img, String text, double seconds) {
return disposeWindowAfter(iround(seconds*1000), showAnimationInTopRightCorner(img, text));
}
static void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) { throw rethrow(__e); } }
static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() { public void run() { try {
result.set(callF(f));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; }});
return result.get();
}
}
static boolean isInstanceOf(Object o, Class type) {
return type.isInstance(o);
}
static String className(Object o) {
return getClassName(o);
}
static Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null) tl.set(l = new ArrayList());
l.add(a);
}
static A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null) return null;
A a = popLast(l);
if (empty(l)) tl.set(null);
return a;
}
static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null) return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}
static String getFrameTitle(Component c) {
JFrame f = getFrame(c);
return f == null ? null : f.getTitle();
}
// f: A -> Comparable
static List sortByCalculatedField(Iterable c, final Object f) {
List l = cloneList(c);
sort(l, new Comparator () {
public int compare(A a, A b) {
return stdcompare(callF(f, a), callF(f, b));
}
});
return l;
}
static Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static ArrayList cloneListSynchronizingOn(Collection l, Object mutex) {
if (l == null) return new ArrayList();
synchronized(mutex) {
return new ArrayList (l);
}
}
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 Object call_withVarargs(Object o, String method, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
{ if (!(isStaticMethod(m))) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) { throw rethrow(__e); } }
static Class __javax;
static Class getJavaX() { try {
return __javax;
} catch (Exception __e) { throw rethrow(__e); } }
// 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 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 void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static Thread currentThread() {
return Thread.currentThread();
}
//static final Map> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init);
static class getOpt_Map extends WeakHashMap {
getOpt_Map() {
if (getOpt_special == null) getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
//print("getOpt clear");
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
//static final Map> getOpt_cache = _registerWeakMap(synchroMap(new getOpt_Map));
static HashMap getOpt_special; // just a marker
/*static void getOpt_special_init(Map map) {
map.put(Class.class, getOpt_special);
map.put(S.class, getOpt_special);
}*/
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
/*if (o instanceof S)
ret getOpt(getBot((S) o), field);*/
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
if (o instanceof DynamicObject)
return mapGet2(((DynamicObject) o).fieldValues, field);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
if (!reflection_classesNotToScan().contains(c.getName())) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
makeAccessible(f);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
}
if (getOpt_cache != null) getOpt_cache.put(c, map);
return map;
}
static List _registerDangerousWeakMap_preList;
static A _registerDangerousWeakMap(A map) {
return _registerDangerousWeakMap(map, null);
}
static A _registerDangerousWeakMap(A map, Object init) {
callF(init, map);
if (init instanceof String) {
final String f = (String) init;
init = new VF1() { public void get(Map map) { try { callMC(f, map) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callMC(f, map)"; }};
}
if (javax() == null) {
// We're in class init
if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList();
_registerDangerousWeakMap_preList.add(pair(map, init));
return map;
}
call(javax(), "_registerDangerousWeakMap", map, init);
return map;
}
static void _onLoad_registerDangerousWeakMap() {
assertNotNull(javax());
if (_registerDangerousWeakMap_preList == null) return;
for (Pair p : _registerDangerousWeakMap_preList)
_registerDangerousWeakMap(p.a, p.b);
_registerDangerousWeakMap_preList = null;
}
static Class mc() {
return main.class;
}
static int iteratorCount_int_close(Iterator i) { try {
int n = 0;
if (i != null) while (i.hasNext()) { i.next(); ++n; }
if (i instanceof AutoCloseable) ((AutoCloseable) i).close();
return n;
} catch (Exception __e) { throw rethrow(__e); } }
static Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static String joinWithSpace(Iterable c) {
return join(" ", c);
}
static String joinWithSpace(String... c) {
return join(" ", c);
}
static List classNames(Collection l) {
return getClassNames(l);
}
static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class) return arg instanceof Boolean;
if (type == int.class) return arg instanceof Integer;
if (type == long.class) return arg instanceof Long;
if (type == float.class) return arg instanceof Float;
if (type == short.class) return arg instanceof Short;
if (type == char.class) return arg instanceof Character;
if (type == byte.class) return arg instanceof Byte;
if (type == double.class) return arg instanceof Double;
return type.isInstance(arg);
}
static void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static boolean loadBufferedImage_useImageCache = true;
static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try {
ping();
if (snippetIDOrURLOrFile == null) return null;
if (isURL(snippetIDOrURLOrFile))
return imageIO_readURL(snippetIDOrURLOrFile);
if (isAbsolutePath(snippetIDOrURLOrFile))
return loadBufferedImage(new File(snippetIDOrURLOrFile));
if (!isSnippetID(snippetIDOrURLOrFile))
throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile);
String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return loadBufferedImage(rl.loadLibrary(snippetID));
File dir = imageSnippetsCacheDir();
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
try {
return ImageIO.read(file);
} catch (Throwable e) {
e.printStackTrace();
// fall back to loading from sourceforge
}
}
String imageURL = snippetImageURL_http(snippetID);
print("Loading image: " + imageURL);
BufferedImage image = imageIO_readURL(imageURL);
if (loadBufferedImage_useImageCache) {
File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
ImageIO.write(image, "png", tempFile);
tempFile.renameTo(new File(dir, snippetID + ".png"));
//Log.info("Cached image.");
}
//Log.info("Loaded image.");
return image;
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage loadBufferedImage(File file) { try {
return file.isFile() ? ImageIO.read(file) : null;
} catch (Exception __e) { throw rethrow(__e); } }
static Object first(Object list) {
return first((Iterable) list);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(IterableIterator i) {
return first((Iterator ) i);
}
static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
static int packFrame_minw = 150, packFrame_minh = 50;
static A packFrame(final A c) {
{ swing(new Runnable() { public void run() { try {
Window w = getWindow(c);
if (w != null) {
w.pack();
int maxW = getScreenWidth()-50, maxH = getScreenHeight()-50;
w.setSize(
min(maxW, max(w.getWidth(), packFrame_minw)),
min(maxH, max(w.getHeight(), packFrame_minh)));
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Window w = getWindow(c);\r\n if (w != null) {\r\n w.pack();\r\n int ma..."; }}); }
return c;
}
static JFrame packFrame(ButtonGroup g) {
return packFrame(getFrame(g));
}
static JFrame showFrame() {
return makeFrame();
}
static JFrame showFrame(Object content) {
return makeFrame(content);
}
static JFrame showFrame(String title) {
return makeFrame(title);
}
static JFrame showFrame(String title, Object content) {
return makeFrame(title, content);
}
static JFrame showFrame(final JFrame f) {
if (f != null) { swing(new Runnable() { public void run() { try {
if (frameTooSmall(f)) frameStandardSize(f);
if (!f.isVisible()) f.setVisible(true); // XXX
if (f.getState() == Frame.ICONIFIED) f.setState(Frame.NORMAL);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (frameTooSmall(f)) frameStandardSize(f);\r\n if (!f.isVisible()) f.setVis..."; }}); }
return f;
}
// make or update frame
static JFrame showFrame(String title, Object content, JFrame frame) {
if (frame == null)
return showFrame(title, content);
else {
frame.setTitle(title);
setFrameContents(frame, content);
return frame;
}
}
static Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
static JFrame setFrameIconLater(Component c, final String imageID) {
final JFrame frame = getFrame(c);
if (frame != null)
startThread("Loading Icon", new Runnable() { public void run() { try {
final Image i = imageIcon(or2(imageID, "#1005557")).getImage();
swingLater(new Runnable() { public void run() { try {
frame.setIconImage(i);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setIconImage(i);"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n swingL..."; }});
return frame;
}
static Frame getAWTFrame(final Object _o) {
return swing(new F0 () { public Frame get() { try {
Object o = _o;
/*
ifdef HaveProcessing
if (o instanceof PApplet) o = ((PApplet) o).getSurface();
endifdef
*/
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 Frame) return (Frame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "O o = _o;\r\n /*\r\n ifdef HaveProcessing\r\n if (o instanceof PApplet) ..."; }});
}
static Graphics2D antiAliasGraphics(BufferedImage img) {
return antiAliasOn(createGraphics(img));
}
static Map createGraphics_modulators = synchroIdentityHashMap();
static Graphics2D createGraphics(BufferedImage img) {
Graphics2D g = img.createGraphics();
Object mod = createGraphics_modulators.get(img);
if (mod != null)
callF(mod, g);
return g;
}
// mod: voidfunc(Graphics2D)
static void createGraphics_modulate(BufferedImage img, Object mod) {
mapPut2(createGraphics_modulators, img, mod);
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static double normalizeTo0to1(double x) {
return Math.min(Math.max(x, 0), 1);
}
static int blend(int x, int y, double yish) {
double xish = 1-yish;
return (int) (x*xish+y*yish);
}
static double blend(double x, double y, double yish) {
double xish = 1-yish;
return x*xish+y*yish;
}
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 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 ThreadLocal componentPopupMenu_mouseEvent;
static void componentPopupMenu_init() {
{ swing(new Runnable() { public void run() { try {
if (componentPopupMenu_mouseEvent == null)
componentPopupMenu_mouseEvent = (ThreadLocal) vm_generalMap_get("mouseEvent");
if (componentPopupMenu_mouseEvent == null)
vm_generalMap_put("componentPopupMenu_mouseEvent" , componentPopupMenu_mouseEvent = new ThreadLocal());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (componentPopupMenu_mouseEvent == null)\r\n componentPopupMenu_mouseEve..."; }}); }
}
// menuMaker = voidfunc(JPopupMenu)
static void componentPopupMenu(final JComponent component, final Object menuMaker) {
if (component == null || menuMaker == null) return;
{ swing(new Runnable() { public void run() { try {
Object adapter = componentPopupMenu_initForComponent(component);
((List) _get(adapter, "maker")).add(menuMaker);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object adapter = componentPopupMenu_initForComponent(component);\r\n ((List)..."; }}); }
}
static Object componentPopupMenu_initForComponent(final JComponent component) {
return component == null ? null : swing(new F0() { public Object get() { try {
componentPopupMenu_init();
Object adapter = findComponentPopupMenuListener_gen(component);
if (adapter == null) {
componentPopupMenu_Adapter a = new componentPopupMenu_Adapter();
component.addMouseListener(a);
adapter = a;
}
return adapter;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "componentPopupMenu_init();\r\n O adapter = findComponentPopupMenuListener_ge..."; }});
}
static class componentPopupMenu_Adapter extends MouseAdapter {
List maker = new ArrayList();
boolean internalFrameLeftButtonMagic = false;
Point pressedAt;
public void mousePressed(MouseEvent e) {
displayMenu(e);
pressedAt = internalFrameLeftButtonMagic && e.getClickCount() == 1 && internalFrameActive(e.getComponent()) ? e.getLocationOnScreen() : null;
}
public void mouseReleased(MouseEvent e) {
// TODO: show a little less often on left mouse click
if (internalFrameLeftButtonMagic && eq(pressedAt, e.getLocationOnScreen()))
displayMenu2(e);
else
displayMenu(e);
}
void displayMenu(MouseEvent e) {
if (e.getSource() instanceof JInternalFrame) return;
if (e.isPopupTrigger()) displayMenu2(e);
}
void displayMenu2(MouseEvent e) {
JPopupMenu menu = new JPopupMenu();
int emptyCount = menu.getComponentCount();
AutoCloseable __1 = tempSetTL(componentPopupMenu_mouseEvent, e); try {
for (Object menuMaker : maker)
pcallF(menuMaker, menu);
vmBus_send("showingPopupMenu", e.getComponent(), menu);
// show menu if any items in it
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
} finally { _close(__1); }}
}
static JMenuItem jMenuItem(final String text) {
return jmenuItem(text);
}
static JMenuItem jMenuItem(String text, Object r) {
return jmenuItem(text, r);
}
static Pair jmenu_autoMnemonic(String s) {
int i = indexOf(s, '&');
if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i+1)))
return pair(substring(s, 0, i) + substring(s, i+1), (int) s.charAt(i+1));
return pair(s, 0);
}
static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
m.m = new String[] {substring(a, strL(b))};
return true;
}
static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a)) return false;
for (int i = 0; i < listL(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static JMenuItem disableMenuItem(final JMenuItem mi) {
if (mi != null) { swing(new Runnable() { public void run() { try { mi.setEnabled(false);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "mi.setEnabled(false);"; }}); }
return mi;
}
static ActionListener actionListenerInNewThread(final Object runnable) {
return actionListenerInNewThread(runnable, null);
}
static ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
startThread("Action Listener", new Runnable() { public void run() { try {
AutoCloseable __1 = holdInstance(instanceToHold); try {
callF(runnable);
} finally { _close(__1); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __1 = holdInstance(instanceToHold); try {\r\n callF(runnable..."; }});
} catch (Throwable __e) { messageBox(__e); }}};
}
static ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
static ActionListener actionListener(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
final Object info = _threadInfo();
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
_threadInheritInfo(info);
AutoCloseable __1 = holdInstance(instanceToHold); try {
callF(runnable);
} finally { _close(__1); }} catch (Throwable __e) { messageBox(__e); }}};
}
static boolean activateFrame(final Component c, Object... __) {
return swing(new F0() { public Boolean get() { try {
Frame f = getAWTFrame(c);
if (f == null) return false;
if (!f.isVisible()) f.setVisible(true);
boolean windowsHack = optPar("windowsHack",__, true);
boolean iconified = f.getState() == Frame.ICONIFIED;
boolean maximize = boolPar("maximize",__);
if (iconified)
f.setState(maximize ? Frame.MAXIMIZED_BOTH : Frame.NORMAL);
// My glorious Windows hack
// See: https://stackoverflow.com/questions/309023/how-to-bring-a-window-to-the-front
if (windowsHack && !iconified && isWindows()) {
boolean fullscreen = f.getExtendedState() == Frame.MAXIMIZED_BOTH;
f.setExtendedState(JFrame.ICONIFIED);
f.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL);
}
f.toFront();
return true;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Frame f = getAWTFrame(c);\r\n if (f == null) false;\r\n if (!f.isVisible())..."; }});
}
static String strUnnull(Object o) {
return o == null ? "" : str(o);
}
static String jlabel_textAsHTML_center_ifNeeded(String text) {
if (swic(text, "") && ewic(text, "")) return text;
if (!containsNewLines(text)) return text;
return jlabel_textAsHTML_center(text);
}
static Object callOpt(Object o) {
return callF(o);
}
static A callOpt(Object o, String method, Object... args) {
return (A) callOpt_withVarargs(o, method, args);
}
static A setFont(final Font font, final A a) {
if (a != null) { swing(new Runnable() { public void run() { try { a.setFont(font);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "a.setFont(font);"; }}); }
return a;
}
static A setFont(A a, Font font) {
return setFont(font, a);
}
static A setFont(final String fontID, float fontSize, final A a) {
return setFont(loadFont_cached(fontID, fontSize), a);
}
static JTextArea jTextArea() {
return jTextArea("");
}
static JTextArea jTextArea(final String text) {
return jTextAreaWithUndo(text);
}
static Font typeWriterFont() {
return typeWriterFont(iround(14*getSwingFontScale()));
}
static Font typeWriterFont(int size) {
return new Font("Courier", Font.PLAIN, size);
}
static String programTitle() {
return getProgramName();
}
static A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static A optParam(ThreadLocal tl) {
return optPar(tl);
}
static Object optParam(String name, Map params) {
return mapGet(params, name);
}
// now also takes a map as single array entry
static A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt))) throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2)
if (eq(opt[i], name))
return (A) opt[i+1];
return defaultValue;
}
static Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
static Object optParam(String name, Object[] params) {
return optParam(params, name);
}
static void _initFrame(JFrame f) {
myFrames_list.put(f, Boolean.TRUE);
standardTitlePopupMenu(f);
}
// c = Component or something implementing swing()
static JComponent wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
static JComponent wrap_2(Object swingable) {
if (swingable == null) return null;
JComponent c;
if (swingable instanceof Component) c = componentToJComponent(((Component) swingable));
else c = componentToJComponent((Component) callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList
|| c instanceof JTextArea || c instanceof JEditorPane
|| c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
static Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400);
static Rectangle defaultNewFrameBounds() {
return swing(new F0() { public Rectangle get() { try {
defaultNewFrameBounds_r.translate(60, 20);
if (!screenRectangle().contains(defaultNewFrameBounds_r))
defaultNewFrameBounds_r.setLocation(30+random(30), 20+random(20));
return new Rectangle(defaultNewFrameBounds_r);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "defaultNewFrameBounds_r.translate(60, 20);\r\n if (!screenRectangle().contai..."; }});
}
static void hideConsole() {
final JFrame frame = consoleFrame();
if (frame != null) {
autoVMExit();
swingLater(new Runnable() { public void run() { try {
frame.setVisible(false);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "frame.setVisible(false);"; }});
}
}
static String getProgramTitle() {
return getProgramName();
}
static CloseableIterableIterator linesFromFile(File f) { try {
if (!f.exists()) return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
return linesFromReader(utf8bufferedReader(f));
} catch (Exception __e) { throw rethrow(__e); } }
static CloseableIterableIterator linesFromFile(String path) {
return linesFromFile(newFile(path));
}
static List lambdaMap(IF1 f, Iterable l) {
return map(l, f);
}
static List lambdaMap(IF1 f, A[] l) {
return map(l, f);
}
static boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
return structure(o, new structure_Data());
}
static String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack))
popLast(d.stack).run();
}
static void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
// info on how to serialize objects of a certain class
static class structure_ClassInfo {
List fields;
Method customSerializer;
boolean special, nullInstances;
}
static class structure_Data {
PrintWriter out;
int stringSizeLimit;
int shareStringsLongerThan = 20;
boolean noStringSharing = false;
IdentityHashMap seen = new IdentityHashMap();
//new BitSet refd;
HashMap strings = new HashMap();
HashSet concepts = new HashSet();
HashMap infoByClass = new HashMap();
HashMap persistenceInfo = new HashMap();
int n; // token count
List stack = new ArrayList();
// append single token
structure_Data append(String token) { out.print(token); ++n; return this; }
structure_Data append(int i) { out.print(i); ++n; return this; }
// append multiple tokens
structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; }
// extend last token
structure_Data app(String token) { out.print(token); return this; }
structure_Data app(int i) { out.print(i); return this; }
}
static void structure_1(final Object o, final structure_Data d) { try {
if (o == null) { d.append("null"); return; }
Class c = o.getClass();
boolean concept = false;
structure_ClassInfo info = d.infoByClass.get(c);
if (info == null) {
d.infoByClass.put(c, info = new structure_ClassInfo());
if ((info.customSerializer = findMethodNamed(c, "_serialize"))
!= null) info.special = true;
}
List lFields = info.fields;
if (lFields == null) {
// these are never back-referenced (for readability)
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; }
if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; }
if (o instanceof Short) { short s = ((Short) o).shortValue(); d.append("sh "); out.print(s); d.n += s < 0 ? 2 : 1; return; }
if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; }
if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; }
if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; }
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f"); return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o)); return;
}
if (o instanceof File) {
d.append("File ").append(quote(((File) o).getPath())); return;
}
// referencable objects follow
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null) ref = d.strings.get((String) o);
if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
if (!(o instanceof String))
d.seen.put(o, d.n); // record token number
else {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out); d.n++; return;
}
if (o instanceof Set) {
/*O set2 = unwrapSynchronizedSet(o);
if (set2 != o) {
d.append("sync");
o = set2;
} TODO */
if (((Set) o) instanceof TreeSet) {
d.append(isCISet_gen(((Set) o)) ? "ciset" : "treeset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
// assume it's a HashSet or LinkedHashSet
d.append(((Set) o) instanceof LinkedHashSet ? "lhs" : "hashset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
String name = c.getName();
if (o instanceof Collection
&& !startsWith(name, "main$")
/* && neq(name, "main$Concept$RefL") */) {
// it's a list
if (name.equals("java.util.Collections$SynchronizedList")
|| name.equals("java.util.Collections$SynchronizedRandomAccessList")) {
d.append("sync ");
{ structure_1(unwrapSynchronizedList(((List) o)), d); return; }
}
else if (name.equals("java.util.LinkedList")) d.append("ll");
d.append("[");
final int l = d.n;
final Iterator it = ((Collection) o).iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.sta..."; }});
return;
}
if (o instanceof Map && !startsWith(name, "main$")) {
if (o instanceof LinkedHashMap) d.append("lhm");
else if (o instanceof HashMap) d.append("hm");
else if (o instanceof TreeMap)
d.append(isCIMap_gen(((TreeMap) o)) ? "cimap" : "tm");
else if (name.equals("java.util.Collections$SynchronizedMap")
|| name.equals("java.util.Collections$SynchronizedSortedMap")
|| name.equals("java.util.Collections$SynchronizedNavigableMap")) {
d.append("sync ");
{ structure_1(unwrapSynchronizedMap(((Map) o)), d); return; }
}
d.append("{");
final int l = d.n;
final Iterator it = ((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
boolean v = false;
Map.Entry e;
public void run() {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(e.getKey(), d);
}
}
}
});
return;
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o))); return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return;
}
String atype = "array"/*, sep = ", "*/; // sep is not used yet
if (o instanceof int[]) {
//ret "intarray " + quote(intArrayToHex((int[]) o));
atype = "intarray";
//sep = " ";
} else if (o instanceof double[]) {
atype = "dblarray";
//sep = " ";
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0) d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
if (d.n != l) d.append(", ");
d.append(i);
}
d.append("}"); return;
}
// Need more cases? This should cover all library classes...
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o))); return; // Hm. this is not unstructure-able
}
/*if (name.equals("main$Lisp")) {
fail("lisp not supported right now");
}*/
if (info.special) {
if (info.customSerializer != null) {
// custom serialization (_serialize method)
Object o2 = invokeMethod(info.customSerializer, o);
d.append("cu ");
String shortName = dropPrefix("main$", name);
d.append(shortName);
d.out.append(' ');
structure_1(o2, d);
return;
} else
if (info.nullInstances) { d.append("null"); return; }
else throw fail("unknown special type");
}
String dynName = shortDynamicClassName(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
// serialize an object with fields.
// first, collect all fields and values in fv.
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
String fieldName = field.getName();
if (fieldName.equals("_persistenceInfo"))
d.persistenceInfo.put(c, field);
if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
continue;
fields.add(field);
// put special cases here...?
}
cc = cc.getSuperclass();
}
// TODO: S fieldOrder = getOpt(c, "_fieldOrder");
lFields = asList(fields);
// Render this$1 first because unstructure needs it for constructor call.
int n = l(lFields);
for (int i = 0; i < n; i++) {
Field f = lFields.get(i);
if (f.getName().equals("this$1")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
info.fields = lFields;
} // << if (lFields == null)
else { // ref handling for lFields != null
Integer ref = d.seen.get(o);
if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
d.seen.put(o, d.n); // record token number
}
Field persistenceInfoField = (Field) (d.persistenceInfo.get(c));
Map persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o);
LinkedHashMap fv = new LinkedHashMap();
for (Field f : lFields) {
Object value;
try {
value = f.get(o);
} catch (Exception e) {
value = "?";
}
if (value != null && (persistenceInfo == null
|| !Boolean.FALSE.equals(persistenceInfo.get(f.getName()))))
fv.put(f.getName(), value);
}
String name = c.getName();
String shortName = dropPrefix("main$", name);
if (startsWithDigit(shortName)) shortName = name; // for anonymous classes
// Now we have fields & values. Process fieldValues if it's a DynamicObject.
// omit field "className" if equal to class's name
if (concept && eq(fv.get("className"), shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
putAll(fv, (Map) fv.get("fieldValues"));
fv.remove("fieldValues");
shortName = shortDynamicClassName(o);
fv.remove("className");
}
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
d.append(shortName);
d.n += countDots(shortName)*2; // correct token count
final int l = d.n;
final Iterator it = fv.entrySet().iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext()) {
if (d.n != l)
d.append(")");
} else {
Map.Entry e = (Map.Entry) it.next();
d.append(d.n == l ? "(" : ", ");
d.append((String) e.getKey()).append("=");
d.stack.add(this);
structure_1(e.getValue(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else..."; }});
} catch (Exception __e) { throw rethrow(__e); } }
static Map emptyMap() {
return new HashMap();
}
static Object[] emptyObjectArray_a = new Object[0];
static Object[] emptyObjectArray() { return emptyObjectArray_a; }
static String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
static List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
static boolean isSubclass(Class a, Class b) {
return a != null && b != null && b.isAssignableFrom(a);
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static List horizontalAutoSplit2ThenAutoCrop(BWImage img) {
List l = new ArrayList();
for (Rect r : horizontalAutoSplit2(img))
l.add(translateRect(autoCropOfBWImage(img.clip(r)), r.x, r.y));
return l;
}
static RGBImage mergeImagePartsHorizontally(RGBImage img, List