forked from imagej/ImageJ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIJ.java
2342 lines (2148 loc) · 78.7 KB
/
IJ.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ij;
import ij.gui.*;
import ij.process.*;
import ij.text.*;
import ij.io.*;
import ij.plugin.*;
import ij.plugin.filter.*;
import ij.util.Tools;
import ij.plugin.frame.Recorder;
import ij.plugin.frame.ThresholdAdjuster;
import ij.macro.Interpreter;
import ij.macro.MacroRunner;
import ij.measure.Calibration;
import ij.measure.ResultsTable;
import ij.measure.Measurements;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import java.awt.*;
import java.applet.Applet;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import javax.net.ssl.*;
import java.security.cert.*;
import java.security.KeyStore;
/** This class consists of static utility methods. */
public class IJ {
/** Image display modes */
public static final int COMPOSITE=1, COLOR=2, GRAYSCALE=3;
public static final String URL = "http://imagej.nih.gov/ij";
public static final int ALL_KEYS = -1;
/** Use setDebugMode(boolean) to enable/disable debug mode. */
public static boolean debugMode;
public static boolean hideProcessStackDialog;
public static final char micronSymbol = '\u00B5';
public static final char angstromSymbol = '\u00C5';
public static final char degreeSymbol = '\u00B0';
private static ImageJ ij;
private static java.applet.Applet applet;
private static ProgressBar progressBar;
private static TextPanel textPanel;
private static String osname, osarch;
private static boolean isMac, isWin, isLinux, is64Bit;
private static int javaVersion;
private static boolean controlDown, altDown, spaceDown, shiftDown;
private static boolean macroRunning;
private static Thread previousThread;
private static TextPanel logPanel;
private static boolean checkForDuplicatePlugins = true;
private static ClassLoader classLoader;
private static boolean memMessageDisplayed;
private static long maxMemory;
private static boolean escapePressed;
private static boolean redirectErrorMessages;
private static boolean suppressPluginNotFoundError;
private static Hashtable commandTable;
private static Vector eventListeners = new Vector();
private static String lastErrorMessage;
private static Properties properties; private static DecimalFormat[] df;
private static DecimalFormat[] sf;
private static DecimalFormatSymbols dfs;
private static boolean trustManagerCreated;
private static String smoothMacro;
private static Interpreter macroInterpreter;
static {
osname = System.getProperty("os.name");
isWin = osname.startsWith("Windows");
isMac = !isWin && osname.startsWith("Mac");
isLinux = osname.startsWith("Linux");
String version = System.getProperty("java.version");
if (version.startsWith("1.8"))
javaVersion = 8;
else if (version.startsWith("1.6"))
javaVersion = 6;
else if (version.startsWith("1.9")||version.startsWith("9"))
javaVersion = 9;
else if (version.startsWith("10"))
javaVersion = 10;
else if (version.startsWith("11"))
javaVersion = 11;
else if (version.startsWith("12"))
javaVersion = 12;
else if (version.startsWith("1.7"))
javaVersion = 7;
else
javaVersion = 6;
dfs = new DecimalFormatSymbols(Locale.US);
df = new DecimalFormat[10];
df[0] = new DecimalFormat("0", dfs);
df[1] = new DecimalFormat("0.0", dfs);
df[2] = new DecimalFormat("0.00", dfs);
df[3] = new DecimalFormat("0.000", dfs);
df[4] = new DecimalFormat("0.0000", dfs);
df[5] = new DecimalFormat("0.00000", dfs);
df[6] = new DecimalFormat("0.000000", dfs);
df[7] = new DecimalFormat("0.0000000", dfs);
df[8] = new DecimalFormat("0.00000000", dfs);
df[9] = new DecimalFormat("0.000000000", dfs);
}
static void init(ImageJ imagej, Applet theApplet) {
ij = imagej;
applet = theApplet;
progressBar = ij.getProgressBar();
}
static void cleanup() {
ij=null; applet=null; progressBar=null; textPanel=null;
}
/**Returns a reference to the "ImageJ" frame.*/
public static ImageJ getInstance() {
return ij;
}
/**Enable/disable debug mode.*/
public static void setDebugMode(boolean b) {
debugMode = b;
LogStream.redirectSystem(debugMode);
}
/** Runs the macro contained in the string <code>macro</code>.
Returns any string value returned by the macro, null if the macro
does not return a value, or "[aborted]" if the macro was aborted
due to an error. The equivalent macro function is eval(). */
public static String runMacro(String macro) {
return runMacro(macro, "");
}
/** Runs the macro contained in the string <code>macro</code>.
The optional string argument can be retrieved in the
called macro using the getArgument() macro function.
Returns any string value returned by the macro, null if the macro
does not return a value, or "[aborted]" if the macro was aborted
due to an error. */
public static String runMacro(String macro, String arg) {
Macro_Runner mr = new Macro_Runner();
return mr.runMacro(macro, arg);
}
/** Runs the specified macro or script file in the current thread.
The file is assumed to be in the macros folder
unless <code>name</code> is a full path.
The optional string argument (<code>arg</code>) can be retrieved in the called
macro or script using the getArgument() function.
Returns any string value returned by the macro, or null. Scripts always return null.
The equivalent macro function is runMacro(). */
public static String runMacroFile(String name, String arg) {
Macro_Runner mr = new Macro_Runner();
return mr.runMacroFile(name, arg);
}
/** Runs the specified macro file. */
public static String runMacroFile(String name) {
return runMacroFile(name, null);
}
/** Runs the specified plugin using the specified image. */
public static Object runPlugIn(ImagePlus imp, String className, String arg) {
if (imp!=null) {
ImagePlus temp = WindowManager.getTempCurrentImage();
WindowManager.setTempCurrentImage(imp);
Object o = runPlugIn("", className, arg);
WindowManager.setTempCurrentImage(temp);
return o;
} else
return runPlugIn(className, arg);
}
/** Runs the specified plugin and returns a reference to it. */
public static Object runPlugIn(String className, String arg) {
return runPlugIn("", className, arg);
}
/** Runs the specified plugin and returns a reference to it. */
public static Object runPlugIn(String commandName, String className, String arg) {
if (arg==null) arg = "";
if (IJ.debugMode)
IJ.log("runPlugIn: "+className+argument(arg));
// Load using custom classloader if this is a user
// plugin and we are not running as an applet
if (!className.startsWith("ij.") && applet==null)
return runUserPlugIn(commandName, className, arg, false);
Object thePlugIn=null;
try {
Class c = Class.forName(className);
thePlugIn = c.newInstance();
if (thePlugIn instanceof PlugIn)
((PlugIn)thePlugIn).run(arg);
else
new PlugInFilterRunner(thePlugIn, commandName, arg);
}
catch (ClassNotFoundException e) {
if (IJ.getApplet()==null)
log("Plugin or class not found: \"" + className + "\"\n(" + e+")");
}
catch (InstantiationException e) {log("Unable to load plugin (ins)");}
catch (IllegalAccessException e) {log("Unable to load plugin, possibly \nbecause it is not public.");}
redirectErrorMessages = false;
return thePlugIn;
}
static Object runUserPlugIn(String commandName, String className, String arg, boolean createNewLoader) {
if (IJ.debugMode)
IJ.log("runUserPlugIn: "+className+", arg="+argument(arg));
if (applet!=null) return null;
if (checkForDuplicatePlugins) {
// check for duplicate classes and jars in the plugins folder
IJ.runPlugIn("ij.plugin.ClassChecker", "");
checkForDuplicatePlugins = false;
}
if (createNewLoader)
classLoader = null;
ClassLoader loader = getClassLoader();
Object thePlugIn = null;
try {
thePlugIn = (loader.loadClass(className)).newInstance();
if (thePlugIn instanceof PlugIn)
((PlugIn)thePlugIn).run(arg);
else if (thePlugIn instanceof PlugInFilter)
new PlugInFilterRunner(thePlugIn, commandName, arg);
}
catch (ClassNotFoundException e) {
if (className.contains("_") && !suppressPluginNotFoundError)
error("Plugin or class not found: \"" + className + "\"\n(" + e+")");
}
catch (NoClassDefFoundError e) {
int dotIndex = className.indexOf('.');
if (dotIndex>=0 && className.contains("_")) {
// rerun plugin after removing folder name
if (debugMode) IJ.log("runUserPlugIn: rerunning "+className);
return runUserPlugIn(commandName, className.substring(dotIndex+1), arg, createNewLoader);
}
if (className.contains("_") && !suppressPluginNotFoundError)
error("Run User Plugin", "Class not found while attempting to run \"" + className + "\"\n \n " + e);
}
catch (InstantiationException e) {error("Unable to load plugin (ins)");}
catch (IllegalAccessException e) {error("Unable to load plugin, possibly \nbecause it is not public.");}
if (thePlugIn!=null && !"HandleExtraFileTypes".equals(className))
redirectErrorMessages = false;
suppressPluginNotFoundError = false;
return thePlugIn;
}
private static String argument(String arg) {
return arg!=null && !arg.equals("") && !arg.contains("\n")?"(\""+arg+"\")":"";
}
static void wrongType(int capabilities, String cmd) {
String s = "\""+cmd+"\" requires an image of type:\n \n";
if ((capabilities&PlugInFilter.DOES_8G)!=0) s += " 8-bit grayscale\n";
if ((capabilities&PlugInFilter.DOES_8C)!=0) s += " 8-bit color\n";
if ((capabilities&PlugInFilter.DOES_16)!=0) s += " 16-bit grayscale\n";
if ((capabilities&PlugInFilter.DOES_32)!=0) s += " 32-bit (float) grayscale\n";
if ((capabilities&PlugInFilter.DOES_RGB)!=0) s += " RGB color\n";
error(s);
}
/** Runs a menu command on a separete thread and returns immediately. */
public static void doCommand(String command) {
new Executer(command, null);
}
/** Runs a menu command on a separete thread, using the specified image. */
public static void doCommand(ImagePlus imp, String command) {
new Executer(command, imp);
}
/** Runs an ImageJ command. Does not return until
the command has finished executing. To avoid "image locked",
errors, plugins that call this method should implement
the PlugIn interface instead of PlugInFilter. */
public static void run(String command) {
run(command, null);
}
/** Runs an ImageJ command, with options that are passed to the
GenericDialog and OpenDialog classes. Does not return until
the command has finished executing. To generate run() calls,
start the recorder (Plugins/Macro/Record) and run commands
from the ImageJ menu bar.
*/
public static void run(String command, String options) {
//IJ.log("run1: "+command+" "+Thread.currentThread().hashCode()+" "+options);
if (ij==null && Menus.getCommands()==null)
init();
Macro.abort = false;
Macro.setOptions(options);
Thread thread = Thread.currentThread();
if (previousThread==null || thread!=previousThread) {
String name = thread.getName();
if (!name.startsWith("Run$_"))
thread.setName("Run$_"+name);
}
command = convert(command);
previousThread = thread;
macroRunning = true;
Executer e = new Executer(command);
e.run();
macroRunning = false;
Macro.setOptions(null);
testAbort();
macroInterpreter = null;
//IJ.log("run2: "+command+" "+Thread.currentThread().hashCode());
}
/** The macro interpreter uses this method to run commands. */
public static void run(Interpreter interpreter, String command, String options) {
macroInterpreter = interpreter;
run(command, options);
macroInterpreter = null;
}
/** Converts commands that have been renamed so
macros using the old names continue to work. */
private static String convert(String command) {
if (commandTable==null) {
commandTable = new Hashtable(30);
commandTable.put("New...", "Image...");
commandTable.put("Threshold", "Make Binary");
commandTable.put("Display...", "Appearance...");
commandTable.put("Start Animation", "Start Animation [\\]");
commandTable.put("Convert Images to Stack", "Images to Stack");
commandTable.put("Convert Stack to Images", "Stack to Images");
commandTable.put("Convert Stack to RGB", "Stack to RGB");
commandTable.put("Convert to Composite", "Make Composite");
commandTable.put("New HyperStack...", "New Hyperstack...");
commandTable.put("Stack to HyperStack...", "Stack to Hyperstack...");
commandTable.put("HyperStack to Stack", "Hyperstack to Stack");
commandTable.put("RGB Split", "Split Channels");
commandTable.put("RGB Merge...", "Merge Channels...");
commandTable.put("Channels...", "Channels Tool...");
commandTable.put("New... ", "Table...");
commandTable.put("Arbitrarily...", "Rotate... ");
commandTable.put("Measurements...", "Results... ");
commandTable.put("List Commands...", "Find Commands...");
commandTable.put("Capture Screen ", "Capture Screen");
commandTable.put("Add to Manager ", "Add to Manager");
commandTable.put("In", "In [+]");
commandTable.put("Out", "Out [-]");
commandTable.put("Enhance Contrast", "Enhance Contrast...");
commandTable.put("XY Coodinates... ", "XY Coordinates... ");
commandTable.put("Statistics...", "Statistics");
commandTable.put("Channels Tool... ", "Channels Tool...");
commandTable.put("Profile Plot Options...", "Plots...");
}
String command2 = (String)commandTable.get(command);
if (command2!=null)
return command2;
else
return command;
}
/** Runs an ImageJ command using the specified image and options.
To generate run() calls, start the recorder (Plugins/Macro/Record)
and run commands from the ImageJ menu bar.*/
public static void run(ImagePlus imp, String command, String options) {
if (ij==null && Menus.getCommands()==null)
init();
if (imp!=null) {
ImagePlus temp = WindowManager.getTempCurrentImage();
WindowManager.setTempCurrentImage(imp);
run(command, options);
WindowManager.setTempCurrentImage(temp);
} else
run(command, options);
}
static void init() {
Menus m = new Menus(null, null);
Prefs.load(m, null);
m.addMenuBar();
}
private static void testAbort() {
if (Macro.abort)
abort();
}
/** Returns true if the run(), open() or newImage() method is executing. */
public static boolean macroRunning() {
return macroRunning;
}
/** Returns true if a macro is running, or if the run(), open()
or newImage() method is executing. */
public static boolean isMacro() {
return macroRunning || Interpreter.getInstance()!=null;
}
/**Returns the Applet that created this ImageJ or null if running as an application.*/
public static java.applet.Applet getApplet() {
return applet;
}
/**Displays a message in the ImageJ status bar.*/
public static void showStatus(String s) {
if (ij!=null)
ij.showStatus(s);
ImagePlus imp = WindowManager.getCurrentImage();
ImageCanvas ic = imp!=null?imp.getCanvas():null;
if (ic!=null)
ic.setShowCursorStatus(s.length()==0?true:false);
}
/**
* @deprecated
* replaced by IJ.log(), ResultsTable.setResult() and TextWindow.append().
* There are examples at
* http://imagej.nih.gov/ij/plugins/sine-cosine.html
*/
public static void write(String s) {
if (textPanel==null && ij!=null)
showResults();
if (textPanel!=null)
textPanel.append(s);
else
System.out.println(s);
}
private static void showResults() {
TextWindow resultsWindow = new TextWindow("Results", "", 400, 250);
textPanel = resultsWindow.getTextPanel();
textPanel.setResultsTable(Analyzer.getResultsTable());
}
public static synchronized void log(String s) {
if (s==null) return;
if (logPanel==null && ij!=null) {
TextWindow logWindow = new TextWindow("Log", "", 400, 250);
logPanel = logWindow.getTextPanel();
logPanel.setFont(new Font("SansSerif", Font.PLAIN, 16));
}
if (logPanel!=null) {
if (s.startsWith("\\"))
handleLogCommand(s);
else {
if (s.endsWith("\n")) {
if (s.equals("\n\n"))
s= "\n \n ";
else if (s.endsWith("\n\n"))
s = s.substring(0, s.length()-2)+"\n \n ";
else
s = s+" ";
}
logPanel.append(s);
}
} else {
LogStream.redirectSystem(false);
System.out.println(s);
}
}
static void handleLogCommand(String s) {
if (s.equals("\\Closed"))
logPanel = null;
else if (s.startsWith("\\Update:")) {
int n = logPanel.getLineCount();
String s2 = s.substring(8, s.length());
if (n==0)
logPanel.append(s2);
else
logPanel.setLine(n-1, s2);
} else if (s.startsWith("\\Update")) {
int cindex = s.indexOf(":");
if (cindex==-1)
{logPanel.append(s); return;}
String nstr = s.substring(7, cindex);
int line = (int)Tools.parseDouble(nstr, -1);
if (line<0 || line>25)
{logPanel.append(s); return;}
int count = logPanel.getLineCount();
while (line>=count) {
log("");
count++;
}
String s2 = s.substring(cindex+1, s.length());
logPanel.setLine(line, s2);
} else if (s.equals("\\Clear")) {
logPanel.clear();
} else if (s.startsWith("\\Heading:")) {
logPanel.updateColumnHeadings(s.substring(10));
} else if (s.equals("\\Close")) {
Frame f = WindowManager.getFrame("Log");
if (f!=null && (f instanceof TextWindow))
((TextWindow)f).close();
} else
logPanel.append(s);
}
/** Returns the contents of the Log window or null if the Log window is not open. */
public static synchronized String getLog() {
if (logPanel==null || ij==null)
return null;
else
return logPanel.getText();
}
/** Clears the "Results" window and sets the column headings to
those in the tab-delimited 'headings' String. Writes to
System.out.println if the "ImageJ" frame is not present.*/
public static void setColumnHeadings(String headings) {
if (textPanel==null && ij!=null)
showResults();
if (textPanel!=null)
textPanel.setColumnHeadings(headings);
else
System.out.println(headings);
}
/** Returns true if the "Results" window is open. */
public static boolean isResultsWindow() {
return textPanel!=null;
}
/** Renames a results window. */
public static void renameResults(String title) {
Frame frame = WindowManager.getFrontWindow();
if (frame!=null && (frame instanceof TextWindow)) {
TextWindow tw = (TextWindow)frame;
if (tw.getResultsTable()==null) {
IJ.error("Rename", "\""+tw.getTitle()+"\" is not a results table");
return;
}
tw.rename(title);
} else if (isResultsWindow()) {
TextPanel tp = getTextPanel();
TextWindow tw = (TextWindow)tp.getParent();
tw.rename(title);
}
}
/** Changes the name of a table window from 'oldTitle' to 'newTitle'. */
public static void renameResults(String oldTitle, String newTitle) {
Frame frame = WindowManager.getFrame(oldTitle);
if (frame==null) {
error("Rename", "\""+oldTitle+"\" not found");
return;
} else if (frame instanceof TextWindow) {
TextWindow tw = (TextWindow)frame;
if (tw.getResultsTable()==null) {
error("Rename", "\""+oldTitle+"\" is not a table");
return;
}
tw.rename(newTitle);
} else
error("Rename", "\""+oldTitle+"\" is not a table");
}
/** Deletes 'row1' through 'row2' of the "Results" window, where
'row1' and 'row2' must be in the range 0-Analyzer.getCounter()-1. */
public static void deleteRows(int row1, int row2) {
ResultsTable rt = Analyzer.getResultsTable();
rt.deleteRows(row1, row2);
rt.show("Results");
}
/** Returns a reference to the "Results" window TextPanel.
Opens the "Results" window if it is currently not open.
Returns null if the "ImageJ" window is not open. */
public static TextPanel getTextPanel() {
if (textPanel==null && ij!=null)
showResults();
return textPanel;
}
/** TextWindow calls this method with a null argument when the "Results" window is closed. */
public static void setTextPanel(TextPanel tp) {
textPanel = tp;
}
/**Displays a "no images are open" dialog box.*/
public static void noImage() {
String msg = "There are no images open.";
if (macroInterpreter!=null) {
macroInterpreter.abort(msg);
macroInterpreter = null;
} else
error("No Image", msg);
}
/** Displays an "out of memory" message to the "Log" window. */
public static void outOfMemory(String name) {
Undo.reset();
System.gc();
lastErrorMessage = "out of memory";
String tot = Runtime.getRuntime().maxMemory()/1048576L+"MB";
if (!memMessageDisplayed)
log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
log("<Out of memory>");
if (!memMessageDisplayed) {
log("<All available memory ("+tot+") has been>");
log("<used. To make more available, use the>");
log("<Edit>Options>Memory & Threads command.>");
log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
memMessageDisplayed = true;
}
Macro.abort();
}
/** Updates the progress bar, where 0<=progress<=1.0. The progress bar is
not shown in BatchMode and erased if progress>=1.0. The progress bar is
updated only if more than 90 ms have passes since the last call. Does nothing
if the ImageJ window is not present. */
public static void showProgress(double progress) {
if (progressBar!=null) progressBar.show(progress, false);
}
/** Updates the progress bar, where the length of the bar is set to
(<code>currentValue+1)/finalValue</code> of the maximum bar length.
The bar is erased if <code>currentValue>=finalValue</code>.
The bar is updated only if more than 90 ms have passed since the last call.
Does nothing if the ImageJ window is not present. */
public static void showProgress(int currentIndex, int finalIndex) {
if (progressBar!=null) {
progressBar.show(currentIndex, finalIndex);
if (currentIndex==finalIndex)
progressBar.setBatchMode(false);
}
}
/** Displays a message in a dialog box titled "Message".
Writes the Java console if ImageJ is not present. */
public static void showMessage(String msg) {
showMessage("Message", msg);
}
/** Displays a message in a dialog box with the specified title.
Displays HTML formatted text if 'msg' starts with "<html>".
There are examples at
"http://imagej.nih.gov/ij/macros/HtmlDialogDemo.txt".
Writes to the Java console if ImageJ is not present. */
public static void showMessage(String title, String msg) {
if (ij!=null) {
if (msg!=null && (msg.startsWith("<html>")||msg.startsWith("<HTML>"))) {
HTMLDialog hd = new HTMLDialog(title, msg);
if (isMacro() && hd.escapePressed())
throw new RuntimeException(Macro.MACRO_CANCELED);
} else {
MessageDialog md = new MessageDialog(ij, title, msg);
if (isMacro() && md.escapePressed())
throw new RuntimeException(Macro.MACRO_CANCELED);
}
} else
System.out.println(msg);
}
/** Displays a message in a dialog box titled "ImageJ". If a
macro or JavaScript is running, it is aborted. Writes to the
Java console if the ImageJ window is not present.*/
public static void error(String msg) {
if (macroInterpreter!=null) {
macroInterpreter.abort(msg);
macroInterpreter = null;
return;
}
error(null, msg);
if (Thread.currentThread().getName().endsWith("JavaScript"))
throw new RuntimeException(Macro.MACRO_CANCELED);
else
Macro.abort();
}
/** Displays a message in a dialog box with the specified title. If a
macro or JavaScript is running, it is aborted. Writes to the
Java console if the ImageJ window is not present. */
public static void error(String title, String msg) {
if (msg!=null && msg.endsWith(Macro.MACRO_CANCELED))
return;
String title2 = title!=null?title:"ImageJ";
boolean abortMacro = title!=null;
lastErrorMessage = msg;
if (redirectErrorMessages) {
IJ.log(title2 + ": " + msg);
if (abortMacro && (title.contains("Open")||title.contains("Reader")))
abortMacro = false;
} else
showMessage(title2, msg);
redirectErrorMessages = false;
if (abortMacro)
Macro.abort();
}
/** Aborts any currently running JavaScript, or use IJ.error(string)
to abort a JavaScript with a message. */
public static void exit() {
if (Thread.currentThread().getName().endsWith("JavaScript"))
throw new RuntimeException(Macro.MACRO_CANCELED);
}
/**
* Returns the last error message written by IJ.error() or null if there
* was no error since the last time this method was called.
* @see #error(String)
*/
public static String getErrorMessage() {
String msg = lastErrorMessage;
lastErrorMessage = null;
return msg;
}
/** Displays a message in a dialog box with the specified title.
Returns false if the user pressed "Cancel". */
public static boolean showMessageWithCancel(String title, String msg) {
GenericDialog gd = new GenericDialog(title);
gd.addMessage(msg);
gd.showDialog();
return !gd.wasCanceled();
}
public static final int CANCELED = Integer.MIN_VALUE;
/** Allows the user to enter a number in a dialog box. Returns the
value IJ.CANCELED (-2,147,483,648) if the user cancels the dialog box.
Returns 'defaultValue' if the user enters an invalid number. */
public static double getNumber(String prompt, double defaultValue) {
GenericDialog gd = new GenericDialog("");
int decimalPlaces = (int)defaultValue==defaultValue?0:2;
gd.addNumericField(prompt, defaultValue, decimalPlaces);
gd.showDialog();
if (gd.wasCanceled())
return CANCELED;
double v = gd.getNextNumber();
if (gd.invalidNumber())
return defaultValue;
else
return v;
}
/** Allows the user to enter a string in a dialog box. Returns
"" if the user cancels the dialog box. */
public static String getString(String prompt, String defaultString) {
GenericDialog gd = new GenericDialog("");
gd.addStringField(prompt, defaultString, 20);
gd.showDialog();
if (gd.wasCanceled())
return "";
return gd.getNextString();
}
/**Delays 'msecs' milliseconds.*/
public static void wait(int msecs) {
try {Thread.sleep(msecs);}
catch (InterruptedException e) { }
}
/** Emits an audio beep. */
public static void beep() {
java.awt.Toolkit.getDefaultToolkit().beep();
}
/** Runs the garbage collector and returns a string something
like "64K of 256MB (25%)" that shows how much of
the available memory is in use. This is the string
displayed when the user clicks in the status bar. */
public static String freeMemory() {
long inUse = currentMemory();
String inUseStr = inUse<10000*1024?inUse/1024L+"K":inUse/1048576L+"MB";
String maxStr="";
long max = maxMemory();
if (max>0L) {
double percent = inUse*100/max;
maxStr = " of "+max/1048576L+"MB ("+(percent<1.0?"<1":d2s(percent,0)) + "%)";
}
return inUseStr + maxStr;
}
/** Returns the amount of memory currently being used by ImageJ. */
public static long currentMemory() {
long freeMem = Runtime.getRuntime().freeMemory();
long totMem = Runtime.getRuntime().totalMemory();
return totMem-freeMem;
}
/** Returns the maximum amount of memory available to ImageJ or
zero if ImageJ is unable to determine this limit. */
public static long maxMemory() {
if (maxMemory==0L) {
Memory mem = new Memory();
maxMemory = mem.getMemorySetting();
if (maxMemory==0L) maxMemory = mem.maxMemory();
}
return maxMemory;
}
public static void showTime(ImagePlus imp, long start, String str) {
showTime(imp, start, str, 1);
}
public static void showTime(ImagePlus imp, long start, String str, int nslices) {
if (Interpreter.isBatchMode()) return;
double seconds = (System.currentTimeMillis()-start)/1000.0;
double pixels = (double)imp.getWidth() * imp.getHeight();
double rate = pixels*nslices/seconds;
String str2;
if (rate>1000000000.0)
str2 = "";
else if (rate<1000000.0)
str2 = ", "+d2s(rate,0)+" pixels/second";
else
str2 = ", "+d2s(rate/1000000.0,1)+" million pixels/second";
showStatus(str+seconds+" seconds"+str2);
}
/** Experimental */
public static String time(ImagePlus imp, long startNanoTime) {
double planes = imp.getStackSize();
double seconds = (System.nanoTime()-startNanoTime)/1000000000.0;
double mpixels = imp.getWidth()*imp.getHeight()*planes/1000000.0;
String time = seconds<1.0?d2s(seconds*1000.0,0)+" ms":d2s(seconds,1)+" seconds";
return time+", "+d2s(mpixels/seconds,1)+" million pixels/second";
}
/** Converts a number to a formatted string using
2 digits to the right of the decimal point. */
public static String d2s(double n) {
return d2s(n, 2);
}
/** Converts a number to a rounded formatted string.
The 'decimalPlaces' argument specifies the number of
digits to the right of the decimal point (0-9). Uses
scientific notation if 'decimalPlaces is negative. */
public static String d2s(double n, int decimalPlaces) {
if (Double.isNaN(n)||Double.isInfinite(n))
return ""+n;
if (n==Float.MAX_VALUE) // divide by 0 in FloatProcessor
return "3.4e38";
double np = n;
if (n<0.0) np = -n;
if (decimalPlaces<0) synchronized(IJ.class) {
decimalPlaces = -decimalPlaces;
if (decimalPlaces>9) decimalPlaces=9;
if (sf==null) {
if (dfs==null)
dfs = new DecimalFormatSymbols(Locale.US);
sf = new DecimalFormat[10];
sf[1] = new DecimalFormat("0.0E0",dfs);
sf[2] = new DecimalFormat("0.00E0",dfs);
sf[3] = new DecimalFormat("0.000E0",dfs);
sf[4] = new DecimalFormat("0.0000E0",dfs);
sf[5] = new DecimalFormat("0.00000E0",dfs);
sf[6] = new DecimalFormat("0.000000E0",dfs);
sf[7] = new DecimalFormat("0.0000000E0",dfs);
sf[8] = new DecimalFormat("0.00000000E0",dfs);
sf[9] = new DecimalFormat("0.000000000E0",dfs);
}
return sf[decimalPlaces].format(n); // use scientific notation
}
if (decimalPlaces<0) decimalPlaces = 0;
if (decimalPlaces>9) decimalPlaces = 9;
return df[decimalPlaces].format(n);
}
/** Converts a number to a rounded formatted string.
* The 'significantDigits' argument specifies the minimum number
* of significant digits, which is also the preferred number of
* digits behind the decimal. Fewer decimals are shown if the
* number would have more than 'maxDigits'.
* Exponential notation is used if more than 'maxDigits' would be needed.
*/
public static String d2s(double x, int significantDigits, int maxDigits) {
double log10 = Math.log10(Math.abs(x));
double roundErrorAtMax = 0.223*Math.pow(10, -maxDigits);
int magnitude = (int)Math.ceil(log10+roundErrorAtMax);
int decimals = x==0 ? 0 : maxDigits - magnitude;
if (decimals<0 || magnitude<significantDigits+1-maxDigits)
return IJ.d2s(x, -significantDigits); // exp notation for large and small numbers
else {
if (decimals>significantDigits)
decimals = Math.max(significantDigits, decimals-maxDigits+significantDigits);
return IJ.d2s(x, decimals);
}
}
/** Pad 'n' with leading zeros to the specified number of digits. */
public static String pad(int n, int digits) {
String str = ""+n;
while (str.length()<digits)
str = "0"+str;
return str;
}
/** Adds the specified class to a Vector to keep it from being garbage
collected, which would cause the classes static fields to be reset.
Probably not needed with Java 1.2 or later. */
public static void register(Class c) {
if (ij!=null) ij.register(c);
}
/** Returns true if the space bar is down. */
public static boolean spaceBarDown() {
return spaceDown;
}
/** Returns true if the control key is down. */
public static boolean controlKeyDown() {
return controlDown;
}
/** Returns true if the alt key is down. */
public static boolean altKeyDown() {
return altDown;
}
/** Returns true if the shift key is down. */
public static boolean shiftKeyDown() {
return shiftDown;
}
public static void setKeyDown(int key) {
if (debugMode) IJ.log("setKeyDown: "+key);
switch (key) {
case KeyEvent.VK_CONTROL:
controlDown=true;
break;
case KeyEvent.VK_META:
if (isMacintosh()) controlDown=true;
break;
case KeyEvent.VK_ALT:
altDown=true;
updateStatus();
break;
case KeyEvent.VK_SHIFT:
shiftDown=true;
if (debugMode) beep();
break;
case KeyEvent.VK_SPACE: {
spaceDown=true;
ImageWindow win = WindowManager.getCurrentWindow();
if (win!=null) win.getCanvas().setCursor(-1,-1,-1, -1);
break;
}
case KeyEvent.VK_ESCAPE: {
escapePressed = true;
break;
}
}
}
public static void setKeyUp(int key) {
if (debugMode) IJ.log("setKeyUp: "+key);
switch (key) {
case KeyEvent.VK_CONTROL: controlDown=false; break;
case KeyEvent.VK_META: if (isMacintosh()) controlDown=false; break;
case KeyEvent.VK_ALT: altDown=false; updateStatus(); break;
case KeyEvent.VK_SHIFT: shiftDown=false; if (debugMode) beep(); break;
case KeyEvent.VK_SPACE:
spaceDown=false;
ImageWindow win = WindowManager.getCurrentWindow();
if (win!=null) win.getCanvas().setCursor(-1,-1,-1,-1);
break;
case ALL_KEYS:
shiftDown=controlDown=altDown=spaceDown=false;
break;
}
}
private static void updateStatus() {
ImagePlus imp = WindowManager.getCurrentImage();
if (imp!=null) {
Roi roi = imp.getRoi();
if (roi!=null && imp.getCalibration().scaled()) {
roi.showStatus();
}
}
}
public static void setInputEvent(InputEvent e) {
altDown = e.isAltDown();
shiftDown = e.isShiftDown();
}
/** Returns true if this machine is a Macintosh. */
public static boolean isMacintosh() {
return isMac;
}
/** Returns true if this machine is a Macintosh running OS X. */
public static boolean isMacOSX() {
return isMacintosh();
}
/** Returns true if this machine is running Windows. */
public static boolean isWindows() {
return isWin;
}
/** Returns the Java version (6, 7, 8, 9, 10, etc.). */
public static int javaVersion() {