PageRenderTime 84ms CodeModel.GetById 44ms RepoModel.GetById 0ms app.codeStats 1ms

/src/ij/IJ.java

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