PageRenderTime 62ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/src/ij/IJ.java

https://gitlab.com/dcarrion87/DRAS
Java | 2163 lines | 1685 code | 169 blank | 309 comment | 405 complexity | d09d9c822666a4800b3e17c8956ba2d9 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.plugin.frame.ThresholdAdjuster;
  11. import ij.macro.Interpreter;
  12. import ij.measure.Calibration;
  13. import ij.measure.ResultsTable;
  14. import ij.measure.Measurements;
  15. import java.awt.event.*;
  16. import java.text.*;
  17. import java.util.*;
  18. import java.awt.*;
  19. import java.applet.Applet;
  20. import java.io.*;
  21. import java.lang.reflect.*;
  22. import java.net.*;
  23. /** This class consists of static utility methods. */
  24. public class IJ {
  25. /** Image display modes */
  26. public static final int COMPOSITE=1, COLOR=2, GRAYSCALE=3;
  27. public static final String URL = "http://imagej.nih.gov/ij";
  28. public static final int ALL_KEYS = -1;
  29. /** Use setDebugMode(boolean) to enable/disable debug mode. */
  30. public static boolean debugMode;
  31. public static boolean hideProcessStackDialog;
  32. public static final char micronSymbol = '\u00B5';
  33. public static final char angstromSymbol = '\u00C5';
  34. public static final char degreeSymbol = '\u00B0';
  35. private static ImageJ ij;
  36. private static java.applet.Applet applet;
  37. private static ProgressBar progressBar;
  38. private static TextPanel textPanel;
  39. private static String osname, osarch;
  40. private static boolean isMac, isWin, isJava16, isJava17, isJava18, isLinux, is64Bit;
  41. private static boolean controlDown, altDown, spaceDown, shiftDown;
  42. private static boolean macroRunning;
  43. private static Thread previousThread;
  44. private static TextPanel logPanel;
  45. private static boolean checkForDuplicatePlugins = true;
  46. private static ClassLoader classLoader;
  47. private static boolean memMessageDisplayed;
  48. private static long maxMemory;
  49. private static boolean escapePressed;
  50. private static boolean redirectErrorMessages;
  51. private static boolean suppressPluginNotFoundError;
  52. private static Hashtable commandTable;
  53. private static Vector eventListeners = new Vector();
  54. private static String lastErrorMessage;
  55. private static Properties properties;
  56. static {
  57. osname = System.getProperty("os.name");
  58. isWin = osname.startsWith("Windows");
  59. isMac = !isWin && osname.startsWith("Mac");
  60. isLinux = osname.startsWith("Linux");
  61. String version = System.getProperty("java.version").substring(0,3);
  62. if (version.compareTo("2.9")<=0) { // JVM on Sharp Zaurus PDA claims to be "3.1"!
  63. isJava16 = version.compareTo("1.5")>0;
  64. isJava17 = version.compareTo("1.6")>0;
  65. isJava18 = version.compareTo("1.7")>0;
  66. }
  67. }
  68. static void init(ImageJ imagej, Applet theApplet) {
  69. ij = imagej;
  70. applet = theApplet;
  71. progressBar = ij.getProgressBar();
  72. }
  73. static void cleanup() {
  74. ij=null; applet=null; progressBar=null; textPanel=null;
  75. }
  76. /**Returns a reference to the "ImageJ" frame.*/
  77. public static ImageJ getInstance() {
  78. return ij;
  79. }
  80. /**Enable/disable debug mode.*/
  81. public static void setDebugMode(boolean b) {
  82. debugMode = b;
  83. LogStream.redirectSystem(debugMode);
  84. }
  85. /** Runs the macro contained in the string <code>macro</code>.
  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. The equivalent macro function is eval(). */
  89. public static String runMacro(String macro) {
  90. return runMacro(macro, "");
  91. }
  92. /** Runs the macro contained in the string <code>macro</code>.
  93. The optional string argument can be retrieved in the
  94. called macro using the getArgument() macro function.
  95. Returns any string value returned by the macro, null if the macro
  96. does not return a value, or "[aborted]" if the macro was aborted
  97. due to an error. */
  98. public static String runMacro(String macro, String arg) {
  99. Macro_Runner mr = new Macro_Runner();
  100. return mr.runMacro(macro, arg);
  101. }
  102. /** Runs the specified macro or script file in the current thread.
  103. The file is assumed to be in the macros folder
  104. unless <code>name</code> is a full path.
  105. The optional string argument (<code>arg</code>) can be retrieved in the called
  106. macro or script (v1.42k or later) using the getArgument() function.
  107. Returns any string value returned by the macro, or null. Scripts always return null.
  108. The equivalent macro function is runMacro(). */
  109. public static String runMacroFile(String name, String arg) {
  110. if (ij==null && Menus.getCommands()==null)
  111. init();
  112. Macro_Runner mr = new Macro_Runner();
  113. return mr.runMacroFile(name, arg);
  114. }
  115. /** Runs the specified macro file. */
  116. public static String runMacroFile(String name) {
  117. return runMacroFile(name, null);
  118. }
  119. /** Runs the specified plugin using the specified image. */
  120. public static Object runPlugIn(ImagePlus imp, String className, String arg) {
  121. if (imp!=null) {
  122. ImagePlus temp = WindowManager.getTempCurrentImage();
  123. WindowManager.setTempCurrentImage(imp);
  124. Object o = runPlugIn("", className, arg);
  125. WindowManager.setTempCurrentImage(temp);
  126. return o;
  127. } else
  128. return runPlugIn(className, arg);
  129. }
  130. /** Runs the specified plugin and returns a reference to it. */
  131. public static Object runPlugIn(String className, String arg) {
  132. return runPlugIn("", className, arg);
  133. }
  134. /** Runs the specified plugin and returns a reference to it. */
  135. public static Object runPlugIn(String commandName, String className, String arg) {
  136. if (arg==null) arg = "";
  137. if (IJ.debugMode)
  138. IJ.log("runPlugIn: "+className+argument(arg));
  139. // Load using custom classloader if this is a user
  140. // plugin and we are not running as an applet
  141. if (!className.startsWith("ij.") && applet==null)
  142. return runUserPlugIn(commandName, className, arg, false);
  143. Object thePlugIn=null;
  144. try {
  145. Class c = Class.forName(className);
  146. thePlugIn = c.newInstance();
  147. if (thePlugIn instanceof PlugIn)
  148. ((PlugIn)thePlugIn).run(arg);
  149. else
  150. new PlugInFilterRunner(thePlugIn, commandName, arg);
  151. }
  152. catch (ClassNotFoundException e) {
  153. if (IJ.getApplet()==null)
  154. log("Plugin or class not found: \"" + className + "\"\n(" + e+")");
  155. }
  156. catch (InstantiationException e) {log("Unable to load plugin (ins)");}
  157. catch (IllegalAccessException e) {log("Unable to load plugin, possibly \nbecause it is not public.");}
  158. redirectErrorMessages = false;
  159. return thePlugIn;
  160. }
  161. static Object runUserPlugIn(String commandName, String className, String arg, boolean createNewLoader) {
  162. if (IJ.debugMode)
  163. IJ.log("runUserPlugIn: "+className+", arg="+argument(arg));
  164. if (applet!=null) return null;
  165. if (checkForDuplicatePlugins) {
  166. // check for duplicate classes and jars in the plugins folder
  167. IJ.runPlugIn("ij.plugin.ClassChecker", "");
  168. checkForDuplicatePlugins = false;
  169. }
  170. if (createNewLoader)
  171. classLoader = null;
  172. ClassLoader loader = getClassLoader();
  173. Object thePlugIn = null;
  174. try {
  175. thePlugIn = (loader.loadClass(className)).newInstance();
  176. if (thePlugIn instanceof PlugIn)
  177. ((PlugIn)thePlugIn).run(arg);
  178. else if (thePlugIn instanceof PlugInFilter)
  179. new PlugInFilterRunner(thePlugIn, commandName, arg);
  180. }
  181. catch (ClassNotFoundException e) {
  182. if (className.contains("_") && !suppressPluginNotFoundError)
  183. error("Plugin or class not found: \"" + className + "\"\n(" + e+")");
  184. }
  185. catch (NoClassDefFoundError e) {
  186. int dotIndex = className.indexOf('.');
  187. if (dotIndex>=0 && className.contains("_")) {
  188. // rerun plugin after removing folder name
  189. if (debugMode) IJ.log("runUserPlugIn: rerunning "+className);
  190. return runUserPlugIn(commandName, className.substring(dotIndex+1), arg, createNewLoader);
  191. }
  192. if (className.contains("_") && !suppressPluginNotFoundError)
  193. error("Run User Plugin", "Class not found while attempting to run \"" + className + "\"\n \n " + e);
  194. }
  195. catch (InstantiationException e) {error("Unable to load plugin (ins)");}
  196. catch (IllegalAccessException e) {error("Unable to load plugin, possibly \nbecause it is not public.");}
  197. if (thePlugIn!=null && !"HandleExtraFileTypes".equals(className))
  198. redirectErrorMessages = false;
  199. suppressPluginNotFoundError = false;
  200. return thePlugIn;
  201. }
  202. private static String argument(String arg) {
  203. return arg!=null && !arg.equals("") && !arg.contains("\n")?"(\""+arg+"\")":"";
  204. }
  205. static void wrongType(int capabilities, String cmd) {
  206. String s = "\""+cmd+"\" requires an image of type:\n \n";
  207. if ((capabilities&PlugInFilter.DOES_8G)!=0) s += " 8-bit grayscale\n";
  208. if ((capabilities&PlugInFilter.DOES_8C)!=0) s += " 8-bit color\n";
  209. if ((capabilities&PlugInFilter.DOES_16)!=0) s += " 16-bit grayscale\n";
  210. if ((capabilities&PlugInFilter.DOES_32)!=0) s += " 32-bit (float) grayscale\n";
  211. if ((capabilities&PlugInFilter.DOES_RGB)!=0) s += " RGB color\n";
  212. error(s);
  213. }
  214. /** Starts executing a menu command in a separete thread and returns immediately. */
  215. public static void doCommand(String command) {
  216. if (ij!=null)
  217. ij.doCommand(command);
  218. }
  219. /** Runs an ImageJ command. Does not return until
  220. the command has finished executing. To avoid "image locked",
  221. errors, plugins that call this method should implement
  222. the PlugIn interface instead of PlugInFilter. */
  223. public static void run(String command) {
  224. run(command, null);
  225. }
  226. /** Runs an ImageJ command, with options that are passed to the
  227. GenericDialog and OpenDialog classes. Does not return until
  228. the command has finished executing. To generate run() calls,
  229. start the recorder (Plugins/Macro/Record) and run commands
  230. from the ImageJ menu bar.
  231. */
  232. public static void run(String command, String options) {
  233. //IJ.log("run1: "+command+" "+Thread.currentThread().hashCode()+" "+options);
  234. if (ij==null && Menus.getCommands()==null)
  235. init();
  236. Macro.abort = false;
  237. Macro.setOptions(options);
  238. Thread thread = Thread.currentThread();
  239. if (previousThread==null || thread!=previousThread) {
  240. String name = thread.getName();
  241. if (!name.startsWith("Run$_"))
  242. thread.setName("Run$_"+name);
  243. }
  244. command = convert(command);
  245. previousThread = thread;
  246. macroRunning = true;
  247. Executer e = new Executer(command);
  248. e.run();
  249. macroRunning = false;
  250. Macro.setOptions(null);
  251. testAbort();
  252. //IJ.log("run2: "+command+" "+Thread.currentThread().hashCode());
  253. }
  254. /** Converts commands that have been renamed so
  255. macros using the old names continue to work. */
  256. private static String convert(String command) {
  257. if (commandTable==null) {
  258. commandTable = new Hashtable(30);
  259. commandTable.put("New...", "Image...");
  260. commandTable.put("Threshold", "Make Binary");
  261. commandTable.put("Display...", "Appearance...");
  262. commandTable.put("Start Animation", "Start Animation [\\]");
  263. commandTable.put("Convert Images to Stack", "Images to Stack");
  264. commandTable.put("Convert Stack to Images", "Stack to Images");
  265. commandTable.put("Convert Stack to RGB", "Stack to RGB");
  266. commandTable.put("Convert to Composite", "Make Composite");
  267. commandTable.put("New HyperStack...", "New Hyperstack...");
  268. commandTable.put("Stack to HyperStack...", "Stack to Hyperstack...");
  269. commandTable.put("HyperStack to Stack", "Hyperstack to Stack");
  270. commandTable.put("RGB Split", "Split Channels");
  271. commandTable.put("RGB Merge...", "Merge Channels...");
  272. commandTable.put("Channels...", "Channels Tool...");
  273. commandTable.put("New... ", "Table...");
  274. commandTable.put("Arbitrarily...", "Rotate... ");
  275. commandTable.put("Measurements...", "Results... ");
  276. commandTable.put("List Commands...", "Find Commands...");
  277. commandTable.put("Capture Screen ", "Capture Screen");
  278. commandTable.put("Add to Manager ", "Add to Manager");
  279. commandTable.put("In", "In [+]");
  280. commandTable.put("Out", "Out [-]");
  281. commandTable.put("Enhance Contrast", "Enhance Contrast...");
  282. commandTable.put("XY Coodinates... ", "XY Coordinates... ");
  283. commandTable.put("Statistics...", "Statistics");
  284. commandTable.put("Channels Tool... ", "Channels Tool...");
  285. }
  286. String command2 = (String)commandTable.get(command);
  287. if (command2!=null)
  288. return command2;
  289. else
  290. return command;
  291. }
  292. /** Runs an ImageJ command using the specified image and options.
  293. To generate run() calls, start the recorder (Plugins/Macro/Record)
  294. and run commands from the ImageJ menu bar.*/
  295. public static void run(ImagePlus imp, String command, String options) {
  296. if (ij==null && Menus.getCommands()==null)
  297. init();
  298. if (imp!=null) {
  299. ImagePlus temp = WindowManager.getTempCurrentImage();
  300. WindowManager.setTempCurrentImage(imp);
  301. run(command, options);
  302. WindowManager.setTempCurrentImage(temp);
  303. } else
  304. run(command, options);
  305. }
  306. static void init() {
  307. Menus m = new Menus(null, null);
  308. Prefs.load(m, null);
  309. m.addMenuBar();
  310. }
  311. private static void testAbort() {
  312. if (Macro.abort)
  313. abort();
  314. }
  315. /** Returns true if the run(), open() or newImage() method is executing. */
  316. public static boolean macroRunning() {
  317. return macroRunning;
  318. }
  319. /** Returns true if a macro is running, or if the run(), open()
  320. or newImage() method is executing. */
  321. public static boolean isMacro() {
  322. return macroRunning || Interpreter.getInstance()!=null;
  323. }
  324. /**Returns the Applet that created this ImageJ or null if running as an application.*/
  325. public static java.applet.Applet getApplet() {
  326. return applet;
  327. }
  328. /**Displays a message in the ImageJ status bar.*/
  329. public static void showStatus(String s) {
  330. if (ij!=null)
  331. ij.showStatus(s);
  332. ImagePlus imp = WindowManager.getCurrentImage();
  333. ImageCanvas ic = imp!=null?imp.getCanvas():null;
  334. if (ic!=null)
  335. ic.setShowCursorStatus(s.length()==0?true:false);
  336. }
  337. /**
  338. * @deprecated
  339. * replaced by IJ.log(), ResultsTable.setResult() and TextWindow.append().
  340. * There are examples at
  341. * http://imagej.nih.gov/ij/plugins/sine-cosine.html
  342. */
  343. public static void write(String s) {
  344. if (textPanel==null && ij!=null)
  345. showResults();
  346. if (textPanel!=null)
  347. textPanel.append(s);
  348. else
  349. System.out.println(s);
  350. }
  351. private static void showResults() {
  352. TextWindow resultsWindow = new TextWindow("Results", "", 400, 250);
  353. textPanel = resultsWindow.getTextPanel();
  354. textPanel.setResultsTable(Analyzer.getResultsTable());
  355. }
  356. public static synchronized void log(String s) {
  357. if (s==null) return;
  358. if (logPanel==null && ij!=null) {
  359. TextWindow logWindow = new TextWindow("Log", "", 400, 250);
  360. logPanel = logWindow.getTextPanel();
  361. logPanel.setFont(new Font("SansSerif", Font.PLAIN, 16));
  362. }
  363. if (logPanel!=null) {
  364. if (s.startsWith("\\"))
  365. handleLogCommand(s);
  366. else
  367. logPanel.append(s);
  368. } else {
  369. LogStream.redirectSystem(false);
  370. System.out.println(s);
  371. }
  372. }
  373. static void handleLogCommand(String s) {
  374. if (s.equals("\\Closed"))
  375. logPanel = null;
  376. else if (s.startsWith("\\Update:")) {
  377. int n = logPanel.getLineCount();
  378. String s2 = s.substring(8, s.length());
  379. if (n==0)
  380. logPanel.append(s2);
  381. else
  382. logPanel.setLine(n-1, s2);
  383. } else if (s.startsWith("\\Update")) {
  384. int cindex = s.indexOf(":");
  385. if (cindex==-1)
  386. {logPanel.append(s); return;}
  387. String nstr = s.substring(7, cindex);
  388. int line = (int)Tools.parseDouble(nstr, -1);
  389. if (line<0 || line>25)
  390. {logPanel.append(s); return;}
  391. int count = logPanel.getLineCount();
  392. while (line>=count) {
  393. log("");
  394. count++;
  395. }
  396. String s2 = s.substring(cindex+1, s.length());
  397. logPanel.setLine(line, s2);
  398. } else if (s.equals("\\Clear")) {
  399. logPanel.clear();
  400. } else if (s.startsWith("\\Heading:")) {
  401. logPanel.updateColumnHeadings(s.substring(10));
  402. } else if (s.equals("\\Close")) {
  403. Frame f = WindowManager.getFrame("Log");
  404. if (f!=null && (f instanceof TextWindow))
  405. ((TextWindow)f).close();
  406. } else
  407. logPanel.append(s);
  408. }
  409. /** Returns the contents of the Log window or null if the Log window is not open. */
  410. public static synchronized String getLog() {
  411. if (logPanel==null || ij==null)
  412. return null;
  413. else
  414. return logPanel.getText();
  415. }
  416. /** Clears the "Results" window and sets the column headings to
  417. those in the tab-delimited 'headings' String. Writes to
  418. System.out.println if the "ImageJ" frame is not present.*/
  419. public static void setColumnHeadings(String headings) {
  420. if (textPanel==null && ij!=null)
  421. showResults();
  422. if (textPanel!=null)
  423. textPanel.setColumnHeadings(headings);
  424. else
  425. System.out.println(headings);
  426. }
  427. /** Returns true if the "Results" window is open. */
  428. public static boolean isResultsWindow() {
  429. return textPanel!=null;
  430. }
  431. /** Renames a results window. */
  432. public static void renameResults(String title) {
  433. Frame frame = WindowManager.getFrontWindow();
  434. if (frame!=null && (frame instanceof TextWindow)) {
  435. TextWindow tw = (TextWindow)frame;
  436. if (tw.getTextPanel().getResultsTable()==null) {
  437. IJ.error("Rename", "\""+tw.getTitle()+"\" is not a results table");
  438. return;
  439. }
  440. tw.rename(title);
  441. } else if (isResultsWindow()) {
  442. TextPanel tp = getTextPanel();
  443. TextWindow tw = (TextWindow)tp.getParent();
  444. tw.rename(title);
  445. }
  446. }
  447. /** Changes the name of a results window from 'oldTitle' to 'newTitle'. */
  448. public static void renameResults(String oldTitle, String newTitle) {
  449. Frame frame = WindowManager.getFrame(oldTitle);
  450. if (frame==null) {
  451. error("Rename", "\""+oldTitle+"\" not found");
  452. return;
  453. } else if (frame instanceof TextWindow) {
  454. TextWindow tw = (TextWindow)frame;
  455. if (tw.getTextPanel().getResultsTable()==null) {
  456. error("Rename", "\""+oldTitle+"\" is not a results table");
  457. return;
  458. }
  459. tw.rename(newTitle);
  460. } else
  461. error("Rename", "\""+oldTitle+"\" is not a results table");
  462. }
  463. /** Deletes 'row1' through 'row2' of the "Results" window. Arguments
  464. must be in the range 0-Analyzer.getCounter()-1. */
  465. public static void deleteRows(int row1, int row2) {
  466. int n = row2 - row1 + 1;
  467. ResultsTable rt = Analyzer.getResultsTable();
  468. for (int i=row1; i<row1+n; i++)
  469. rt.deleteRow(row1);
  470. rt.show("Results");
  471. }
  472. /** Returns a reference to the "Results" window TextPanel.
  473. Opens the "Results" window if it is currently not open.
  474. Returns null if the "ImageJ" window is not open. */
  475. public static TextPanel getTextPanel() {
  476. if (textPanel==null && ij!=null)
  477. showResults();
  478. return textPanel;
  479. }
  480. /** TextWindow calls this method with a null argument when the "Results" window is closed. */
  481. public static void setTextPanel(TextPanel tp) {
  482. textPanel = tp;
  483. }
  484. /**Displays a "no images are open" dialog box.*/
  485. public static void noImage() {
  486. error("No Image", "There are no images open.");
  487. }
  488. /** Displays an "out of memory" message to the "Log" window. */
  489. public static void outOfMemory(String name) {
  490. Undo.reset();
  491. System.gc();
  492. lastErrorMessage = "out of memory";
  493. String tot = Runtime.getRuntime().totalMemory()/1048576L+"MB";
  494. if (!memMessageDisplayed)
  495. log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
  496. log("<Out of memory>");
  497. if (!memMessageDisplayed) {
  498. log("<All available memory ("+tot+") has been>");
  499. log("<used. To make more available, use the>");
  500. log("<Edit>Options>Memory & Threads command.>");
  501. log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
  502. memMessageDisplayed = true;
  503. }
  504. Macro.abort();
  505. }
  506. /** Updates the progress bar, where 0<=progress<=1.0. The progress bar is
  507. not shown in BatchMode and erased if progress>=1.0. The progress bar is
  508. updated only if more than 90 ms have passes since the last call. Does nothing
  509. if the ImageJ window is not present. */
  510. public static void showProgress(double progress) {
  511. if (progressBar!=null) progressBar.show(progress, false);
  512. }
  513. /** Updates the progress bar, where the length of the bar is set to
  514. (<code>currentValue+1)/finalValue</code> of the maximum bar length.
  515. The bar is erased if <code>currentValue&gt;=finalValue</code>.
  516. The bar is updated only if more than 90 ms have passed since the last call.
  517. Does nothing if the ImageJ window is not present. */
  518. public static void showProgress(int currentIndex, int finalIndex) {
  519. if (progressBar!=null) {
  520. progressBar.show(currentIndex, finalIndex);
  521. if (currentIndex==finalIndex)
  522. progressBar.setBatchMode(false);
  523. }
  524. }
  525. /** Displays a message in a dialog box titled "Message".
  526. Writes the Java console if ImageJ is not present. */
  527. public static void showMessage(String msg) {
  528. showMessage("Message", msg);
  529. }
  530. /** Displays a message in a dialog box with the specified title.
  531. Displays HTML formatted text if 'msg' starts with "<html>".
  532. There are examples at
  533. "http://imagej.nih.gov/ij/macros/HtmlDialogDemo.txt".
  534. Writes to the Java console if ImageJ is not present. */
  535. public static void showMessage(String title, String msg) {
  536. if (ij!=null) {
  537. if (msg!=null && msg.startsWith("<html>")) {
  538. HTMLDialog hd = new HTMLDialog(title, msg);
  539. if (isMacro() && hd.escapePressed())
  540. throw new RuntimeException(Macro.MACRO_CANCELED);
  541. } else {
  542. MessageDialog md = new MessageDialog(ij, title, msg);
  543. if (isMacro() && md.escapePressed())
  544. throw new RuntimeException(Macro.MACRO_CANCELED);
  545. }
  546. } else
  547. System.out.println(msg);
  548. }
  549. /** Displays a message in a dialog box titled "ImageJ". If a
  550. macro is running, it is aborted. Writes to the Java console
  551. if the ImageJ window is not present.*/
  552. public static void error(String msg) {
  553. error(null, msg);
  554. if (Thread.currentThread().getName().endsWith("JavaScript"))
  555. throw new RuntimeException(Macro.MACRO_CANCELED);
  556. else
  557. Macro.abort();
  558. }
  559. /**Displays a message in a dialog box with the specified title.
  560. If a macro is running, it is aborted. Writes to the Java
  561. console if ImageJ is not present. */
  562. public static void error(String title, String msg) {
  563. if (msg!=null && msg.endsWith(Macro.MACRO_CANCELED))
  564. return;
  565. String title2 = title!=null?title:"ImageJ";
  566. boolean abortMacro = title!=null;
  567. lastErrorMessage = msg;
  568. if (redirectErrorMessages) {
  569. IJ.log(title2 + ": " + msg);
  570. if (abortMacro && (title.contains("Open")||title.contains("Reader")))
  571. abortMacro = false;
  572. } else
  573. showMessage(title2, msg);
  574. redirectErrorMessages = false;
  575. if (abortMacro)
  576. Macro.abort();
  577. }
  578. /**
  579. * Returns the last error message written by IJ.error() or null if there
  580. * was no error since the last time this method was called.
  581. * @see #error(String)
  582. */
  583. public static String getErrorMessage() {
  584. String msg = lastErrorMessage;
  585. lastErrorMessage = null;
  586. return msg;
  587. }
  588. /** Displays a message in a dialog box with the specified title.
  589. Returns false if the user pressed "Cancel". */
  590. public static boolean showMessageWithCancel(String title, String msg) {
  591. GenericDialog gd = new GenericDialog(title);
  592. gd.addMessage(msg);
  593. gd.showDialog();
  594. return !gd.wasCanceled();
  595. }
  596. public static final int CANCELED = Integer.MIN_VALUE;
  597. /** Allows the user to enter a number in a dialog box. Returns the
  598. value IJ.CANCELED (-2,147,483,648) if the user cancels the dialog box.
  599. Returns 'defaultValue' if the user enters an invalid number. */
  600. public static double getNumber(String prompt, double defaultValue) {
  601. GenericDialog gd = new GenericDialog("");
  602. int decimalPlaces = (int)defaultValue==defaultValue?0:2;
  603. gd.addNumericField(prompt, defaultValue, decimalPlaces);
  604. gd.showDialog();
  605. if (gd.wasCanceled())
  606. return CANCELED;
  607. double v = gd.getNextNumber();
  608. if (gd.invalidNumber())
  609. return defaultValue;
  610. else
  611. return v;
  612. }
  613. /** Allows the user to enter a string in a dialog box. Returns
  614. "" if the user cancels the dialog box. */
  615. public static String getString(String prompt, String defaultString) {
  616. GenericDialog gd = new GenericDialog("");
  617. gd.addStringField(prompt, defaultString, 20);
  618. gd.showDialog();
  619. if (gd.wasCanceled())
  620. return "";
  621. return gd.getNextString();
  622. }
  623. /**Delays 'msecs' milliseconds.*/
  624. public static void wait(int msecs) {
  625. try {Thread.sleep(msecs);}
  626. catch (InterruptedException e) { }
  627. }
  628. /** Emits an audio beep. */
  629. public static void beep() {
  630. java.awt.Toolkit.getDefaultToolkit().beep();
  631. }
  632. /** Runs the garbage collector and returns a string something
  633. like "64K of 256MB (25%)" that shows how much of
  634. the available memory is in use. This is the string
  635. displayed when the user clicks in the status bar. */
  636. public static String freeMemory() {
  637. long inUse = currentMemory();
  638. String inUseStr = inUse<10000*1024?inUse/1024L+"K":inUse/1048576L+"MB";
  639. String maxStr="";
  640. long max = maxMemory();
  641. if (max>0L) {
  642. double percent = inUse*100/max;
  643. maxStr = " of "+max/1048576L+"MB ("+(percent<1.0?"<1":d2s(percent,0)) + "%)";
  644. }
  645. return inUseStr + maxStr;
  646. }
  647. /** Returns the amount of memory currently being used by ImageJ. */
  648. public static long currentMemory() {
  649. long freeMem = Runtime.getRuntime().freeMemory();
  650. long totMem = Runtime.getRuntime().totalMemory();
  651. return totMem-freeMem;
  652. }
  653. /** Returns the maximum amount of memory available to ImageJ or
  654. zero if ImageJ is unable to determine this limit. */
  655. public static long maxMemory() {
  656. if (maxMemory==0L) {
  657. Memory mem = new Memory();
  658. maxMemory = mem.getMemorySetting();
  659. if (maxMemory==0L) maxMemory = mem.maxMemory();
  660. }
  661. return maxMemory;
  662. }
  663. public static void showTime(ImagePlus imp, long start, String str) {
  664. showTime(imp, start, str, 1);
  665. }
  666. public static void showTime(ImagePlus imp, long start, String str, int nslices) {
  667. if (Interpreter.isBatchMode()) return;
  668. double seconds = (System.currentTimeMillis()-start)/1000.0;
  669. double pixels = (double)imp.getWidth() * imp.getHeight();
  670. double rate = pixels*nslices/seconds;
  671. String str2;
  672. if (rate>1000000000.0)
  673. str2 = "";
  674. else if (rate<1000000.0)
  675. str2 = ", "+d2s(rate,0)+" pixels/second";
  676. else
  677. str2 = ", "+d2s(rate/1000000.0,1)+" million pixels/second";
  678. showStatus(str+seconds+" seconds"+str2);
  679. }
  680. /** Experimental */
  681. public static String time(ImagePlus imp, long startNanoTime) {
  682. double planes = imp.getStackSize();
  683. double seconds = (System.nanoTime()-startNanoTime)/1000000000.0;
  684. double mpixels = imp.getWidth()*imp.getHeight()*planes/1000000.0;
  685. String time = seconds<1.0?d2s(seconds*1000.0,0)+" ms":d2s(seconds,1)+" seconds";
  686. return time+", "+d2s(mpixels/seconds,1)+" million pixels/second";
  687. }
  688. /** Converts a number to a formatted string using
  689. 2 digits to the right of the decimal point. */
  690. public static String d2s(double n) {
  691. return d2s(n, 2);
  692. }
  693. private static DecimalFormat[] df;
  694. private static DecimalFormat[] sf;
  695. private static DecimalFormatSymbols dfs;
  696. /** Converts a number to a rounded formatted string.
  697. The 'decimalPlaces' argument specifies the number of
  698. digits to the right of the decimal point (0-9). Uses
  699. scientific notation if 'decimalPlaces is negative. */
  700. public static String d2s(double n, int decimalPlaces) {
  701. if (Double.isNaN(n)||Double.isInfinite(n))
  702. return ""+n;
  703. if (n==Float.MAX_VALUE) // divide by 0 in FloatProcessor
  704. return "3.4e38";
  705. double np = n;
  706. if (n<0.0) np = -n;
  707. if (decimalPlaces<0) {
  708. decimalPlaces = -decimalPlaces;
  709. if (decimalPlaces>9) decimalPlaces=9;
  710. if (sf==null) {
  711. if (dfs==null)
  712. dfs = new DecimalFormatSymbols(Locale.US);
  713. sf = new DecimalFormat[10];
  714. sf[1] = new DecimalFormat("0.0E0",dfs);
  715. sf[2] = new DecimalFormat("0.00E0",dfs);
  716. sf[3] = new DecimalFormat("0.000E0",dfs);
  717. sf[4] = new DecimalFormat("0.0000E0",dfs);
  718. sf[5] = new DecimalFormat("0.00000E0",dfs);
  719. sf[6] = new DecimalFormat("0.000000E0",dfs);
  720. sf[7] = new DecimalFormat("0.0000000E0",dfs);
  721. sf[8] = new DecimalFormat("0.00000000E0",dfs);
  722. sf[9] = new DecimalFormat("0.000000000E0",dfs);
  723. }
  724. return sf[decimalPlaces].format(n); // use scientific notation
  725. }
  726. if (decimalPlaces<0) decimalPlaces = 0;
  727. if (decimalPlaces>9) decimalPlaces = 9;
  728. if (df==null) {
  729. dfs = new DecimalFormatSymbols(Locale.US);
  730. df = new DecimalFormat[10];
  731. df[0] = new DecimalFormat("0", dfs);
  732. df[1] = new DecimalFormat("0.0", dfs);
  733. df[2] = new DecimalFormat("0.00", dfs);
  734. df[3] = new DecimalFormat("0.000", dfs);
  735. df[4] = new DecimalFormat("0.0000", dfs);
  736. df[5] = new DecimalFormat("0.00000", dfs);
  737. df[6] = new DecimalFormat("0.000000", dfs);
  738. df[7] = new DecimalFormat("0.0000000", dfs);
  739. df[8] = new DecimalFormat("0.00000000", dfs);
  740. df[9] = new DecimalFormat("0.000000000", dfs);
  741. }
  742. return df[decimalPlaces].format(n);
  743. }
  744. /** Converts a number to a rounded formatted string.
  745. * The 'significantDigits' argument specifies the minimum number
  746. * of significant digits, which is also the preferred number of
  747. * digits behind the decimal. Fewer decimals are shown if the
  748. * number would have more than 'maxDigits'.
  749. * Exponential notation is used if more than 'maxDigits' would be needed.
  750. */
  751. public static String d2s(double x, int significantDigits, int maxDigits) {
  752. double log10 = Math.log10(Math.abs(x));
  753. double roundErrorAtMax = 0.223*Math.pow(10, -maxDigits);
  754. int magnitude = (int)Math.ceil(log10+roundErrorAtMax);
  755. int decimals = x==0 ? 0 : maxDigits - magnitude;
  756. if (decimals<0 || magnitude<significantDigits+1-maxDigits)
  757. return IJ.d2s(x, -significantDigits); // exp notation for large and small numbers
  758. else {
  759. if (decimals>significantDigits)
  760. decimals = Math.max(significantDigits, decimals-maxDigits+significantDigits);
  761. return IJ.d2s(x, decimals);
  762. }
  763. }
  764. /** Pad 'n' with leading zeros to the specified number of digits. */
  765. public static String pad(int n, int digits) {
  766. String str = ""+n;
  767. while (str.length()<digits)
  768. str = "0"+str;
  769. return str;
  770. }
  771. /** Adds the specified class to a Vector to keep it from being garbage
  772. collected, which would cause the classes static fields to be reset.
  773. Probably not needed with Java 1.2 or later. */
  774. public static void register(Class c) {
  775. if (ij!=null) ij.register(c);
  776. }
  777. /** Returns true if the space bar is down. */
  778. public static boolean spaceBarDown() {
  779. return spaceDown;
  780. }
  781. /** Returns true if the control key is down. */
  782. public static boolean controlKeyDown() {
  783. return controlDown;
  784. }
  785. /** Returns true if the alt key is down. */
  786. public static boolean altKeyDown() {
  787. return altDown;
  788. }
  789. /** Returns true if the shift key is down. */
  790. public static boolean shiftKeyDown() {
  791. return shiftDown;
  792. }
  793. public static void setKeyDown(int key) {
  794. if (debugMode) IJ.log("setKeyDown: "+key);
  795. switch (key) {
  796. case KeyEvent.VK_CONTROL:
  797. controlDown=true;
  798. break;
  799. case KeyEvent.VK_META:
  800. if (isMacintosh()) controlDown=true;
  801. break;
  802. case KeyEvent.VK_ALT:
  803. altDown=true;
  804. break;
  805. case KeyEvent.VK_SHIFT:
  806. shiftDown=true;
  807. if (debugMode) beep();
  808. break;
  809. case KeyEvent.VK_SPACE: {
  810. spaceDown=true;
  811. ImageWindow win = WindowManager.getCurrentWindow();
  812. if (win!=null) win.getCanvas().setCursor(-1,-1,-1, -1);
  813. break;
  814. }
  815. case KeyEvent.VK_ESCAPE: {
  816. escapePressed = true;
  817. break;
  818. }
  819. }
  820. }
  821. public static void setKeyUp(int key) {
  822. if (debugMode) IJ.log("setKeyUp: "+key);
  823. switch (key) {
  824. case KeyEvent.VK_CONTROL: controlDown=false; break;
  825. case KeyEvent.VK_META: if (isMacintosh()) controlDown=false; break;
  826. case KeyEvent.VK_ALT: altDown=false; break;
  827. case KeyEvent.VK_SHIFT: shiftDown=false; if (debugMode) beep(); break;
  828. case KeyEvent.VK_SPACE:
  829. spaceDown=false;
  830. ImageWindow win = WindowManager.getCurrentWindow();
  831. if (win!=null) win.getCanvas().setCursor(-1,-1,-1,-1);
  832. break;
  833. case ALL_KEYS:
  834. shiftDown=controlDown=altDown=spaceDown=false;
  835. break;
  836. }
  837. }
  838. public static void setInputEvent(InputEvent e) {
  839. altDown = e.isAltDown();
  840. shiftDown = e.isShiftDown();
  841. }
  842. /** Returns true if this machine is a Macintosh. */
  843. public static boolean isMacintosh() {
  844. return isMac;
  845. }
  846. /** Returns true if this machine is a Macintosh running OS X. */
  847. public static boolean isMacOSX() {
  848. return isMacintosh();
  849. }
  850. /** Returns true if this machine is running Windows. */
  851. public static boolean isWindows() {
  852. return isWin;
  853. }
  854. /** Always returns true. */
  855. public static boolean isJava2() {
  856. return true;
  857. }
  858. /** Always returns true. */
  859. public static boolean isJava14() {
  860. return true;
  861. }
  862. /** Always returns true. */
  863. public static boolean isJava15() {
  864. return true;
  865. }
  866. /** Returns true if ImageJ is running on a Java 1.6 or greater JVM. */
  867. public static boolean isJava16() {
  868. return isJava16;
  869. }
  870. /** Returns true if ImageJ is running on a Java 1.7 or greater JVM. */
  871. public static boolean isJava17() {
  872. return isJava17;
  873. }
  874. /** Returns true if ImageJ is running on a Java 1.8 or greater JVM. */
  875. public static boolean isJava18() {
  876. return isJava18;
  877. }
  878. /** Returns true if ImageJ is running on Linux. */
  879. public static boolean isLinux() {
  880. return isLinux;
  881. }
  882. /** Obsolete; always returns false. */
  883. public static boolean isVista() {
  884. return false;
  885. }
  886. /** Returns true if ImageJ is running a 64-bit version of Java. */
  887. public static boolean is64Bit() {
  888. if (osarch==null)
  889. osarch = System.getProperty("os.arch");
  890. return osarch!=null && osarch.indexOf("64")!=-1;
  891. }
  892. /** Displays an error message and returns true if the
  893. ImageJ version is less than the one specified. */
  894. public static boolean versionLessThan(String version) {
  895. boolean lessThan = ImageJ.VERSION.compareTo(version)<0;
  896. if (lessThan)
  897. error("This plugin or macro requires ImageJ "+version+" or later. Use\nHelp>Update ImageJ to upgrade to the latest version.");
  898. return lessThan;
  899. }
  900. /** Displays a "Process all images?" dialog. Returns
  901. 'flags'+PlugInFilter.DOES_STACKS if the user selects "Yes",
  902. 'flags' if the user selects "No" and PlugInFilter.DONE
  903. if the user selects "Cancel".
  904. */
  905. public static int setupDialog(ImagePlus imp, int flags) {
  906. if (imp==null || (ij!=null&&ij.hotkey)) {
  907. if (ij!=null) ij.hotkey=false;
  908. return flags;
  909. }
  910. int stackSize = imp.getStackSize();
  911. if (stackSize>1) {
  912. String macroOptions = Macro.getOptions();
  913. if (imp.isComposite() && ((CompositeImage)imp).getMode()==IJ.COMPOSITE) {
  914. if (macroOptions==null || !macroOptions.contains("slice"))
  915. return flags | PlugInFilter.DOES_STACKS;
  916. }
  917. if (macroOptions!=null) {
  918. if (macroOptions.indexOf("stack ")>=0)
  919. return flags | PlugInFilter.DOES_STACKS;
  920. else
  921. return flags;
  922. }
  923. if (hideProcessStackDialog)
  924. return flags;
  925. String note = ((flags&PlugInFilter.NO_CHANGES)==0)?" There is\nno Undo if you select \"Yes\".":"";
  926. YesNoCancelDialog d = new YesNoCancelDialog(getInstance(),
  927. "Process Stack?", "Process all "+stackSize+" images?"+note);
  928. if (d.cancelPressed())
  929. return PlugInFilter.DONE;
  930. else if (d.yesPressed()) {
  931. if (imp.getStack().isVirtual() && ((flags&PlugInFilter.NO_CHANGES)==0)) {
  932. int size = (stackSize*imp.getWidth()*imp.getHeight()*imp.getBytesPerPixel()+524288)/1048576;
  933. String msg =
  934. "Use the Process>Batch>Virtual Stack command\n"+
  935. "to process a virtual stack or convert it into a\n"+
  936. "normal stack using Image>Duplicate, which\n"+
  937. "will require "+size+"MB of additional memory.";
  938. error(msg);
  939. return PlugInFilter.DONE;
  940. }
  941. if (Recorder.record)
  942. Recorder.recordOption("stack");
  943. return flags | PlugInFilter.DOES_STACKS;
  944. }
  945. if (Recorder.record)
  946. Recorder.recordOption("slice");
  947. }
  948. return flags;
  949. }
  950. /** Creates a rectangular selection. Removes any existing
  951. selection if width or height are less than 1. */
  952. public static void makeRectangle(int x, int y, int width, int height) {
  953. if (width<=0 || height<0)
  954. getImage().deleteRoi();
  955. else {
  956. ImagePlus img = getImage();
  957. if (Interpreter.isBatchMode())
  958. img.setRoi(new Roi(x,y,width,height), false);
  959. else
  960. img.setRoi(x, y, width, height);
  961. }
  962. }
  963. /** Creates a subpixel resolution rectangular selection. */
  964. public static void makeRectangle(double x, double y, double width, double height) {
  965. if (width<=0 || height<0)
  966. getImage().deleteRoi();
  967. else
  968. getImage().setRoi(new Roi(x,y,width,height), !Interpreter.isBatchMode());
  969. }
  970. /** Creates an oval selection. Removes any existing
  971. selection if width or height are less than 1. */
  972. public static void makeOval(int x, int y, int width, int height) {
  973. if (width<=0 || height<0)
  974. getImage().deleteRoi();
  975. else {
  976. ImagePlus img = getImage();
  977. img.setRoi(new OvalRoi(x, y, width, height));
  978. }
  979. }
  980. /** Creates an subpixel resolution oval selection. */
  981. public static void makeOval(double x, double y, double width, double height) {
  982. if (width<=0 || height<0)
  983. getImage().deleteRoi();
  984. else
  985. getImage().setRoi(new OvalRoi(x, y, width, height));
  986. }
  987. /** Creates a straight line selection. */
  988. public static void makeLine(int x1, int y1, int x2, int y2) {
  989. getImage().setRoi(new Line(x1, y1, x2, y2));
  990. }
  991. /** Creates a straight line selection using floating point coordinates. */
  992. public static void makeLine(double x1, double y1, double x2, double y2) {
  993. getImage().setRoi(new Line(x1, y1, x2, y2));
  994. }
  995. /** Creates a point selection using integer coordinates.. */
  996. public static void makePoint(int x, int y) {
  997. ImagePlus img = getImage();
  998. Roi roi = img.getRoi();
  999. if (shiftKeyDown() && roi!=null && roi.getType()==Roi.POINT) {
  1000. Polygon p = roi.getPolygon();
  1001. p.addPoint(x, y);
  1002. img.setRoi(new PointRoi(p.xpoints, p.ypoints, p.npoints));
  1003. IJ.setKeyUp(KeyEvent.VK_SHIFT);
  1004. } else if (altKeyDown() && roi!=null && roi.getType()==Roi.POINT) {
  1005. ((PolygonRoi)roi).deleteHandle(x, y);
  1006. IJ.setKeyUp(KeyEvent.VK_ALT);
  1007. } else
  1008. img.setRoi(new PointRoi(x, y));
  1009. }
  1010. /** Creates a point selection using floating point coordinates. */
  1011. public static void makePoint(double x, double y) {
  1012. ImagePlus img = getImage();
  1013. Roi roi = img.getRoi();
  1014. if (shiftKeyDown() && roi!=null && roi.getType()==Roi.POINT) {
  1015. Polygon p = roi.getPolygon();
  1016. p.addPoint((int)Math.round(x), (int)Math.round(y));
  1017. img.setRoi(new PointRoi(p.xpoints, p.ypoints, p.npoints));
  1018. IJ.setKeyUp(KeyEvent.VK_SHIFT);
  1019. } else if (altKeyDown() && roi!=null && roi.getType()==Roi.POINT) {
  1020. ((PolygonRoi)roi).deleteHandle(x, y);
  1021. IJ.setKeyUp(KeyEvent.VK_ALT);
  1022. } else
  1023. img.setRoi(new PointRoi(x, y));
  1024. }
  1025. /** Sets the display range (minimum and maximum displayed pixel values) of the current image. */
  1026. public static void setMinAndMax(double min, double max) {
  1027. setMinAndMax(getImage(), min, max, 7);
  1028. }
  1029. /** Sets the display range (minimum and maximum displayed pixel values) of the specified image. */
  1030. public static void setMinAndMax(ImagePlus img, double min, double max) {
  1031. setMinAndMax(img, min, max, 7);
  1032. }
  1033. /** Sets the minimum and maximum displayed pixel values on the specified RGB
  1034. channels, where 4=red, 2=green and 1=blue. */
  1035. public static void setMinAndMax(double min, double max, int channels) {
  1036. setMinAndMax(getImage(), min, max, channels);
  1037. }
  1038. private static void setMinAndMax(ImagePlus img, double min, double max, int channels) {
  1039. Calibration cal = img.getCalibration();
  1040. min = cal.getRawValue(min);
  1041. max = cal.getRawValue(max);
  1042. if (channels==7)
  1043. img.setDisplayRange(min, max);
  1044. else
  1045. img.setDisplayRange(min, max, channels);
  1046. img.updateAndDraw();
  1047. }
  1048. /** Resets the minimum and maximum displayed pixel values of the
  1049. current image to be the same as the min and max pixel values. */
  1050. public static void resetMinAndMax() {
  1051. resetMinAndMax(getImage());
  1052. }
  1053. /** Resets the minimum and maximum displayed pixel values of the
  1054. specified image to be the same as the min and max pixel values. */
  1055. public static void resetMinAndMax(ImagePlus img) {
  1056. img.resetDisplayRange();
  1057. img.updateAndDraw();
  1058. }
  1059. /** Sets the lower and upper threshold levels and displays the image
  1060. using red to highlight thresholded pixels. May not work correctly on
  1061. 16 and 32 bit images unless the display range has been reset using IJ.resetMinAndMax().
  1062. */
  1063. public static void setThreshold(double lowerThreshold, double upperThresold) {
  1064. setThreshold(lowerThreshold, upperThresold, null);
  1065. }
  1066. /** Sets the lower and upper threshold levels and displays the image using
  1067. the specified <code>displayMode</code> ("Red", "Black & White", "Over/Under" or "No Update"). */
  1068. public static void setThreshold(double lowerThreshold, double upperThreshold, String displayMode) {
  1069. setThreshold(getImage(), lowerThreshold, upperThreshold, displayMode);
  1070. }
  1071. /** Sets the lower and upper threshold levels of the specified image. */
  1072. public static void setThreshold(ImagePlus img, double lowerThreshold, double upperThreshold) {
  1073. setThreshold(img, lowerThreshold, upperThreshold, "Red");
  1074. }
  1075. /** Sets the lower and upper threshold levels of the specified image and updates the display using
  1076. the specified <code>displayMode</code> ("Red", "Black & White", "Over/Under" or "No Update"). */
  1077. public static void setThreshold(ImagePlus img, double lowerThreshold, double upperThreshold, String displayMode) {
  1078. int mode = ImageProcessor.RED_LUT;
  1079. if (displayMode!=null) {
  1080. displayMode = displayMode.toLowerCase(Locale.US);
  1081. if (displayMode.indexOf("black")!=-1)
  1082. mode = ImageProcessor.BLACK_AND_WHITE_LUT;
  1083. else if (displayMode.indexOf("over")!=-1)
  1084. mode = ImageProcessor.OVER_UNDER_LUT;
  1085. else if (displayMode.indexOf("no")!=-1)
  1086. mode = ImageProcessor.NO_LUT_UPDATE;
  1087. }
  1088. Calibration cal = img.getCalibration();
  1089. lowerThreshold = cal.getRawValue(lowerThreshold);
  1090. upperThreshold = cal.getRawValue(upperThreshold);
  1091. img.getProcessor().setThreshold(lowerThreshold, upperThreshold, mode);
  1092. if (mode!=ImageProcessor.NO_LUT_UPDATE && img.getWindow()!=null) {
  1093. img.getProcessor().setLutAnimation(true);
  1094. img.updateAndDraw();
  1095. ThresholdAdjuster.update();
  1096. }
  1097. }
  1098. public static void setAutoThreshold(ImagePlus imp, String method) {
  1099. ImageProcessor ip = imp.getProcessor();
  1100. if (ip instanceof ColorProcessor)
  1101. throw new IllegalArgumentException("Non-RGB image required");
  1102. ip.setRoi(imp.getRoi());
  1103. if (method!=null) {
  1104. try {
  1105. if (method.indexOf("stack")!=-1)
  1106. setStackThreshold(imp, ip, method);
  1107. else
  1108. ip.setAutoThreshold(method);
  1109. } catch (Exception e) {
  1110. log(e.getMessage());
  1111. }
  1112. } else
  1113. ip.setAutoThreshold(ImageProcessor.ISODATA2, ImageProcessor.RED_LUT);
  1114. imp.updateAndDraw();
  1115. }
  1116. private static void setStackThreshold(ImagePlus imp, ImageProcessor ip, String method) {
  1117. boolean darkBackground = method.indexOf("dark")!=-1;
  1118. int measurements = Analyzer.getMeasurements();
  1119. Analyzer.setMeasurements(Measurements.AREA+Measurements.MIN_MAX);
  1120. ImageStatistics stats = new StackStatistics(imp);
  1121. Analyzer.setMeasurements(measurements);
  1122. AutoThresholder thresholder = new AutoThresholder();
  1123. double min=0.0, max=255.0;
  1124. if (imp.getBitDepth()!=8) {
  1125. min = stats.min;
  1126. max = stats.max;
  1127. }
  1128. int threshold = thresholder.getThreshold(method, stats.histogram);
  1129. double lower, upper;
  1130. if (darkBackground) {
  1131. if (ip.isInvertedLut())
  1132. {lower=0.0; upper=threshold;}
  1133. else
  1134. {lower=threshold+1; upper=255.0;}
  1135. } else {
  1136. if (ip.isInvertedLut())
  1137. {lower=threshold+1; upper=255.0;}
  1138. else
  1139. {lower=0.0; upper=threshold;}
  1140. }
  1141. if (lower>255) lower = 255;
  1142. if (max>min) {
  1143. lower = min + (lower/255.0)*(max-min);
  1144. upper = min + (upper/255.0)*(max-min);
  1145. } else
  1146. lower = upper = min;
  1147. ip.setMinAndMax(min, max);
  1148. ip.setThreshold(lower, upper, ImageProcessor.RED_LUT);
  1149. imp.updateAndDraw();
  1150. }
  1151. /** Disables thresholding on the current image. */
  1152. public static void resetThreshold() {
  1153. resetThreshold(getImage());
  1154. }
  1155. /** Disables thresholding on the specified image. */
  1156. public static void resetThreshold(ImagePlus img) {
  1157. ImageProcessor ip = img.getProcessor();
  1158. ip.resetThreshold();
  1159. ip.setLutAnimation(true);
  1160. img.updateAndDraw();
  1161. ThresholdAdjuster.update();
  1162. }
  1163. /** For IDs less than zero, activates the image with the specified ID.
  1164. For IDs greater than zero, activates the Nth image. */
  1165. public static void selectWindow(int id) {
  1166. if (id>0)
  1167. id = WindowManager.getNthImageID(id);
  1168. ImagePlus imp = WindowManager.getImage(id);
  1169. if (imp==null)
  1170. error("Macro Error", "Image "+id+" not found or no images are open.");
  1171. if (Interpreter.isBatchMode()) {
  1172. ImagePlus impT = WindowManager.getTempCurrentImage();
  1173. ImagePlus impC = WindowManager.getCurrentImage();
  1174. if (impC!=null && impC!=imp && impT!=null)
  1175. impC.saveRoi();
  1176. WindowManager.setTempCurrentImage(imp);
  1177. WindowManager.setWindow(null);
  1178. } else {
  1179. ImageWindow win = imp.getWindow();
  1180. if (win!=null) {
  1181. win.toFront();
  1182. WindowManager.setWindow(win);
  1183. }
  1184. long start = System.currentTimeMillis();
  1185. // timeout after 2 seconds unless current thread is event dispatch thread
  1186. String thread = Thread.currentThread().getName();
  1187. int timeout = thread!=null&&thread.indexOf("EventQueue")!=-1?0:2000;
  1188. while (true) {
  1189. wait(10);
  1190. imp = WindowManager.getCurrentImage();
  1191. if (imp!=null && imp.getID()==id)
  1192. return; // specified image is now active
  1193. if ((System.currentTimeMillis()-start)>timeout && win!=null) {
  1194. WindowManager.setCurrentWindow(win);
  1195. return;
  1196. }
  1197. }
  1198. }
  1199. }
  1200. /** Activates the window with the specified title. */
  1201. public static void selectWindow(String title) {
  1202. if (title.equals("ImageJ")&&ij!=null)
  1203. {ij.toFront(); return;}
  1204. long start = System.currentTimeMillis();
  1205. while (System.currentTimeMillis()-start<3000) { // 3 sec timeout
  1206. Window win = WindowManager.getWindow(title);
  1207. if (win!=null && !(win instanceof ImageWindow)) {
  1208. selectWindow(win);
  1209. return;
  1210. }
  1211. int[] wList = WindowManager.getIDList();
  1212. int len = wList!=null?wList.length:0;
  1213. for (int i=0; i<len; i++) {
  1214. ImagePlus imp = WindowManager.getImage(wList[i]);
  1215. if (imp!=null) {
  1216. if (imp.getTitle().equals(title)) {
  1217. selectWindow(imp.getID());
  1218. return;
  1219. }
  1220. }
  1221. }
  1222. wait(10);
  1223. }
  1224. error("Macro Error", "No window with the title \""+title+"\" found.");
  1225. }
  1226. static void selectWindow(Window win) {
  1227. if (win instanceof Frame)
  1228. ((Frame)win).toFront();
  1229. else
  1230. ((Dialog)win).toFront();
  1231. long start = System.currentTimeMillis();
  1232. while (true) {
  1233. wait(10);
  1234. if (WindowManager.getActiveWindow()==win)
  1235. return; // specified window is now in front
  1236. if ((System.currentTimeMillis()-start)>1000) {
  1237. WindowManager.setWindow(win);
  1238. return; // 1 second timeout
  1239. }
  1240. }
  1241. }
  1242. /** Sets the foreground color. */
  1243. public static void setForegroundColor(int red, int green, int blue) {
  1244. setColor(red, green, blue, true);
  1245. }
  1246. /** Sets the background color. */
  1247. public static void setBackgroundColor(int red, int green, int blue) {
  1248. setColor(red, green, blue, false);
  1249. }
  1250. static void setColor(int red, int green, int blue, boolean foreground) {
  1251. if (red<0) red=0; if (green<0) green=0; if (blue<0) blue=0;
  1252. if (red>255) red=255; if (green>255) green=255; if (blue>255) blue=255;
  1253. Color c = new Color(red, green, blue);
  1254. if (foreground) {
  1255. Toolbar.setForegroundColor(c);
  1256. ImagePlus img = WindowManager.getCurrentImage();
  1257. if (img!=null)
  1258. img.getProcessor().setColor(c);
  1259. } else
  1260. Toolbar.setBackgroundColor(c);
  1261. }
  1262. /** Switches to the specified tool, where id = Toolbar.RECTANGLE (0),
  1263. Toolbar.OVAL (1), etc. */
  1264. public static void setTool(int id) {
  1265. Toolbar.getInstance().setTool(id);
  1266. }
  1267. /** Switches to the specified tool, where 'name' is "rect", "elliptical",
  1268. "brush", etc. Returns 'false' if the name is not recognized. */
  1269. public static boolean setTool(String name) {
  1270. return Toolbar.getInstance().setTool(name);
  1271. }
  1272. /** Returns the name of the current tool. */
  1273. public static String getToolName() {
  1274. return Toolbar.getToolName();
  1275. }
  1276. /** Equivalent to clicking on the current image at (x,y) with the
  1277. wand tool. Returns the number of points in the resulting ROI. */
  1278. public static int doWand(int x, int y) {
  1279. return doWand(getImage(), x, y, 0, null);
  1280. }
  1281. /** Traces the boundary of the area with pixel values within
  1282. * 'tolerance' of the value of the pixel at the starting location.
  1283. * 'tolerance' is in uncalibrated units.
  1284. * 'mode' can be "4-connected", "8-connected" or "Legacy".
  1285. * "Legacy" is for compatibility with previous versions of ImageJ;
  1286. * it is ignored if 'tolerance' > 0.
  1287. */
  1288. public static int doWand(int x, int y, double tolerance, String mode) {
  1289. return doWand(getImage(), x, y, tolerance, mode);
  1290. }
  1291. /** This version of doWand adds an ImagePlus argument. */
  1292. public static int doWand(ImagePlus img, int x, int y, double tolerance, String mode) {
  1293. ImageProcessor ip = img.getProcessor();
  1294. if ((img.getType()==ImagePlus.GRAY32) && Double.isNaN(ip.getPixelValue(x,y)))
  1295. return 0;
  1296. int imode = Wand.LEGACY_MODE;
  1297. if (mode!=null) {
  1298. if (mode.startsWith("4"))
  1299. imode = Wand.FOUR_CONNECTED;
  1300. else if (mode.startsWith("8"))
  1301. imode = Wand.EIGHT_CONNECTED;
  1302. }
  1303. Wand w = new Wand(ip);
  1304. double t1 = ip.getMinThreshold();
  1305. if (t1==ImageProcessor.NO_THRESHOLD || (ip.getLutUpdateMode()==ImageProcessor.NO_LUT_UPDATE&& tolerance>0.0))
  1306. w.autoOutline(x, y, tolerance, imode);
  1307. else
  1308. w.autoOutline(x, y, t1, ip.getMaxThreshold(), imode);
  1309. if (w.npoints>0) {
  1310. Roi previousRoi = img.getRoi();
  1311. int type = Wand.allPoints()?Roi.FREEROI:Roi.TRACED_ROI;
  1312. Roi roi = new PolygonRoi(w.xpoints, w.ypoints, w.npoints, type);
  1313. img.deleteRoi();
  1314. img.setRoi(roi);
  1315. // add/subtract this ROI to the previous one if the shift/alt key is down
  1316. if (previousRoi!=null)
  1317. roi.update(shiftKeyDown(), altKeyDown());
  1318. }
  1319. return w.npoints;
  1320. }
  1321. /** Sets the transfer mode used by the <i>Edit/Paste</i> command, where mode is "Copy", "Blend", "Average", "Difference",
  1322. "Transparent", "Transparent2", "AND", "OR", "XOR", "Add", "Subtract", "Multiply", or "Divide". */
  1323. public static void setPasteMode(String mode) {
  1324. mode = mode.toLowerCase(Locale.US);
  1325. int m = Blitter.COPY;
  1326. if (mode.startsWith("ble") || mode.startsWith("ave"))
  1327. m = Blitter.AVERAGE;
  1328. else if (mode.startsWith("diff"))
  1329. m = Blitter.DIFFERENCE;
  1330. else if (mode.indexOf("zero")!=-1)
  1331. m = Blitter.COPY_ZERO_TRANSPARENT

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