PageRenderTime 103ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/ij/IJ.java

https://gitlab.com/jnorthrup1/imagej
Java | 1880 lines | 1490 code | 145 blank | 245 comment | 349 complexity | ab516c6958d03fc29030a639b5e79b50 MD5 | raw file

Large files files are truncated, but you can click here to view the full 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)).get

Large files files are truncated, but you can click here to view the full file