PageRenderTime 72ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/ij/IJ.java

https://gitlab.com/jnorthrup1/imagej
Java | 1880 lines | 1490 code | 145 blank | 245 comment | 349 complexity | ab516c6958d03fc29030a639b5e79b50 MD5 | raw file
  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 ij.macro.Interpreter;
  11. import ij.measure.Calibration;
  12. import ij.measure.ResultsTable;
  13. import java.awt.event.*;
  14. import java.text.*;
  15. import java.util.*;
  16. import java.awt.*;
  17. import java.applet.Applet;
  18. import java.io.*;
  19. import java.lang.reflect.*;
  20. import java.net.*;
  21. /** This class consists of static utility methods. */
  22. public class IJ {
  23. public static final String URL = "http://imagej.nih.gov/ij";
  24. public static final int ALL_KEYS = -1;
  25. public static boolean debugMode;
  26. public static boolean hideProcessStackDialog;
  27. public static final char micronSymbol = '\u00B5';
  28. public static final char angstromSymbol = '\u00C5';
  29. public static final char degreeSymbol = '\u00B0';
  30. private static ImageJ ij;
  31. private static java.applet.Applet applet;
  32. private static ProgressBar progressBar;
  33. private static TextPanel textPanel;
  34. private static String osname, osarch;
  35. private static boolean isMac, isWin, isJava2, isJava14, isJava15, isJava16, isJava17, isLinux, isVista, is64Bit;
  36. private static boolean controlDown, altDown, spaceDown, shiftDown;
  37. private static boolean macroRunning;
  38. private static Thread previousThread;
  39. private static TextPanel logPanel;
  40. private static boolean checkForDuplicatePlugins = true;
  41. private static ClassLoader classLoader;
  42. private static boolean memMessageDisplayed;
  43. private static long maxMemory;
  44. private static boolean escapePressed;
  45. private static boolean redirectErrorMessages, redirectErrorMessages2;
  46. private static boolean suppressPluginNotFoundError;
  47. private static Hashtable commandTable;
  48. private static Vector eventListeners = new Vector();
  49. static {
  50. osname = System.getProperty("os.name");
  51. isWin = osname.startsWith("Windows");
  52. isMac = !isWin && osname.startsWith("Mac");
  53. isLinux = osname.startsWith("Linux");
  54. isVista = isWin && (osname.indexOf("Vista")!=-1||osname.indexOf(" 7")!=-1);
  55. String version = System.getProperty("java.version").substring(0,3);
  56. if (version.compareTo("2.9")<=0) { // JVM on Sharp Zaurus PDA claims to be "3.1"!
  57. isJava2 = version.compareTo("1.1")>0;
  58. isJava14 = version.compareTo("1.3")>0;
  59. isJava15 = version.compareTo("1.4")>0;
  60. isJava16 = version.compareTo("1.5")>0;
  61. isJava17 = version.compareTo("1.6")>0;
  62. }
  63. }
  64. static void init(ImageJ imagej, Applet theApplet) {
  65. ij = imagej;
  66. applet = theApplet;
  67. progressBar = ij.getProgressBar();
  68. }
  69. static void cleanup() {
  70. ij=null; applet=null; progressBar=null; textPanel=null;
  71. }
  72. /**Returns a reference to the "ImageJ" frame.*/
  73. public static ImageJ getInstance() {
  74. return ij;
  75. }
  76. /** Runs the macro contained in the string <code>macro</code>.
  77. Returns any string value returned by the macro, null if the macro
  78. does not return a value, or "[aborted]" if the macro was aborted
  79. due to an error. The equivalent macro function is eval(). */
  80. public static String runMacro(String macro) {
  81. return runMacro(macro, "");
  82. }
  83. /** Runs the macro contained in the string <code>macro</code>.
  84. The optional string argument can be retrieved in the
  85. called macro using the getArgument() macro function.
  86. Returns any string value returned by the macro, null if the macro
  87. does not return a value, or "[aborted]" if the macro was aborted
  88. due to an error. */
  89. public static String runMacro(String macro, String arg) {
  90. Macro_Runner mr = new Macro_Runner();
  91. return mr.runMacro(macro, arg);
  92. }
  93. /** Runs the specified macro or script file in the current thread.
  94. The file is assumed to be in the macros folder
  95. unless <code>name</code> is a full path. ".txt" is
  96. added if <code>name</code> does not have an extension.
  97. The optional string argument (<code>arg</code>) can be retrieved in the called
  98. macro or script (v1.42k or later) using the getArgument() function.
  99. Returns any string value returned by the macro, or null. Scripts always return null.
  100. The equivalent macro function is runMacro(). */
  101. public static String runMacroFile(String name, String arg) {
  102. if (ij==null && Menus.getCommands()==null)
  103. init();
  104. Macro_Runner mr = new Macro_Runner();
  105. return mr.runMacroFile(name, arg);
  106. }
  107. /** Runs the specified macro file. */
  108. public static String runMacroFile(String name) {
  109. return runMacroFile(name, null);
  110. }
  111. /** Runs the specified plugin using the specified image. */
  112. public static Object runPlugIn(ImagePlus imp, String className, String arg) {
  113. if (imp!=null) {
  114. ImagePlus temp = WindowManager.getTempCurrentImage();
  115. WindowManager.setTempCurrentImage(imp);
  116. Object o = runPlugIn("", className, arg);
  117. WindowManager.setTempCurrentImage(temp);
  118. return o;
  119. } else
  120. return runPlugIn(className, arg);
  121. }
  122. /** Runs the specified plugin and returns a reference to it. */
  123. public static Object runPlugIn(String className, String arg) {
  124. return runPlugIn("", className, arg);
  125. }
  126. /** Runs the specified plugin and returns a reference to it. */
  127. static Object runPlugIn(String commandName, String className, String arg) {
  128. if (IJ.debugMode)
  129. IJ.log("runPlugin: "+className+" "+arg);
  130. if (arg==null) arg = "";
  131. // Load using custom classloader if this is a user
  132. // plugin and we are not running as an applet
  133. if (!className.startsWith("ij.") && applet==null)
  134. return runUserPlugIn(commandName, className, arg, false);
  135. Object thePlugIn=null;
  136. try {
  137. Class c = Class.forName(className);
  138. thePlugIn = c.newInstance();
  139. if (thePlugIn instanceof PlugIn)
  140. ((PlugIn)thePlugIn).run(arg);
  141. else
  142. new PlugInFilterRunner(thePlugIn, commandName, arg);
  143. }
  144. catch (ClassNotFoundException e) {
  145. if (IJ.getApplet()==null)
  146. log("Plugin or class not found: \"" + className + "\"\n(" + e+")");
  147. }
  148. catch (InstantiationException e) {log("Unable to load plugin (ins)");}
  149. catch (IllegalAccessException e) {log("Unable to load plugin, possibly \nbecause it is not public.");}
  150. redirectErrorMessages = false;
  151. return thePlugIn;
  152. }
  153. static Object runUserPlugIn(String commandName, String className, String arg, boolean createNewLoader) {
  154. if (applet!=null) return null;
  155. if (checkForDuplicatePlugins) {
  156. // check for duplicate classes and jars in the plugins folder
  157. IJ.runPlugIn("ij.plugin.ClassChecker", "");
  158. checkForDuplicatePlugins = false;
  159. }
  160. if (createNewLoader) classLoader = null;
  161. ClassLoader loader = getClassLoader();
  162. Object thePlugIn = null;
  163. try {
  164. thePlugIn = (loader.loadClass(className)).newInstance();
  165. if (thePlugIn instanceof PlugIn)
  166. ((PlugIn)thePlugIn).run(arg);
  167. else if (thePlugIn instanceof PlugInFilter)
  168. new PlugInFilterRunner(thePlugIn, commandName, arg);
  169. }
  170. catch (ClassNotFoundException e) {
  171. if (className.indexOf('_')!=-1 && !suppressPluginNotFoundError)
  172. error("Plugin or class not found: \"" + className + "\"\n(" + e+")");
  173. }
  174. catch (NoClassDefFoundError e) {
  175. int dotIndex = className.indexOf('.');
  176. if (dotIndex >= 0)
  177. return runUserPlugIn(commandName, className.substring(dotIndex + 1), arg, createNewLoader);
  178. if (className.indexOf('_')!=-1 && !suppressPluginNotFoundError)
  179. error("Plugin or class not found: \"" + className + "\"\n(" + e+")");
  180. }
  181. catch (InstantiationException e) {error("Unable to load plugin (ins)");}
  182. catch (IllegalAccessException e) {error("Unable to load plugin, possibly \nbecause it is not public.");}
  183. if (redirectErrorMessages && !"HandleExtraFileTypes".equals(className))
  184. redirectErrorMessages = false;
  185. suppressPluginNotFoundError = false;
  186. return thePlugIn;
  187. }
  188. static void wrongType(int capabilities, String cmd) {
  189. String s = "\""+cmd+"\" requires an image of type:\n \n";
  190. if ((capabilities&PlugInFilter.DOES_8G)!=0) s += " 8-bit grayscale\n";
  191. if ((capabilities&PlugInFilter.DOES_8C)!=0) s += " 8-bit color\n";
  192. if ((capabilities&PlugInFilter.DOES_16)!=0) s += " 16-bit grayscale\n";
  193. if ((capabilities&PlugInFilter.DOES_32)!=0) s += " 32-bit (float) grayscale\n";
  194. if ((capabilities&PlugInFilter.DOES_RGB)!=0) s += " RGB color\n";
  195. error(s);
  196. }
  197. /** Starts executing a menu command in a separete thread and returns immediately. */
  198. public static void doCommand(String command) {
  199. if (ij!=null)
  200. ij.doCommand(command);
  201. }
  202. /** Runs an ImageJ command. Does not return until
  203. the command has finished executing. To avoid "image locked",
  204. errors, plugins that call this method should implement
  205. the PlugIn interface instead of PlugInFilter. */
  206. public static void run(String command) {
  207. run(command, null);
  208. }
  209. /** Runs an ImageJ command, with options that are passed to the
  210. GenericDialog and OpenDialog classes. Does not return until
  211. the command has finished executing. */
  212. public static void run(String command, String options) {
  213. //IJ.log("run1: "+command+" "+Thread.currentThread().hashCode());
  214. if (ij==null && Menus.getCommands()==null)
  215. init();
  216. Macro.abort = false;
  217. Macro.setOptions(options);
  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. command = convert(command);
  225. previousThread = thread;
  226. macroRunning = true;
  227. Executer e = new Executer(command);
  228. e.run();
  229. macroRunning = false;
  230. Macro.setOptions(null);
  231. testAbort();
  232. //IJ.log("run2: "+command+" "+Thread.currentThread().hashCode());
  233. }
  234. /** Converts commands that have been renamed so
  235. macros using the old names continue to work. */
  236. private static String convert(String command) {
  237. if (commandTable==null) {
  238. commandTable = new Hashtable(23); // initial capacity should be increased as needed
  239. commandTable.put("New...", "Image...");
  240. commandTable.put("Threshold", "Make Binary");
  241. commandTable.put("Display...", "Appearance...");
  242. commandTable.put("Start Animation", "Start Animation [\\]");
  243. commandTable.put("Convert Images to Stack", "Images to Stack");
  244. commandTable.put("Convert Stack to Images", "Stack to Images");
  245. commandTable.put("Convert Stack to RGB", "Stack to RGB");
  246. commandTable.put("Convert to Composite", "Make Composite");
  247. commandTable.put("New HyperStack...", "New Hyperstack...");
  248. commandTable.put("Stack to HyperStack...", "Stack to Hyperstack...");
  249. commandTable.put("HyperStack to Stack", "Hyperstack to Stack");
  250. commandTable.put("RGB Split", "Split Channels");
  251. commandTable.put("RGB Merge...", "Merge Channels...");
  252. commandTable.put("Channels...", "Channels Tool...");
  253. commandTable.put("New... ", "Table...");
  254. commandTable.put("Arbitrarily...", "Rotate... ");
  255. commandTable.put("Measurements...", "Results... ");
  256. commandTable.put("List Commands...", "Find Commands...");
  257. commandTable.put("Capture Screen ", "Capture Screen");
  258. commandTable.put("Add to Manager ", "Add to Manager");
  259. commandTable.put("In", "In [+]");
  260. commandTable.put("Out", "Out [-]");
  261. }
  262. String command2 = (String)commandTable.get(command);
  263. if (command2!=null)
  264. return command2;
  265. else
  266. return command;
  267. }
  268. /** Runs an ImageJ command using the specified image and options. */
  269. public static void run(ImagePlus imp, String command, String options) {
  270. if (imp!=null) {
  271. ImagePlus temp = WindowManager.getTempCurrentImage();
  272. WindowManager.setTempCurrentImage(imp);
  273. run(command, options);
  274. WindowManager.setTempCurrentImage(temp);
  275. } else
  276. run(command, options);
  277. }
  278. static void init() {
  279. Menus m = new Menus(null, null);
  280. Prefs.load(m, null);
  281. m.addMenuBar();
  282. }
  283. private static void testAbort() {
  284. if (Macro.abort)
  285. abort();
  286. }
  287. /** Returns true if the run(), open() or newImage() method is executing. */
  288. public static boolean macroRunning() {
  289. return macroRunning;
  290. }
  291. /** Returns true if a macro is running, or if the run(), open()
  292. or newImage() method is executing. */
  293. public static boolean isMacro() {
  294. return macroRunning || Interpreter.getInstance()!=null;
  295. }
  296. /**Returns the Applet that created this ImageJ or null if running as an application.*/
  297. public static java.applet.Applet getApplet() {
  298. return applet;
  299. }
  300. /**Displays a message in the ImageJ status bar.*/
  301. public static void showStatus(String s) {
  302. if (ij!=null) ij.showStatus(s);
  303. ImagePlus imp = WindowManager.getCurrentImage();
  304. ImageCanvas ic = imp!=null?imp.getCanvas():null;
  305. if (ic!=null)
  306. ic.setShowCursorStatus(s.length()==0?true:false);
  307. }
  308. /**
  309. * @deprecated
  310. * replaced by IJ.log(), ResultsTable.setResult() and TextWindow.append().
  311. * There are examples at
  312. * http://imagej.nih.gov/ij/plugins/sine-cosine.html
  313. */
  314. public static void write(String s) {
  315. if (textPanel==null && ij!=null)
  316. showResults();
  317. if (textPanel!=null)
  318. textPanel.append(s);
  319. else
  320. System.out.println(s);
  321. }
  322. private static void showResults() {
  323. TextWindow resultsWindow = new TextWindow("Results", "", 400, 250);
  324. textPanel = resultsWindow.getTextPanel();
  325. textPanel.setResultsTable(Analyzer.getResultsTable());
  326. }
  327. public static synchronized void log(String s) {
  328. if (s==null) return;
  329. if (logPanel==null && ij!=null) {
  330. TextWindow logWindow = new TextWindow("Log", "", 400, 250);
  331. logPanel = logWindow.getTextPanel();
  332. logPanel.setFont(new Font("SansSerif", Font.PLAIN, 16));
  333. }
  334. if (logPanel!=null) {
  335. if (s.startsWith("\\"))
  336. handleLogCommand(s);
  337. else
  338. logPanel.append(s);
  339. } else
  340. System.out.println(s);
  341. }
  342. static void handleLogCommand(String s) {
  343. if (s.equals("\\Closed"))
  344. logPanel = null;
  345. else if (s.startsWith("\\Update:")) {
  346. int n = logPanel.getLineCount();
  347. String s2 = s.substring(8, s.length());
  348. if (n==0)
  349. logPanel.append(s2);
  350. else
  351. logPanel.setLine(n-1, s2);
  352. } else if (s.startsWith("\\Update")) {
  353. int cindex = s.indexOf(":");
  354. if (cindex==-1)
  355. {logPanel.append(s); return;}
  356. String nstr = s.substring(7, cindex);
  357. int line = (int)Tools.parseDouble(nstr, -1);
  358. if (line<0 || line>25)
  359. {logPanel.append(s); return;}
  360. int count = logPanel.getLineCount();
  361. while (line>=count) {
  362. log("");
  363. count++;
  364. }
  365. String s2 = s.substring(cindex+1, s.length());
  366. logPanel.setLine(line, s2);
  367. } else if (s.equals("\\Clear")) {
  368. logPanel.clear();
  369. } else if (s.equals("\\Close")) {
  370. Frame f = WindowManager.getFrame("Log");
  371. if (f!=null && (f instanceof TextWindow))
  372. ((TextWindow)f).close();
  373. } else
  374. logPanel.append(s);
  375. }
  376. /** Returns the contents of the Log window or null if the Log window is not open. */
  377. public static synchronized String getLog() {
  378. if (logPanel==null || ij==null)
  379. return null;
  380. else
  381. return logPanel.getText();
  382. }
  383. /** Clears the "Results" window and sets the column headings to
  384. those in the tab-delimited 'headings' String. Writes to
  385. System.out.println if the "ImageJ" frame is not present.*/
  386. public static void setColumnHeadings(String headings) {
  387. if (textPanel==null && ij!=null)
  388. showResults();
  389. if (textPanel!=null)
  390. textPanel.setColumnHeadings(headings);
  391. else
  392. System.out.println(headings);
  393. }
  394. /** Returns true if the "Results" window is open. */
  395. public static boolean isResultsWindow() {
  396. return textPanel!=null;
  397. }
  398. /** Renames a results window. */
  399. public static void renameResults(String title) {
  400. Frame frame = WindowManager.getFrontWindow();
  401. if (frame!=null && (frame instanceof TextWindow)) {
  402. TextWindow tw = (TextWindow)frame;
  403. if (tw.getTextPanel().getResultsTable()==null) {
  404. IJ.error("Rename", "\""+tw.getTitle()+"\" is not a results table");
  405. return;
  406. }
  407. tw.rename(title);
  408. } else if (isResultsWindow()) {
  409. TextPanel tp = getTextPanel();
  410. TextWindow tw = (TextWindow)tp.getParent();
  411. tw.rename(title);
  412. }
  413. }
  414. /** Changes the name of a results window from 'oldTitle' to 'newTitle'. */
  415. public static void renameResults(String oldTitle, String newTitle) {
  416. Frame frame = WindowManager.getFrame(oldTitle);
  417. if (frame==null) {
  418. error("Rename", "\""+oldTitle+"\" not found");
  419. return;
  420. } else if (frame instanceof TextWindow) {
  421. TextWindow tw = (TextWindow)frame;
  422. if (tw.getTextPanel().getResultsTable()==null) {
  423. error("Rename", "\""+oldTitle+"\" is not a results table");
  424. return;
  425. }
  426. tw.rename(newTitle);
  427. } else
  428. error("Rename", "\""+oldTitle+"\" is not a results table");
  429. }
  430. /** Deletes 'row1' through 'row2' of the "Results" window. Arguments
  431. must be in the range 0-Analyzer.getCounter()-1. */
  432. public static void deleteRows(int row1, int row2) {
  433. int n = row2 - row1 + 1;
  434. ResultsTable rt = Analyzer.getResultsTable();
  435. for (int i=row1; i<row1+n; i++)
  436. rt.deleteRow(row1);
  437. rt.show("Results");
  438. }
  439. /** Returns a reference to the "Results" window TextPanel.
  440. Opens the "Results" window if it is currently not open.
  441. Returns null if the "ImageJ" window is not open. */
  442. public static TextPanel getTextPanel() {
  443. if (textPanel==null && ij!=null)
  444. showResults();
  445. return textPanel;
  446. }
  447. /** TextWindow calls this method with a null argument when the "Results" window is closed. */
  448. public static void setTextPanel(TextPanel tp) {
  449. textPanel = tp;
  450. }
  451. /**Displays a "no images are open" dialog box.*/
  452. public static void noImage() {
  453. error("No Image", "There are no images open.");
  454. }
  455. /** Displays an "out of memory" message to the "Log" window. */
  456. public static void outOfMemory(String name) {
  457. Undo.reset();
  458. System.gc();
  459. String tot = Runtime.getRuntime().totalMemory()/1048576L+"MB";
  460. if (!memMessageDisplayed)
  461. log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
  462. log("<Out of memory>");
  463. if (!memMessageDisplayed) {
  464. log("<All available memory ("+tot+") has been>");
  465. log("<used. Instructions for making more>");
  466. log("<available can be found in the \"Memory\" >");
  467. log("<sections of the installation notes at>");
  468. log("<"+IJ.URL+"/docs/install/>");
  469. log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
  470. memMessageDisplayed = true;
  471. }
  472. Macro.abort();
  473. }
  474. /** Updates the progress bar, where 0<=progress<=1.0. The progress bar is
  475. not shown in BatchMode and erased if progress>=1.0. The progress bar is
  476. updated only if more than 90 ms have passes since the last call. Does nothing
  477. if the ImageJ window is not present. */
  478. public static void showProgress(double progress) {
  479. if (progressBar!=null) progressBar.show(progress, false);
  480. }
  481. /** Updates the progress bar, where the length of the bar is set to
  482. (<code>currentValue+1)/finalValue</code> of the maximum bar length.
  483. The bar is erased if <code>currentValue&gt;=finalValue</code>.
  484. The bar is updated only if more than 90 ms have passed since the last call.
  485. Does nothing if the ImageJ window is not present. */
  486. public static void showProgress(int currentIndex, int finalIndex) {
  487. if (progressBar!=null) {
  488. progressBar.show(currentIndex, finalIndex);
  489. if (currentIndex==finalIndex)
  490. progressBar.setBatchMode(false);
  491. }
  492. }
  493. /** Displays a message in a dialog box titled "Message".
  494. Writes the Java console if ImageJ is not present. */
  495. public static void showMessage(String msg) {
  496. showMessage("Message", msg);
  497. }
  498. /** Displays a message in a dialog box with the specified title.
  499. Displays HTML formatted text if 'msg' starts with "<html>".
  500. There are examples at
  501. "http://imagej.nih.gov/ij/macros/HtmlDialogDemo.txt".
  502. Writes to the Java console if ImageJ is not present. */
  503. public static void showMessage(String title, String msg) {
  504. if (ij!=null) {
  505. if (msg!=null && msg.startsWith("<html>")) {
  506. HTMLDialog hd = new HTMLDialog(title, msg);
  507. if (isMacro() && hd.escapePressed())
  508. throw new RuntimeException(Macro.MACRO_CANCELED);
  509. } else {
  510. MessageDialog md = new MessageDialog(ij, title, msg);
  511. if (isMacro() && md.escapePressed())
  512. throw new RuntimeException(Macro.MACRO_CANCELED);
  513. }
  514. } else
  515. System.out.println(msg);
  516. }
  517. /** Displays a message in a dialog box titled "ImageJ". If a
  518. macro is running, it is aborted. Writes to the Java console
  519. if the ImageJ window is not present.*/
  520. public static void error(String msg) {
  521. error(null, msg);
  522. if (Thread.currentThread().getName().endsWith("JavaScript"))
  523. throw new RuntimeException(Macro.MACRO_CANCELED);
  524. else
  525. Macro.abort();
  526. }
  527. /**Displays a message in a dialog box with the specified title.
  528. If a macro is running, it is aborted. Writes to the Java
  529. console if ImageJ is not present. */
  530. public static void error(String title, String msg) {
  531. String title2 = title!=null?title:"ImageJ";
  532. boolean abortMacro = title!=null;
  533. if (redirectErrorMessages || redirectErrorMessages2) {
  534. IJ.log(title2 + ": " + msg);
  535. if (abortMacro && (title.equals("Opener")||title.equals("Open URL")||title.equals("DicomDecoder")))
  536. abortMacro = false;
  537. } else
  538. showMessage(title2, msg);
  539. redirectErrorMessages = false;
  540. if (abortMacro) Macro.abort();
  541. }
  542. /** Displays a message in a dialog box with the specified title.
  543. Returns false if the user pressed "Cancel". */
  544. public static boolean showMessageWithCancel(String title, String msg) {
  545. GenericDialog gd = new GenericDialog(title);
  546. gd.addMessage(msg);
  547. gd.showDialog();
  548. return !gd.wasCanceled();
  549. }
  550. public static final int CANCELED = Integer.MIN_VALUE;
  551. /** Allows the user to enter a number in a dialog box. Returns the
  552. value IJ.CANCELED (-2,147,483,648) if the user cancels the dialog box.
  553. Returns 'defaultValue' if the user enters an invalid number. */
  554. public static double getNumber(String prompt, double defaultValue) {
  555. GenericDialog gd = new GenericDialog("");
  556. int decimalPlaces = (int)defaultValue==defaultValue?0:2;
  557. gd.addNumericField(prompt, defaultValue, decimalPlaces);
  558. gd.showDialog();
  559. if (gd.wasCanceled())
  560. return CANCELED;
  561. double v = gd.getNextNumber();
  562. if (gd.invalidNumber())
  563. return defaultValue;
  564. else
  565. return v;
  566. }
  567. /** Allows the user to enter a string in a dialog box. Returns
  568. "" if the user cancels the dialog box. */
  569. public static String getString(String prompt, String defaultString) {
  570. GenericDialog gd = new GenericDialog("");
  571. gd.addStringField(prompt, defaultString, 20);
  572. gd.showDialog();
  573. if (gd.wasCanceled())
  574. return "";
  575. return gd.getNextString();
  576. }
  577. /**Delays 'msecs' milliseconds.*/
  578. public static void wait(int msecs) {
  579. try {Thread.sleep(msecs);}
  580. catch (InterruptedException e) { }
  581. }
  582. /** Emits an audio beep. */
  583. public static void beep() {
  584. java.awt.Toolkit.getDefaultToolkit().beep();
  585. }
  586. /** Runs the garbage collector and returns a string something
  587. like "64K of 256MB (25%)" that shows how much of
  588. the available memory is in use. This is the string
  589. displayed when the user clicks in the status bar. */
  590. public static String freeMemory() {
  591. long inUse = currentMemory();
  592. String inUseStr = inUse<10000*1024?inUse/1024L+"K":inUse/1048576L+"MB";
  593. String maxStr="";
  594. long max = maxMemory();
  595. if (max>0L) {
  596. double percent = inUse*100/max;
  597. maxStr = " of "+max/1048576L+"MB ("+(percent<1.0?"<1":d2s(percent,0)) + "%)";
  598. }
  599. return inUseStr + maxStr;
  600. }
  601. /** Returns the amount of memory currently being used by ImageJ. */
  602. public static long currentMemory() {
  603. long freeMem = Runtime.getRuntime().freeMemory();
  604. long totMem = Runtime.getRuntime().totalMemory();
  605. return totMem-freeMem;
  606. }
  607. /** Returns the maximum amount of memory available to ImageJ or
  608. zero if ImageJ is unable to determine this limit. */
  609. public static long maxMemory() {
  610. if (maxMemory==0L) {
  611. Memory mem = new Memory();
  612. maxMemory = mem.getMemorySetting();
  613. if (maxMemory==0L) maxMemory = mem.maxMemory();
  614. }
  615. return maxMemory;
  616. }
  617. public static void showTime(ImagePlus imp, long start, String str) {
  618. showTime(imp, start, str, 1);
  619. }
  620. public static void showTime(ImagePlus imp, long start, String str, int nslices) {
  621. if (Interpreter.isBatchMode()) return;
  622. double seconds = (System.currentTimeMillis()-start)/1000.0;
  623. double pixels = (double)imp.getWidth() * imp.getHeight();
  624. double rate = pixels*nslices/seconds;
  625. String str2;
  626. if (rate>1000000000.0)
  627. str2 = "";
  628. else if (rate<1000000.0)
  629. str2 = ", "+d2s(rate,0)+" pixels/second";
  630. else
  631. str2 = ", "+d2s(rate/1000000.0,1)+" million pixels/second";
  632. showStatus(str+seconds+" seconds"+str2);
  633. }
  634. /** Experimental */
  635. public static String time(ImagePlus imp, long startNanoTime) {
  636. double planes = imp.getStackSize();
  637. double seconds = (System.nanoTime()-startNanoTime)/1000000000.0;
  638. double mpixels = imp.getWidth()*imp.getHeight()*planes/1000000.0;
  639. String time = seconds<1.0?d2s(seconds*1000.0,0)+" ms":d2s(seconds,1)+" seconds";
  640. return time+", "+d2s(mpixels/seconds,1)+" million pixels/second";
  641. }
  642. /** Converts a number to a formatted string using
  643. 2 digits to the right of the decimal point. */
  644. public static String d2s(double n) {
  645. return d2s(n, 2);
  646. }
  647. private static DecimalFormat[] df;
  648. private static DecimalFormat[] sf;
  649. private static DecimalFormatSymbols dfs;
  650. /** Converts a number to a rounded formatted string.
  651. The 'decimalPlaces' argument specifies the number of
  652. digits to the right of the decimal point (0-9). Uses
  653. scientific notation if 'decimalPlaces is negative. */
  654. public static String d2s(double n, int decimalPlaces) {
  655. if (Double.isNaN(n)||Double.isInfinite(n))
  656. return ""+n;
  657. if (n==Float.MAX_VALUE) // divide by 0 in FloatProcessor
  658. return "3.4e38";
  659. double np = n;
  660. if (n<0.0) np = -n;
  661. if (df==null) {
  662. dfs = new DecimalFormatSymbols(Locale.US);
  663. df = new DecimalFormat[10];
  664. df[0] = new DecimalFormat("0", dfs);
  665. df[1] = new DecimalFormat("0.0", dfs);
  666. df[2] = new DecimalFormat("0.00", dfs);
  667. df[3] = new DecimalFormat("0.000", dfs);
  668. df[4] = new DecimalFormat("0.0000", dfs);
  669. df[5] = new DecimalFormat("0.00000", dfs);
  670. df[6] = new DecimalFormat("0.000000", dfs);
  671. df[7] = new DecimalFormat("0.0000000", dfs);
  672. df[8] = new DecimalFormat("0.00000000", dfs);
  673. df[9] = new DecimalFormat("0.000000000", dfs);
  674. }
  675. if (decimalPlaces<0) {
  676. decimalPlaces = -decimalPlaces;
  677. if (decimalPlaces>9) decimalPlaces=9;
  678. if (sf==null) {
  679. sf = new DecimalFormat[10];
  680. sf[1] = new DecimalFormat("0.0E0",dfs);
  681. sf[2] = new DecimalFormat("0.00E0",dfs);
  682. sf[3] = new DecimalFormat("0.000E0",dfs);
  683. sf[4] = new DecimalFormat("0.0000E0",dfs);
  684. sf[5] = new DecimalFormat("0.00000E0",dfs);
  685. sf[6] = new DecimalFormat("0.000000E0",dfs);
  686. sf[7] = new DecimalFormat("0.0000000E0",dfs);
  687. sf[8] = new DecimalFormat("0.00000000E0",dfs);
  688. sf[9] = new DecimalFormat("0.000000000E0",dfs);
  689. }
  690. return sf[decimalPlaces].format(n); // use scientific notation
  691. }
  692. if (decimalPlaces<0) decimalPlaces = 0;
  693. if (decimalPlaces>9) decimalPlaces = 9;
  694. return df[decimalPlaces].format(n);
  695. }
  696. /** Converts a number to a rounded formatted string.
  697. * The 'significantDigits' argument specifies the minimum number
  698. * of significant digits, which is also the preferred number of
  699. * digits behind the decimal. Fewer decimals are shown if the
  700. * number would have more than 'maxDigits'.
  701. * Exponential notation is used if more than 'maxDigits' would be needed.
  702. */
  703. public static String d2s(double x, int significantDigits, int maxDigits) {
  704. double log10 = Math.log10(Math.abs(x));
  705. double roundErrorAtMax = 0.223*Math.pow(10, -maxDigits);
  706. int magnitude = (int)Math.ceil(log10+roundErrorAtMax);
  707. int decimals = x==0 ? 0 : maxDigits - magnitude;
  708. if (decimals<0 || magnitude<significantDigits+1-maxDigits)
  709. return IJ.d2s(x, -significantDigits); // exp notation for large and small numbers
  710. else {
  711. if (decimals>significantDigits)
  712. decimals = Math.max(significantDigits, decimals-maxDigits+significantDigits);
  713. return IJ.d2s(x, decimals);
  714. }
  715. }
  716. /** Pad 'n' with leading zeros to the specified number of digits. */
  717. public static String pad(int n, int digits) {
  718. String str = ""+n;
  719. while (str.length()<digits)
  720. str = "0"+str;
  721. return str;
  722. }
  723. /** Adds the specified class to a Vector to keep it from being garbage
  724. collected, which would cause the classes static fields to be reset.
  725. Probably not needed with Java 1.2 or later. */
  726. public static void register(Class c) {
  727. if (ij!=null) ij.register(c);
  728. }
  729. /** Returns true if the space bar is down. */
  730. public static boolean spaceBarDown() {
  731. return spaceDown;
  732. }
  733. /** Returns true if the control key is down. */
  734. public static boolean controlKeyDown() {
  735. return controlDown;
  736. }
  737. /** Returns true if the alt key is down. */
  738. public static boolean altKeyDown() {
  739. return altDown;
  740. }
  741. /** Returns true if the shift key is down. */
  742. public static boolean shiftKeyDown() {
  743. return shiftDown;
  744. }
  745. public static void setKeyDown(int key) {
  746. if (debugMode) IJ.log("setKeyDown: "+key);
  747. switch (key) {
  748. case KeyEvent.VK_CONTROL:
  749. controlDown=true;
  750. break;
  751. case KeyEvent.VK_META:
  752. if (isMacintosh()) controlDown=true;
  753. break;
  754. case KeyEvent.VK_ALT:
  755. altDown=true;
  756. break;
  757. case KeyEvent.VK_SHIFT:
  758. shiftDown=true;
  759. if (debugMode) beep();
  760. break;
  761. case KeyEvent.VK_SPACE: {
  762. spaceDown=true;
  763. ImageWindow win = WindowManager.getCurrentWindow();
  764. if (win!=null) win.getCanvas().setCursor(-1,-1,-1, -1);
  765. break;
  766. }
  767. case KeyEvent.VK_ESCAPE: {
  768. escapePressed = true;
  769. break;
  770. }
  771. }
  772. }
  773. public static void setKeyUp(int key) {
  774. if (debugMode) IJ.log("setKeyUp: "+key);
  775. switch (key) {
  776. case KeyEvent.VK_CONTROL: controlDown=false; break;
  777. case KeyEvent.VK_META: if (isMacintosh()) controlDown=false; break;
  778. case KeyEvent.VK_ALT: altDown=false; break;
  779. case KeyEvent.VK_SHIFT: shiftDown=false; if (debugMode) beep(); break;
  780. case KeyEvent.VK_SPACE:
  781. spaceDown=false;
  782. ImageWindow win = WindowManager.getCurrentWindow();
  783. if (win!=null) win.getCanvas().setCursor(-1,-1,-1,-1);
  784. break;
  785. case ALL_KEYS:
  786. shiftDown=controlDown=altDown=spaceDown=false;
  787. break;
  788. }
  789. }
  790. public static void setInputEvent(InputEvent e) {
  791. altDown = e.isAltDown();
  792. shiftDown = e.isShiftDown();
  793. }
  794. /** Returns true if this machine is a Macintosh. */
  795. public static boolean isMacintosh() {
  796. return isMac;
  797. }
  798. /** Returns true if this machine is a Macintosh running OS X. */
  799. public static boolean isMacOSX() {
  800. return isMacintosh();
  801. }
  802. /** Returns true if this machine is running Windows. */
  803. public static boolean isWindows() {
  804. return isWin;
  805. }
  806. /** Always returns true. */
  807. public static boolean isJava2() {
  808. return isJava2;
  809. }
  810. /** Returns true if ImageJ is running on a Java 1.4 or greater JVM. */
  811. public static boolean isJava14() {
  812. return isJava14;
  813. }
  814. /** Returns true if ImageJ is running on a Java 1.5 or greater JVM. */
  815. public static boolean isJava15() {
  816. return isJava15;
  817. }
  818. /** Returns true if ImageJ is running on a Java 1.6 or greater JVM. */
  819. public static boolean isJava16() {
  820. return isJava16;
  821. }
  822. /** Returns true if ImageJ is running on a Java 1.7 or greater JVM. */
  823. public static boolean isJava17() {
  824. return isJava17;
  825. }
  826. /** Returns true if ImageJ is running on Linux. */
  827. public static boolean isLinux() {
  828. return isLinux;
  829. }
  830. /** Returns true if ImageJ is running on Windows Vista. */
  831. public static boolean isVista() {
  832. return isVista;
  833. }
  834. /** Returns true if ImageJ is running a 64-bit version of Java. */
  835. public static boolean is64Bit() {
  836. if (osarch==null)
  837. osarch = System.getProperty("os.arch");
  838. return osarch!=null && osarch.indexOf("64")!=-1;
  839. }
  840. /** Displays an error message and returns false if the
  841. ImageJ version is less than the one specified. */
  842. public static boolean versionLessThan(String version) {
  843. boolean lessThan = ImageJ.VERSION.compareTo(version)<0;
  844. if (lessThan)
  845. error("This plugin or macro requires ImageJ "+version+" or later. Use\nHelp>Update ImageJ to upgrade to the latest version.");
  846. return lessThan;
  847. }
  848. /** Displays a "Process all images?" dialog. Returns
  849. 'flags'+PlugInFilter.DOES_STACKS if the user selects "Yes",
  850. 'flags' if the user selects "No" and PlugInFilter.DONE
  851. if the user selects "Cancel".
  852. */
  853. public static int setupDialog(ImagePlus imp, int flags) {
  854. if (imp==null || (ij!=null&&ij.hotkey))
  855. return flags;
  856. int stackSize = imp.getStackSize();
  857. if (stackSize>1) {
  858. String macroOptions = Macro.getOptions();
  859. if (imp.isComposite() && ((CompositeImage)imp).getMode()==CompositeImage.COMPOSITE) {
  860. if (macroOptions==null || !macroOptions.contains("slice"))
  861. return flags+PlugInFilter.DOES_STACKS;
  862. }
  863. if (macroOptions!=null) {
  864. if (macroOptions.indexOf("stack ")>=0)
  865. return flags+PlugInFilter.DOES_STACKS;
  866. else
  867. return flags;
  868. }
  869. if (hideProcessStackDialog)
  870. return flags;
  871. String note = ((flags&PlugInFilter.NO_CHANGES)==0)?" There is\nno Undo if you select \"Yes\".":"";
  872. YesNoCancelDialog d = new YesNoCancelDialog(getInstance(),
  873. "Process Stack?", "Process all "+stackSize+" images?"+note);
  874. if (d.cancelPressed())
  875. return PlugInFilter.DONE;
  876. else if (d.yesPressed()) {
  877. if (imp.getStack().isVirtual() && ((flags&PlugInFilter.NO_CHANGES)==0)) {
  878. int size = (stackSize*imp.getWidth()*imp.getHeight()*imp.getBytesPerPixel()+524288)/1048576;
  879. String msg =
  880. "Use the Process>Batch>Virtual Stack command\n"+
  881. "to process a virtual stack ike this one or convert\n"+
  882. "it to a normal stack using Image>Duplicate, which\n"+
  883. "will require "+size+"MB of additional memory.";
  884. error(msg);
  885. return PlugInFilter.DONE;
  886. }
  887. if (Recorder.record)
  888. Recorder.recordOption("stack");
  889. return flags+PlugInFilter.DOES_STACKS;
  890. }
  891. if (Recorder.record)
  892. Recorder.recordOption("slice");
  893. }
  894. return flags;
  895. }
  896. /** Creates a rectangular selection. Removes any existing
  897. selection if width or height are less than 1. */
  898. public static void makeRectangle(int x, int y, int width, int height) {
  899. if (width<=0 || height<0)
  900. getImage().killRoi();
  901. else {
  902. ImagePlus img = getImage();
  903. if (Interpreter.isBatchMode())
  904. img.setRoi(new Roi(x,y,width,height), false);
  905. else
  906. img.setRoi(x, y, width, height);
  907. }
  908. }
  909. /** Creates an oval selection. Removes any existing
  910. selection if width or height are less than 1. */
  911. public static void makeOval(int x, int y, int width, int height) {
  912. if (width<=0 || height<0)
  913. getImage().killRoi();
  914. else {
  915. ImagePlus img = getImage();
  916. img.setRoi(new OvalRoi(x, y, width, height));
  917. }
  918. }
  919. /** Creates a straight line selection. */
  920. public static void makeLine(int x1, int y1, int x2, int y2) {
  921. getImage().setRoi(new Line(x1, y1, x2, y2));
  922. }
  923. /** Creates a straight line selection using floating point coordinates. */
  924. public static void makeLine(double x1, double y1, double x2, double y2) {
  925. getImage().setRoi(new Line(x1, y1, x2, y2));
  926. }
  927. /** Creates a point selection. */
  928. public static void makePoint(int x, int y) {
  929. ImagePlus img = getImage();
  930. Roi roi = img.getRoi();
  931. if (shiftKeyDown() && roi!=null && roi.getType()==Roi.POINT) {
  932. Polygon p = roi.getPolygon();
  933. p.addPoint(x, y);
  934. img.setRoi(new PointRoi(p.xpoints, p.ypoints, p.npoints));
  935. IJ.setKeyUp(KeyEvent.VK_SHIFT);
  936. } else if (altKeyDown() && roi!=null && roi.getType()==Roi.POINT) {
  937. ((PolygonRoi)roi).deleteHandle(x, y);
  938. IJ.setKeyUp(KeyEvent.VK_ALT);
  939. } else
  940. img.setRoi(new PointRoi(x, y));
  941. }
  942. /** Sets the display range (minimum and maximum displayed pixel values) of the current image. */
  943. public static void setMinAndMax(double min, double max) {
  944. setMinAndMax(getImage(), min, max, 7);
  945. }
  946. /** Sets the display range (minimum and maximum displayed pixel values) of the specified image. */
  947. public static void setMinAndMax(ImagePlus img, double min, double max) {
  948. setMinAndMax(img, min, max, 7);
  949. }
  950. /** Sets the minimum and maximum displayed pixel values on the specified RGB
  951. channels, where 4=red, 2=green and 1=blue. */
  952. public static void setMinAndMax(double min, double max, int channels) {
  953. setMinAndMax(getImage(), min, max, channels);
  954. }
  955. private static void setMinAndMax(ImagePlus img, double min, double max, int channels) {
  956. Calibration cal = img.getCalibration();
  957. min = cal.getRawValue(min);
  958. max = cal.getRawValue(max);
  959. if (channels==7)
  960. img.setDisplayRange(min, max);
  961. else
  962. img.setDisplayRange(min, max, channels);
  963. img.updateAndDraw();
  964. }
  965. /** Resets the minimum and maximum displayed pixel values of the
  966. current image to be the same as the min and max pixel values. */
  967. public static void resetMinAndMax() {
  968. resetMinAndMax(getImage());
  969. }
  970. /** Resets the minimum and maximum displayed pixel values of the
  971. specified image to be the same as the min and max pixel values. */
  972. public static void resetMinAndMax(ImagePlus img) {
  973. img.resetDisplayRange();
  974. img.updateAndDraw();
  975. }
  976. /** Sets the lower and upper threshold levels and displays the image
  977. using red to highlight thresholded pixels. May not work correctly on
  978. 16 and 32 bit images unless the display range has been reset using IJ.resetMinAndMax().
  979. */
  980. public static void setThreshold(double lowerThreshold, double upperThresold) {
  981. setThreshold(lowerThreshold, upperThresold, null);
  982. }
  983. /** Sets the lower and upper threshold levels and displays the image using
  984. the specified <code>displayMode</code> ("Red", "Black & White", "Over/Under" or "No Update"). */
  985. public static void setThreshold(double lowerThreshold, double upperThreshold, String displayMode) {
  986. setThreshold(getImage(), lowerThreshold, upperThreshold, displayMode);
  987. }
  988. /** Sets the lower and upper threshold levels of the specified image. */
  989. public static void setThreshold(ImagePlus img, double lowerThreshold, double upperThreshold) {
  990. setThreshold(img, lowerThreshold, upperThreshold, "Red");
  991. }
  992. /** Sets the lower and upper threshold levels of the specified image and updates the display using
  993. the specified <code>displayMode</code> ("Red", "Black & White", "Over/Under" or "No Update"). */
  994. public static void setThreshold(ImagePlus img, double lowerThreshold, double upperThreshold, String displayMode) {
  995. int mode = ImageProcessor.RED_LUT;
  996. if (displayMode!=null) {
  997. displayMode = displayMode.toLowerCase(Locale.US);
  998. if (displayMode.indexOf("black")!=-1)
  999. mode = ImageProcessor.BLACK_AND_WHITE_LUT;
  1000. else if (displayMode.indexOf("over")!=-1)
  1001. mode = ImageProcessor.OVER_UNDER_LUT;
  1002. else if (displayMode.indexOf("no")!=-1)
  1003. mode = ImageProcessor.NO_LUT_UPDATE;
  1004. }
  1005. Calibration cal = img.getCalibration();
  1006. lowerThreshold = cal.getRawValue(lowerThreshold);
  1007. upperThreshold = cal.getRawValue(upperThreshold);
  1008. img.getProcessor().setThreshold(lowerThreshold, upperThreshold, mode);
  1009. if (mode != ImageProcessor.NO_LUT_UPDATE) {
  1010. img.getProcessor().setLutAnimation(true);
  1011. img.updateAndDraw();
  1012. }
  1013. }
  1014. public static void setAutoThreshold(ImagePlus imp, String method) {
  1015. ImageProcessor ip = imp.getProcessor();
  1016. if (ip instanceof ColorProcessor)
  1017. throw new IllegalArgumentException("Non-RGB image required");
  1018. ip.setRoi(imp.getRoi());
  1019. if (method!=null) {
  1020. try {
  1021. if (method.indexOf("stack")!=-1)
  1022. setStackThreshold(imp, ip, method);
  1023. else
  1024. ip.setAutoThreshold(method);
  1025. } catch (Exception e) {
  1026. log(e.getMessage());
  1027. }
  1028. } else
  1029. ip.setAutoThreshold(ImageProcessor.ISODATA2, ImageProcessor.RED_LUT);
  1030. imp.updateAndDraw();
  1031. }
  1032. private static void setStackThreshold(ImagePlus imp, ImageProcessor ip, String method) {
  1033. boolean darkBackground = method.indexOf("dark")!=-1;
  1034. ImageStatistics stats = new StackStatistics(imp);
  1035. AutoThresholder thresholder = new AutoThresholder();
  1036. double min=0.0, max=255.0;
  1037. if (imp.getBitDepth()!=8) {
  1038. min = stats.min;
  1039. max = stats.max;
  1040. }
  1041. int threshold = thresholder.getThreshold(method, stats.histogram);
  1042. double lower, upper;
  1043. if (darkBackground) {
  1044. if (ip.isInvertedLut())
  1045. {lower=0.0; upper=threshold;}
  1046. else
  1047. {lower=threshold+1; upper=255.0;}
  1048. } else {
  1049. if (ip.isInvertedLut())
  1050. {lower=threshold+1; upper=255.0;}
  1051. else
  1052. {lower=0.0; upper=threshold;}
  1053. }
  1054. if (lower>255) lower = 255;
  1055. if (max>min) {
  1056. lower = min + (lower/255.0)*(max-min);
  1057. upper = min + (upper/255.0)*(max-min);
  1058. } else
  1059. lower = upper = min;
  1060. ip.setMinAndMax(min, max);
  1061. ip.setThreshold(lower, upper, ImageProcessor.RED_LUT);
  1062. imp.updateAndDraw();
  1063. }
  1064. /** Disables thresholding on the current image. */
  1065. public static void resetThreshold() {
  1066. resetThreshold(getImage());
  1067. }
  1068. /** Disables thresholding on the specified image. */
  1069. public static void resetThreshold(ImagePlus img) {
  1070. ImageProcessor ip = img.getProcessor();
  1071. ip.resetThreshold();
  1072. ip.setLutAnimation(true);
  1073. img.updateAndDraw();
  1074. }
  1075. /** For IDs less than zero, activates the image with the specified ID.
  1076. For IDs greater than zero, activates the Nth image. */
  1077. public static void selectWindow(int id) {
  1078. if (id>0)
  1079. id = WindowManager.getNthImageID(id);
  1080. ImagePlus imp = WindowManager.getImage(id);
  1081. if (imp==null)
  1082. error("Macro Error", "Image "+id+" not found or no images are open.");
  1083. if (Interpreter.isBatchMode()) {
  1084. ImagePlus impT = WindowManager.getTempCurrentImage();
  1085. ImagePlus impC = WindowManager.getCurrentImage();
  1086. if (impC!=null && impC!=imp && impT!=null)
  1087. impC.saveRoi();
  1088. WindowManager.setTempCurrentImage(imp);
  1089. WindowManager.setWindow(null);
  1090. } else {
  1091. ImageWindow win = imp.getWindow();
  1092. win.toFront();
  1093. WindowManager.setWindow(win);
  1094. long start = System.currentTimeMillis();
  1095. // timeout after 2 seconds unless current thread is event dispatch thread
  1096. String thread = Thread.currentThread().getName();
  1097. int timeout = thread!=null&&thread.indexOf("EventQueue")!=-1?0:2000;
  1098. while (true) {
  1099. wait(10);
  1100. imp = WindowManager.getCurrentImage();
  1101. if (imp!=null && imp.getID()==id)
  1102. return; // specified image is now active
  1103. if ((System.currentTimeMillis()-start)>timeout) {
  1104. WindowManager.setCurrentWindow(win);
  1105. return;
  1106. }
  1107. }
  1108. }
  1109. }
  1110. /** Activates the window with the specified title. */
  1111. public static void selectWindow(String title) {
  1112. if (title.equals("ImageJ")&&ij!=null)
  1113. {ij.toFront(); return;}
  1114. long start = System.currentTimeMillis();
  1115. while (System.currentTimeMillis()-start<3000) { // 3 sec timeout
  1116. Frame frame = WindowManager.getFrame(title);
  1117. if (frame!=null && !(frame instanceof ImageWindow)) {
  1118. selectWindow(frame);
  1119. return;
  1120. }
  1121. int[] wList = WindowManager.getIDList();
  1122. int len = wList!=null?wList.length:0;
  1123. for (int i=0; i<len; i++) {
  1124. ImagePlus imp = WindowManager.getImage(wList[i]);
  1125. if (imp!=null) {
  1126. if (imp.getTitle().equals(title)) {
  1127. selectWindow(imp.getID());
  1128. return;
  1129. }
  1130. }
  1131. }
  1132. wait(10);
  1133. }
  1134. error("Macro Error", "No window with the title \""+title+"\" found.");
  1135. }
  1136. static void selectWindow(Frame frame) {
  1137. frame.toFront();
  1138. long start = System.currentTimeMillis();
  1139. while (true) {
  1140. wait(10);
  1141. if (WindowManager.getFrontWindow()==frame)
  1142. return; // specified window is now in front
  1143. if ((System.currentTimeMillis()-start)>1000) {
  1144. WindowManager.setWindow(frame);
  1145. return; // 1 second timeout
  1146. }
  1147. }
  1148. }
  1149. /** Sets the foreground color. */
  1150. public static void setForegroundColor(int red, int green, int blue) {
  1151. setColor(red, green, blue, true);
  1152. }
  1153. /** Sets the background color. */
  1154. public static void setBackgroundColor(int red, int green, int blue) {
  1155. setColor(red, green, blue, false);
  1156. }
  1157. static void setColor(int red, int green, int blue, boolean foreground) {
  1158. if (red<0) red=0; if (green<0) green=0; if (blue<0) blue=0;
  1159. if (red>255) red=255; if (green>255) green=255; if (blue>255) blue=255;
  1160. Color c = new Color(red, green, blue);
  1161. if (foreground) {
  1162. Toolbar.setForegroundColor(c);
  1163. ImagePlus img = WindowManager.getCurrentImage();
  1164. if (img!=null)
  1165. img.getProcessor().setColor(c);
  1166. } else
  1167. Toolbar.setBackgroundColor(c);
  1168. }
  1169. /** Switches to the specified tool, where id = Toolbar.RECTANGLE (0),
  1170. Toolbar.OVAL (1), etc. */
  1171. public static void setTool(int id) {
  1172. Toolbar.getInstance().setTool(id);
  1173. }
  1174. /** Switches to the specified tool, where 'name' is "rect", "elliptical",
  1175. "brush", etc. Returns 'false' if the name is not recognized. */
  1176. public static boolean setTool(String name) {
  1177. return Toolbar.getInstance().setTool(name);
  1178. }
  1179. /** Returns the name of the current tool. */
  1180. public static String getToolName() {
  1181. return Toolbar.getToolName();
  1182. }
  1183. /** Equivalent to clicking on the current image at (x,y) with the
  1184. wand tool. Returns the number of points in the resulting ROI. */
  1185. public static int doWand(int x, int y) {
  1186. return doWand(getImage(), x, y, 0, null);
  1187. }
  1188. /** Traces the boundary of the area with pixel values within
  1189. * 'tolerance' of the value of the pixel at the starting location.
  1190. * 'tolerance' is in uncalibrated units.
  1191. * 'mode' can be "4-connected", "8-connected" or "Legacy".
  1192. * "Legacy" is for compatibility with previous versions of ImageJ;
  1193. * it is ignored if 'tolerance' > 0.
  1194. */
  1195. public static int doWand(int x, int y, double tolerance, String mode) {
  1196. return doWand(getImage(), x, y, tolerance, mode);
  1197. }
  1198. /** This version of doWand adds an ImagePlus argument. */
  1199. public static int doWand(ImagePlus img, int x, int y, double tolerance, String mode) {
  1200. ImageProcessor ip = img.getProcessor();
  1201. if ((img.getType()==ImagePlus.GRAY32) && Double.isNaN(ip.getPixelValue(x,y)))
  1202. return 0;
  1203. int imode = Wand.LEGACY_MODE;
  1204. if (mode!=null) {
  1205. if (mode.startsWith("4"))
  1206. imode = Wand.FOUR_CONNECTED;
  1207. else if (mode.startsWith("8"))
  1208. imode = Wand.EIGHT_CONNECTED;
  1209. }
  1210. Wand w = new Wand(ip);
  1211. double t1 = ip.getMinThreshold();
  1212. if (t1==ImageProcessor.NO_THRESHOLD || (ip.getLutUpdateMode()==ImageProcessor.NO_LUT_UPDATE&& tolerance>0.0))
  1213. w.autoOutline(x, y, tolerance, imode);
  1214. else
  1215. w.autoOutline(x, y, t1, ip.getMaxThreshold(), imode);
  1216. if (w.npoints>0) {
  1217. Roi previousRoi = img.getRoi();
  1218. int type = Wand.allPoints()?Roi.FREEROI:Roi.TRACED_ROI;
  1219. Roi roi = new PolygonRoi(w.xpoints, w.ypoints, w.npoints, type);
  1220. img.killRoi();
  1221. img.setRoi(roi);
  1222. // add/subtract this ROI to the previous one if the shift/alt key is down
  1223. if (previousRoi!=null)
  1224. roi.update(shiftKeyDown(), altKeyDown());
  1225. }
  1226. return w.npoints;
  1227. }
  1228. /** Sets the transfer mode used by the <i>Edit/Paste</i> command, where mode is "Copy", "Blend", "Average", "Difference",
  1229. "Transparent", "Transparent2", "AND", "OR", "XOR", "Add", "Subtract", "Multiply", or "Divide". */
  1230. public static void setPasteMode(String mode) {
  1231. mode = mode.toLowerCase(Locale.US);
  1232. int m = Blitter.COPY;
  1233. if (mode.startsWith("ble") || mode.startsWith("ave"))
  1234. m = Blitter.AVERAGE;
  1235. else if (mode.startsWith("diff"))
  1236. m = Blitter.DIFFERENCE;
  1237. else if (mode.indexOf("zero")!=-1)
  1238. m = Blitter.COPY_ZERO_TRANSPARENT;
  1239. else if (mode.startsWith("tran"))
  1240. m = Blitter.COPY_TRANSPARENT;
  1241. else if (mode.startsWith("and"))
  1242. m = Blitter.AND;
  1243. else if (mode.startsWith("or"))
  1244. m = Blitter.OR;
  1245. else if (mode.startsWith("xor"))
  1246. m = Blitter.XOR;
  1247. else if (mode.startsWith("sub"))
  1248. m = Blitter.SUBTRACT;
  1249. else if (mode.startsWith("add"))
  1250. m = Blitter.ADD;
  1251. else if (mode.startsWith("div"))
  1252. m = Blitter.DIVIDE;
  1253. else if (mode.startsWith("mul"))
  1254. m = Blitter.MULTIPLY;
  1255. else if (mode.startsWith("min"))
  1256. m = Blitter.MIN;
  1257. else if (mode.startsWith("max"))
  1258. m = Blitter.MAX;
  1259. Roi.setPasteMode(m);
  1260. }
  1261. /** Returns a reference to the active image. Displays an error
  1262. message and aborts the macro if no images are open. */
  1263. public static ImagePlus getImage() { //ts
  1264. ImagePlus img = WindowManager.getCurrentImage();
  1265. if (img==null) {
  1266. IJ.noImage();
  1267. if (ij==null)
  1268. System.exit(0);
  1269. else
  1270. abort();
  1271. }
  1272. return img;
  1273. }
  1274. /** Switches to the specified stack slice, where 1<='slice'<=stack-size. */
  1275. public static void setSlice(int slice) {
  1276. getImage().setSlice(slice);
  1277. }
  1278. /** Returns the ImageJ version number as a string. */
  1279. public static String getVersion() {
  1280. return ImageJ.VERSION;
  1281. }
  1282. /** Returns the path to the home ("user.home"), startup, ImageJ, plugins, macros,
  1283. luts, temp, current or image directory if <code>title</code> is "home", "startup",
  1284. "imagej", "plugins", "macros", "luts", "temp", "current" or "image", otherwise,
  1285. displays a dialog and returns the path to the directory selected by the user.
  1286. Returns null if the specified directory is not found or the user
  1287. cancels the dialog box. Also aborts the macro if the user cancels
  1288. the dialog box.*/
  1289. public static String getDirectory(String title) {
  1290. if (title.equals("plugins"))
  1291. return Menus.getPlugInsPath();
  1292. else if (title.equals("macros"))
  1293. return Menus.getMacrosPath();
  1294. else if (title.equals("luts")) {
  1295. String ijdir = getIJDir();
  1296. if (ijdir!=null)
  1297. return ijdir + "luts" + File.separator;
  1298. else
  1299. return null;
  1300. } else if (title.equals("home"))
  1301. return System.getProperty("user.home") + File.separator;
  1302. else if (title.equals("startup"))
  1303. return Prefs.getHomeDir() + File.separator;
  1304. else if (title.equals("imagej"))
  1305. return getIJDir();
  1306. else if (title.equals("current"))
  1307. return OpenDialog.getDefaultDirectory();
  1308. else if (title.equals("temp")) {
  1309. String dir = System.getProperty("java.io.tmpdir");
  1310. if (isMacintosh()) dir = "/tmp/";
  1311. if (dir!=null && !dir.endsWith(File.separator)) dir += File.separator;
  1312. return dir;
  1313. } else if (title.equals("image")) {
  1314. ImagePlus imp = WindowManager.getCurrentImage();
  1315. FileInfo fi = imp!=null?imp.getOriginalFileInfo():null;
  1316. if (fi!=null && fi.directory!=null)
  1317. return fi.directory;
  1318. else
  1319. return null;
  1320. } else {
  1321. DirectoryChooser dc = new DirectoryChooser(title);
  1322. String dir = dc.getDirectory();
  1323. if (dir==null) Macro.abort();
  1324. return dir;
  1325. }
  1326. }
  1327. private static String getIJDir() {
  1328. String path = Menus.getPlugInsPath();
  1329. if (path==null) return null;
  1330. String ijdir = (new File(path)).getParent();
  1331. if (ijdir!=null) ijdir += File.separator;
  1332. return ijdir;
  1333. }
  1334. /** Displays a file open dialog box and then opens the tiff, dicom,
  1335. fits, pgm, jpeg, bmp, gif, lut, roi, or text file selected by
  1336. the user. Displays an error message if the selected file is not
  1337. in one of the supported formats, or if it is not found. */
  1338. public static void open() {
  1339. open(null);
  1340. }
  1341. /** Opens and displays a tiff, dicom, fits, pgm, jpeg, bmp, gif, lut,
  1342. roi, or text file. Displays an error message if the specified file
  1343. is not in one of the supported formats, or if it is not found.
  1344. With 1.41k or later, opens images specified by a URL.
  1345. */
  1346. public static void open(String path) {
  1347. if (ij==null && Menus.getCommands()==null) init();
  1348. Opener o = new Opener();
  1349. macroRunning = true;
  1350. if (path==null || path.equals(""))
  1351. o.open();
  1352. else
  1353. o.open(path);
  1354. macroRunning = false;
  1355. }
  1356. /** Opens and displays the nth image in the specified tiff stack. */
  1357. public static void open(String path, int n) {
  1358. if (ij==null && Menus.getCommands()==null) init();
  1359. ImagePlus imp = openImage(path, n);
  1360. if (imp!=null) imp.show();
  1361. }
  1362. /** Opens the specified file as a tiff, bmp, dicom, fits, pgm, gif
  1363. or jpeg image and returns an ImagePlus object if successful.
  1364. Calls HandleExtraFileTypes plugin if the file type is not recognised.
  1365. Displays a file open dialog if 'path' is null or an empty string.
  1366. Note that 'path' can also be a URL. Some reader plugins, including
  1367. the Bio-Formats plugin, display the image and return null. */
  1368. public static ImagePlus openImage(String path) {
  1369. return (new Opener()).openImage(path);
  1370. }
  1371. /** Opens the nth image of the specified tiff stack. */
  1372. public static ImagePlus openImage(String path, int n) {
  1373. return (new Opener()).openImage(path, n);
  1374. }
  1375. /** Opens an image using a file open dialog and returns it as an ImagePlus object. */
  1376. public static ImagePlus openImage() {
  1377. return openImage(null);
  1378. }
  1379. /** Opens a URL and returns the contents as a string.
  1380. Returns "<Error: message>" if there an error, including
  1381. host or file not found. */
  1382. public static String openUrlAsString(String url) {
  1383. StringBuffer sb = null;
  1384. url = url.replaceAll(" ", "%20");
  1385. try {
  1386. URL u = new URL(url);
  1387. URLConnection uc = u.openConnection();
  1388. long len = uc.getContentLength();
  1389. if (len>1048576L)
  1390. return "<Error: file is larger than 1MB>";
  1391. InputStream in = u.openStream();
  1392. BufferedReader br = new BufferedReader(new InputStreamReader(in));
  1393. sb = new StringBuffer() ;
  1394. String line;
  1395. while ((line=br.readLine()) != null)
  1396. sb.append (line + "\n");
  1397. in.close ();
  1398. } catch (Exception e) {
  1399. return("<Error: "+e+">");
  1400. }
  1401. if (sb!=null)
  1402. return new String(sb);
  1403. else
  1404. return "";
  1405. }
  1406. /** Saves the current image, lookup table, selection or text window to the specified file path.
  1407. The path must end in ".tif", ".jpg", ".gif", ".zip", ".raw", ".avi", ".bmp", ".fits", ".pgm", ".png", ".lut", ".roi" or ".txt". */
  1408. public static void save(String path) {
  1409. save(null, path);
  1410. }
  1411. /** Saves the specified image, lookup table or selection to the specified file path.
  1412. The file path must end with ".tif", ".jpg", ".gif", ".zip", ".raw", ".avi", ".bmp",
  1413. ".fits", ".pgm", ".png", ".lut", ".roi" or ".txt". */
  1414. public static void save(ImagePlus imp, String path) {
  1415. int dotLoc = path.lastIndexOf('.');
  1416. if (dotLoc!=-1) {
  1417. ImagePlus imp2 = imp;
  1418. if (imp2==null) imp2 = WindowManager.getCurrentImage();
  1419. String title = imp2!=null?imp2.getTitle():null;
  1420. saveAs(imp, path.substring(dotLoc+1), path);
  1421. if (title!=null) imp2.setTitle(title);
  1422. } else
  1423. error("The file path passed to IJ.save() method or save()\nmacro function is missing the required extension.\n \n\""+path+"\"");
  1424. }
  1425. /* Saves the active image, lookup table, selection, measurement results, selection XY
  1426. coordinates or text window to the specified file path. The format argument must be "tiff",
  1427. "jpeg", "gif", "zip", "raw", "avi", "bmp", "fits", "pgm", "png", "text image", "lut", "selection", "measurements",
  1428. "xy Coordinates" or "text". If <code>path</code> is null or an emply string, a file
  1429. save dialog is displayed. */
  1430. public static void saveAs(String format, String path) {
  1431. saveAs(null, format, path);
  1432. }
  1433. /* Saves the specified image. The format argument must be "tiff",
  1434. "jpeg", "gif", "zip", "raw", "avi", "bmp", "fits", "pgm", "png",
  1435. "text image", "lut", "selection" or "xy Coordinates". */
  1436. public static void saveAs(ImagePlus imp, String format, String path) {
  1437. if (format==null) return;
  1438. if (path!=null && path.length()==0) path = null;
  1439. format = format.toLowerCase(Locale.US);
  1440. if (format.indexOf("tif")!=-1) {
  1441. if (path!=null&&!path.endsWith(".tiff"))
  1442. path = updateExtension(path, ".tif");
  1443. format = "Tiff...";
  1444. } else if (format.indexOf("jpeg")!=-1 || format.indexOf("jpg")!=-1) {
  1445. path = updateExtension(path, ".jpg");
  1446. format = "Jpeg...";
  1447. } else if (format.indexOf("gif")!=-1) {
  1448. path = updateExtension(path, ".gif");
  1449. format = "Gif...";
  1450. } else if (format.indexOf("text image")!=-1) {
  1451. path = updateExtension(path, ".txt");
  1452. format = "Text Image...";
  1453. } else if (format.indexOf("text")!=-1 || format.indexOf("txt")!=-1) {
  1454. if (path!=null && !path.endsWith(".xls"))
  1455. path = updateExtension(path, ".txt");
  1456. format = "Text...";
  1457. } else if (format.indexOf("zip")!=-1) {
  1458. path = updateExtension(path, ".zip");
  1459. format = "ZIP...";
  1460. } else if (format.indexOf("raw")!=-1) {
  1461. //path = updateExtension(path, ".raw");
  1462. format = "Raw Data...";
  1463. } else if (format.indexOf("avi")!=-1) {
  1464. path = updateExtension(path, ".avi");
  1465. format = "AVI... ";
  1466. } else if (format.indexOf("bmp")!=-1) {
  1467. path = updateExtension(path, ".bmp");
  1468. format = "BMP...";
  1469. } else if (format.indexOf("fits")!=-1) {
  1470. path = updateExtension(path, ".fits");
  1471. format = "FITS...";
  1472. } else if (format.indexOf("png")!=-1) {
  1473. path = updateExtension(path, ".png");
  1474. format = "PNG...";
  1475. } else if (format.indexOf("pgm")!=-1) {
  1476. path = updateExtension(path, ".pgm");
  1477. format = "PGM...";
  1478. } else if (format.indexOf("lut")!=-1) {
  1479. path = updateExtension(path, ".lut");
  1480. format = "LUT...";
  1481. } else if (format.indexOf("results")!=-1 || format.indexOf("measurements")!=-1) {
  1482. format = "Results...";
  1483. } else if (format.indexOf("selection")!=-1 || format.indexOf("roi")!=-1) {
  1484. path = updateExtension(path, ".roi");
  1485. format = "Selection...";
  1486. } else if (format.indexOf("xy")!=-1 || format.indexOf("coordinates")!=-1) {
  1487. path = updateExtension(path, ".txt");
  1488. format = "XY Coordinates...";
  1489. } else
  1490. error("Unsupported save() or saveAs() file format: \""+format+"\"\n \n\""+path+"\"");
  1491. if (path==null)
  1492. run(format);
  1493. else
  1494. run(imp, format, "save=["+path+"]");
  1495. }
  1496. static String updateExtension(String path, String extension) {
  1497. if (path==null) return null;
  1498. int dotIndex = path.lastIndexOf(".");
  1499. int separatorIndex = path.lastIndexOf(File.separator);
  1500. if (dotIndex>=0 && dotIndex>separatorIndex && (path.length()-dotIndex)<=5) {
  1501. if (dotIndex+1<path.length() && Character.isDigit(path.charAt(dotIndex+1)))
  1502. path += extension;
  1503. else
  1504. path = path.substring(0, dotIndex) + extension;
  1505. } else
  1506. path += extension;
  1507. return path;
  1508. }
  1509. /** Saves a string as a file. Displays a file save dialog if
  1510. 'path' is null or blank. Returns an error message
  1511. if there is an exception, otherwise returns null. */
  1512. public static String saveString(String string, String path) {
  1513. return write(string, path, false);
  1514. }
  1515. /** Appends a string to the end of a file. A newline character ("\n")
  1516. is added to the end of the string before it is written. Returns an
  1517. error message if there is an exception, otherwise returns null. */
  1518. public static String append(String string, String path) {
  1519. return write(string+"\n", path, true);
  1520. }
  1521. private static String write(String string, String path, boolean append) {
  1522. if (path==null || path.equals("")) {
  1523. String msg = append?"Append String...":"Save String...";
  1524. SaveDialog sd = new SaveDialog(msg, "Untitled", ".txt");
  1525. String name = sd.getFileName();
  1526. if (name==null) return null;
  1527. path = sd.getDirectory() + name;
  1528. }
  1529. try {
  1530. BufferedWriter out = new BufferedWriter(new FileWriter(path, append));
  1531. out.write(string);
  1532. out.close();
  1533. } catch (IOException e) {
  1534. return ""+e;
  1535. }
  1536. return null;
  1537. }
  1538. /** Opens a text file as a string. Displays a file open dialog
  1539. if path is null or blank. Returns null if the user cancels
  1540. the file open dialog. If there is an error, returns a
  1541. message in the form "Error: message". */
  1542. public static String openAsString(String path) {
  1543. if (path==null || path.equals("")) {
  1544. OpenDialog od = new OpenDialog("Open Text File", "");
  1545. String directory = od.getDirectory();
  1546. String name = od.getFileName();
  1547. if (name==null) return null;
  1548. path = directory + name;
  1549. }
  1550. String str = "";
  1551. File file = new File(path);
  1552. if (!file.exists())
  1553. return "Error: file not found";
  1554. try {
  1555. StringBuffer sb = new StringBuffer(5000);
  1556. BufferedReader r = new BufferedReader(new FileReader(file));
  1557. while (true) {
  1558. String s=r.readLine();
  1559. if (s==null)
  1560. break;
  1561. else
  1562. sb.append(s+"\n");
  1563. }
  1564. r.close();
  1565. str = new String(sb);
  1566. }
  1567. catch (Exception e) {
  1568. str = "Error: "+e.getMessage();
  1569. }
  1570. return str;
  1571. }
  1572. /** Creates a new imagePlus. <code>Type</code> should contain "8-bit", "16-bit", "32-bit" or "RGB".
  1573. In addition, it can contain "white", "black" or "ramp" (the default is "white"). <code>Width</code>
  1574. and <code>height</code> specify the width and height of the image in pixels.
  1575. <code>Depth</code> specifies the number of stack slices. */
  1576. public static ImagePlus createImage(String title, String type, int width, int height, int depth) {
  1577. type = type.toLowerCase(Locale.US);
  1578. int bitDepth = 8;
  1579. if (type.indexOf("16")!=-1) bitDepth = 16;
  1580. if (type.indexOf("24")!=-1||type.indexOf("rgb")!=-1) bitDepth = 24;
  1581. if (type.indexOf("32")!=-1) bitDepth = 32;
  1582. int options = NewImage.FILL_WHITE;
  1583. if (bitDepth==16 || bitDepth==32)
  1584. options = NewImage.FILL_BLACK;
  1585. if (type.indexOf("white")!=-1)
  1586. options = NewImage.FILL_WHITE;
  1587. else if (type.indexOf("black")!=-1)
  1588. options = NewImage.FILL_BLACK;
  1589. else if (type.indexOf("ramp")!=-1)
  1590. options = NewImage.FILL_RAMP;
  1591. options += NewImage.CHECK_AVAILABLE_MEMORY;
  1592. return NewImage.createImage(title, width, height, depth, bitDepth, options);
  1593. }
  1594. /** Opens a new image. <code>Type</code> should contain "8-bit", "16-bit", "32-bit" or "RGB".
  1595. In addition, it can contain "white", "black" or "ramp" (the default is "white"). <code>Width</code>
  1596. and <code>height</code> specify the width and height of the image in pixels.
  1597. <code>Depth</code> specifies the number of stack slices. */
  1598. public static void newImage(String title, String type, int width, int height, int depth) {
  1599. ImagePlus imp = createImage(title, type, width, height, depth);
  1600. if (imp!=null) {
  1601. macroRunning = true;
  1602. imp.show();
  1603. macroRunning = false;
  1604. }
  1605. }
  1606. /** Returns true if the <code>Esc</code> key was pressed since the
  1607. last ImageJ command started to execute or since resetEscape() was called. */
  1608. public static boolean escapePressed() {
  1609. return escapePressed;
  1610. }
  1611. /** This method sets the <code>Esc</code> key to the "up" position.
  1612. The Executer class calls this method when it runs
  1613. an ImageJ command in a separate thread. */
  1614. public static void resetEscape() {
  1615. escapePressed = false;
  1616. }
  1617. /** Causes IJ.error() output to be temporarily redirected to the "Log" window. */
  1618. public static void redirectErrorMessages() {
  1619. redirectErrorMessages = true;
  1620. }
  1621. /** Set 'true' and IJ.error() output will be redirected to the "Log" window. */
  1622. public static void redirectErrorMessages(boolean redirect) {
  1623. redirectErrorMessages2 = redirect;
  1624. }
  1625. /** Returns the state of the 'redirectErrorMessages' flag. The File/Import/Image Sequence command sets this flag.*/
  1626. public static boolean redirectingErrorMessages() {
  1627. return redirectErrorMessages || redirectErrorMessages2;
  1628. }
  1629. /** Temporarily suppress "plugin not found" errors. */
  1630. public static void suppressPluginNotFoundError() {
  1631. suppressPluginNotFoundError = true;
  1632. }
  1633. /** Returns the class loader ImageJ uses to run plugins or the
  1634. system class loader if Menus.getPlugInsPath() returns null. */
  1635. public static ClassLoader getClassLoader() {
  1636. if (classLoader==null) {
  1637. String pluginsDir = Menus.getPlugInsPath();
  1638. if (pluginsDir==null) {
  1639. String home = System.getProperty("plugins.dir");
  1640. if (home!=null) {
  1641. if (!home.endsWith(Prefs.separator)) home+=Prefs.separator;
  1642. pluginsDir = home+"plugins"+Prefs.separator;
  1643. if (!(new File(pluginsDir)).isDirectory()) pluginsDir = home;
  1644. }
  1645. }
  1646. if (pluginsDir==null)
  1647. return IJ.class.getClassLoader();
  1648. else {
  1649. if (Menus.jnlp)
  1650. classLoader = new PluginClassLoader(pluginsDir, true);
  1651. else
  1652. classLoader = new PluginClassLoader(pluginsDir);
  1653. }
  1654. }
  1655. return classLoader;
  1656. }
  1657. /** Returns the size, in pixels, of the primary display. */
  1658. public static Dimension getScreenSize() {
  1659. if (isWindows()) // GraphicsEnvironment.getConfigurations is *very* slow on Windows
  1660. return Toolkit.getDefaultToolkit().getScreenSize();
  1661. if (GraphicsEnvironment.isHeadless())
  1662. return new Dimension(0, 0);
  1663. // Can't use Toolkit.getScreenSize() on Linux because it returns
  1664. // size of all displays rather than just the primary display.
  1665. GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
  1666. GraphicsDevice[] gd = ge.getScreenDevices();
  1667. GraphicsConfiguration[] gc = gd[0].getConfigurations();
  1668. Rectangle bounds = gc[0].getBounds();
  1669. if (bounds.x==0&&bounds.y==0)
  1670. return new Dimension(bounds.width, bounds.height);
  1671. else
  1672. return Toolkit.getDefaultToolkit().getScreenSize();
  1673. }
  1674. static void abort() {
  1675. if (ij!=null || Interpreter.isBatchMode())
  1676. throw new RuntimeException(Macro.MACRO_CANCELED);
  1677. }
  1678. static void setClassLoader(ClassLoader loader) {
  1679. classLoader = loader;
  1680. }
  1681. /** Displays a stack trace. Use the setExceptionHandler
  1682. method() to override with a custom exception handler. */
  1683. public static void handleException(Throwable e) {
  1684. if (exceptionHandler!=null) {
  1685. exceptionHandler.handle(e);
  1686. return;
  1687. }
  1688. CharArrayWriter caw = new CharArrayWriter();
  1689. PrintWriter pw = new PrintWriter(caw);
  1690. e.printStackTrace(pw);
  1691. String s = caw.toString();
  1692. if (getInstance()!=null)
  1693. new TextWindow("Exception", s, 500, 300);
  1694. else
  1695. log(s);
  1696. }
  1697. /** Installs a custom exception handler that
  1698. overrides the handleException() method. */
  1699. public static void setExceptionHandler(ExceptionHandler handler) {
  1700. exceptionHandler = handler;
  1701. }
  1702. public interface ExceptionHandler {
  1703. public void handle(Throwable e);
  1704. }
  1705. static ExceptionHandler exceptionHandler;
  1706. public static void addEventListener(IJEventListener listener) {
  1707. eventListeners.addElement(listener);
  1708. }
  1709. public static void removeEventListener(IJEventListener listener) {
  1710. eventListeners.removeElement(listener);
  1711. }
  1712. public static void notifyEventListeners(int eventID) {
  1713. synchronized (eventListeners) {
  1714. for (int i=0; i<eventListeners.size(); i++) {
  1715. IJEventListener listener = (IJEventListener)eventListeners.elementAt(i);
  1716. listener.eventOccurred(eventID);
  1717. }
  1718. }
  1719. }
  1720. }