Squiz Matrix  4.12.2
 All Data Structures Namespaces Functions Variables Pages
IJ.java
1 package ij;
2 import ij.gui.*;
3 import ij.process.*;
4 import ij.text.*;
5 import ij.io.*;
6 import ij.plugin.*;
7 import ij.plugin.filter.*;
8 import ij.util.Tools;
9 import ij.plugin.frame.Recorder;
10 import java.awt.event.*;
11 import java.text.*;
12 import java.util.Locale;
13 import java.awt.*;
14 import java.applet.Applet;
15 import java.io.*;
16 import java.lang.reflect.*;
17 import javax.swing.*;
18 
20 public class IJ {
21  public static boolean debugMode = false;
22 
23  public static final char micronSymbol = (char)181;
24  public static final char angstromSymbol = (char)197;
25  public static final char degreeSymbol = (char)176;
26 
27  private static ImageJ ij;
28  private static java.applet.Applet applet;
29  private static ProgressBar progressBar;
30  private static TextPanel textPanel;
31  private static String osname;
32  private static boolean isMac, isWin, isJava2, isJava14;
33  private static boolean altDown, spaceDown, shiftDown;
34  private static boolean macroRunning;
35  private static Thread previousThread;
36  private static TextPanel logPanel;
37  private static boolean notVerified = true;
38  private static PluginClassLoader classLoader;
39  private static boolean memMessageDisplayed;
40  private static long maxMemory;
41 
42  static {
43  osname = System.getProperty("os.name");
44  isWin = osname.startsWith("Windows");
45  isMac = !isWin && osname.startsWith("Mac");
46  String version = System.getProperty("java.version").substring(0,3);
47  // JVM on Sharp Zaurus PDA claims to be "3.1"!
48  isJava2 = version.compareTo("1.1")>0 && version.compareTo("2.9")<=0;
49  isJava14 = version.compareTo("1.3")>0 && version.compareTo("2.9")<=0;
50  }
51 
52  static void init(ImageJ imagej, Applet theApplet) {
53  ij = imagej;
54  applet = theApplet;
55  progressBar = ij.getProgressBar();
56  }
57 
59  public static ImageJ getInstance() {
60  return ij;
61  }
62 
64  public static Object runPlugIn(String className, String arg) {
65  return runPlugIn("", className, arg);
66  }
67 
69  static Object runPlugIn(String commandName, String className, String arg) {
70  if (IJ.debugMode)
71  IJ.log("runPlugin: "+className+" "+arg);
72  Object thePlugIn=null;
73  try {
74  Class c = Class.forName(className);
75  thePlugIn = c.newInstance();
76  if (thePlugIn instanceof PlugIn) {
77  ((PlugIn)thePlugIn).run(arg);
78  } else {
79  runFilterPlugIn(thePlugIn, commandName, arg);
80  }
81  }
82  catch (ClassNotFoundException e) {
83  if (IJ.getApplet()==null)
84  System.err.println("Plugin not found: " + className);
85  }
86  catch (InstantiationException e) {log("Unable to load plugin (ins)");}
87  catch (IllegalAccessException e) {log("Unable to load plugin, possibly \nbecause it is not public.");}
88  return thePlugIn;
89  }
90 
91  static void runFilterPlugIn(Object theFilter, String cmd, String arg) {
92  ImagePlus imp = IJ.getInstance().getImagePlus();
93  int capabilities = ((PlugInFilter)theFilter).setup(arg, imp);
94  if ((capabilities&PlugInFilter.DONE)!=0)
95  return;
96  if ((capabilities&PlugInFilter.NO_IMAGE_REQUIRED)!=0)
97  {((PlugInFilter)theFilter).run(null); return;}
98  if (imp==null)
99  {IJ.noImage(); return;}
100  if ((capabilities&PlugInFilter.ROI_REQUIRED)!=0 && imp.getRoi()==null)
101  {IJ.error("Selection required"); return;}
102  int type = imp.getType();
103  switch (type) {
104  case ImagePlus.GRAY8:
105  if ((capabilities&PlugInFilter.DOES_8G)==0)
106  {wrongType(capabilities, cmd); return;}
107  break;
108  case ImagePlus.COLOR_256:
109  if ((capabilities&PlugInFilter.DOES_8C)==0)
110  {wrongType(capabilities, cmd); return;}
111  break;
112  case ImagePlus.GRAY16:
113  if ((capabilities&PlugInFilter.DOES_16)==0)
114  {wrongType(capabilities, cmd); return;}
115  break;
116  case ImagePlus.GRAY32:
117  if ((capabilities&PlugInFilter.DOES_32)==0)
118  {wrongType(capabilities, cmd); return;}
119  break;
120  case ImagePlus.COLOR_RGB:
121  if ((capabilities&PlugInFilter.DOES_RGB)==0)
122  {wrongType(capabilities, cmd); return;}
123  break;
124  }
125  if (!imp.lock())
126  return; // exit if image is in use
127  imp.startTiming();
128  IJ.showStatus(cmd + "...");
129  ImageProcessor ip;
130  ImageProcessor mask = null;
131  float[] cTable = imp.getCalibration().getCTable();
132  ip = imp.getProcessor();
133  mask = imp.getMask();
134  if ((capabilities&PlugInFilter.NO_UNDO)!=0)
135  Undo.reset();
136  else {
137  Undo.setup(Undo.FILTER, imp);
138  ip.snapshot();
139  }
140  //ip.setMask(mask);
141  ip.setCalibrationTable(cTable);
142  ((PlugInFilter)theFilter).run(ip);
143  if ((capabilities&PlugInFilter.SUPPORTS_MASKING)!=0)
144  ip.reset(ip.getMask()); //restore image outside irregular roi
145  IJ.showTime(imp, imp.getStartTime(), cmd + ": ", 1);
146  if ((capabilities&PlugInFilter.NO_CHANGES)==0) {
147  imp.changes = true;
148  imp.updateAndDraw();
149  }
150  imp.unlock();
151  }
152 
153  static Object runUserPlugIn(String commandName, String className, String arg, boolean createNewLoader) {
154  if (applet!=null)
155  return null;
156  String pluginsDir = Menus.getPlugInsPath();
157  if (pluginsDir==null)
158  return null;
159  if (notVerified) {
160  // check for duplicate classes in the plugins folder
161  IJ.runPlugIn("ij.plugin.ClassChecker", "");
162  notVerified = false;
163  }
164  PluginClassLoader loader;
165  if (createNewLoader)
166  loader = new PluginClassLoader(pluginsDir);
167  else {
168  if (classLoader==null)
169  classLoader = new PluginClassLoader(pluginsDir);
170  loader = classLoader;
171  }
172  Object thePlugIn = null;
173  try {
174  thePlugIn = (loader.loadClass(className)).newInstance();
175  if (thePlugIn instanceof PlugIn)
176  ((PlugIn)thePlugIn).run(arg);
177  else if (thePlugIn instanceof PlugInFilter)
178  runFilterPlugIn(thePlugIn, commandName, arg);
179  }
180  catch (ClassNotFoundException e) {
181  if (className.indexOf('_')!=-1)
182  IJ.error("Plugin not found: "+className);
183  }
184  catch (InstantiationException e) {IJ.error("Unable to load plugin (ins)");}
185  catch (IllegalAccessException e) {IJ.error("Unable to load plugin, possibly \nbecause it is not public.");}
186  return thePlugIn;
187  }
188 
189  static void wrongType(int capabilities, String cmd) {
190  String s = "\""+cmd+"\" requires an image of type:\n \n";
191  if ((capabilities&PlugInFilter.DOES_8G)!=0) s += " 8-bit grayscale\n";
192  if ((capabilities&PlugInFilter.DOES_8C)!=0) s += " 8-bit color\n";
193  if ((capabilities&PlugInFilter.DOES_16)!=0) s += " 16-bit grayscale\n";
194  if ((capabilities&PlugInFilter.DOES_32)!=0) s += " 32-bit (float) grayscale\n";
195  if ((capabilities&PlugInFilter.DOES_RGB)!=0) s += " RGB color\n";
196  IJ.error(s);
197  }
198 
200  public static void doCommand(String command) {
201  if (ij!=null)
202  ij.doCommand(command);
203  }
204 
207  public static void run(String command) {
208  run(command, null);
209  }
210 
214  public static void run(String command, String options) {
215  //IJ.log("run: "+command+" "+Thread.currentThread().getName());
216  if (ij==null && Menus.getCommands()==null)
217  init();
218  Thread thread = Thread.currentThread();
219  if (previousThread==null || thread!=previousThread) {
220  String name = thread.getName();
221  if (!name.startsWith("Run$_"))
222  thread.setName("Run$_"+name);
223  }
224  if (command.equals("Miscellaneous..."))
225  command = "Misc...";
226  previousThread = thread;
227  Executer e = new Executer(command);
228  e.run();
229  testAbort();
230  }
231 
232  static void init() {
233  Menus m = new Menus(null, null);
234  Prefs.load(m, null);
235  m.addMenuBar();
236  }
237 
238  private static void testAbort() {
239  }
240 
242  public static boolean macroRunning() {
243  return macroRunning;
244  }
245 
247  public static java.applet.Applet getApplet() {
248  return applet;
249  }
250 
252  public static void showStatus(String s) {
253  if (ij!=null) ij.showStatus(s);
254  }
255 
258  public static void write(String s) {
259  if (textPanel==null)
260  showResults();
261  if (textPanel!=null)
262  textPanel.append(s);
263  else
264  System.out.println(s);
265  }
266 
267  private static void showResults() {
268  TextWindow resultsWindow = new TextWindow("Results", "", 300, 200);
269  textPanel = resultsWindow.getTextPanel();
270  if (ij!=null)
271  textPanel.addKeyListener(ij);
272  }
273 
276  public static synchronized void log(String s) {
277  System.out.println(s);
278  }
279 
282  public static void setColumnHeadings(String headings) {
283  if (textPanel==null)
284  showResults();
285  if (textPanel!=null)
286  textPanel.setColumnHeadings(headings);
287  }
288 
290  public static boolean isResultsWindow() {
291  return textPanel!=null;
292  }
293 
296  public static TextPanel getTextPanel() {
297  if (textPanel==null)
298  showResults();
299  return textPanel;
300  }
301 
303  public static void setTextPanel(TextPanel tp) {
304  textPanel = tp;
305  }
306 
308  public static void noImage() {
309  showMessage("No Image", "There are no images open.");
310  }
311 
313  public static void outOfMemory(String name) {
314  Undo.reset();
315  System.gc();
316  String tot = Runtime.getRuntime().totalMemory()/1048576L+"MB";
317  if (!memMessageDisplayed)
318  log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
319  log("<Out of memory>");
320  if (!memMessageDisplayed) {
321  log("<All available memory ("+tot+") has been>");
322  log("<used. Instructions for making more>");
323  log("<available can be found in the \"Memory\" >");
324  log("<sections of the installation notes at>");
325  log("<http://rsb.info.nih.gov/ij/docs/install/>");
326  log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
327  memMessageDisplayed = true;
328  }
329  }
330 
335  public static void showProgress(double progress) {
336  if (progressBar!=null) progressBar.show(progress);
337  }
338 
342  public static void showProgress(int currentIndex, int finalIndex) {
343  if (progressBar!=null) progressBar.show(currentIndex, finalIndex);
344  }
345 
348  public static void showMessage(String title, String msg) {
349  if (ij!=null) {
350  if (msg.startsWith("<html>") && isJava2())
351  new HTMLDialog(title, msg);
352  else {
353  JOptionPane.showMessageDialog(null, msg);
354  ij.repaint();
355  }
356  } else {
357  System.out.println(msg);
358  }
359  }
360 
363  public static void showMessage(String msg) {
364  showMessage("Message", msg);
365  }
366 
369  public static void error(String msg) {
370  if (ij!=null) {
371  JOptionPane.showMessageDialog(null, msg);
372  ij.repaint();
373  }
374  else
375  System.err.println(msg);
376  }
377 
380  public static boolean showMessageWithCancel(String title, String msg) {
381  GenericDialog gd = new GenericDialog(title);
382  gd.addMessage(msg);
383  gd.showDialog();
384  return !gd.wasCanceled();
385  }
386 
387  public static final int CANCELED = Integer.MIN_VALUE;
388 
392  public static double getNumber(String prompt, double defaultValue) {
393  GenericDialog gd = new GenericDialog("");
394  int decimalPlaces = (int)defaultValue==defaultValue?0:2;
395  gd.addNumericField(prompt, defaultValue, decimalPlaces);
396  gd.showDialog();
397  if (gd.wasCanceled())
398  return CANCELED;
399  double v = gd.getNextNumber();
400  if (gd.invalidNumber())
401  return defaultValue;
402  else
403  return v;
404  }
405 
408  public static String getString(String prompt, String defaultString) {
409  GenericDialog gd = new GenericDialog("");
410  gd.addStringField(prompt, defaultString, 20);
411  gd.showDialog();
412  if (gd.wasCanceled())
413  return "";
414  return gd.getNextString();
415  }
416 
418  public synchronized static void wait(int msecs) {
419  try {Thread.sleep(msecs);}
420  catch (InterruptedException e) { }
421  }
422 
424  public static void beep() {
425  java.awt.Toolkit.getDefaultToolkit().beep();
426  }
427 
428  public static String freeMemory() {
429  System.gc();
430  long freeMem = Runtime.getRuntime().freeMemory();
431  long totMem = Runtime.getRuntime().totalMemory();
432  long inUse = (int)(totMem-freeMem);
433  String inUseStr = inUse<10000*1024?inUse/1024L+"K":inUse/1048576L+"MB";
434  String maxStr="";
435  long max = maxMemory();
436  if (max>0L) {
437  double percent = inUse*100/max;
438  maxStr = " of "+max/1048576L+"MB ("+(percent<1.0?"<1":d2s(percent,0)) + "%)";
439  }
440  return inUseStr + maxStr;
441  }
442 
445  public static long maxMemory() {
446  if (maxMemory==0L) {
447  Memory mem = new Memory();
448  maxMemory = mem.getMemorySetting();
449  if (maxMemory==0L) maxMemory = mem.maxMemory();
450  }
451  return maxMemory;
452  }
453 
454  public static void showTime(ImagePlus imp, long start, String str) {
455  showTime(imp, start, str, 1);
456  }
457 
458  static void showTime(ImagePlus imp, long start, String str, int nslices) {
459  long elapsedTime = System.currentTimeMillis() - start;
460  double seconds = elapsedTime / 1000.0;
461  long pixels = imp.getWidth() * imp.getHeight();
462  int rate = (int)((double)pixels*nslices/seconds);
463  String str2;
464  if (rate>1000000000)
465  str2 = "";
466  else if (rate<1000000)
467  str2 = ", "+rate+" pixels/second";
468  else
469  str2 = ", "+d2s(rate/1000000.0,1)+" million pixels/second";
470  showStatus(str+seconds+" seconds"+str2);
471  }
472 
475  public static String d2s(double n) {
476  return d2s(n, 2);
477  }
478 
479  private static DecimalFormat df =
480  new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.US));
481  private static int dfDigits = 2;
482 
486  public static String d2s(double n, int decimalPlaces) {
487  if (n==Float.MAX_VALUE) // divide by 0 in FloatProcessor
488  return "3.4e38";
489  boolean negative = n<0.0;
490  if (negative)
491  n = -n;
492  double whole = Math.round(n * Math.pow(10, decimalPlaces));
493  double rounded = whole/Math.pow(10, decimalPlaces);
494  if (negative)
495  rounded = -rounded;
496  if (decimalPlaces!=dfDigits)
497  switch (decimalPlaces) {
498  case 0: df.applyPattern("0"); dfDigits=0; break;
499  case 1: df.applyPattern("0.0"); dfDigits=1; break;
500  case 2: df.applyPattern("0.00"); dfDigits=2; break;
501  case 3: df.applyPattern("0.000"); dfDigits=3; break;
502  case 4: df.applyPattern("0.0000"); dfDigits=4; break;
503  case 5: df.applyPattern("0.00000"); dfDigits=5; break;
504  case 6: df.applyPattern("0.000000"); dfDigits=6; break;
505  case 7: df.applyPattern("0.0000000"); dfDigits=7; break;
506  case 8: df.applyPattern("0.00000000"); dfDigits=8; break;
507  }
508  String s = df.format(rounded);
509  return s;
510  }
511 
514  public static void register(Class c) {
515  if (ij!=null) ij.register(c);
516  }
517 
519  public static boolean spaceBarDown() {
520  return spaceDown;
521  }
522 
524  public static boolean altKeyDown() {
525  return altDown;
526  }
527 
529  public static boolean shiftKeyDown() {
530  return shiftDown;
531  }
532 
533  public static void setKeyDown(int key) {
534  switch (key) {
535  case KeyEvent.VK_ALT:
536  altDown=true;
537  break;
538  case KeyEvent.VK_SHIFT:
539  shiftDown=true;
540  break;
541  }
542  }
543 
544  public static void setKeyUp(int key) {
545  switch (key) {
546  case KeyEvent.VK_ALT: altDown=false; break;
547  case KeyEvent.VK_SHIFT: shiftDown=false; break;
548  }
549  }
550 
551  public static void setInputEvent(InputEvent e) {
552  altDown = e.isAltDown();
553  shiftDown = e.isShiftDown();
554  }
555 
557  public static boolean isMacintosh() {
558  return isMac;
559  }
560 
562  public static boolean isMacOSX() {
563  return isMacintosh() && isJava2();
564  }
565 
567  public static boolean isWindows() {
568  return isWin;
569  }
570 
572  public static boolean isJava2() {
573  return isJava2;
574  }
575 
577  public static boolean isJava14() {
578  return isJava14;
579  }
580 
583  public static boolean versionLessThan(String version) {
584  boolean lessThan = ImageJ.VERSION.compareTo(version)<0;
585  if (lessThan)
586  error("This plugin or macro requires ImageJ "+version+" or later.");
587  return lessThan;
588  }
589 
595  public static int setupDialog(ImagePlus imp, int flags) {
596  return flags;
597  }
598 
601  public static void makeRectangle(int x, int y, int width, int height) {
602  if (width<=0 || height<0)
603  getImage().killRoi();
604  else
605  getImage().setRoi(x, y, width, height);
606  }
607 
610  public static void makeOval(int x, int y, int width, int height) {
611  if (width<=0 || height<0)
612  getImage().killRoi();
613  else
614  getImage().setRoi(new OvalRoi(x, y, width, height));
615  }
616 
618  public static void makeLine(int x1, int y1, int x2, int y2) {
619  getImage().setRoi(new Line(x1, y1, x2, y2));
620  //wait(100);
621  }
622 
624  public static void setMinAndMax(double min, double max) {
625  ImagePlus img = getImage();
626  img.getProcessor().setMinAndMax(min, max);
627  img.updateAndDraw();
628  }
629 
632  public static void resetMinAndMax() {
633  ImagePlus img = getImage();
634  img.getProcessor().resetMinAndMax();
635  img.updateAndDraw();
636  }
637 
639  public static void setThreshold(double lowerThreshold, double upperThresold) {
640  ImagePlus img = getImage();
641  img.getProcessor().setThreshold(lowerThreshold,upperThresold,ImageProcessor.RED_LUT);
642  img.updateAndDraw();
643  }
644 
646  public static void resetThreshold() {
647  ImagePlus img = getImage();
648  img.getProcessor().resetThreshold();
649  img.updateAndDraw();
650  }
651 
654  public static void selectWindow(int id) {
655  }
656 
657  static void selectWindow(Frame frame) {
658 
659  }
660 
662  public static void setForegroundColor(int red, int green, int blue) {
663  setColor(red, green, blue, true);
664  }
665 
667  public static void setBackgroundColor(int red, int green, int blue) {
668  setColor(red, green, blue, false);
669  }
670 
671  static void setColor(int red, int green, int blue, boolean foreground) {
672  if (red<0) red=0; if (green<0) green=0; if (blue<0) blue=0;
673  if (red>255) red=255; if (green>255) green=255; if (blue>255) blue=255;
674  Color c = new Color(red, green, blue);
675  if (foreground) {
676  Toolbar.setForegroundColor(c);
677  ImagePlus img = IJ.getInstance().getImagePlus();
678  if (img!=null)
679  img.getProcessor().setColor(c);
680  } else
681  Toolbar.setBackgroundColor(c);
682  }
683 
686  public static void setTool(int id) {
687  Toolbar.getInstance().setTool(id);
688  }
689 
692  public static int doWand(int x, int y) {
693  ImagePlus img = getImage();
694  ImageProcessor ip = img.getProcessor();
695  Wand w = new Wand(ip);
696  double t1 = ip.getMinThreshold();
697  if (t1==ip.NO_THRESHOLD)
698  w.autoOutline(x, y);
699  else
700  w.autoOutline(x, y, (int)t1, (int)ip.getMaxThreshold());
701  if (w.npoints>0) {
702  Roi roi = new PolygonRoi(w.xpoints, w.ypoints, w.npoints, Roi.TRACED_ROI);
703  img.setRoi(roi);
704  if (shiftKeyDown() || altKeyDown())
705  roi.modifyRoi();
706  }
707  return w.npoints;
708  }
709 
712  public static void setPasteMode(String mode) {
713  mode = mode.toLowerCase(Locale.US);
714  int m = Blitter.COPY;
715  if (mode.startsWith("ble") || mode.startsWith("ave"))
716  m = Blitter.AVERAGE;
717  else if (mode.startsWith("diff"))
718  m = Blitter.DIFFERENCE;
719  else if (mode.startsWith("tran"))
720  m = Blitter.COPY_TRANSPARENT;
721  else if (mode.startsWith("and"))
722  m = Blitter.AND;
723  else if (mode.startsWith("or"))
724  m = Blitter.OR;
725  else if (mode.startsWith("xor"))
726  m = Blitter.XOR;
727  else if (mode.startsWith("sub"))
728  m = Blitter.SUBTRACT;
729  else if (mode.startsWith("add"))
730  m = Blitter.ADD;
731  else if (mode.startsWith("div"))
732  m = Blitter.DIVIDE;
733  else if (mode.startsWith("mul"))
734  m = Blitter.MULTIPLY;
735  Roi.setPasteMode(m);
736  }
737 
740  public static ImagePlus getImage() {
741  ImagePlus img = IJ.getInstance().getImagePlus();
742  if (img==null) {
743  IJ.noImage();
744  abort();
745  }
746  return img;
747  }
748 
750  public static String getVersion() {
751  return ImageJ.VERSION;
752  }
753 
760  public static String getDirectory(String title) {
761  // Not applicable to applet version
762  return "";
763  }
764 
765  static void abort() {
766  throw new RuntimeException("Macro canceled");
767  }
768 
769 }