PageRenderTime 63ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/ImageJ/ImageJ_Source/ij/IJ.java

https://github.com/JoshThomas11/AMREGoodyearCSCI
Java | 1773 lines | 1690 code | 32 blank | 51 comment | 54 complexity | 8f2aba7029ba72e9c86aa86d14206457 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. }
  260. String command2 = (String)commandTable.get(command);
  261. if (command2!=null)
  262. return command2;
  263. else
  264. return command;
  265. }
  266. /** Runs an ImageJ command using the specified image and options. */
  267. public static void run(ImagePlus imp, String command, String options) {
  268. if (imp!=null) {
  269. ImagePlus temp = WindowManager.getTempCurrentImage();
  270. WindowManager.setTempCurrentImage(imp);
  271. run(command, options);
  272. WindowManager.setTempCurrentImage(temp);
  273. } else
  274. run(command, options);
  275. }
  276. static void init() {
  277. Menus m = new Menus(null, null);
  278. Prefs.load(m, null);
  279. m.addMenuBar();
  280. }
  281. private static void testAbort() {
  282. if (Macro.abort)
  283. abort();
  284. }
  285. /** Returns true if the run(), open() or newImage() method is executing. */
  286. public static boolean macroRunning() {
  287. return macroRunning;
  288. }
  289. /** Returns true if a macro is running, or if the run(), open()
  290. or newImage() method is executing. */
  291. public static boolean isMacro() {
  292. return macroRunning || Interpreter.getInstance()!=null;
  293. }
  294. /**Returns the Applet that created this ImageJ or null if running as an application.*/
  295. public static java.applet.Applet getApplet() {
  296. return applet;
  297. }
  298. /**Displays a message in the ImageJ status bar.*/
  299. public static void showStatus(String s) {
  300. if (ij!=null) ij.showStatus(s);
  301. ImagePlus imp = WindowManager.getCurrentImage();
  302. ImageCanvas ic = imp!=null?imp.getCanvas():null;
  303. if (ic!=null)
  304. ic.setShowCursorStatus(s.length()==0?true:false);
  305. }
  306. /**
  307. * @deprecated
  308. * replaced by IJ.log(), ResultsTable.setResult() and TextWindow.append().
  309. * There are examples at
  310. * http://imagej.nih.gov/ij/plugins/sine-cosine.html
  311. */
  312. public static void write(String s) {
  313. if (textPanel==null && ij!=null)
  314. showResults();
  315. if (textPanel!=null)
  316. textPanel.append(s);
  317. else
  318. System.out.println(s);
  319. }
  320. private static void showResults() {
  321. TextWindow resultsWindow = new TextWindow("Results", "", 400, 250);
  322. textPanel = resultsWindow.getTextPanel();
  323. textPanel.setResultsTable(Analyzer.getResultsTable());
  324. if (ij!=null)
  325. textPanel.addKeyListener(ij);
  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. /** Deletes 'row1' through 'row2' of the "Results" window. Arguments
  415. must be in the range 0-Analyzer.getCounter()-1. */
  416. public static void deleteRows(int row1, int row2) {
  417. int n = row2 - row1 + 1;
  418. ResultsTable rt = Analyzer.getResultsTable();
  419. for (int i=row1; i<row1+n; i++)
  420. rt.deleteRow(row1);
  421. rt.show("Results");
  422. }
  423. /** Returns a reference to the "Results" window TextPanel.
  424. Opens the "Results" window if it is currently not open.
  425. Returns null if the "ImageJ" window is not open. */
  426. public static TextPanel getTextPanel() {
  427. if (textPanel==null && ij!=null)
  428. showResults();
  429. return textPanel;
  430. }
  431. /** TextWindow calls this method with a null argument when the "Results" window is closed. */
  432. public static void setTextPanel(TextPanel tp) {
  433. textPanel = tp;
  434. }
  435. /**Displays a "no images are open" dialog box.*/
  436. public static void noImage() {
  437. error("No Image", "There are no images open.");
  438. }
  439. /** Displays an "out of memory" message to the "Log" window. */
  440. public static void outOfMemory(String name) {
  441. Undo.reset();
  442. System.gc();
  443. String tot = Runtime.getRuntime().totalMemory()/1048576L+"MB";
  444. if (!memMessageDisplayed)
  445. log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
  446. log("<Out of memory>");
  447. if (!memMessageDisplayed) {
  448. log("<All available memory ("+tot+") has been>");
  449. log("<used. Instructions for making more>");
  450. log("<available can be found in the \"Memory\" >");
  451. log("<sections of the installation notes at>");
  452. log("<"+IJ.URL+"/docs/install/>");
  453. log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
  454. memMessageDisplayed = true;
  455. }
  456. Macro.abort();
  457. }
  458. /** Updates the progress bar, where 0<=progress<=1.0. The progress bar is
  459. not shown in BatchMode and erased if progress>=1.0. The progress bar is
  460. updated only if more than 90 ms have passes since the last call. Does nothing
  461. if the ImageJ window is not present. */
  462. public static void showProgress(double progress) {
  463. if (progressBar!=null) progressBar.show(progress, false);
  464. }
  465. /** Updates the progress bar, where the length of the bar is set to
  466. (<code>currentValue+1)/finalValue</code> of the maximum bar length.
  467. The bar is erased if <code>currentValue&gt;=finalValue</code>.
  468. The bar is updated only if more than 90 ms have passed since the last call.
  469. Does nothing if the ImageJ window is not present. */
  470. public static void showProgress(int currentIndex, int finalIndex) {
  471. if (progressBar!=null) {
  472. progressBar.show(currentIndex, finalIndex);
  473. if (currentIndex==finalIndex)
  474. progressBar.setBatchMode(false);
  475. }
  476. }
  477. /** Displays a message in a dialog box titled "Message".
  478. Writes the Java console if ImageJ is not present. */
  479. public static void showMessage(String msg) {
  480. showMessage("Message", msg);
  481. }
  482. /** Displays a message in a dialog box with the specified title.
  483. Writes the Java console if ImageJ is not present. */
  484. public static void showMessage(String title, String msg) {
  485. if (ij!=null) {
  486. if (msg!=null && msg.startsWith("<html>"))
  487. new HTMLDialog(title, msg);
  488. else
  489. new MessageDialog(ij, title, msg);
  490. } else
  491. System.out.println(msg);
  492. }
  493. /** Displays a message in a dialog box titled "ImageJ". If a
  494. macro is running, it is aborted. Writes to the Java console
  495. if the ImageJ window is not present.*/
  496. public static void error(String msg) {
  497. error(null, msg);
  498. if (Thread.currentThread().getName().endsWith("JavaScript"))
  499. throw new RuntimeException(Macro.MACRO_CANCELED);
  500. else
  501. Macro.abort();
  502. }
  503. /**Displays a message in a dialog box with the specified title.
  504. If a macro is running, it is aborted. Writes to the Java
  505. console if ImageJ is not present. */
  506. public static void error(String title, String msg) {
  507. String title2 = title!=null?title:"ImageJ";
  508. boolean abortMacro = title!=null;
  509. if (redirectErrorMessages || redirectErrorMessages2) {
  510. IJ.log(title2 + ": " + msg);
  511. if (abortMacro && title.equals("Opener")) abortMacro = false;
  512. } else
  513. showMessage(title2, msg);
  514. redirectErrorMessages = false;
  515. if (abortMacro) Macro.abort();
  516. }
  517. /** Displays a message in a dialog box with the specified title.
  518. Returns false if the user pressed "Cancel". */
  519. public static boolean showMessageWithCancel(String title, String msg) {
  520. GenericDialog gd = new GenericDialog(title);
  521. gd.addMessage(msg);
  522. gd.showDialog();
  523. return !gd.wasCanceled();
  524. }
  525. public static final int CANCELED = Integer.MIN_VALUE;
  526. /** Allows the user to enter a number in a dialog box. Returns the
  527. value IJ.CANCELED (-2,147,483,648) if the user cancels the dialog box.
  528. Returns 'defaultValue' if the user enters an invalid number. */
  529. public static double getNumber(String prompt, double defaultValue) {
  530. GenericDialog gd = new GenericDialog("");
  531. int decimalPlaces = (int)defaultValue==defaultValue?0:2;
  532. gd.addNumericField(prompt, defaultValue, decimalPlaces);
  533. gd.showDialog();
  534. if (gd.wasCanceled())
  535. return CANCELED;
  536. double v = gd.getNextNumber();
  537. if (gd.invalidNumber())
  538. return defaultValue;
  539. else
  540. return v;
  541. }
  542. /** Allows the user to enter a string in a dialog box. Returns
  543. "" if the user cancels the dialog box. */
  544. public static String getString(String prompt, String defaultString) {
  545. GenericDialog gd = new GenericDialog("");
  546. gd.addStringField(prompt, defaultString, 20);
  547. gd.showDialog();
  548. if (gd.wasCanceled())
  549. return "";
  550. return gd.getNextString();
  551. }
  552. /**Delays 'msecs' milliseconds.*/
  553. public static void wait(int msecs) {
  554. try {Thread.sleep(msecs);}
  555. catch (InterruptedException e) { }
  556. }
  557. /** Emits an audio beep. */
  558. public static void beep() {
  559. java.awt.Toolkit.getDefaultToolkit().beep();
  560. }
  561. /** Runs the garbage collector and returns a string something
  562. like "64K of 256MB (25%)" that shows how much of
  563. the available memory is in use. This is the string
  564. displayed when the user clicks in the status bar. */
  565. public static String freeMemory() {
  566. long inUse = currentMemory();
  567. String inUseStr = inUse<10000*1024?inUse/1024L+"K":inUse/1048576L+"MB";
  568. String maxStr="";
  569. long max = maxMemory();
  570. if (max>0L) {
  571. double percent = inUse*100/max;
  572. maxStr = " of "+max/1048576L+"MB ("+(percent<1.0?"<1":d2s(percent,0)) + "%)";
  573. }
  574. return inUseStr + maxStr;
  575. }
  576. /** Returns the amount of memory currently being used by ImageJ. */
  577. public static long currentMemory() {
  578. long freeMem = Runtime.getRuntime().freeMemory();
  579. long totMem = Runtime.getRuntime().totalMemory();
  580. return totMem-freeMem;
  581. }
  582. /** Returns the maximum amount of memory available to ImageJ or
  583. zero if ImageJ is unable to determine this limit. */
  584. public static long maxMemory() {
  585. if (maxMemory==0L) {
  586. Memory mem = new Memory();
  587. maxMemory = mem.getMemorySetting();
  588. if (maxMemory==0L) maxMemory = mem.maxMemory();
  589. }
  590. return maxMemory;
  591. }
  592. public static void showTime(ImagePlus imp, long start, String str) {
  593. showTime(imp, start, str, 1);
  594. }
  595. public static void showTime(ImagePlus imp, long start, String str, int nslices) {
  596. if (Interpreter.isBatchMode()) return;
  597. double seconds = (System.currentTimeMillis()-start)/1000.0;
  598. double pixels = (double)imp.getWidth() * imp.getHeight();
  599. double rate = pixels*nslices/seconds;
  600. String str2;
  601. if (rate>1000000000.0)
  602. str2 = "";
  603. else if (rate<1000000.0)
  604. str2 = ", "+d2s(rate,0)+" pixels/second";
  605. else
  606. str2 = ", "+d2s(rate/1000000.0,1)+" million pixels/second";
  607. showStatus(str+seconds+" seconds"+str2);
  608. }
  609. /** Experimental */
  610. public static String time(ImagePlus imp, long startNanoTime) {
  611. double planes = imp.getStackSize();
  612. double seconds = (System.nanoTime()-startNanoTime)/1000000000.0;
  613. double mpixels = imp.getWidth()*imp.getHeight()*planes/1000000.0;
  614. String time = seconds<1.0?d2s(seconds*1000.0,0)+" ms":d2s(seconds,1)+" seconds";
  615. return time+", "+d2s(mpixels/seconds,1)+" million pixels/second";
  616. }
  617. /** Converts a number to a formatted string using
  618. 2 digits to the right of the decimal point. */
  619. public static String d2s(double n) {
  620. return d2s(n, 2);
  621. }
  622. private static DecimalFormat[] df;
  623. private static DecimalFormat[] sf;
  624. private static DecimalFormatSymbols dfs;
  625. /** Converts a number to a rounded formatted string.
  626. The 'decimalPlaces' argument specifies the number of
  627. digits to the right of the decimal point (0-9). Uses
  628. scientific notation if 'decimalPlaces is negative. */
  629. public static String d2s(double n, int decimalPlaces) {
  630. if (Double.isNaN(n)||Double.isInfinite(n))
  631. return ""+n;
  632. if (n==Float.MAX_VALUE) // divide by 0 in FloatProcessor
  633. return "3.4e38";
  634. double np = n;
  635. if (n<0.0) np = -n;
  636. if (df==null) {
  637. dfs = new DecimalFormatSymbols(Locale.US);
  638. df = new DecimalFormat[10];
  639. df[0] = new DecimalFormat("0", dfs);
  640. df[1] = new DecimalFormat("0.0", dfs);
  641. df[2] = new DecimalFormat("0.00", dfs);
  642. df[3] = new DecimalFormat("0.000", dfs);
  643. df[4] = new DecimalFormat("0.0000", dfs);
  644. df[5] = new DecimalFormat("0.00000", dfs);
  645. df[6] = new DecimalFormat("0.000000", dfs);
  646. df[7] = new DecimalFormat("0.0000000", dfs);
  647. df[8] = new DecimalFormat("0.00000000", dfs);
  648. df[9] = new DecimalFormat("0.000000000", dfs);
  649. }
  650. if (decimalPlaces<0) {
  651. decimalPlaces = -decimalPlaces;
  652. if (decimalPlaces>9) decimalPlaces=9;
  653. if (sf==null) {
  654. sf = new DecimalFormat[10];
  655. sf[1] = new DecimalFormat("0.0E0",dfs);
  656. sf[2] = new DecimalFormat("0.00E0",dfs);
  657. sf[3] = new DecimalFormat("0.000E0",dfs);
  658. sf[4] = new DecimalFormat("0.0000E0",dfs);
  659. sf[5] = new DecimalFormat("0.00000E0",dfs);
  660. sf[6] = new DecimalFormat("0.000000E0",dfs);
  661. sf[7] = new DecimalFormat("0.0000000E0",dfs);
  662. sf[8] = new DecimalFormat("0.00000000E0",dfs);
  663. sf[9] = new DecimalFormat("0.000000000E0",dfs);
  664. }
  665. return sf[decimalPlaces].format(n); // use scientific notation
  666. }
  667. if (decimalPlaces<0) decimalPlaces = 0;
  668. if (decimalPlaces>9) decimalPlaces = 9;
  669. return df[decimalPlaces].format(n);
  670. }
  671. /** Adds the specified class to a Vector to keep it from being garbage
  672. collected, which would cause the classes static fields to be reset.
  673. Probably not needed with Java 1.2 or later. */
  674. public static void register(Class c) {
  675. if (ij!=null) ij.register(c);
  676. }
  677. /** Returns true if the space bar is down. */
  678. public static boolean spaceBarDown() {
  679. return spaceDown;
  680. }
  681. /** Returns true if the control key is down. */
  682. public static boolean controlKeyDown() {
  683. return controlDown;
  684. }
  685. /** Returns true if the alt key is down. */
  686. public static boolean altKeyDown() {
  687. return altDown;
  688. }
  689. /** Returns true if the shift key is down. */
  690. public static boolean shiftKeyDown() {
  691. return shiftDown;
  692. }
  693. public static void setKeyDown(int key) {
  694. if (debugMode) IJ.log("setKeyDown: "+key);
  695. switch (key) {
  696. case KeyEvent.VK_CONTROL:
  697. controlDown=true;
  698. break;
  699. case KeyEvent.VK_META:
  700. if (isMacintosh()) controlDown=true;
  701. break;
  702. case KeyEvent.VK_ALT:
  703. altDown=true;
  704. break;
  705. case KeyEvent.VK_SHIFT:
  706. shiftDown=true;
  707. if (debugMode) beep();
  708. break;
  709. case KeyEvent.VK_SPACE: {
  710. spaceDown=true;
  711. ImageWindow win = WindowManager.getCurrentWindow();
  712. if (win!=null) win.getCanvas().setCursor(-1,-1,-1, -1);
  713. break;
  714. }
  715. case KeyEvent.VK_ESCAPE: {
  716. escapePressed = true;
  717. break;
  718. }
  719. }
  720. }
  721. public static void setKeyUp(int key) {
  722. if (debugMode) IJ.log("setKeyUp: "+key);
  723. switch (key) {
  724. case KeyEvent.VK_CONTROL: controlDown=false; break;
  725. case KeyEvent.VK_META: if (isMacintosh()) controlDown=false; break;
  726. case KeyEvent.VK_ALT: altDown=false; break;
  727. case KeyEvent.VK_SHIFT: shiftDown=false; if (debugMode) beep(); break;
  728. case KeyEvent.VK_SPACE:
  729. spaceDown=false;
  730. ImageWindow win = WindowManager.getCurrentWindow();
  731. if (win!=null) win.getCanvas().setCursor(-1,-1,-1,-1);
  732. break;
  733. case ALL_KEYS:
  734. shiftDown=controlDown=altDown=spaceDown=false;
  735. break;
  736. }
  737. }
  738. public static void setInputEvent(InputEvent e) {
  739. altDown = e.isAltDown();
  740. shiftDown = e.isShiftDown();
  741. }
  742. /** Returns true if this machine is a Macintosh. */
  743. public static boolean isMacintosh() {
  744. return isMac;
  745. }
  746. /** Returns true if this machine is a Macintosh running OS X. */
  747. public static boolean isMacOSX() {
  748. return isMacintosh();
  749. }
  750. /** Returns true if this machine is running Windows. */
  751. public static boolean isWindows() {
  752. return isWin;
  753. }
  754. /** Always returns true. */
  755. public static boolean isJava2() {
  756. return isJava2;
  757. }
  758. /** Returns true if ImageJ is running on a Java 1.4 or greater JVM. */
  759. public static boolean isJava14() {
  760. return isJava14;
  761. }
  762. /** Returns true if ImageJ is running on a Java 1.5 or greater JVM. */
  763. public static boolean isJava15() {
  764. return isJava15;
  765. }
  766. /** Returns true if ImageJ is running on a Java 1.6 or greater JVM. */
  767. public static boolean isJava16() {
  768. return isJava16;
  769. }
  770. /** Returns true if ImageJ is running on a Java 1.7 or greater JVM. */
  771. public static boolean isJava17() {
  772. return isJava17;
  773. }
  774. /** Returns true if ImageJ is running on Linux. */
  775. public static boolean isLinux() {
  776. return isLinux;
  777. }
  778. /** Returns true if ImageJ is running on Windows Vista. */
  779. public static boolean isVista() {
  780. return isVista;
  781. }
  782. /** Returns true if ImageJ is running a 64-bit version of Java. */
  783. public static boolean is64Bit() {
  784. if (osarch==null)
  785. osarch = System.getProperty("os.arch");
  786. return osarch!=null && osarch.indexOf("64")!=-1;
  787. }
  788. /** Displays an error message and returns false if the
  789. ImageJ version is less than the one specified. */
  790. public static boolean versionLessThan(String version) {
  791. boolean lessThan = ImageJ.VERSION.compareTo(version)<0;
  792. if (lessThan)
  793. error("This plugin or macro requires ImageJ "+version+" or later. Use\nHelp>Update ImageJ to upgrade to the latest version.");
  794. return lessThan;
  795. }
  796. /** Displays a "Process all images?" dialog. Returns
  797. 'flags'+PlugInFilter.DOES_STACKS if the user selects "Yes",
  798. 'flags' if the user selects "No" and PlugInFilter.DONE
  799. if the user selects "Cancel".
  800. */
  801. public static int setupDialog(ImagePlus imp, int flags) {
  802. if (imp==null || (ij!=null&&ij.hotkey))
  803. return flags;
  804. int stackSize = imp.getStackSize();
  805. if (stackSize>1) {
  806. if (imp.isComposite() && ((CompositeImage)imp).getMode()==CompositeImage.COMPOSITE)
  807. return flags+PlugInFilter.DOES_STACKS;
  808. String macroOptions = Macro.getOptions();
  809. if (macroOptions!=null) {
  810. if (macroOptions.indexOf("stack ")>=0)
  811. return flags+PlugInFilter.DOES_STACKS;
  812. else
  813. return flags;
  814. }
  815. if (hideProcessStackDialog)
  816. return flags;
  817. String note = ((flags&PlugInFilter.NO_CHANGES)==0)?" There is\nno Undo if you select \"Yes\".":"";
  818. YesNoCancelDialog d = new YesNoCancelDialog(getInstance(),
  819. "Process Stack?", "Process all "+stackSize+" images?"+note);
  820. if (d.cancelPressed())
  821. return PlugInFilter.DONE;
  822. else if (d.yesPressed()) {
  823. if (imp.getStack().isVirtual() && ((flags&PlugInFilter.NO_CHANGES)==0)) {
  824. int size = (stackSize*imp.getWidth()*imp.getHeight()*imp.getBytesPerPixel()+524288)/1048576;
  825. String msg =
  826. "Use the Process>Batch>Virtual Stack command\n"+
  827. "to process a virtual stack ike this one or convert\n"+
  828. "it to a normal stack using Image>Duplicate, which\n"+
  829. "will require "+size+"MB of additional memory.";
  830. error(msg);
  831. return PlugInFilter.DONE;
  832. }
  833. if (Recorder.record)
  834. Recorder.recordOption("stack");
  835. return flags+PlugInFilter.DOES_STACKS;
  836. }
  837. if (Recorder.record)
  838. Recorder.recordOption("slice");
  839. }
  840. return flags;
  841. }
  842. /** Creates a rectangular selection. Removes any existing
  843. selection if width or height are less than 1. */
  844. public static void makeRectangle(int x, int y, int width, int height) {
  845. if (width<=0 || height<0)
  846. getImage().killRoi();
  847. else {
  848. ImagePlus img = getImage();
  849. if (Interpreter.isBatchMode())
  850. img.setRoi(new Roi(x,y,width,height), false);
  851. else
  852. img.setRoi(x, y, width, height);
  853. }
  854. }
  855. /** Creates an oval selection. Removes any existing
  856. selection if width or height are less than 1. */
  857. public static void makeOval(int x, int y, int width, int height) {
  858. if (width<=0 || height<0)
  859. getImage().killRoi();
  860. else {
  861. ImagePlus img = getImage();
  862. img.setRoi(new OvalRoi(x, y, width, height));
  863. }
  864. }
  865. /** Creates a straight line selection. */
  866. public static void makeLine(int x1, int y1, int x2, int y2) {
  867. getImage().setRoi(new Line(x1, y1, x2, y2));
  868. }
  869. /** Creates a point selection. */
  870. public static void makePoint(int x, int y) {
  871. ImagePlus img = getImage();
  872. Roi roi = img.getRoi();
  873. if (shiftKeyDown() && roi!=null && roi.getType()==Roi.POINT) {
  874. Polygon p = roi.getPolygon();
  875. p.addPoint(x, y);
  876. img.setRoi(new PointRoi(p.xpoints, p.ypoints, p.npoints));
  877. } else
  878. img.setRoi(new PointRoi(x, y));
  879. }
  880. /** Creates a straight line selection using double coordinates. */
  881. public static void makeLine(double x1, double y1, double x2, double y2) {
  882. getImage().setRoi(new Line(x1, y1, x2, y2));
  883. }
  884. /** Sets the display range (minimum and maximum displayed pixel values) of the current image. */
  885. public static void setMinAndMax(double min, double max) {
  886. setMinAndMax(getImage(), min, max, 7);
  887. }
  888. /** Sets the display range (minimum and maximum displayed pixel values) of the specified image. */
  889. public static void setMinAndMax(ImagePlus img, double min, double max) {
  890. setMinAndMax(img, min, max, 7);
  891. }
  892. /** Sets the minimum and maximum displayed pixel values on the specified RGB
  893. channels, where 4=red, 2=green and 1=blue. */
  894. public static void setMinAndMax(double min, double max, int channels) {
  895. setMinAndMax(getImage(), min, max, channels);
  896. }
  897. private static void setMinAndMax(ImagePlus img, double min, double max, int channels) {
  898. Calibration cal = img.getCalibration();
  899. min = cal.getRawValue(min);
  900. max = cal.getRawValue(max);
  901. if (channels==7)
  902. img.setDisplayRange(min, max);
  903. else
  904. img.setDisplayRange(min, max, channels);
  905. img.updateAndDraw();
  906. }
  907. /** Resets the minimum and maximum displayed pixel values of the
  908. current image to be the same as the min and max pixel values. */
  909. public static void resetMinAndMax() {
  910. resetMinAndMax(getImage());
  911. }
  912. /** Resets the minimum and maximum displayed pixel values of the
  913. specified image to be the same as the min and max pixel values. */
  914. public static void resetMinAndMax(ImagePlus img) {
  915. img.resetDisplayRange();
  916. img.updateAndDraw();
  917. }
  918. /** Sets the lower and upper threshold levels and displays the image
  919. using red to highlight thresholded pixels. May not work correctly on
  920. 16 and 32 bit images unless the display range has been reset using IJ.resetMinAndMax().
  921. */
  922. public static void setThreshold(double lowerThreshold, double upperThresold) {
  923. setThreshold(lowerThreshold, upperThresold, null);
  924. }
  925. /** Sets the lower and upper threshold levels and displays the image using
  926. the specified <code>displayMode</code> ("Red", "Black & White", "Over/Under" or "No Update"). */
  927. public static void setThreshold(double lowerThreshold, double upperThreshold, String displayMode) {
  928. setThreshold(getImage(), lowerThreshold, upperThreshold, displayMode);
  929. }
  930. /** Sets the lower and upper threshold levels of the specified image. */
  931. public static void setThreshold(ImagePlus img, double lowerThreshold, double upperThreshold) {
  932. setThreshold(img, lowerThreshold, upperThreshold, "Red");
  933. }
  934. /** Sets the lower and upper threshold levels of the specified image and updates the display using
  935. the specified <code>displayMode</code> ("Red", "Black & White", "Over/Under" or "No Update"). */
  936. public static void setThreshold(ImagePlus img, double lowerThreshold, double upperThreshold, String displayMode) {
  937. int mode = ImageProcessor.RED_LUT;
  938. if (displayMode!=null) {
  939. displayMode = displayMode.toLowerCase(Locale.US);
  940. if (displayMode.indexOf("black")!=-1)
  941. mode = ImageProcessor.BLACK_AND_WHITE_LUT;
  942. else if (displayMode.indexOf("over")!=-1)
  943. mode = ImageProcessor.OVER_UNDER_LUT;
  944. else if (displayMode.indexOf("no")!=-1)
  945. mode = ImageProcessor.NO_LUT_UPDATE;
  946. }
  947. Calibration cal = img.getCalibration();
  948. lowerThreshold = cal.getRawValue(lowerThreshold);
  949. upperThreshold = cal.getRawValue(upperThreshold);
  950. img.getProcessor().setThreshold(lowerThreshold, upperThreshold, mode);
  951. if (mode != ImageProcessor.NO_LUT_UPDATE) {
  952. img.getProcessor().setLutAnimation(true);
  953. img.updateAndDraw();
  954. }
  955. }
  956. public static void setAutoThreshold(ImagePlus img, String method) {
  957. ImageProcessor ip = img.getProcessor();
  958. if (ip instanceof ColorProcessor)
  959. throw new IllegalArgumentException("Non-RGB image required");
  960. ip.setRoi(img.getRoi());
  961. if (method!=null) {
  962. try {ip.setAutoThreshold(method);}
  963. catch (Exception e) {IJ.log(e.getMessage());}
  964. } else
  965. ip.setAutoThreshold(ImageProcessor.ISODATA2, ImageProcessor.RED_LUT);
  966. img.updateAndDraw();
  967. }
  968. /** Disables thresholding on the current image. */
  969. public static void resetThreshold() {
  970. resetThreshold(getImage());
  971. }
  972. /** Disables thresholding on the specified image. */
  973. public static void resetThreshold(ImagePlus img) {
  974. ImageProcessor ip = img.getProcessor();
  975. ip.resetThreshold();
  976. ip.setLutAnimation(true);
  977. img.updateAndDraw();
  978. }
  979. /** For IDs less than zero, activates the image with the specified ID.
  980. For IDs greater than zero, activates the Nth image. */
  981. public static void selectWindow(int id) {
  982. if (id>0)
  983. id = WindowManager.getNthImageID(id);
  984. ImagePlus imp = WindowManager.getImage(id);
  985. if (imp==null)
  986. error("Macro Error", "Image "+id+" not found or no images are open.");
  987. if (Interpreter.isBatchMode()) {
  988. ImagePlus imp2 = WindowManager.getCurrentImage();
  989. if (imp2!=null && imp2!=imp) imp2.saveRoi();
  990. WindowManager.setTempCurrentImage(imp);
  991. WindowManager.setWindow(null);
  992. } else {
  993. ImageWindow win = imp.getWindow();
  994. win.toFront();
  995. WindowManager.setWindow(win);
  996. long start = System.currentTimeMillis();
  997. // timeout after 2 seconds unless current thread is event dispatch thread
  998. String thread = Thread.currentThread().getName();
  999. int timeout = thread!=null&&thread.indexOf("EventQueue")!=-1?0:2000;
  1000. while (true) {
  1001. wait(10);
  1002. imp = WindowManager.getCurrentImage();
  1003. if (imp!=null && imp.getID()==id)
  1004. return; // specified image is now active
  1005. if ((System.currentTimeMillis()-start)>timeout) {
  1006. WindowManager.setCurrentWindow(win);
  1007. return;
  1008. }
  1009. }
  1010. }
  1011. }
  1012. /** Activates the window with the specified title. */
  1013. public static void selectWindow(String title) {
  1014. if (title.equals("ImageJ")&&ij!=null)
  1015. {ij.toFront(); return;}
  1016. long start = System.currentTimeMillis();
  1017. while (System.currentTimeMillis()-start<3000) { // 3 sec timeout
  1018. Frame frame = WindowManager.getFrame(title);
  1019. if (frame!=null && !(frame instanceof ImageWindow)) {
  1020. selectWindow(frame);
  1021. return;
  1022. }
  1023. int[] wList = WindowManager.getIDList();
  1024. int len = wList!=null?wList.length:0;
  1025. for (int i=0; i<len; i++) {
  1026. ImagePlus imp = WindowManager.getImage(wList[i]);
  1027. if (imp!=null) {
  1028. if (imp.getTitle().equals(title)) {
  1029. selectWindow(imp.getID());
  1030. return;
  1031. }
  1032. }
  1033. }
  1034. wait(10);
  1035. }
  1036. error("Macro Error", "No window with the title \""+title+"\" found.");
  1037. }
  1038. static void selectWindow(Frame frame) {
  1039. frame.toFront();
  1040. long start = System.currentTimeMillis();
  1041. while (true) {
  1042. wait(10);
  1043. if (WindowManager.getFrontWindow()==frame)
  1044. return; // specified window is now in front
  1045. if ((System.currentTimeMillis()-start)>1000) {
  1046. WindowManager.setWindow(frame);
  1047. return; // 1 second timeout
  1048. }
  1049. }
  1050. }
  1051. /** Sets the foreground color. */
  1052. public static void setForegroundColor(int red, int green, int blue) {
  1053. setColor(red, green, blue, true);
  1054. }
  1055. /** Sets the background color. */
  1056. public static void setBackgroundColor(int red, int green, int blue) {
  1057. setColor(red, green, blue, false);
  1058. }
  1059. static void setColor(int red, int green, int blue, boolean foreground) {
  1060. if (red<0) red=0; if (green<0) green=0; if (blue<0) blue=0;
  1061. if (red>255) red=255; if (green>255) green=255; if (blue>255) blue=255;
  1062. Color c = new Color(red, green, blue);
  1063. if (foreground) {
  1064. Toolbar.setForegroundColor(c);
  1065. ImagePlus img = WindowManager.getCurrentImage();
  1066. if (img!=null)
  1067. img.getProcessor().setColor(c);
  1068. } else
  1069. Toolbar.setBackgroundColor(c);
  1070. }
  1071. /** Switches to the specified tool, where id = Toolbar.RECTANGLE (0),
  1072. Toolbar.OVAL (1), etc. */
  1073. public static void setTool(int id) {
  1074. Toolbar.getInstance().setTool(id);
  1075. }
  1076. /** Switches to the specified tool, where 'name' is "rect", "elliptical",
  1077. "brush", etc. Returns 'false' if the name is not recognized. */
  1078. public static boolean setTool(String name) {
  1079. return Toolbar.getInstance().setTool(name);
  1080. }
  1081. /** Returns the name of the current tool. */
  1082. public static String getToolName() {
  1083. return Toolbar.getToolName();
  1084. }
  1085. /** Equivalent to clicking on the current image at (x,y) with the
  1086. wand tool. Returns the number of points in the resulting ROI. */
  1087. public static int doWand(int x, int y) {
  1088. return doWand(x, y, 0, null);
  1089. }
  1090. /** Traces the boundary of the area with pixel values within
  1091. * 'tolerance' of the value of the pixel at the starting location.
  1092. * 'tolerance' is in uncalibrated units.
  1093. * 'mode' can be "4-connected", "8-connected" or "Legacy".
  1094. * "Legacy" is for compatibility with previous versions of ImageJ;
  1095. * it is ignored if 'tolerance' > 0.
  1096. */
  1097. public static int doWand(int x, int y, double tolerance, String mode) {
  1098. ImagePlus img = getImage();
  1099. ImageProcessor ip = img.getProcessor();
  1100. if ((img.getType()==ImagePlus.GRAY32) && Double.isNaN(ip.getPixelValue(x,y)))
  1101. return 0;
  1102. int imode = Wand.LEGACY_MODE;
  1103. if (mode!=null) {
  1104. if (mode.startsWith("4"))
  1105. imode = Wand.FOUR_CONNECTED;
  1106. else if (mode.startsWith("8"))
  1107. imode = Wand.EIGHT_CONNECTED;
  1108. }
  1109. Wand w = new Wand(ip);
  1110. double t1 = ip.getMinThreshold();
  1111. if (t1==ImageProcessor.NO_THRESHOLD || (ip.getLutUpdateMode()==ImageProcessor.NO_LUT_UPDATE&& tolerance>0.0))
  1112. w.autoOutline(x, y, tolerance, imode);
  1113. else
  1114. w.autoOutline(x, y, t1, ip.getMaxThreshold(), imode);
  1115. if (w.npoints>0) {
  1116. Roi previousRoi = img.getRoi();
  1117. int type = Wand.allPoints()?Roi.FREEROI:Roi.TRACED_ROI;
  1118. Roi roi = new PolygonRoi(w.xpoints, w.ypoints, w.npoints, type);
  1119. img.killRoi();
  1120. img.setRoi(roi);
  1121. // add/subtract this ROI to the previous one if the shift/alt key is down
  1122. if (previousRoi!=null)
  1123. roi.update(shiftKeyDown(), altKeyDown());
  1124. }
  1125. return w.npoints;
  1126. }
  1127. /** Sets the transfer mode used by the <i>Edit/Paste</i> command, where mode is "Copy", "Blend", "Average", "Difference",
  1128. "Transparent", "Transparent2", "AND", "OR", "XOR", "Add", "Subtract", "Multiply", or "Divide". */
  1129. public static void setPasteMode(String mode) {
  1130. mode = mode.toLowerCase(Locale.US);
  1131. int m = Blitter.COPY;
  1132. if (mode.startsWith("ble") || mode.startsWith("ave"))
  1133. m = Blitter.AVERAGE;
  1134. else if (mode.startsWith("diff"))
  1135. m = Blitter.DIFFERENCE;
  1136. else if (mode.indexOf("zero")!=-1)
  1137. m = Blitter.COPY_ZERO_TRANSPARENT;
  1138. else if (mode.startsWith("tran"))
  1139. m = Blitter.COPY_TRANSPARENT;
  1140. else if (mode.startsWith("and"))
  1141. m = Blitter.AND;
  1142. else if (mode.startsWith("or"))
  1143. m = Blitter.OR;
  1144. else if (mode.startsWith("xor"))
  1145. m = Blitter.XOR;
  1146. else if (mode.startsWith("sub"))
  1147. m = Blitter.SUBTRACT;
  1148. else if (mode.startsWith("add"))
  1149. m = Blitter.ADD;
  1150. else if (mode.startsWith("div"))
  1151. m = Blitter.DIVIDE;
  1152. else if (mode.startsWith("mul"))
  1153. m = Blitter.MULTIPLY;
  1154. else if (mode.startsWith("min"))
  1155. m = Blitter.MIN;
  1156. else if (mode.startsWith("max"))
  1157. m = Blitter.MAX;
  1158. Roi.setPasteMode(m);
  1159. }
  1160. /** Returns a reference to the active image. Displays an error
  1161. message and aborts the macro if no images are open. */
  1162. public static ImagePlus getImage() { //ts
  1163. ImagePlus img = WindowManager.getCurrentImage();
  1164. if (img==null) {
  1165. IJ.noImage();
  1166. if (ij==null)
  1167. System.exit(0);
  1168. else
  1169. abort();
  1170. }
  1171. return img;
  1172. }
  1173. /** Switches to the specified stack slice, where 1<='slice'<=stack-size. */
  1174. public static void setSlice(int slice) {
  1175. getImage().setSlice(slice);
  1176. }
  1177. /** Returns the ImageJ version number as a string. */
  1178. public static String getVersion() {
  1179. return ImageJ.VERSION;
  1180. }
  1181. /** Returns the path to the home ("user.home"), startup, ImageJ, plugins, macros,
  1182. luts, temp, current or image directory if <code>title</code> is "home", "startup",
  1183. "imagej", "plugins", "macros", "luts", "temp", "current" or "image", otherwise,
  1184. displays a dialog and returns the path to the directory selected by the user.
  1185. Returns null if the specified directory is not found or the user
  1186. cancels the dialog box. Also aborts the macro if the user cancels
  1187. the dialog box.*/
  1188. public static String getDirectory(String title) {
  1189. if (title.equals("plugins"))
  1190. return Menus.getPlugInsPath();
  1191. else if (title.equals("macros"))
  1192. return Menus.getMacrosPath();
  1193. else if (title.equals("luts")) {
  1194. String ijdir = getIJDir();
  1195. if (ijdir!=null)
  1196. return ijdir + "luts" + File.separator;
  1197. else
  1198. return null;
  1199. } else if (title.equals("home"))
  1200. return System.getProperty("user.home") + File.separator;
  1201. else if (title.equals("startup"))
  1202. return Prefs.getHomeDir() + File.separator;
  1203. else if (title.equals("imagej"))
  1204. return getIJDir();
  1205. else if (title.equals("current"))
  1206. return OpenDialog.getDefaultDirectory();
  1207. else if (title.equals("temp")) {
  1208. String dir = System.getProperty("java.io.tmpdir");
  1209. if (isMacintosh()) dir = "/tmp/";
  1210. if (dir!=null && !dir.endsWith(File.separator)) dir += File.separator;
  1211. return dir;
  1212. } else if (title.equals("image")) {
  1213. ImagePlus imp = WindowManager.getCurrentImage();
  1214. FileInfo fi = imp!=null?imp.getOriginalFileInfo():null;
  1215. if (fi!=null && fi.directory!=null)
  1216. return fi.directory;
  1217. else
  1218. return null;
  1219. } else {
  1220. DirectoryChooser dc = new DirectoryChooser(title);
  1221. String dir = dc.getDirectory();
  1222. if (dir==null) Macro.abort();
  1223. return dir;
  1224. }
  1225. }
  1226. private static String getIJDir() {
  1227. String path = Menus.getPlugInsPath();
  1228. if (path==null) return null;
  1229. String ijdir = (new File(path)).getParent();
  1230. if (ijdir!=null) ijdir += File.separator;
  1231. return ijdir;
  1232. }
  1233. /** Displays a file open dialog box and then opens the tiff, dicom,
  1234. fits, pgm, jpeg, bmp, gif, lut, roi, or text file selected by
  1235. the user. Displays an error message if the selected file is not
  1236. in one of the supported formats, or if it is not found. */
  1237. public static void open() {
  1238. open(null);
  1239. }
  1240. /** Opens and displays a tiff, dicom, fits, pgm, jpeg, bmp, gif, lut,
  1241. roi, or text file. Displays an error message if the specified file
  1242. is not in one of the supported formats, or if it is not found.
  1243. With 1.41k or later, opens images specified by a URL.
  1244. */
  1245. public static void open(String path) {
  1246. if (ij==null && Menus.getCommands()==null) init();
  1247. Opener o = new Opener();
  1248. macroRunning = true;
  1249. if (path==null || path.equals(""))
  1250. o.open();
  1251. else
  1252. o.open(path);
  1253. macroRunning = false;
  1254. }
  1255. /** Opens and displays the nth image in the specified tiff stack. */
  1256. public static void open(String path, int n) {
  1257. if (ij==null && Menus.getCommands()==null) init();
  1258. ImagePlus imp = openImage(path, n);
  1259. if (imp!=null) imp.show();
  1260. }
  1261. /** Opens the specified file as a tiff, bmp, dicom, fits, pgm, gif
  1262. or jpeg image and returns an ImagePlus object if successful.
  1263. Calls HandleExtraFileTypes plugin if the file type is not recognised.
  1264. Displays a file open dialog if 'path' is null or an empty string.
  1265. Note that 'path' can also be a URL. Some reader plugins, including
  1266. the Bio-Formats plugin, display the image and return null. */
  1267. public static ImagePlus openImage(String path) {
  1268. return (new Opener()).openImage(path);
  1269. }
  1270. /** Opens the nth image of the specified tiff stack. */
  1271. public static ImagePlus openImage(String path, int n) {
  1272. return (new Opener()).openImage(path, n);
  1273. }
  1274. /** Opens an image using a file open dialog and returns it as an ImagePlus object. */
  1275. public static ImagePlus openImage() {
  1276. return openImage(null);
  1277. }
  1278. /** Opens a URL and returns the contents as a string.
  1279. Returns "<Error: message>" if there an error, including
  1280. host or file not found. */
  1281. public static String openUrlAsString(String url) {
  1282. StringBuffer sb = null;
  1283. url = url.replaceAll(" ", "%20");
  1284. try {
  1285. URL u = new URL(url);
  1286. URLConnection uc = u.openConnection();
  1287. long len = uc.getContentLength();
  1288. if (len>1048576L)
  1289. return "<Error: file is larger than 1MB>";
  1290. InputStream in = u.openStream();
  1291. BufferedReader br = new BufferedReader(new InputStreamReader(in));
  1292. sb = new StringBuffer() ;
  1293. String line;
  1294. while ((line=br.readLine()) != null)
  1295. sb.append (line + "\n");
  1296. in.close ();
  1297. } catch (Exception e) {
  1298. return("<Error: "+e+">");
  1299. }
  1300. if (sb!=null)
  1301. return new String(sb);
  1302. else
  1303. return "";
  1304. }
  1305. /** Saves the current image, lookup table, selection or text window to the specified file path.
  1306. The path must end in ".tif", ".jpg", ".gif", ".zip", ".raw", ".avi", ".bmp", ".fits", ".pgm", ".png", ".lut", ".roi" or ".txt". */
  1307. public static void save(String path) {
  1308. save(null, path);
  1309. }
  1310. /** Saves the specified image, lookup table or selection to the specified file path.
  1311. The path must end in ".tif", ".jpg", ".gif", ".zip", ".raw", ".avi", ".bmp", ".fits", ".pgm", ".png", ".lut", ".roi" or ".txt". */
  1312. public static void save(ImagePlus imp, String path) {
  1313. int dotLoc = path.lastIndexOf('.');
  1314. if (dotLoc!=-1) {
  1315. ImagePlus imp2 = imp;
  1316. if (imp2==null) imp2 = WindowManager.getCurrentImage();
  1317. String title = imp2!=null?imp2.getTitle():null;
  1318. saveAs(imp, path.substring(dotLoc+1), path);
  1319. if (title!=null) imp2.setTitle(title);
  1320. } else
  1321. error("The save() macro function requires a file name extension.\n \n"+path);
  1322. }
  1323. /* Saves the active image, lookup table, selection, measurement results, selection XY
  1324. coordinates or text window to the specified file path. The format argument must be "tiff",
  1325. "jpeg", "gif", "zip", "raw", "avi", "bmp", "fit…

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