PageRenderTime 78ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/ij/IJ.java

https://github.com/imagej/imagej1
Java | 2589 lines | 2010 code | 189 blank | 390 comment | 474 complexity | 68e52a630aa6a54a7e540fe599ed0dfa 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.plugin.frame.ThresholdAdjuster;
  11. import ij.macro.Interpreter;
  12. import ij.macro.MacroRunner;
  13. import ij.measure.Calibration;
  14. import ij.measure.ResultsTable;
  15. import ij.measure.Measurements;
  16. import java.awt.event.*;
  17. import java.text.*;
  18. import java.util.*;
  19. import java.awt.*;
  20. import java.applet.Applet;
  21. import java.io.*;
  22. import java.lang.reflect.*;
  23. import java.net.*;
  24. import javax.net.ssl.*;
  25. import java.security.cert.*;
  26. import java.security.KeyStore;
  27. import java.nio.ByteBuffer;
  28. import java.math.RoundingMode;
  29. /** This class consists of static utility methods. */
  30. public class IJ {
  31. /** SansSerif, plain, 10-point font */
  32. public static Font font10 = new Font("SansSerif", Font.PLAIN, 10);
  33. /** SansSerif, plain, 12-point font */
  34. public static Font font12 = ImageJ.SansSerif12;
  35. /** Image display modes */
  36. public static final int COMPOSITE=1, COLOR=2, GRAYSCALE=3;
  37. public static final String URL = "http://imagej.nih.gov/ij";
  38. public static final int ALL_KEYS = -1;
  39. /** Use setDebugMode(boolean) to enable/disable debug mode. */
  40. public static boolean debugMode;
  41. public static boolean hideProcessStackDialog;
  42. public static final char micronSymbol = '\u00B5';
  43. public static final char angstromSymbol = '\u00C5';
  44. public static final char degreeSymbol = '\u00B0';
  45. private static ImageJ ij;
  46. private static java.applet.Applet applet;
  47. private static ProgressBar progressBar;
  48. private static TextPanel textPanel;
  49. private static String osname, osarch;
  50. private static boolean isMac, isWin, isLinux, is64Bit;
  51. private static int javaVersion;
  52. private static boolean controlDown, altDown, spaceDown, shiftDown;
  53. private static boolean macroRunning;
  54. private static Thread previousThread;
  55. private static TextPanel logPanel;
  56. private static boolean checkForDuplicatePlugins = true;
  57. private static ClassLoader classLoader;
  58. private static boolean memMessageDisplayed;
  59. private static long maxMemory;
  60. private static boolean escapePressed;
  61. private static boolean redirectErrorMessages;
  62. private static boolean suppressPluginNotFoundError;
  63. private static Hashtable commandTable;
  64. private static Vector eventListeners = new Vector();
  65. private static String lastErrorMessage;
  66. private static Properties properties; private static DecimalFormat[] df;
  67. private static DecimalFormat[] sf;
  68. private static DecimalFormatSymbols dfs;
  69. private static boolean trustManagerCreated;
  70. private static String smoothMacro;
  71. private static Interpreter macroInterpreter;
  72. private static boolean protectStatusBar;
  73. private static Thread statusBarThread;
  74. static {
  75. osname = System.getProperty("os.name");
  76. isWin = osname.startsWith("Windows");
  77. isMac = !isWin && osname.startsWith("Mac");
  78. isLinux = osname.startsWith("Linux");
  79. String version = System.getProperty("java.version");
  80. if (version==null || version.length()<2)
  81. version = "1.8";
  82. if (version.startsWith("1.8"))
  83. javaVersion = 8;
  84. else if (version.charAt(0)=='1' && Character.isDigit(version.charAt(1)))
  85. javaVersion = 10 + (version.charAt(1) - '0');
  86. else if (version.charAt(0)=='2' && Character.isDigit(version.charAt(1)))
  87. javaVersion = 20 + (version.charAt(1) - '0');
  88. else if (version.startsWith("1.6"))
  89. javaVersion = 6;
  90. else if (version.startsWith("1.9")||version.startsWith("9"))
  91. javaVersion = 9;
  92. else if (version.startsWith("1.7"))
  93. javaVersion = 7;
  94. else
  95. javaVersion = 8;
  96. dfs = new DecimalFormatSymbols(Locale.US);
  97. df = new DecimalFormat[10];
  98. df[0] = new DecimalFormat("0", dfs);
  99. df[1] = new DecimalFormat("0.0", dfs);
  100. df[2] = new DecimalFormat("0.00", dfs);
  101. df[3] = new DecimalFormat("0.000", dfs);
  102. df[4] = new DecimalFormat("0.0000", dfs);
  103. df[5] = new DecimalFormat("0.00000", dfs);
  104. df[6] = new DecimalFormat("0.000000", dfs);
  105. df[7] = new DecimalFormat("0.0000000", dfs);
  106. df[8] = new DecimalFormat("0.00000000", dfs);
  107. df[9] = new DecimalFormat("0.000000000", dfs);
  108. df[0].setRoundingMode(RoundingMode.HALF_UP);
  109. }
  110. static void init(ImageJ imagej, Applet theApplet) {
  111. ij = imagej;
  112. applet = theApplet;
  113. progressBar = ij.getProgressBar();
  114. }
  115. static void cleanup() {
  116. ij=null; applet=null; progressBar=null; textPanel=null;
  117. }
  118. /**Returns a reference to the "ImageJ" frame.*/
  119. public static ImageJ getInstance() {
  120. return ij;
  121. }
  122. /**Enable/disable debug mode.*/
  123. public static void setDebugMode(boolean b) {
  124. debugMode = b;
  125. LogStream.redirectSystem(debugMode);
  126. }
  127. /** Runs the macro contained in the string <code>macro</code>
  128. on the current thread. Returns any string value returned by
  129. the macro, null if the macro does not return a value, or
  130. "[aborted]" if the macro was aborted due to an error. The
  131. equivalent macro function is eval(). */
  132. public static String runMacro(String macro) {
  133. return runMacro(macro, "");
  134. }
  135. /** Runs the macro contained in the string <code>macro</code>
  136. on the current thread. The optional string argument can be
  137. retrieved in the called macro using the getArgument() macro
  138. function. Returns any string value returned by the macro, null
  139. if the macro does not return a value, or "[aborted]" if the
  140. macro was aborted due to an error. */
  141. public static String runMacro(String macro, String arg) {
  142. Macro_Runner mr = new Macro_Runner();
  143. return mr.runMacro(macro, arg);
  144. }
  145. /** Runs the specified macro or script file in the current thread.
  146. The file is assumed to be in the macros folder
  147. unless <code>name</code> is a full path.
  148. The optional string argument (<code>arg</code>) can be retrieved in the called
  149. macro or script using the getArgument() function.
  150. Returns any string value returned by the macro, or null. Scripts always return null.
  151. The equivalent macro function is runMacro(). */
  152. public static String runMacroFile(String name, String arg) {
  153. Macro_Runner mr = new Macro_Runner();
  154. return mr.runMacroFile(name, arg);
  155. }
  156. /** Runs the specified macro file. */
  157. public static String runMacroFile(String name) {
  158. return runMacroFile(name, null);
  159. }
  160. /** Runs the specified plugin using the specified image. */
  161. public static Object runPlugIn(ImagePlus imp, String className, String arg) {
  162. if (imp!=null) {
  163. ImagePlus temp = WindowManager.getTempCurrentImage();
  164. WindowManager.setTempCurrentImage(imp);
  165. Object o = runPlugIn("", className, arg);
  166. WindowManager.setTempCurrentImage(temp);
  167. return o;
  168. } else
  169. return runPlugIn(className, arg);
  170. }
  171. /** Runs the specified plugin and returns a reference to it. */
  172. public static Object runPlugIn(String className, String arg) {
  173. return runPlugIn("", className, arg);
  174. }
  175. /** Runs the specified plugin and returns a reference to it. */
  176. public static Object runPlugIn(String commandName, String className, String arg) {
  177. if (arg==null) arg = "";
  178. if (IJ.debugMode)
  179. IJ.log("runPlugIn: "+className+argument(arg));
  180. // Load using custom classloader if this is a user
  181. // plugin and we are not running as an applet
  182. if (!className.startsWith("ij.") && applet==null)
  183. return runUserPlugIn(commandName, className, arg, false);
  184. Object thePlugIn=null;
  185. try {
  186. Class c = Class.forName(className);
  187. thePlugIn = c.newInstance();
  188. if (thePlugIn instanceof PlugIn)
  189. ((PlugIn)thePlugIn).run(arg);
  190. else
  191. new PlugInFilterRunner(thePlugIn, commandName, arg);
  192. } catch (ClassNotFoundException e) {
  193. if (!(className!=null && className.startsWith("ij.plugin.MacAdapter"))) {
  194. log("Plugin or class not found: \"" + className + "\"\n(" + e+")");
  195. String path = Prefs.getCustomPropsPath();
  196. if (path!=null);
  197. log("Error may be due to custom properties at " + path);
  198. }
  199. }
  200. catch (InstantiationException e) {log("Unable to load plugin (ins)");}
  201. catch (IllegalAccessException e) {log("Unable to load plugin, possibly \nbecause it is not public.");}
  202. redirectErrorMessages = false;
  203. return thePlugIn;
  204. }
  205. static Object runUserPlugIn(String commandName, String className, String arg, boolean createNewLoader) {
  206. if (IJ.debugMode)
  207. IJ.log("runUserPlugIn: "+className+", arg="+argument(arg));
  208. if (applet!=null) return null;
  209. if (checkForDuplicatePlugins) {
  210. // check for duplicate classes and jars in the plugins folder
  211. IJ.runPlugIn("ij.plugin.ClassChecker", "");
  212. checkForDuplicatePlugins = false;
  213. }
  214. if (createNewLoader)
  215. classLoader = null;
  216. ClassLoader loader = getClassLoader();
  217. Object thePlugIn = null;
  218. try {
  219. thePlugIn = (loader.loadClass(className)).newInstance();
  220. if (thePlugIn instanceof PlugIn)
  221. ((PlugIn)thePlugIn).run(arg);
  222. else if (thePlugIn instanceof PlugInFilter)
  223. new PlugInFilterRunner(thePlugIn, commandName, arg);
  224. }
  225. catch (ClassNotFoundException e) {
  226. if (className.startsWith("macro:"))
  227. runMacro(className.substring(6));
  228. else if (className.contains("_") && !suppressPluginNotFoundError)
  229. error("Plugin or class not found: \"" + className + "\"\n(" + e+")");
  230. }
  231. catch (NoClassDefFoundError e) {
  232. int dotIndex = className.indexOf('.');
  233. if (dotIndex>=0 && className.contains("_")) {
  234. // rerun plugin after removing folder name
  235. if (debugMode) IJ.log("runUserPlugIn: rerunning "+className);
  236. return runUserPlugIn(commandName, className.substring(dotIndex+1), arg, createNewLoader);
  237. }
  238. if (className.contains("_") && !suppressPluginNotFoundError)
  239. error("Run User Plugin", "Class not found while attempting to run \"" + className + "\"\n \n " + e);
  240. }
  241. catch (InstantiationException e) {error("Unable to load plugin (ins)");}
  242. catch (IllegalAccessException e) {error("Unable to load plugin, possibly \nbecause it is not public.");}
  243. if (thePlugIn!=null && !"HandleExtraFileTypes".equals(className))
  244. redirectErrorMessages = false;
  245. suppressPluginNotFoundError = false;
  246. return thePlugIn;
  247. }
  248. private static String argument(String arg) {
  249. return arg!=null && !arg.equals("") && !arg.contains("\n")?"(\""+arg+"\")":"";
  250. }
  251. static void wrongType(int capabilities, String cmd) {
  252. String s = "\""+cmd+"\" requires an image of type:\n \n";
  253. if ((capabilities&PlugInFilter.DOES_8G)!=0) s += " 8-bit grayscale\n";
  254. if ((capabilities&PlugInFilter.DOES_8C)!=0) s += " 8-bit color\n";
  255. if ((capabilities&PlugInFilter.DOES_16)!=0) s += " 16-bit grayscale\n";
  256. if ((capabilities&PlugInFilter.DOES_32)!=0) s += " 32-bit (float) grayscale\n";
  257. if ((capabilities&PlugInFilter.DOES_RGB)!=0) s += " RGB color\n";
  258. error(s);
  259. }
  260. /** Runs a menu command on a separete thread and returns immediately. */
  261. public static void doCommand(String command) {
  262. new Executer(command, null);
  263. }
  264. /** Runs a menu command on a separete thread, using the specified image. */
  265. public static void doCommand(ImagePlus imp, String command) {
  266. new Executer(command, imp);
  267. }
  268. /** Runs an ImageJ command. Does not return until
  269. the command has finished executing. To avoid "image locked",
  270. errors, plugins that call this method should implement
  271. the PlugIn interface instead of PlugInFilter. */
  272. public static void run(String command) {
  273. run(command, null);
  274. }
  275. /** Runs an ImageJ command, with options that are passed to the
  276. GenericDialog and OpenDialog classes. Does not return until
  277. the command has finished executing. To generate run() calls,
  278. start the recorder (Plugins/Macro/Record) and run commands
  279. from the ImageJ menu bar.
  280. */
  281. public static void run(String command, String options) {
  282. //IJ.log("run1: "+command+" "+Thread.currentThread().hashCode()+" "+options);
  283. if (ij==null && Menus.getCommands()==null)
  284. init();
  285. Macro.abort = false;
  286. Macro.setOptions(options);
  287. Thread thread = Thread.currentThread();
  288. if (previousThread==null || thread!=previousThread) {
  289. String name = thread.getName();
  290. if (!name.startsWith("Run$_"))
  291. thread.setName("Run$_"+name);
  292. }
  293. command = convert(command);
  294. previousThread = thread;
  295. macroRunning = true;
  296. Executer e = new Executer(command);
  297. e.run();
  298. macroRunning = false;
  299. Macro.setOptions(null);
  300. testAbort();
  301. macroInterpreter = null;
  302. //IJ.log("run2: "+command+" "+Thread.currentThread().hashCode());
  303. }
  304. /** The macro interpreter uses this method to run commands. */
  305. public static void run(Interpreter interpreter, String command, String options) {
  306. macroInterpreter = interpreter;
  307. run(command, options);
  308. macroInterpreter = null;
  309. }
  310. /** Converts commands that have been renamed so
  311. macros using the old names continue to work. */
  312. private static String convert(String command) {
  313. if (commandTable==null) {
  314. commandTable = new Hashtable(30);
  315. commandTable.put("New...", "Image...");
  316. commandTable.put("Threshold", "Make Binary");
  317. commandTable.put("Display...", "Appearance...");
  318. commandTable.put("Start Animation", "Start Animation [\\]");
  319. commandTable.put("Convert Images to Stack", "Images to Stack");
  320. commandTable.put("Convert Stack to Images", "Stack to Images");
  321. commandTable.put("Convert Stack to RGB", "Stack to RGB");
  322. commandTable.put("Convert to Composite", "Make Composite");
  323. commandTable.put("RGB Split", "Split Channels");
  324. commandTable.put("RGB Merge...", "Merge Channels...");
  325. commandTable.put("Channels...", "Channels Tool...");
  326. commandTable.put("New... ", "Table...");
  327. commandTable.put("Arbitrarily...", "Rotate... ");
  328. commandTable.put("Measurements...", "Results... ");
  329. commandTable.put("List Commands...", "Find Commands...");
  330. commandTable.put("Capture Screen ", "Capture Screen");
  331. commandTable.put("Add to Manager ", "Add to Manager");
  332. commandTable.put("In", "In [+]");
  333. commandTable.put("Out", "Out [-]");
  334. commandTable.put("Enhance Contrast", "Enhance Contrast...");
  335. commandTable.put("XY Coodinates... ", "XY Coordinates... ");
  336. commandTable.put("Statistics...", "Statistics");
  337. commandTable.put("Channels Tool... ", "Channels Tool...");
  338. commandTable.put("Profile Plot Options...", "Plots...");
  339. commandTable.put("AuPbSn 40 (56K)", "AuPbSn 40");
  340. commandTable.put("Bat Cochlea Volume (19K)", "Bat Cochlea Volume");
  341. commandTable.put("Bat Cochlea Renderings (449K)", "Bat Cochlea Renderings");
  342. commandTable.put("Blobs (25K)", "Blobs");
  343. commandTable.put("Boats (356K)", "Boats");
  344. commandTable.put("Cardio (768K, RGB DICOM)", "Cardio (RGB DICOM)");
  345. commandTable.put("Cell Colony (31K)", "Cell Colony");
  346. commandTable.put("Clown (14K)", "Clown");
  347. commandTable.put("Confocal Series (2.2MB)", "Confocal Series");
  348. commandTable.put("CT (420K, 16-bit DICOM)", "CT (16-bit DICOM)");
  349. commandTable.put("Dot Blot (7K)", "Dot Blot");
  350. commandTable.put("Embryos (42K)", "Embryos");
  351. commandTable.put("Fluorescent Cells (400K)", "Fluorescent Cells");
  352. commandTable.put("Fly Brain (1MB)", "Fly Brain");
  353. commandTable.put("Gel (105K)", "Gel");
  354. commandTable.put("HeLa Cells (1.3M, 48-bit RGB)", "HeLa Cells (48-bit RGB)");
  355. commandTable.put("Leaf (36K)", "Leaf");
  356. commandTable.put("Line Graph (21K)", "Line Graph");
  357. commandTable.put("Mitosis (26MB, 5D stack)", "Mitosis (5D stack)");
  358. commandTable.put("MRI Stack (528K)", "MRI Stack");
  359. commandTable.put("M51 Galaxy (177K, 16-bits)", "M51 Galaxy (16-bits)");
  360. commandTable.put("Neuron (1.6M, 5 channels)", "Neuron (5 channels)");
  361. commandTable.put("Nile Bend (1.9M)", "Nile Bend");
  362. commandTable.put("Organ of Corti (2.8M, 4D stack)", "Organ of Corti (4D stack)");
  363. commandTable.put("Particles (75K)", "Particles");
  364. commandTable.put("T1 Head (2.4M, 16-bits)", "T1 Head (16-bits)");
  365. commandTable.put("T1 Head Renderings (736K)", "T1 Head Renderings");
  366. commandTable.put("TEM Filter (112K)", "TEM Filter");
  367. commandTable.put("Tree Rings (48K)", "Tree Rings");
  368. }
  369. String command2 = (String)commandTable.get(command);
  370. if (command2!=null)
  371. return command2;
  372. else
  373. return command;
  374. }
  375. /** Runs an ImageJ command using the specified image and options.
  376. To generate run() calls, start the recorder (Plugins/Macro/Record)
  377. and run commands from the ImageJ menu bar.*/
  378. public static void run(ImagePlus imp, String command, String options) {
  379. if (ij==null && Menus.getCommands()==null)
  380. init();
  381. if (imp!=null) {
  382. ImagePlus temp = WindowManager.getTempCurrentImage();
  383. WindowManager.setTempCurrentImage(imp);
  384. run(command, options);
  385. WindowManager.setTempCurrentImage(temp);
  386. } else
  387. run(command, options);
  388. }
  389. static void init() {
  390. Menus m = new Menus(null, null);
  391. Prefs.load(m, null);
  392. m.addMenuBar();
  393. }
  394. private static void testAbort() {
  395. if (Macro.abort)
  396. abort();
  397. }
  398. /** Returns true if the run(), open() or newImage() method is executing. */
  399. public static boolean macroRunning() {
  400. return macroRunning;
  401. }
  402. /** Returns true if a macro is running, or if the run(), open()
  403. or newImage() method is executing. */
  404. public static boolean isMacro() {
  405. return macroRunning || Interpreter.getInstance()!=null;
  406. }
  407. /**Returns the Applet that created this ImageJ or null if running as an application.*/
  408. public static java.applet.Applet getApplet() {
  409. return applet;
  410. }
  411. /**Displays a message in the ImageJ status bar. If 's' starts
  412. with '!', subsequent showStatus() calls in the current
  413. thread (without "!" in the message) are suppressed. */
  414. public static void showStatus(String s) {
  415. if ((Interpreter.getInstance()==null&&statusBarThread==null)
  416. || (statusBarThread!=null&&Thread.currentThread()!=statusBarThread))
  417. protectStatusBar(false);
  418. boolean doProtect = s.startsWith("!"); // suppress subsequent showStatus() calls
  419. if (doProtect) {
  420. protectStatusBar(true);
  421. statusBarThread = Thread.currentThread();
  422. s = s.substring(1);
  423. }
  424. if (doProtect || !protectStatusBar) {
  425. if (ij!=null)
  426. ij.showStatus(s);
  427. ImagePlus imp = WindowManager.getCurrentImage();
  428. ImageCanvas ic = imp!=null?imp.getCanvas():null;
  429. if (ic!=null)
  430. ic.setShowCursorStatus(s.length()==0?true:false);
  431. }
  432. }
  433. /**Displays a message in the status bar and flashes
  434. * either the status bar or the active image.<br>
  435. * See: http://wsr.imagej.net/macros/FlashingStatusMessages.txt
  436. */
  437. public static void showStatus(String message, String options) {
  438. showStatus(message);
  439. if (options==null)
  440. return;
  441. options = options.replace("flash", "");
  442. options = options.replace("ms", "");
  443. Color optionalColor = null;
  444. int index1 = options.indexOf("#");
  445. if (index1>=0) { // hex color?
  446. int index2 = options.indexOf(" ", index1);
  447. if (index2==-1) index2 = options.length();
  448. String hexColor = options.substring(index1, index2);
  449. optionalColor = Colors.decode(hexColor, null);
  450. options = options.replace(hexColor, "");
  451. }
  452. if (optionalColor==null) { // "red", "green", etc.
  453. for (String c : Colors.colors) {
  454. if (options.contains(c)) {
  455. optionalColor = Colors.getColor(c, ImageJ.backgroundColor);
  456. options = options.replace(c, "");
  457. break;
  458. }
  459. }
  460. }
  461. boolean flashImage = options.contains("image");
  462. Color defaultColor = new Color(255,255,245);
  463. int defaultDelay = 500;
  464. ImagePlus imp = WindowManager.getCurrentImage();
  465. if (flashImage) {
  466. options = options.replace("image", "");
  467. if (imp!=null && imp.getWindow()!=null) {
  468. defaultColor = Color.black;
  469. defaultDelay = 100;
  470. }
  471. else
  472. flashImage = false;
  473. }
  474. Color color = optionalColor!=null?optionalColor:defaultColor;
  475. int delay = (int)Tools.parseDouble(options, defaultDelay);
  476. if (delay>8000)
  477. delay = 8000;
  478. String colorString = null;
  479. ImageJ ij = IJ.getInstance();
  480. if (flashImage) {
  481. Color previousColor = imp.getWindow().getBackground();
  482. imp.getWindow().setBackground(color);
  483. if (delay>0) {
  484. wait(delay);
  485. imp.getWindow().setBackground(previousColor);
  486. }
  487. } else if (ij!=null) {
  488. ij.getStatusBar().setBackground(color);
  489. wait(delay);
  490. ij.getStatusBar().setBackground(ij.backgroundColor);
  491. }
  492. }
  493. /**
  494. * @deprecated
  495. * replaced by IJ.log(), ResultsTable.setResult() and TextWindow.append().
  496. * There are examples at
  497. * http://imagej.nih.gov/ij/plugins/sine-cosine.html
  498. */
  499. public static void write(String s) {
  500. if (textPanel==null && ij!=null)
  501. showResults();
  502. if (textPanel!=null)
  503. textPanel.append(s);
  504. else
  505. System.out.println(s);
  506. }
  507. private static void showResults() {
  508. TextWindow resultsWindow = new TextWindow("Results", "", 400, 250);
  509. textPanel = resultsWindow.getTextPanel();
  510. textPanel.setResultsTable(Analyzer.getResultsTable());
  511. }
  512. public static synchronized void log(String s) {
  513. if (s==null) return;
  514. if (logPanel==null && ij!=null) {
  515. TextWindow logWindow = new TextWindow("Log", "", 400, 250);
  516. logPanel = logWindow.getTextPanel();
  517. logPanel.setFont(new Font("SansSerif", Font.PLAIN, 16));
  518. }
  519. if (logPanel!=null) {
  520. if (s.startsWith("\\"))
  521. handleLogCommand(s);
  522. else {
  523. if (s.endsWith("\n")) {
  524. if (s.equals("\n\n"))
  525. s= "\n \n ";
  526. else if (s.endsWith("\n\n"))
  527. s = s.substring(0, s.length()-2)+"\n \n ";
  528. else
  529. s = s+" ";
  530. }
  531. logPanel.append(s);
  532. }
  533. } else {
  534. LogStream.redirectSystem(false);
  535. System.out.println(s);
  536. }
  537. }
  538. static void handleLogCommand(String s) {
  539. if (s.equals("\\Closed"))
  540. logPanel = null;
  541. else if (s.startsWith("\\Update:")) {
  542. int n = logPanel.getLineCount();
  543. String s2 = s.substring(8, s.length());
  544. if (n==0)
  545. logPanel.append(s2);
  546. else
  547. logPanel.setLine(n-1, s2);
  548. } else if (s.startsWith("\\Update")) {
  549. int cindex = s.indexOf(":");
  550. if (cindex==-1)
  551. {logPanel.append(s); return;}
  552. String nstr = s.substring(7, cindex);
  553. int line = (int)Tools.parseDouble(nstr, -1);
  554. if (line<0 || line>25)
  555. {logPanel.append(s); return;}
  556. int count = logPanel.getLineCount();
  557. while (line>=count) {
  558. log("");
  559. count++;
  560. }
  561. String s2 = s.substring(cindex+1, s.length());
  562. logPanel.setLine(line, s2);
  563. } else if (s.equals("\\Clear")) {
  564. logPanel.clear();
  565. } else if (s.startsWith("\\Heading:")) {
  566. logPanel.updateColumnHeadings(s.substring(10));
  567. } else if (s.equals("\\Close")) {
  568. Frame f = WindowManager.getFrame("Log");
  569. if (f!=null && (f instanceof TextWindow))
  570. ((TextWindow)f).close();
  571. } else
  572. logPanel.append(s);
  573. }
  574. /** Returns the contents of the Log window or null if the Log window is not open. */
  575. public static synchronized String getLog() {
  576. if (logPanel==null || ij==null)
  577. return null;
  578. else
  579. return logPanel.getText();
  580. }
  581. /** Clears the "Results" window and sets the column headings to
  582. those in the tab-delimited 'headings' String. Writes to
  583. System.out.println if the "ImageJ" frame is not present.*/
  584. public static void setColumnHeadings(String headings) {
  585. if (textPanel==null && ij!=null)
  586. showResults();
  587. if (textPanel!=null)
  588. textPanel.setColumnHeadings(headings);
  589. else
  590. System.out.println(headings);
  591. }
  592. /** Returns true if the "Results" window is open. */
  593. public static boolean isResultsWindow() {
  594. return textPanel!=null;
  595. }
  596. /** Renames a results window. */
  597. public static void renameResults(String title) {
  598. Frame frame = WindowManager.getFrontWindow();
  599. if (frame!=null && (frame instanceof TextWindow)) {
  600. TextWindow tw = (TextWindow)frame;
  601. if (tw.getResultsTable()==null) {
  602. IJ.error("Rename", "\""+tw.getTitle()+"\" is not a results table");
  603. return;
  604. }
  605. tw.rename(title);
  606. } else if (isResultsWindow()) {
  607. TextPanel tp = getTextPanel();
  608. TextWindow tw = (TextWindow)tp.getParent();
  609. tw.rename(title);
  610. }
  611. }
  612. /** Changes the name of a table window from 'oldTitle' to 'newTitle'. */
  613. public static void renameResults(String oldTitle, String newTitle) {
  614. Frame frame = WindowManager.getFrame(oldTitle);
  615. if (frame==null) {
  616. error("Rename", "\""+oldTitle+"\" not found");
  617. return;
  618. } else if (frame instanceof TextWindow) {
  619. TextWindow tw = (TextWindow)frame;
  620. if (tw.getResultsTable()==null) {
  621. error("Rename", "\""+oldTitle+"\" is not a table");
  622. return;
  623. }
  624. tw.rename(newTitle);
  625. } else
  626. error("Rename", "\""+oldTitle+"\" is not a table");
  627. }
  628. /** Deletes 'row1' through 'row2' of the "Results" window, where
  629. 'row1' and 'row2' must be in the range 0-Analyzer.getCounter()-1. */
  630. public static void deleteRows(int row1, int row2) {
  631. ResultsTable rt = Analyzer.getResultsTable();
  632. int tableSize = rt.size();
  633. rt.deleteRows(row1, row2);
  634. ImagePlus imp = WindowManager.getCurrentImage();
  635. if (imp!=null)
  636. Overlay.updateTableOverlay(imp, row1, row2, tableSize);
  637. rt.show("Results");
  638. }
  639. /** Returns a measurement result, where 'measurement' is "Area",
  640. * "Mean", "StdDev", "Mode", "Min", "Max", "X", "Y", "XM", "YM",
  641. * "Perim.", "BX", "BY", "Width", "Height", "Major", "Minor", "Angle",
  642. * "Circ.", "Feret", "IntDen", "Median", "Skew", "Kurt", "%Area",
  643. * "RawIntDen", "Ch", "Slice", "Frame", "FeretX", "FeretY",
  644. * "FeretAngle", "MinFeret", "AR", "Round", "Solidity", "MinThr"
  645. * or "MaxThr". Add " raw" to the argument to disable calibration,
  646. * for example IJ.getValue("Mean raw"). Add " limit" to enable
  647. * the "limit to threshold" option.
  648. */
  649. public static double getValue(ImagePlus imp, String measurement) {
  650. String options = "";
  651. int index = measurement.indexOf(" ");
  652. if (index>0) {
  653. if (index<measurement.length()-1)
  654. options = measurement.substring(index+1, measurement.length());
  655. measurement = measurement.substring(0, index);
  656. }
  657. int measurements = Measurements.ALL_STATS + Measurements.SLICE;
  658. if (options.contains("limit"))
  659. measurements += Measurements.LIMIT;
  660. Calibration cal = null;
  661. if (options.contains("raw")) {
  662. cal = imp.getCalibration();
  663. imp.setCalibration(null);
  664. }
  665. ResultsTable rt = new ResultsTable();
  666. Analyzer analyzer = new Analyzer(imp, measurements, rt);
  667. analyzer.measure();
  668. double value = Double.NaN;
  669. try {
  670. value = rt.getValue(measurement, 0);
  671. } catch (Exception e) {};
  672. if (cal!=null)
  673. imp.setCalibration(cal);
  674. return value;
  675. }
  676. /** Returns a reference to the "Results" window TextPanel.
  677. Opens the "Results" window if it is currently not open.
  678. Returns null if the "ImageJ" window is not open. */
  679. public static TextPanel getTextPanel() {
  680. if (textPanel==null && ij!=null)
  681. showResults();
  682. return textPanel;
  683. }
  684. /** TextWindow calls this method with a null argument when the "Results" window is closed. */
  685. public static void setTextPanel(TextPanel tp) {
  686. textPanel = tp;
  687. }
  688. /**Displays a "no images are open" dialog box.*/
  689. public static void noImage() {
  690. String msg = "There are no images open";
  691. if (macroInterpreter!=null) {
  692. macroInterpreter.abort(msg);
  693. macroInterpreter = null;
  694. } else
  695. error("No Image", msg);
  696. }
  697. /** Displays an "out of memory" message to the "Log" window. */
  698. public static void outOfMemory(String name) {
  699. Undo.reset();
  700. System.gc();
  701. lastErrorMessage = "out of memory";
  702. String tot = Runtime.getRuntime().maxMemory()/1048576L+"MB";
  703. if (!memMessageDisplayed)
  704. log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
  705. log("<Out of memory>");
  706. if (!memMessageDisplayed) {
  707. log("<All available memory ("+tot+") has been>");
  708. log("<used. To make more available, use the>");
  709. log("<Edit>Options>Memory & Threads command.>");
  710. log(">>>>>>>>>>>>>>>>>>>>>>>>>>>");
  711. memMessageDisplayed = true;
  712. }
  713. Macro.abort();
  714. }
  715. /** Updates the progress bar, where 0<=progress<=1.0. The progress bar is
  716. not shown in BatchMode and erased if progress>=1.0. The progress bar is
  717. updated only if more than 90 ms have passes since the last call. Does nothing
  718. if the ImageJ window is not present. */
  719. public static void showProgress(double progress) {
  720. if (progressBar!=null) progressBar.show(progress, false);
  721. }
  722. /** Updates the progress bar, where the length of the bar is set to
  723. * (<code>currentValue+1)/finalValue</code> of the maximum bar length.
  724. * The bar is erased if <code>currentValue&gt;=finalValue</code>.
  725. * The bar is updated only if more than 90 ms have passed since the
  726. * last call. Displays subordinate progress bars as dots if
  727. * 'currentIndex' is negative (example: Plugins/Utilities/Benchmark).
  728. */
  729. public static void showProgress(int currentIndex, int finalIndex) {
  730. if (progressBar!=null) {
  731. progressBar.show(currentIndex, finalIndex);
  732. if (currentIndex==finalIndex)
  733. progressBar.setBatchMode(false);
  734. }
  735. }
  736. /** Displays a message in a dialog box titled "Message".
  737. Writes the Java console if ImageJ is not present. */
  738. public static void showMessage(String msg) {
  739. showMessage("Message", msg);
  740. }
  741. /** Displays a message in a dialog box with the specified title.
  742. Displays HTML formatted text if 'msg' starts with "<html>".
  743. There are examples at
  744. "http://imagej.nih.gov/ij/macros/HtmlDialogDemo.txt".
  745. Writes to the Java console if ImageJ is not present. */
  746. public static void showMessage(String title, String msg) {
  747. if (ij!=null) {
  748. if (msg!=null && (msg.startsWith("<html>")||msg.startsWith("<HTML>"))) {
  749. HTMLDialog hd = new HTMLDialog(title, msg);
  750. if (isMacro() && hd.escapePressed())
  751. throw new RuntimeException(Macro.MACRO_CANCELED);
  752. } else {
  753. MessageDialog md = new MessageDialog(ij, title, msg);
  754. if (isMacro() && md.escapePressed())
  755. throw new RuntimeException(Macro.MACRO_CANCELED);
  756. }
  757. } else
  758. System.out.println(msg);
  759. }
  760. /** Displays a message in a dialog box titled "ImageJ". If a
  761. macro or JavaScript is running, it is aborted. Writes to the
  762. Java console if the ImageJ window is not present.*/
  763. public static void error(String msg) {
  764. error(null, msg);
  765. if (Thread.currentThread().getName().endsWith("JavaScript"))
  766. throw new RuntimeException(Macro.MACRO_CANCELED);
  767. else
  768. Macro.abort();
  769. }
  770. /** Displays a message in a dialog box with the specified title. If a
  771. macro or JavaScript is running, it is aborted. Writes to the
  772. Java console if the ImageJ window is not present. */
  773. public static void error(String title, String msg) {
  774. if (macroInterpreter!=null) {
  775. macroInterpreter.abort(msg);
  776. macroInterpreter = null;
  777. return;
  778. }
  779. if (msg!=null && msg.endsWith(Macro.MACRO_CANCELED))
  780. return;
  781. String title2 = title!=null?title:"ImageJ";
  782. boolean abortMacro = title!=null;
  783. lastErrorMessage = msg;
  784. if (redirectErrorMessages) {
  785. IJ.log(title2 + ": " + msg);
  786. if (abortMacro && (title.contains("Open")||title.contains("Reader")))
  787. abortMacro = false;
  788. } else
  789. showMessage(title2, msg);
  790. redirectErrorMessages = false;
  791. if (abortMacro)
  792. Macro.abort();
  793. }
  794. /** Aborts any currently running JavaScript, or use IJ.error(string)
  795. to abort a JavaScript with a message. */
  796. public static void exit() {
  797. if (Thread.currentThread().getName().endsWith("JavaScript"))
  798. throw new RuntimeException(Macro.MACRO_CANCELED);
  799. }
  800. /**
  801. * Returns the last error message written by IJ.error() or null if there
  802. * was no error since the last time this method was called.
  803. * @see #error(String)
  804. */
  805. public static String getErrorMessage() {
  806. String msg = lastErrorMessage;
  807. lastErrorMessage = null;
  808. return msg;
  809. }
  810. /** Displays a message in a dialog box with the specified title.
  811. Returns false if the user pressed "Cancel". */
  812. public static boolean showMessageWithCancel(String title, String msg) {
  813. GenericDialog gd = new GenericDialog(title);
  814. gd.addMessage(msg);
  815. gd.showDialog();
  816. return !gd.wasCanceled();
  817. }
  818. public static final int CANCELED = Integer.MIN_VALUE;
  819. /** Allows the user to enter a number in a dialog box. Returns the
  820. value IJ.CANCELED (-2,147,483,648) if the user cancels the dialog box.
  821. Returns 'defaultValue' if the user enters an invalid number. */
  822. public static double getNumber(String prompt, double defaultValue) {
  823. GenericDialog gd = new GenericDialog("");
  824. int decimalPlaces = (int)defaultValue==defaultValue?0:2;
  825. gd.addNumericField(prompt, defaultValue, decimalPlaces);
  826. gd.showDialog();
  827. if (gd.wasCanceled())
  828. return CANCELED;
  829. double v = gd.getNextNumber();
  830. if (gd.invalidNumber())
  831. return defaultValue;
  832. else
  833. return v;
  834. }
  835. /** Allows the user to enter a string in a dialog box. Returns
  836. "" if the user cancels the dialog box. */
  837. public static String getString(String prompt, String defaultString) {
  838. GenericDialog gd = new GenericDialog("");
  839. gd.addStringField(prompt, defaultString, 20);
  840. gd.showDialog();
  841. if (gd.wasCanceled())
  842. return "";
  843. return gd.getNextString();
  844. }
  845. /**Delays 'msecs' milliseconds.*/
  846. public static void wait(int msecs) {
  847. try {Thread.sleep(msecs);}
  848. catch (InterruptedException e) { }
  849. }
  850. /** Emits an audio beep. */
  851. public static void beep() {
  852. java.awt.Toolkit.getDefaultToolkit().beep();
  853. }
  854. /** Returns a string something like "64K of 256MB (25%)"
  855. * that shows how much of the available memory is in use.
  856. * This is the string displayed when the user clicks in the
  857. * status bar.
  858. */
  859. public static String freeMemory() {
  860. long inUse = currentMemory();
  861. String inUseStr = inUse<10000*1024?inUse/1024L+"K":inUse/1048576L+"MB";
  862. String maxStr="";
  863. long max = maxMemory();
  864. if (max>0L) {
  865. double percent = inUse*100/max;
  866. maxStr = " of "+max/1048576L+"MB ("+(percent<1.0?"<1":d2s(percent,0)) + "%)";
  867. }
  868. return inUseStr + maxStr;
  869. }
  870. /** Returns the amount of memory currently being used by ImageJ. */
  871. public static long currentMemory() {
  872. long freeMem = Runtime.getRuntime().freeMemory();
  873. long totMem = Runtime.getRuntime().totalMemory();
  874. return totMem-freeMem;
  875. }
  876. /** Returns the maximum amount of memory available to ImageJ or
  877. zero if ImageJ is unable to determine this limit. */
  878. public static long maxMemory() {
  879. if (maxMemory==0L) {
  880. Memory mem = new Memory();
  881. maxMemory = mem.getMemorySetting();
  882. if (maxMemory==0L) maxMemory = mem.maxMemory();
  883. }
  884. return maxMemory;
  885. }
  886. public static void showTime(ImagePlus imp, long start, String str) {
  887. showTime(imp, start, str, 1);
  888. }
  889. public static void showTime(ImagePlus imp, long start, String str, int nslices) {
  890. if (Interpreter.isBatchMode())
  891. return;
  892. double seconds = (System.currentTimeMillis()-start)/1000.0;
  893. if (seconds<=0.5 && macroRunning())
  894. return;
  895. double pixels = (double)imp.getWidth() * imp.getHeight();
  896. double rate = pixels*nslices/seconds;
  897. String str2;
  898. if (rate>1000000000.0)
  899. str2 = "";
  900. else if (rate<1000000.0)
  901. str2 = ", "+d2s(rate,0)+" pixels/second";
  902. else
  903. str2 = ", "+d2s(rate/1000000.0,1)+" million pixels/second";
  904. showStatus(str+seconds+" seconds"+str2);
  905. }
  906. /** Experimental */
  907. public static String time(ImagePlus imp, long startNanoTime) {
  908. double planes = imp.getStackSize();
  909. double seconds = (System.nanoTime()-startNanoTime)/1000000000.0;
  910. double mpixels = imp.getWidth()*imp.getHeight()*planes/1000000.0;
  911. String time = seconds<1.0?d2s(seconds*1000.0,0)+" ms":d2s(seconds,1)+" seconds";
  912. return time+", "+d2s(mpixels/seconds,1)+" million pixels/second";
  913. }
  914. /** Converts a number to a formatted string using
  915. 2 digits to the right of the decimal point. */
  916. public static String d2s(double n) {
  917. return d2s(n, 2);
  918. }
  919. /** Converts a number to a rounded formatted string.
  920. The 'decimalPlaces' argument specifies the number of
  921. digits to the right of the decimal point (0-9). Uses
  922. scientific notation if 'decimalPlaces is negative. */
  923. public static String d2s(double n, int decimalPlaces) {
  924. if (Double.isNaN(n)||Double.isInfinite(n))
  925. return ""+n;
  926. if (n==Float.MAX_VALUE) // divide by 0 in FloatProcessor
  927. return "3.4e38";
  928. double np = n;
  929. if (n<0.0) np = -n;
  930. if (decimalPlaces<0) synchronized(IJ.class) {
  931. decimalPlaces = -decimalPlaces;
  932. if (decimalPlaces>9) decimalPlaces=9;
  933. if (sf==null) {
  934. if (dfs==null)
  935. dfs = new DecimalFormatSymbols(Locale.US);
  936. sf = new DecimalFormat[10];
  937. sf[1] = new DecimalFormat("0.0E0",dfs);
  938. sf[2] = new DecimalFormat("0.00E0",dfs);
  939. sf[3] = new DecimalFormat("0.000E0",dfs);
  940. sf[4] = new DecimalFormat("0.0000E0",dfs);
  941. sf[5] = new DecimalFormat("0.00000E0",dfs);
  942. sf[6] = new DecimalFormat("0.000000E0",dfs);
  943. sf[7] = new DecimalFormat("0.0000000E0",dfs);
  944. sf[8] = new DecimalFormat("0.00000000E0",dfs);
  945. sf[9] = new DecimalFormat("0.000000000E0",dfs);
  946. }
  947. return sf[decimalPlaces].format(n); // use scientific notation
  948. }
  949. if (decimalPlaces<0) decimalPlaces = 0;
  950. if (decimalPlaces>9) decimalPlaces = 9;
  951. return df[decimalPlaces].format(n);
  952. }
  953. /** Converts a number to a rounded formatted string.
  954. * The 'significantDigits' argument specifies the minimum number
  955. * of significant digits, which is also the preferred number of
  956. * digits behind the decimal. Fewer decimals are shown if the
  957. * number would have more than 'maxDigits'.
  958. * Exponential notation is used if more than 'maxDigits' would be needed.
  959. */
  960. public static String d2s(double x, int significantDigits, int maxDigits) {
  961. double log10 = Math.log10(Math.abs(x));
  962. double roundErrorAtMax = 0.223*Math.pow(10, -maxDigits);
  963. int magnitude = (int)Math.ceil(log10+roundErrorAtMax);
  964. int decimals = x==0 ? 0 : maxDigits - magnitude;
  965. if (decimals<0 || magnitude<significantDigits+1-maxDigits)
  966. return IJ.d2s(x, -significantDigits); // exp notation for large and small numbers
  967. else {
  968. if (decimals>significantDigits)
  969. decimals = Math.max(significantDigits, decimals-maxDigits+significantDigits);
  970. return IJ.d2s(x, decimals);
  971. }
  972. }
  973. /** Pad 'n' with leading zeros to the specified number of digits. */
  974. public static String pad(int n, int digits) {
  975. String str = ""+n;
  976. while (str.length()<digits)
  977. str = "0"+str;
  978. return str;
  979. }
  980. /** Pad 's' with leading zeros to the specified number of digits. */
  981. public static String pad(String s, int digits) {
  982. String str = ""+s;
  983. while (str.length()<digits)
  984. str = "0"+str;
  985. return str;
  986. }
  987. /** Adds the specified class to a Vector to keep it from being garbage
  988. collected, which would cause the classes static fields to be reset.
  989. Probably not needed with Java 1.2 or later. */
  990. public static void register(Class c) {
  991. if (ij!=null) ij.register(c);
  992. }
  993. /** Returns true if the space bar is down. */
  994. public static boolean spaceBarDown() {
  995. return spaceDown;
  996. }
  997. /** Returns true if the control key is down. */
  998. public static boolean controlKeyDown() {
  999. return controlDown;
  1000. }
  1001. /** Returns true if the alt key is down. */
  1002. public static boolean altKeyDown() {
  1003. return altDown;
  1004. }
  1005. /** Returns true if the shift key is down. */
  1006. public static boolean shiftKeyDown() {
  1007. return shiftDown;
  1008. }
  1009. public static void setKeyDown(int key) {
  1010. switch (key) {
  1011. case KeyEvent.VK_CONTROL:
  1012. controlDown=true;
  1013. break;
  1014. case KeyEvent.VK_META:
  1015. if (isMacintosh()) controlDown=true;
  1016. break;
  1017. case KeyEvent.VK_ALT:
  1018. altDown=true;
  1019. updateStatus();
  1020. break;
  1021. case KeyEvent.VK_SHIFT:
  1022. shiftDown=true;
  1023. if (debugMode) beep();
  1024. break;
  1025. case KeyEvent.VK_SPACE: {
  1026. spaceDown=true;
  1027. ImageWindow win = WindowManager.getCurrentWindow();
  1028. //if (win!=null) win.getCanvas().setCursor(-1,-1,-1, -1);
  1029. break;
  1030. }
  1031. case KeyEvent.VK_ESCAPE: {
  1032. escapePressed = true;
  1033. break;
  1034. }
  1035. }
  1036. }
  1037. public static void setKeyUp(int key) {
  1038. switch (key) {
  1039. case KeyEvent.VK_CONTROL: controlDown=false; break;
  1040. case KeyEvent.VK_META: if (isMacintosh()) controlDown=false; break;
  1041. case KeyEvent.VK_ALT: altDown=false; updateStatus(); break;
  1042. case KeyEvent.VK_SHIFT: shiftDown=false; if (debugMode) beep(); break;
  1043. case KeyEvent.VK_SPACE:
  1044. spaceDown=false;
  1045. ImageWindow win = WindowManager.getCurrentWindow();
  1046. //if (win!=null) win.getCanvas().setCursor(-1,-1,-1,-1);
  1047. break;
  1048. case ALL_KEYS:
  1049. shiftDown=controlDown=altDown=spaceDown=false;
  1050. break;
  1051. }
  1052. }
  1053. private static void updateStatus() {
  1054. ImagePlus imp = WindowManager.getCurrentImage();
  1055. if (imp!=null) {
  1056. Roi roi = imp.getRoi();
  1057. if (roi!=null && imp.getCalibration().scaled()) {
  1058. roi.showStatus();
  1059. }
  1060. }
  1061. }
  1062. public static void setInputEvent(InputEvent e) {
  1063. altDown = e.isAltDown();
  1064. shiftDown = e.isShiftDown();
  1065. }
  1066. /** Returns true if this machine is a Macintosh. */
  1067. public static boolean isMacintosh() {
  1068. return isMac;
  1069. }
  1070. /** Returns true if this machine is a Macintosh running OS X. */
  1071. public static boolean isMacOSX() {
  1072. return isMacintosh();
  1073. }
  1074. /** Returns true if this machine is running Windows. */
  1075. public static boolean isWindows() {
  1076. return isWin;
  1077. }
  1078. /** Returns the Java version (6, 7, 8, 9, 10, etc.). */
  1079. public static int javaVersion() {
  1080. return javaVersion;
  1081. }
  1082. /** Always returns true. */
  1083. public static boolean isJava2() {
  1084. return true;
  1085. }
  1086. /** Always returns true. */
  1087. public static boolean isJava14() {
  1088. return true;
  1089. }
  1090. /** Always returns true. */
  1091. public static boolean isJava15() {
  1092. return true;
  1093. }
  1094. /** Returns true if ImageJ is running on a Java 1.6 or greater JVM. */
  1095. public static boolean isJava16() {
  1096. return javaVersion >= 6;
  1097. }
  1098. /** Returns true if ImageJ is running on a Java 1.7 or greater JVM. */
  1099. public static boolean isJava17() {
  1100. return javaVersion >= 7;
  1101. }
  1102. /** Returns true if ImageJ is running on a Java 1.8 or greater JVM. */
  1103. public static boolean isJava18() {
  1104. return javaVersion >= 8;
  1105. }
  1106. /** Returns true if ImageJ is running on a Java 1.9 or greater JVM. */
  1107. public static boolean isJava19() {
  1108. return javaVersion >= 9;
  1109. }
  1110. /** Returns true if ImageJ is running on Linux. */
  1111. public static boolean isLinux() {
  1112. return isLinux;
  1113. }
  1114. /** Obsolete; always returns false. */
  1115. public static boolean isVista() {
  1116. return false;
  1117. }
  1118. /** Returns true if ImageJ is running a 64-bit version of Java. */
  1119. public static boolean is64Bit() {
  1120. if (osarch==null)
  1121. osarch = System.getProperty("os.arch");
  1122. return osarch!=null && osarch.indexOf("64")!=-1;
  1123. }
  1124. /** Displays an error message and returns true if the
  1125. ImageJ version is less than the one specified. */
  1126. public static boolean versionLessThan(String version) {
  1127. boolean lessThan = ImageJ.VERSION.compareTo(version)<0;
  1128. if (lessThan)
  1129. error("This plugin or macro requires ImageJ "+version+" or later. Use\nHelp>Update ImageJ to upgrade to the latest version.");
  1130. return lessThan;
  1131. }
  1132. /** Displays a "Process all images?" dialog. Returns
  1133. 'flags'+PlugInFilter.DOES_STACKS if the user selects "Yes",
  1134. 'flags' if the user selects "No" and PlugInFilter.DONE
  1135. if the user selects "Cancel".
  1136. */
  1137. public static int setupDialog(ImagePlus imp, int flags) {
  1138. if (imp==null || (ij!=null&&ij.hotkey)) {
  1139. if (ij!=null) ij.hotkey=false;
  1140. return flags;
  1141. }
  1142. int stackSize = imp.getStackSize();
  1143. if (stackSize>1) {
  1144. String macroOptions = Macro.getOptions();
  1145. if (imp.isComposite() && ((CompositeImage)imp).getMode()==IJ.COMPOSITE) {
  1146. if (macroOptions==null || !macroOptions.contains("slice"))
  1147. return flags | PlugInFilter.DOES_STACKS;
  1148. }
  1149. if (macroOptions!=null) {
  1150. if (macroOptions.indexOf("stack ")>=0)
  1151. return flags | PlugInFilter.DOES_STACKS;
  1152. else
  1153. return flags;
  1154. }
  1155. if (hideProcessStackDialog)
  1156. return flags;
  1157. String note = ((flags&PlugInFilter.NO_CHANGES)==0)?" There is\nno Undo if you select \"Yes\".":"";
  1158. YesNoCancelDialog d = new YesNoCancelDialog(getInstance(),
  1159. "Process Stack?", "Process all "+stackSize+" images?"+note);
  1160. if (d.cancelPressed())
  1161. return PlugInFilter.DONE;
  1162. else if (d.yesPressed()) {
  1163. if (imp.getStack().isVirtual() && ((flags&PlugInFilter.NO_CHANGES)==0)) {
  1164. int size = (stackSize*imp.getWidth()*imp.getHeight()*imp.getBytesPerPixel()+524288)/1048576;
  1165. String msg =
  1166. "Use the Process>Batch>Virtual Stack command\n"+
  1167. "to process a virtual stack or convert it into a\n"+
  1168. "normal stack using Image>Duplicate, which\n"+
  1169. "will require "+size+"MB of additional memory.";
  1170. error(msg);
  1171. return PlugInFilter.DONE;
  1172. }
  1173. if (Recorder.record)
  1174. Recorder.recordOption("stack");
  1175. return flags | PlugInFilter.DOES_STACKS;
  1176. }
  1177. if (Recorder.record)
  1178. Recorder.recordOption("slice");
  1179. }
  1180. return flags;
  1181. }
  1182. /** Creates a rectangular selection. Removes any existing
  1183. selection if width or height are less than 1. */
  1184. public static void makeRectangle(int x, int y, int width, int height) {
  1185. if (width<=0 || height<0)
  1186. getImage().deleteRoi();
  1187. else {
  1188. ImagePlus img = getImage();
  1189. if (Interpreter.isBatchMode())
  1190. img.setRoi(new Roi(x,y,width,height), false);
  1191. else
  1192. img.setRoi(x, y, width, height);
  1193. }
  1194. }
  1195. /** Creates a subpixel resolution rectangular selection. */
  1196. public static void makeRectangle(double x, double y, double width, double height) {
  1197. if (width<=0 || height<0)
  1198. getImage().deleteRoi();
  1199. else
  1200. getImage().setRoi(new Roi(x,y,width,height), !Interpreter.isBatchMode());
  1201. }
  1202. /** Creates an oval selection. Removes any existing
  1203. selection if width or height are less than 1. */
  1204. public static void makeOval(int x, int y, int width, int height) {
  1205. if (width<=0 || height<0)
  1206. getImage().deleteRoi();
  1207. else {
  1208. ImagePlus img = getImage();
  1209. img.setRoi(new OvalRoi(x, y, width, height));
  1210. }
  1211. }
  1212. /** Creates an subpixel resolution oval selection. */
  1213. public static void makeOval(double x, double y, double width, double height) {
  1214. if (width<=0 || height<0)
  1215. getImage().deleteRoi();
  1216. else
  1217. getImage().setRoi(new OvalRoi(x, y, width, height));
  1218. }
  1219. /** Creates a straight line selection. */
  1220. public static void makeLine(int x1, int y1, int x2, int y2) {
  1221. getImage().setRoi(new Line(x1, y1, x2, y2));
  1222. }
  1223. /** Creates a straight line selection using floating point coordinates. */
  1224. public static void makeLine(double x1, double y1, double x2, double y2) {
  1225. getImage().setRoi(new Line(x1, y1, x2, y2));
  1226. }
  1227. /** Creates a point selection using integer coordinates.. */
  1228. public static void makePoint(int x, int y) {
  1229. ImagePlus img = getImage();
  1230. Roi roi = img.getRoi();
  1231. if (shiftKeyDown() && roi!=null && roi.getType()==Roi.POINT) {
  1232. Polygon p = roi.getPolygon();
  1233. p.addPoint(x, y);
  1234. img.setRoi(new PointRoi(p.xpoints, p.ypoints, p.npoints));
  1235. IJ.setKeyUp(KeyEvent.VK_SHIFT);
  1236. } else if (altKeyDown() && roi!=null && roi.getType()==Roi.POINT) {
  1237. ((PolygonRoi)roi).deleteHandle(x, y);
  1238. IJ.setKeyUp(KeyEvent.VK_ALT);
  1239. } else
  1240. img.setRoi(new PointRoi(x, y));
  1241. }
  1242. /** Creates a point selection using floating point coordinates. */
  1243. public static void makePoint(double x, double y) {
  1244. ImagePlus img = getImage();
  1245. Roi roi = img.getRoi();
  1246. if (shiftKeyDown() && roi!=null && roi.getType()==Roi.POINT) {
  1247. Polygon p = roi.getPolygon();
  1248. p.addPoint((int)Math.round(x), (int)Math.round(y));
  1249. img.setRoi(new PointRoi(p.xpoints, p.ypoints, p.npoints));
  1250. IJ.setKeyUp(KeyEvent.VK_SHIFT);
  1251. } else if (altKeyDown() && roi!=null && roi.getType()==Roi.POINT) {
  1252. ((PolygonRoi)roi).deleteHandle(x, y);
  1253. IJ.setKeyUp(KeyEvent.VK_ALT);
  1254. } else
  1255. img.setRoi(new PointRoi(x, y));
  1256. }
  1257. /** Creates an Roi. */
  1258. public static Roi Roi(double x, double y, double width, double height) {
  1259. return new Roi(x, y, width, height);
  1260. }
  1261. /** Creates an OvalRoi. */
  1262. public static OvalRoi OvalRoi(double x, double y, double width, double height) {
  1263. return new OvalRoi(x, y, width, height);
  1264. }
  1265. /** Sets the display range (minimum and maximum displayed pixel values) of the current image. */
  1266. public static void setMinAndMax(double min, double max) {
  1267. setMinAndMax(getImage(), min, max, 7);
  1268. }
  1269. /** Sets the display range (minimum and maximum displayed pixel values) of the specified image. */
  1270. public static void setMinAndMax(ImagePlus img, double min, double max) {
  1271. setMinAndMax(img, min, max, 7);
  1272. }
  1273. /** Sets the minimum and maximum displayed pixel values on the specified RGB
  1274. channels, where 4=red, 2=green and 1=blue. */
  1275. public static void setMinAndMax(double min, double max, int channels) {
  1276. setMinAndMax(getImage(), min, max, channels);
  1277. }
  1278. private static void setMinAndMax(ImagePlus img, double min, double max, int channels) {
  1279. Calibration cal = img.getCalibration();
  1280. min = cal.getRawValue(min);
  1281. max = cal.getRawValue(max);
  1282. if (channels==7)
  1283. img.setDisplayRange(min, max);
  1284. else
  1285. img.setDisplayRange(min, max, channels);
  1286. img.updateAndDraw();
  1287. }
  1288. /** Resets the minimum and maximum displayed pixel values of the
  1289. current image to be the same as the min and max pixel values. */
  1290. public static void resetMinAndMax() {
  1291. resetMinAndMax(getImage());
  1292. }
  1293. /** Resets the minimum and maximum displayed pixel values of the
  1294. specified image to be the same as the min and max pixel values. */
  1295. public static void resetMinAndMax(ImagePlus img) {
  1296. img.resetDisplayRange();
  1297. img.updateAndDraw();
  1298. }
  1299. /** Sets the lower and upper threshold levels and displays the image
  1300. using red to highlight thresholded pixels. May not work correctly on
  1301. 16 and 32 bit images unless the display range has been reset using IJ.resetMinAndMax().
  1302. */
  1303. public static void setThreshold(double lowerThreshold, double upperThresold) {
  1304. setThreshold(lowerThreshold, upperThresold, null);
  1305. }
  1306. /** Sets the lower and upper threshold levels and displays the image using
  1307. the specified <code>displayMode</code> ("Red", "Black & White", "Over/Under" or "No Update"). */
  1308. public static void setThreshold(double lowerThreshold, double upperThreshold, String displayMode) {
  1309. setThreshold(getImage(), lowerThreshold, upperThreshold, displayMode);
  1310. }
  1311. /** Sets the lower and upper threshold levels of the specified image. */
  1312. public static void setThreshold(ImagePlus img, double lowerThreshold, double upperThreshold) {
  1313. setThreshold(img, lowerThreshold, upperThreshold, "Red");
  1314. }
  1315. /** Sets the lower and upper threshold levels of the specified image and updates the display using
  1316. the specified <code>displayMode</code> ("Red", "Black & White", "Over/Under" or "No Update").
  1317. With calibrated images, 'lowerThreshold' and 'upperThreshold' must be density calibrated values.
  1318. Use setRawThreshold() to set the threshold using raw (uncalibrated) values. */
  1319. public static void setThreshold(ImagePlus img, double lowerThreshold, double upperThreshold, String displayMode) {
  1320. Calibration cal = img.getCalibration();
  1321. if (displayMode==null || !displayMode.contains("raw")) {
  1322. lowerThreshold = cal.getRawValue(lowerThreshold);
  1323. upperThreshold = cal.getRawValue(upperThreshold);
  1324. }
  1325. setRawThreshold(img, lowerThreshold, upperThreshold, displayMode);
  1326. }
  1327. /** This is a version of setThreshold() that uses raw (uncalibrated)
  1328. * values in the range 0-255 for 8-bit images and 0-65535 for 16-bit
  1329. * images and the "Red" LUT display mode.
  1330. */
  1331. public static void setRawThreshold(ImagePlus img, double lowerThreshold, double upperThreshold) {
  1332. setRawThreshold(img, lowerThreshold, upperThreshold, null);
  1333. }
  1334. /** This is a version of setThreshold() that always uses raw (uncalibrated) values
  1335. * in the range 0-255 for 8-bit images and 0-65535 for 16-bit images.
  1336. */
  1337. public static void setRawThreshold(ImagePlus img, double lowerThreshold, double upperThreshold, String displayMode) {
  1338. int mode = ImageProcessor.RED_LUT;
  1339. if (displayMode!=null) {
  1340. displayMode = displayMode.toLowerCase(Locale.US);
  1341. if (displayMode.contains("black"))
  1342. mode = ImageProcessor.BLACK_AND_WHITE_LUT;
  1343. else if (displayMode.contains("over"))
  1344. mode = ImageProcessor.OVER_UNDER_LUT;
  1345. else if (displayMode.contains("no"))
  1346. mode = ImageProcessor.NO_LUT_UPDATE;
  1347. }
  1348. img.getProcessor().setThreshold(lowerThreshold, upperThreshold, mode);
  1349. if (mode!=ImageProcessor.NO_LUT_UPDATE && img.getWindow()!=null) {
  1350. img.getProcessor().setLutAnimation(true);
  1351. img.updateAndDraw();
  1352. ThresholdAdjuster.update();
  1353. }
  1354. }
  1355. public static void setAutoThreshold(ImagePlus imp, String method) {
  1356. ImageProcessor ip = imp.getProcessor();
  1357. if (ip instanceof ColorProcessor)
  1358. throw new IllegalArgumentException("Non-RGB image required");
  1359. ip.setRoi(imp.getRoi());
  1360. if (method!=null) {
  1361. try {
  1362. if (method.indexOf("stack")!=-1)
  1363. setStackThreshold(imp, ip, method);
  1364. else
  1365. ip.setAutoThreshold(method);
  1366. } catch (Exception e) {
  1367. log(e.getMessage());
  1368. }
  1369. } else
  1370. ip.setAutoThreshold(ImageProcessor.ISODATA2, ImageProcessor.RED_LUT);
  1371. imp.updateAndDraw();
  1372. }
  1373. private static void setStackThreshold(ImagePlus imp, ImageProcessor ip, String method) {
  1374. boolean darkBackground = method.indexOf("dark")!=-1;
  1375. int measurements = Analyzer.getMeasurements();
  1376. Analyzer.setMeasurements(Measurements.AREA+Measurements.MIN_MAX);
  1377. ImageStatistics stats = new StackStatistics(imp);
  1378. Analyzer.setMeasurements(measurements);
  1379. AutoThresholder thresholder = new AutoThresholder();
  1380. double min=0.0, max=255.0;
  1381. if (imp.getBitDepth()!=8) {
  1382. min = stats.min;
  1383. max = stats.max;
  1384. }
  1385. int threshold = thresholder.getThreshold(method, stats.histogram);
  1386. double lower, upper;
  1387. if (darkBackground) {
  1388. if (ip.isInvertedLut())
  1389. {lower=0.0; upper=threshold;}
  1390. else
  1391. {lower=threshold+1; upper=255.0;}
  1392. } else {
  1393. if (ip.isInvertedLut())
  1394. {lower=threshold+1; upper=255.0;}
  1395. else
  1396. {lower=0.0; upper=threshold;}
  1397. }
  1398. if (lower>255) lower = 255;
  1399. if (max>min) {
  1400. lower = min + (lower/255.0)*(max-min);
  1401. upper = min + (upper/255.0)*(max-min);
  1402. } else
  1403. lower = upper = min;
  1404. ip.setMinAndMax(min, max);
  1405. ip.setThreshold(lower, upper, ImageProcessor.RED_LUT);
  1406. imp.updateAndDraw();
  1407. }
  1408. /** Disables thresholding on the current image. */
  1409. public static void resetThreshold() {
  1410. resetThreshold(getImage());
  1411. }
  1412. /** Disables thresholding on the specified image. */
  1413. public static void resetThreshold(ImagePlus img) {
  1414. ImageProcessor ip = img.getProcessor();
  1415. ip.resetThreshold();
  1416. ip.setLutAnimation(true);
  1417. img.updateAndDraw();
  1418. ThresholdAdjuster.update();
  1419. }
  1420. /** For IDs less than zero, activates the image with the specified ID.
  1421. For IDs greater than zero, activates the Nth image. */
  1422. public static void selectWindow(int id) {
  1423. if (id>0)
  1424. id = WindowManager.getNthImageID(id);
  1425. ImagePlus imp = WindowManager.getImage(id);
  1426. if (imp==null)
  1427. error("Macro Error", "Image "+id+" not found or no images are open.");
  1428. if (Interpreter.isBatchMode()) {
  1429. ImagePlus impT = WindowManager.getTempCurrentImage();
  1430. ImagePlus impC = WindowManager.getCurrentImage();
  1431. if (impC!=null && impC!=imp && impT!=null)
  1432. impC.saveRoi();
  1433. WindowManager.setTempCurrentImage(imp);
  1434. Interpreter.activateImage(imp);
  1435. WindowManager.setWindow(null);
  1436. } else {
  1437. if (imp==null)
  1438. return;
  1439. ImageWindow win = imp.getWindow();
  1440. if (win!=null) {
  1441. win.toFront();
  1442. win.setState(Frame.NORMAL);
  1443. WindowManager.setWindow(win);
  1444. }
  1445. long start = System.currentTimeMillis();
  1446. // timeout after 1 second unless current thread is event dispatch thread
  1447. String thread = Thread.currentThread().getName();
  1448. int timeout = thread!=null&&thread.indexOf("EventQueue")!=-1?0:1000;
  1449. if (IJ.isMacOSX() && IJ.isJava18() && timeout>0)
  1450. timeout = 250; //work around OS X/Java 8 window activation bug
  1451. while (true) {
  1452. wait(10);
  1453. imp = WindowManager.getCurrentImage();
  1454. if (imp!=null && imp.getID()==id)
  1455. return; // specified image is now active
  1456. if ((System.currentTimeMillis()-start)>timeout && win!=null) {
  1457. WindowManager.setCurrentWindow(win);
  1458. return;
  1459. }
  1460. }
  1461. }
  1462. }
  1463. /** Activates the window with the specified title. */
  1464. public static void selectWindow(String title) {
  1465. if (title.equals("ImageJ")&&ij!=null) {
  1466. ij.toFront();
  1467. return;
  1468. }
  1469. long start = System.currentTimeMillis();
  1470. while (System.currentTimeMillis()-start<3000) { // 3 sec timeout
  1471. Window win = WindowManager.getWindow(title);
  1472. if (win!=null && !(win instanceof ImageWindow)) {
  1473. selectWindow(win);
  1474. return;
  1475. }
  1476. int[] wList = WindowManager.getIDList();
  1477. int len = wList!=null?wList.length:0;
  1478. for (int i=0; i<len; i++) {
  1479. ImagePlus imp = WindowManager.getImage(wList[i]);
  1480. if (imp!=null) {
  1481. if (imp.getTitle().equals(title)) {
  1482. selectWindow(imp.getID());
  1483. return;
  1484. }
  1485. }
  1486. }
  1487. wait(10);
  1488. }
  1489. error("Macro Error", "No window with the title \""+title+"\" found.");
  1490. }
  1491. static void selectWindow(Window win) {
  1492. if (win instanceof Frame) {
  1493. ((Frame)win).toFront();
  1494. ((Frame)win).setState(Frame.NORMAL);
  1495. } else
  1496. ((Dialog)win).toFront();
  1497. long start = System.currentTimeMillis();
  1498. while (true) {
  1499. wait(10);
  1500. if (WindowManager.getActiveWindow()==win)
  1501. return; // specified window is now in front
  1502. if ((System.currentTimeMillis()-start)>1000) {
  1503. WindowManager.setWindow(win);
  1504. return; // 1 second timeout
  1505. }
  1506. }
  1507. }
  1508. /** Sets the foreground color. */
  1509. public static void setForegroundColor(int red, int green, int blue) {
  1510. setColor(red, green, blue, true);
  1511. }
  1512. /** Sets the background color. */
  1513. public static void setBackgroundColor(int red, int green, int blue) {
  1514. setColor(red, green, blue, false);
  1515. }
  1516. static void setColor(int red, int green, int blue, boolean foreground) {
  1517. Color c = Colors.toColor(red, green, blue);
  1518. if (foreground) {
  1519. Toolbar.setForegroundColor(c);
  1520. ImagePlus img = WindowManager.getCurrentImage();
  1521. if (img!=null)
  1522. img.getProcessor().setColor(c);
  1523. } else
  1524. Toolbar.setBackgroundColor(c);
  1525. }
  1526. /** Switches to the specified tool, where id = Toolbar.RECTANGLE (0),
  1527. Toolbar.OVAL (1), etc. */
  1528. public static void setTool(int id) {
  1529. Toolbar.getInstance().setTool(id);
  1530. }
  1531. /** Switches to the specified tool, where 'name' is "rect", "elliptical",
  1532. "brush", etc. Returns 'false' if the name is not recognized. */
  1533. public static boolean setTool(String name) {
  1534. return Toolbar.getInstance().setTool(name);
  1535. }
  1536. /** Returns the name of the current tool. */
  1537. public static String getToolName() {
  1538. return Toolbar.getToolName();
  1539. }
  1540. /** Equivalent to clicking on the current image at (x,y) with the
  1541. wand tool. Returns the number of points in the resulting ROI. */
  1542. public static int doWand(int x, int y) {
  1543. return doWand(getImage(), x, y, 0, null);
  1544. }
  1545. /** Traces the boundary of the area with pixel values within
  1546. * 'tolerance' of the value of the pixel at the starting location.
  1547. * 'tolerance' is in uncalibrated units.
  1548. * 'mode' can be "4-connected", "8-connected" or "Legacy".
  1549. * "Legacy" is for compatibility with previous versions of ImageJ;
  1550. * it is ignored if 'tolerance' > 0.
  1551. */
  1552. public static int doWand(int x, int y, double tolerance, String mode) {
  1553. return doWand(getImage(), x, y, tolerance, mode);
  1554. }
  1555. /** This version of doWand adds an ImagePlus argument. */
  1556. public static int doWand(ImagePlus img, int x, int y, double tolerance, String mode) {
  1557. ImageProcessor ip = img.getProcessor();
  1558. if ((img.getType()==ImagePlus.GRAY32) && Double.isNaN(ip.getPixelValue(x,y)))
  1559. return 0;
  1560. int imode = Wand.LEGACY_MODE;
  1561. boolean smooth = false;
  1562. if (mode!=null) {
  1563. if (mode.startsWith("4"))
  1564. imode = Wand.FOUR_CONNECTED;
  1565. else if (mode.startsWith("8"))
  1566. imode = Wand.EIGHT_CONNECTED;
  1567. smooth = mode.contains("smooth");
  1568. }
  1569. Wand w = new Wand(ip);
  1570. double t1 = ip.getMinThreshold();
  1571. if (t1==ImageProcessor.NO_THRESHOLD || (ip.getLutUpdateMode()==ImageProcessor.NO_LUT_UPDATE&& tolerance>0.0)) {
  1572. w.autoOutline(x, y, tolerance, imode);
  1573. smooth = false;
  1574. } else
  1575. w.autoOutline(x, y, t1, ip.getMaxThreshold(), imode);
  1576. if (w.npoints>0) {
  1577. Roi previousRoi = img.getRoi();
  1578. Roi roi = new PolygonRoi(w.xpoints, w.ypoints, w.npoints, Roi.TRACED_ROI);
  1579. img.deleteRoi();
  1580. img.setRoi(roi);
  1581. if (previousRoi!=null)
  1582. roi.update(shiftKeyDown(), altKeyDown()); // add/subtract ROI to previous one if shift/alt key down
  1583. Roi roi2 = img.getRoi();
  1584. if (smooth && roi2!=null && roi2.getType()==Roi.TRACED_ROI) {
  1585. Rectangle bounds = roi2.getBounds();
  1586. if (bounds.width>1 && bounds.height>1) {
  1587. if (smoothMacro==null)
  1588. smoothMacro = BatchProcessor.openMacroFromJar("SmoothWandTool.txt");
  1589. if (EventQueue.isDispatchThread())
  1590. new MacroRunner(smoothMacro); // run on separate thread
  1591. else
  1592. Macro.eval(smoothMacro);
  1593. }
  1594. }
  1595. }
  1596. return w.npoints;
  1597. }
  1598. /** Sets the transfer mode used by the <i>Edit/Paste</i> command, where mode is "Copy", "Blend", "Average", "Difference",
  1599. "Transparent", "Transparent2", "AND", "OR", "XOR", "Add", "Subtract", "Multiply", or "Divide". */
  1600. public static void setPasteMode(String mode) {
  1601. Roi.setPasteMode(stringToPasteMode(mode));
  1602. }
  1603. public static int stringToPasteMode(String mode) {
  1604. if (mode==null)
  1605. return Blitter.COPY;
  1606. mode = mode.toLowerCase(Locale.US);
  1607. int m = Blitter.COPY;
  1608. if (mode.startsWith("ble") || mode.startsWith("ave"))
  1609. m = Blitter.AVERAGE;
  1610. else if (mode.startsWith("diff"))
  1611. m = Blitter.DIFFERENCE;
  1612. else if (mode.indexOf("zero")!=-1)
  1613. m = Blitter.COPY_ZERO_TRANSPARENT;
  1614. else if (mode.startsWith("tran"))
  1615. m = Blitter.COPY_TRANSPARENT;
  1616. else if (mode.startsWith("and"))
  1617. m = Blitter.AND;
  1618. else if (mode.startsWith("or"))
  1619. m = Blitter.OR;
  1620. else if (mode.startsWith("xor"))
  1621. m = Blitter.XOR;
  1622. else if (mode.startsWith("sub"))
  1623. m = Blitter.SUBTRACT;
  1624. else if (mode.startsWith("add"))
  1625. m = Blitter.ADD;
  1626. else if (mode.startsWith("div"))
  1627. m = Blitter.DIVIDE;
  1628. else if (mode.startsWith("mul"))
  1629. m = Blitter.MULTIPLY;
  1630. else if (mode.startsWith("min"))
  1631. m = Blitter.MIN;
  1632. else if (mode.startsWith("max"))
  1633. m = Blitter.MAX;
  1634. return m;
  1635. }
  1636. /** Returns a reference to the active image, or displays an error
  1637. message and aborts the plugin or macro if no images are open. */
  1638. public static ImagePlus getImage() {
  1639. ImagePlus img = WindowManager.getCurrentImage();
  1640. if (img==null) {
  1641. IJ.noImage();
  1642. if (ij==null)
  1643. System.exit(0);
  1644. else
  1645. abort();
  1646. }
  1647. return img;
  1648. }
  1649. /**The macro interpreter uses this method to call getImage().*/
  1650. public static ImagePlus getImage(Interpreter interpreter) {
  1651. macroInterpreter = interpreter;
  1652. ImagePlus imp = getImage();
  1653. macroInterpreter = null;
  1654. return imp;
  1655. }
  1656. /** Returns the active image or stack slice as an ImageProcessor, or displays
  1657. an error message and aborts the plugin or macro if no images are open. */
  1658. public static ImageProcessor getProcessor() {
  1659. ImagePlus imp = IJ.getImage();
  1660. return imp.getProcessor();
  1661. }
  1662. /** Switches to the specified stack slice, where 1<='slice'<=stack-size. */
  1663. public static void setSlice(int slice) {
  1664. getImage().setSlice(slice);
  1665. }
  1666. /** Returns the ImageJ version number as a string. */
  1667. public static String getVersion() {
  1668. return ImageJ.VERSION;
  1669. }
  1670. /** Returns the ImageJ version and build number as a String, for
  1671. example "1.46n05", or 1.46n99 if there is no build number. */
  1672. public static String getFullVersion() {
  1673. String build = ImageJ.BUILD;
  1674. if (build.length()==0)
  1675. build = "99";
  1676. else if (build.length()==1)
  1677. build = "0" + build;
  1678. return ImageJ.VERSION+build;
  1679. }
  1680. /** Returns the path to the specified directory if <code>title</code> is
  1681. "home" ("user.home"), "downloads", "startup", "imagej" (ImageJ directory),
  1682. "plugins", "macros", "luts", "temp", "current", "default",
  1683. "image" (directory active image was loaded from), "file"
  1684. (directory most recently used to open or save a file), "cwd"
  1685. (current working directory) or "preferences" (location of
  1686. "IJ_Prefs.txt" file), otherwise displays a dialog and
  1687. returns the path to the directory selected by the user. Returns
  1688. null if the specified directory is not found or the user cancels the
  1689. dialog box. Also aborts the macro if the user cancels the
  1690. dialog box.*/
  1691. public static String getDirectory(String title) {
  1692. String dir = null;
  1693. String title2 = title.toLowerCase(Locale.US);
  1694. if (title2.equals("plugins"))
  1695. dir = Menus.getPlugInsPath();
  1696. else if (title2.equals("macros"))
  1697. dir = Menus.getMacrosPath();
  1698. else if (title2.equals("luts")) {
  1699. String ijdir = Prefs.getImageJDir();
  1700. if (ijdir!=null)
  1701. dir = ijdir + "luts" + File.separator;
  1702. else
  1703. dir = null;
  1704. } else if (title2.equals("home"))
  1705. dir = System.getProperty("user.home");
  1706. else if (title2.equals("downloads"))
  1707. dir = System.getProperty("user.home")+File.separator+"Downloads";
  1708. else if (title2.equals("startup"))
  1709. dir = Prefs.getImageJDir();
  1710. else if (title2.equals("imagej"))
  1711. dir = Prefs.getImageJDir();
  1712. else if (title2.equals("current") || title2.equals("default"))
  1713. dir = OpenDialog.getDefaultDirectory();
  1714. else if (title2.equals("preferences"))
  1715. dir = Prefs.getPrefsDir();
  1716. else if (title2.equals("temp")) {
  1717. dir = System.getProperty("java.io.tmpdir");
  1718. if (isMacintosh()) dir = "/tmp/";
  1719. } else if (title2.equals("image")) {
  1720. ImagePlus imp = WindowManager.getCurrentImage();
  1721. FileInfo fi = imp!=null?imp.getOriginalFileInfo():null;
  1722. if (fi!=null && fi.directory!=null) {
  1723. dir = fi.directory;
  1724. } else
  1725. dir = null;
  1726. } else if (title2.equals("file"))
  1727. dir = OpenDialog.getLastDirectory();
  1728. else if (title2.equals("cwd"))
  1729. dir = System.getProperty("user.dir");
  1730. else {
  1731. DirectoryChooser dc = new DirectoryChooser(title);
  1732. dir = dc.getDirectory();
  1733. if (dir==null) Macro.abort();
  1734. }
  1735. dir = addSeparator(dir);
  1736. return dir;
  1737. }
  1738. public static String addSeparator(String path) {
  1739. if (path==null)
  1740. return null;
  1741. if (path.length()>0 && !(path.endsWith(File.separator)||path.endsWith("/"))) {
  1742. if (IJ.isWindows()&&path.contains(File.separator))
  1743. path += File.separator;
  1744. else
  1745. path += "/";
  1746. }
  1747. return path;
  1748. }
  1749. /** Alias for getDirectory(). */
  1750. public static String getDir(String title) {
  1751. return getDirectory(title);
  1752. }
  1753. /** Displays an open file dialog and returns the path to the
  1754. choosen file, or returns null if the dialog is canceled. */
  1755. public static String getFilePath(String dialogTitle) {
  1756. OpenDialog od = new OpenDialog(dialogTitle);
  1757. return od.getPath();
  1758. }
  1759. /** Displays a file open dialog box and then opens the tiff, dicom,
  1760. fits, pgm, jpeg, bmp, gif, lut, roi, or text file selected by
  1761. the user. Displays an error message if the selected file is not
  1762. in one of the supported formats, or if it is not found. */
  1763. public static void open() {
  1764. open(null);
  1765. }
  1766. /** Opens and displays a tiff, dicom, fits, pgm, jpeg, bmp, gif, lut,
  1767. roi, or text file. Displays an error message if the specified file
  1768. is not in one of the supported formats, or if it is not found.
  1769. With 1.41k or later, opens images specified by a URL.
  1770. */
  1771. public static void open(String path) {
  1772. if (ij==null && Menus.getCommands()==null)
  1773. init();
  1774. Opener o = new Opener();
  1775. macroRunning = true;
  1776. if (path==null || path.equals(""))
  1777. o.open();
  1778. else
  1779. o.open(path);
  1780. macroRunning = false;
  1781. }
  1782. /** Opens and displays the nth image in the specified tiff stack. */
  1783. public static void open(String path, int n) {
  1784. if (ij==null && Menus.getCommands()==null)
  1785. init();
  1786. ImagePlus imp = openImage(path, n);
  1787. if (imp!=null) imp.show();
  1788. }
  1789. /** Opens the specified file as a tiff, bmp, dicom, fits, pgm, gif, jpeg
  1790. or text image and returns an ImagePlus object if successful.
  1791. Calls HandleExtraFileTypes plugin if the file type is not recognised.
  1792. Displays a file open dialog if 'path' is null or an empty string.
  1793. Note that 'path' can also be a URL. Some reader plugins, including
  1794. the Bio-Formats plugin, display the image and return null.
  1795. Use IJ.open() to display a file open dialog box.
  1796. */
  1797. public static ImagePlus openImage(String path) {
  1798. macroRunning = true;
  1799. ImagePlus imp = (new Opener()).openImage(path);
  1800. macroRunning = false;
  1801. return imp;
  1802. }
  1803. /** Opens the nth image of the specified tiff stack. */
  1804. public static ImagePlus openImage(String path, int n) {
  1805. return (new Opener()).openImage(path, n);
  1806. }
  1807. /** Opens the specified tiff file as a virtual stack. */
  1808. public static ImagePlus openVirtual(String path) {
  1809. return FileInfoVirtualStack.openVirtual(path);
  1810. }
  1811. /** Opens an image using a file open dialog and returns it as an ImagePlus object. */
  1812. public static ImagePlus openImage() {
  1813. return openImage(null);
  1814. }
  1815. /** Opens a URL and returns the contents as a string.
  1816. Returns "<Error: message>" if there an error, including
  1817. host or file not found. */
  1818. public static String openUrlAsString(String url) {
  1819. //if (!trustManagerCreated && url.contains("nih.gov")) trustAllCerts();
  1820. url = Opener.updateUrl(url);
  1821. if (debugMode) log("OpenUrlAsString: "+url);
  1822. StringBuffer sb = null;
  1823. url = url.replaceAll(" ", "%20");
  1824. try {
  1825. //if (url.contains("nih.gov")) addRootCA();
  1826. URL u = new URL(url);
  1827. URLConnection uc = u.openConnection();
  1828. long len = uc.getContentLength();
  1829. if (len>5242880L)
  1830. return "<Error: file is larger than 5MB>";
  1831. InputStream in = u.openStream();
  1832. BufferedReader br = new BufferedReader(new InputStreamReader(in));
  1833. sb = new StringBuffer() ;
  1834. String line;
  1835. while ((line=br.readLine()) != null)
  1836. sb.append (line + "\n");
  1837. in.close ();
  1838. } catch (Exception e) {
  1839. return("<Error: "+e+">");
  1840. }
  1841. if (sb!=null)
  1842. return new String(sb);
  1843. else
  1844. return "";
  1845. }
  1846. /*
  1847. public static void addRootCA() throws Exception {
  1848. String path = "/Users/wayne/Downloads/Certificates/lets-encrypt-x1-cross-signed.pem";
  1849. InputStream fis = new BufferedInputStream(new FileInputStream(path));
  1850. Certificate ca = CertificateFactory.getInstance("X.509").generateCertificate(fis);
  1851. KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  1852. ks.load(null, null);
  1853. ks.setCertificateEntry(Integer.toString(1), ca);
  1854. TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  1855. tmf.init(ks);
  1856. SSLContext ctx = SSLContext.getInstance("TLS");
  1857. ctx.init(null, tmf.getTrustManagers(), null);
  1858. HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
  1859. }
  1860. */
  1861. /*
  1862. // Create a new trust manager that trust all certificates
  1863. // http://stackoverflow.com/questions/10135074/download-file-from-https-server-using-java
  1864. private static void trustAllCerts() {
  1865. trustManagerCreated = true;
  1866. TrustManager[] trustAllCerts = new TrustManager[] {
  1867. new X509TrustManager() {
  1868. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  1869. return null;
  1870. }
  1871. public void checkClientTrusted (java.security.cert.X509Certificate[] certs, String authType) {
  1872. }
  1873. public void checkServerTrusted (java.security.cert.X509Certificate[] certs, String authType) {
  1874. }
  1875. }
  1876. };
  1877. // Activate the new trust manager
  1878. try {
  1879. SSLContext sc = SSLContext.getInstance("SSL");
  1880. sc.init(null, trustAllCerts, new java.security.SecureRandom());
  1881. HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  1882. } catch (Exception e) {
  1883. IJ.log(""+e);
  1884. }
  1885. }
  1886. */
  1887. /** Saves the current image, lookup table, selection or text window to the specified file path.
  1888. The path must end in ".tif", ".jpg", ".gif", ".zip", ".raw", ".avi", ".bmp", ".fits", ".pgm", ".png", ".lut", ".roi" or ".txt". */
  1889. public static void save(String path) {
  1890. save(null, path);
  1891. }
  1892. /** Saves the specified image, lookup table or selection to the specified file path.
  1893. The file path should end with ".tif", ".jpg", ".gif", ".zip", ".raw", ".avi", ".bmp",
  1894. ".fits", ".pgm", ".png", ".lut", ".roi" or ".txt". The specified image is saved in
  1895. TIFF format if there is no extension. */
  1896. public static void save(ImagePlus imp, String path) {
  1897. ImagePlus imp2 = imp;
  1898. if (imp2==null)
  1899. imp2 = WindowManager.getCurrentImage();
  1900. int dotLoc = path.lastIndexOf('.');
  1901. if (dotLoc==-1 && imp2!=null) {
  1902. path = path + ".tif"; // save as TIFF if file name does not have an extension
  1903. dotLoc = path.lastIndexOf('.');
  1904. }
  1905. if (dotLoc!=-1) {
  1906. String title = imp2!=null?imp2.getTitle():null;
  1907. saveAs(imp, path.substring(dotLoc+1), path);
  1908. if (title!=null)
  1909. imp2.setTitle(title);
  1910. } else
  1911. error("The file path passed to IJ.save() method or save()\nmacro function is missing the required extension.\n \n\""+path+"\"");
  1912. }
  1913. /* Saves the active image, lookup table, selection, measurement results, selection XY
  1914. coordinates or text window to the specified file path. The format argument must be "tiff",
  1915. "jpeg", "gif", "zip", "raw", "avi", "bmp", "fits", "pgm", "png", "text image", "lut", "selection", "measurements",
  1916. "xy Coordinates" or "text". If <code>path</code> is null or an emply string, a file
  1917. save dialog is displayed. */
  1918. public static void saveAs(String format, String path) {
  1919. saveAs(null, format, path);
  1920. }
  1921. /* Saves the specified image. The format argument must be "tiff",
  1922. "jpeg", "gif", "zip", "raw", "avi", "bmp", "fits", "pgm", "png",
  1923. "text image", "lut", "selection" or "xy Coordinates". */
  1924. public static void saveAs(ImagePlus imp, String format, String path) {
  1925. if (format==null)
  1926. return;
  1927. if (path!=null && path.length()==0)
  1928. path = null;
  1929. format = format.toLowerCase(Locale.US);
  1930. Roi roi2 = imp!=null?imp.getRoi():null;
  1931. if (roi2!=null)
  1932. roi2.endPaste();
  1933. if (format.indexOf("tif")!=-1) {
  1934. saveAsTiff(imp, path);
  1935. return;
  1936. } else if (format.indexOf("jpeg")!=-1 || format.indexOf("jpg")!=-1) {
  1937. path = updateExtension(path, ".jpg");
  1938. JpegWriter.save(imp, path, FileSaver.getJpegQuality());
  1939. return;
  1940. } else if (format.indexOf("gif")!=-1) {
  1941. path = updateExtension(path, ".gif");
  1942. GifWriter.save(imp, path);
  1943. return;
  1944. } else if (format.indexOf("text image")!=-1) {
  1945. path = updateExtension(path, ".txt");
  1946. format = "Text Image...";
  1947. } else if (format.indexOf("text")!=-1 || format.indexOf("txt")!=-1) {
  1948. if (path!=null && !path.endsWith(".xls") && !path.endsWith(".csv") && !path.endsWith(".tsv"))
  1949. path = updateExtension(path, ".txt");
  1950. format = "Text...";
  1951. } else if (format.indexOf("zip")!=-1) {
  1952. path = updateExtension(path, ".zip");
  1953. format = "ZIP...";
  1954. } else if (format.indexOf("raw")!=-1) {
  1955. //path = updateExtension(path, ".raw");
  1956. format = "Raw Data...";
  1957. } else if (format.indexOf("avi")!=-1) {
  1958. path = updateExtension(path, ".avi");
  1959. format = "AVI... ";
  1960. } else if (format.indexOf("bmp")!=-1) {
  1961. path = updateExtension(path, ".bmp");
  1962. format = "BMP...";
  1963. } else if (format.indexOf("fits")!=-1) {
  1964. path = updateExtension(path, ".fits");
  1965. format = "FITS...";
  1966. } else if (format.indexOf("png")!=-1) {
  1967. path = updateExtension(path, ".png");
  1968. format = "PNG...";
  1969. } else if (format.indexOf("pgm")!=-1) {
  1970. path = updateExtension(path, ".pgm");
  1971. format = "PGM...";
  1972. } else if (format.indexOf("lut")!=-1) {
  1973. path = updateExtension(path, ".lut");
  1974. format = "LUT...";
  1975. } else if (format.contains("results") || format.contains("measurements") || format.contains("table")) {
  1976. format = "Results...";
  1977. } else if (format.contains("selection") || format.contains("roi")) {
  1978. path = updateExtension(path, ".roi");
  1979. format = "Selection...";
  1980. } else if (format.indexOf("xy")!=-1 || format.indexOf("coordinates")!=-1) {
  1981. path = updateExtension(path, ".txt");
  1982. format = "XY Coordinates...";
  1983. } else
  1984. error("Unsupported save() or saveAs() file format: \""+format+"\"\n \n\""+path+"\"");
  1985. if (path==null)
  1986. run(format);
  1987. else {
  1988. if (path.contains(" "))
  1989. run(imp, format, "save=["+path+"]");
  1990. else
  1991. run(imp, format, "save="+path);
  1992. }
  1993. }
  1994. /** Saves the specified image in TIFF format. Displays a file save dialog
  1995. if 'path' is null or an empty string. Returns 'false' if there is an
  1996. error or if the user selects "Cancel" in the file save dialog. */
  1997. public static boolean saveAsTiff(ImagePlus imp, String path) {
  1998. if (imp==null)
  1999. imp = getImage();
  2000. if (path==null || path.equals(""))
  2001. return (new FileSaver(imp)).saveAsTiff();
  2002. if (!path.endsWith(".tiff"))
  2003. path = updateExtension(path, ".tif");
  2004. FileSaver fs = new FileSaver(imp);
  2005. boolean ok;
  2006. if (imp.getStackSize()>1)
  2007. ok = fs.saveAsTiffStack(path);
  2008. else
  2009. ok = fs.saveAsTiff(path);
  2010. if (ok)
  2011. fs.updateImagePlus(path, FileInfo.TIFF);
  2012. return ok;
  2013. }
  2014. static String updateExtension(String path, String extension) {
  2015. if (path==null) return null;
  2016. int dotIndex = path.lastIndexOf(".");
  2017. int separatorIndex = path.lastIndexOf(File.separator);
  2018. if (dotIndex>=0 && dotIndex>separatorIndex && (path.length()-dotIndex)<=5) {
  2019. if (dotIndex+1<path.length() && Character.isDigit(path.charAt(dotIndex+1)))
  2020. path += extension;
  2021. else
  2022. path = path.substring(0, dotIndex) + extension;
  2023. } else
  2024. path += extension;
  2025. return path;
  2026. }
  2027. /** Saves a string as a file. Displays a file save dialog if
  2028. 'path' is null or blank. Returns an error message
  2029. if there is an exception, otherwise returns null. */
  2030. public static String saveString(String string, String path) {
  2031. return write(string, path, false);
  2032. }
  2033. /** Appends a string to the end of a file. A newline character ("\n")
  2034. is added to the end of the string before it is written. Returns an
  2035. error message if there is an exception, otherwise returns null. */
  2036. public static String append(String string, String path) {
  2037. return write(string+"\n", path, true);
  2038. }
  2039. private static String write(String string, String path, boolean append) {
  2040. if (path==null || path.equals("")) {
  2041. String msg = append?"Append String...":"Save String...";
  2042. SaveDialog sd = new SaveDialog(msg, "Untitled", ".txt");
  2043. String name = sd.getFileName();
  2044. if (name==null) return null;
  2045. path = sd.getDirectory() + name;
  2046. }
  2047. try {
  2048. BufferedWriter out = new BufferedWriter(new FileWriter(path, append));
  2049. out.write(string);
  2050. out.close();
  2051. } catch (IOException e) {
  2052. return ""+e;
  2053. }
  2054. return null;
  2055. }
  2056. /** Opens a text file as a string. Displays a file open dialog
  2057. if path is null or blank. Returns null if the user cancels
  2058. the file open dialog. If there is an error, returns a
  2059. message in the form "Error: message". */
  2060. public static String openAsString(String path) {
  2061. if (path==null || path.equals("")) {
  2062. OpenDialog od = new OpenDialog("Open Text File", "");
  2063. String directory = od.getDirectory();
  2064. String name = od.getFileName();
  2065. if (name==null) return null;
  2066. path = directory + name;
  2067. }
  2068. String str = "";
  2069. File file = new File(path);
  2070. if (!file.exists())
  2071. return "Error: file not found";
  2072. try {
  2073. StringBuffer sb = new StringBuffer(5000);
  2074. BufferedReader r = new BufferedReader(new FileReader(file));
  2075. while (true) {
  2076. String s=r.readLine();
  2077. if (s==null)
  2078. break;
  2079. else
  2080. sb.append(s+"\n");
  2081. }
  2082. r.close();
  2083. str = new String(sb);
  2084. }
  2085. catch (Exception e) {
  2086. str = "Error: "+e.getMessage();
  2087. }
  2088. return str;
  2089. }
  2090. public static ByteBuffer openAsByteBuffer(String path) {
  2091. if (path==null || path.equals("")) {
  2092. OpenDialog od = new OpenDialog("Open as ByteBuffer", "");
  2093. String directory = od.getDirectory();
  2094. String name = od.getFileName();
  2095. if (name==null) return null;
  2096. path = directory + name;
  2097. }
  2098. File file = new File(path);
  2099. if (!file.exists()) {
  2100. error("OpenAsByteBuffer", "File not found");
  2101. return null;
  2102. }
  2103. int len = (int)file.length();
  2104. byte[] buffer = new byte[len];
  2105. try {
  2106. InputStream in = new BufferedInputStream(new FileInputStream(path));
  2107. DataInputStream dis = new DataInputStream(in);
  2108. dis.readFully(buffer);
  2109. dis.close();
  2110. }
  2111. catch (Exception e) {
  2112. error("OpenAsByteBuffer", e.getMessage());
  2113. return null;
  2114. }
  2115. return ByteBuffer.wrap(buffer);
  2116. }
  2117. /** Creates a new image.
  2118. * @param title image name
  2119. * @param width image width in pixels
  2120. * @param height image height in pixels
  2121. * @param depth number of stack images
  2122. * @param bitdepth 8, 16, 32 (float) or 24 (RGB)
  2123. */
  2124. public static ImagePlus createImage(String title, int width, int height, int depth, int bitdepth) {
  2125. return NewImage.createImage(title, width, height, depth, bitdepth, NewImage.FILL_BLACK);
  2126. }
  2127. /** Creates a new imagePlus. <code>Type</code> should contain "8-bit", "16-bit", "32-bit" or "RGB".
  2128. In addition, it can contain "white", "black" or "ramp". <code>Width</code>
  2129. and <code>height</code> specify the width and height of the image in pixels.
  2130. <code>Depth</code> specifies the number of stack slices. */
  2131. public static ImagePlus createImage(String title, String type, int width, int height, int depth) {
  2132. type = type.toLowerCase(Locale.US);
  2133. int bitDepth = 8;
  2134. if (type.contains("16"))
  2135. bitDepth = 16;
  2136. boolean signedInt = type.contains("32-bit int");
  2137. if (type.contains("32"))
  2138. bitDepth = 32;
  2139. if (type.contains("24") || type.contains("rgb") || signedInt)
  2140. bitDepth = 24;
  2141. int options = NewImage.FILL_WHITE;
  2142. if (bitDepth==16 || bitDepth==32)
  2143. options = NewImage.FILL_BLACK;
  2144. if (type.contains("white"))
  2145. options = NewImage.FILL_WHITE;
  2146. else if (type.contains("black"))
  2147. options = NewImage.FILL_BLACK;
  2148. else if (type.contains("ramp"))
  2149. options = NewImage.FILL_RAMP;
  2150. else if (type.contains("noise") || type.contains("random"))
  2151. options = NewImage.FILL_NOISE;
  2152. options += NewImage.CHECK_AVAILABLE_MEMORY;
  2153. if (signedInt)
  2154. options += NewImage.SIGNED_INT;
  2155. return NewImage.createImage(title, width, height, depth, bitDepth, options);
  2156. }
  2157. /** Creates a new hyperstack.
  2158. * @param title image name
  2159. * @param type "8-bit", "16-bit", "32-bit" or "RGB". May also
  2160. * contain "white" , "black" (the default), "ramp", "composite-mode",
  2161. * "color-mode", "grayscale-mode or "label".
  2162. * @param width image width in pixels
  2163. * @param height image height in pixels
  2164. * @param channels number of channels
  2165. * @param slices number of slices
  2166. * @param frames number of frames
  2167. */
  2168. public static ImagePlus createImage(String title, String type, int width, int height, int channels, int slices, int frames) {
  2169. if (type.contains("label"))
  2170. type += "ramp";
  2171. if (!(type.contains("white")||type.contains("ramp")))
  2172. type += "black";
  2173. ImagePlus imp = IJ.createImage(title, type, width, height, channels*slices*frames);
  2174. imp.setDimensions(channels, slices, frames);
  2175. int mode = IJ.COLOR;
  2176. if (type.contains("composite"))
  2177. mode = IJ.COMPOSITE;
  2178. if (type.contains("grayscale"))
  2179. mode = IJ.GRAYSCALE;
  2180. if (channels>1 && imp.getBitDepth()!=24)
  2181. imp = new CompositeImage(imp, mode);
  2182. imp.setOpenAsHyperStack(true);
  2183. if (type.contains("label"))
  2184. HyperStackMaker.labelHyperstack(imp);
  2185. return imp;
  2186. }
  2187. /** Creates a new hyperstack.
  2188. * @param title image name
  2189. * @param width image width in pixels
  2190. * @param height image height in pixels
  2191. * @param channels number of channels
  2192. * @param slices number of slices
  2193. * @param frames number of frames
  2194. * @param bitdepth 8, 16, 32 (float) or 24 (RGB)
  2195. */
  2196. public static ImagePlus createHyperStack(String title, int width, int height, int channels, int slices, int frames, int bitdepth) {
  2197. ImagePlus imp = createImage(title, width, height, channels*slices*frames, bitdepth);
  2198. imp.setDimensions(channels, slices, frames);
  2199. if (channels>1 && bitdepth!=24)
  2200. imp = new CompositeImage(imp, IJ.COMPOSITE);
  2201. imp.setOpenAsHyperStack(true);
  2202. return imp;
  2203. }
  2204. /** Opens a new image. <code>Type</code> should contain "8-bit", "16-bit", "32-bit" or "RGB".
  2205. In addition, it can contain "white", "black" or "ramp". <code>Width</code>
  2206. and <code>height</code> specify the width and height of the image in pixels.
  2207. <code>Depth</code> specifies the number of stack slices. */
  2208. public static void newImage(String title, String type, int width, int height, int depth) {
  2209. ImagePlus imp = createImage(title, type, width, height, depth);
  2210. if (imp!=null) {
  2211. macroRunning = true;
  2212. imp.show();
  2213. macroRunning = false;
  2214. }
  2215. }
  2216. /** Returns true if the <code>Esc</code> key was pressed since the
  2217. last ImageJ command started to execute or since resetEscape() was called. */
  2218. public static boolean escapePressed() {
  2219. return escapePressed;
  2220. }
  2221. /** This method sets the <code>Esc</code> key to the "up" position.
  2222. The Executer class calls this method when it runs
  2223. an ImageJ command in a separate thread. */
  2224. public static void resetEscape() {
  2225. escapePressed = false;
  2226. }
  2227. /** Causes IJ.error() output to be temporarily redirected to the "Log" window. */
  2228. public static void redirectErrorMessages() {
  2229. redirectErrorMessages = true;
  2230. lastErrorMessage = null;
  2231. }
  2232. /** Set 'true' and IJ.error() output will be temporarily redirected to the "Log" window. */
  2233. public static void redirectErrorMessages(boolean redirect) {
  2234. redirectErrorMessages = redirect;
  2235. lastErrorMessage = null;
  2236. }
  2237. /** Returns the state of the 'redirectErrorMessages' flag, which is set by File/Import/Image Sequence. */
  2238. public static boolean redirectingErrorMessages() {
  2239. return redirectErrorMessages;
  2240. }
  2241. /** Temporarily suppress "plugin not found" errors. */
  2242. public static void suppressPluginNotFoundError() {
  2243. suppressPluginNotFoundError = true;
  2244. }
  2245. /** Returns the class loader ImageJ uses to run plugins or the
  2246. system class loader if Menus.getPlugInsPath() returns null. */
  2247. public static ClassLoader getClassLoader() {
  2248. if (classLoader==null) {
  2249. String pluginsDir = Menus.getPlugInsPath();
  2250. if (pluginsDir==null) {
  2251. String home = System.getProperty("plugins.dir");
  2252. if (home!=null) {
  2253. if (!home.endsWith(Prefs.separator)) home+=Prefs.separator;
  2254. pluginsDir = home+"plugins"+Prefs.separator;
  2255. if (!(new File(pluginsDir)).isDirectory())
  2256. pluginsDir = home;
  2257. }
  2258. }
  2259. if (pluginsDir==null)
  2260. return IJ.class.getClassLoader();
  2261. else {
  2262. if (Menus.jnlp)
  2263. classLoader = new PluginClassLoader(pluginsDir, true);
  2264. else
  2265. classLoader = new PluginClassLoader(pluginsDir);
  2266. }
  2267. }
  2268. return classLoader;
  2269. }
  2270. /** Returns the size, in pixels, of the primary display. */
  2271. public static Dimension getScreenSize() {
  2272. Rectangle bounds = GUI.getScreenBounds();
  2273. return new Dimension(bounds.width, bounds.height);
  2274. }
  2275. /** Returns, as an array of strings, a list of the LUTs in the
  2276. * Image/Lookup Tables menu.
  2277. * @see ij.plugin#LutLoader.getLut
  2278. * See also: Help>Examples>JavaScript/Show all LUTs
  2279. * and Image/Color/Display LUTs
  2280. */
  2281. public static String[] getLuts() {
  2282. ArrayList list = new ArrayList();
  2283. Hashtable commands = Menus.getCommands();
  2284. Menu lutsMenu = Menus.getImageJMenu("Image>Lookup Tables");
  2285. if (commands==null || lutsMenu==null)
  2286. return new String[0];
  2287. for (int i=0; i<lutsMenu.getItemCount(); i++) {
  2288. MenuItem menuItem = lutsMenu.getItem(i);
  2289. String label = menuItem.getLabel();
  2290. if (label.equals("-") || label.equals("Invert LUT") || label.equals("Apply LUT"))
  2291. continue;
  2292. String command = (String)commands.get(label);
  2293. if (command==null || command.startsWith("ij.plugin.LutLoader"))
  2294. list.add(label);
  2295. }
  2296. return (String[])list.toArray(new String[list.size()]);
  2297. }
  2298. static void abort() {
  2299. if ((ij!=null || Interpreter.isBatchMode()) && macroInterpreter==null)
  2300. throw new RuntimeException(Macro.MACRO_CANCELED);
  2301. }
  2302. static void setClassLoader(ClassLoader loader) {
  2303. classLoader = loader;
  2304. }
  2305. public static void resetClassLoader() {
  2306. setClassLoader(null);
  2307. }
  2308. /** Displays a stack trace. Use the setExceptionHandler
  2309. method() to override with a custom exception handler. */
  2310. public static void handleException(Throwable e) {
  2311. if (exceptionHandler!=null) {
  2312. exceptionHandler.handle(e);
  2313. return;
  2314. }
  2315. if (Macro.MACRO_CANCELED.equals(e.getMessage()))
  2316. return;
  2317. CharArrayWriter caw = new CharArrayWriter();
  2318. PrintWriter pw = new PrintWriter(caw);
  2319. e.printStackTrace(pw);
  2320. String s = caw.toString();
  2321. String lineNumber = "";
  2322. if (s!=null && s.contains("ThreadDeath"))
  2323. return;
  2324. Interpreter interpreter = Thread.currentThread().getName().endsWith("Macro$") ? Interpreter.getInstance() : null;
  2325. if (interpreter!=null)
  2326. lineNumber = "\nMacro line number: " + interpreter.getLineNumber();
  2327. if (getInstance()!=null) {
  2328. s = IJ.getInstance().getInfo()+lineNumber+"\n \n"+s;
  2329. new TextWindow("Exception", s, 500, 340);
  2330. } else
  2331. log(s);
  2332. }
  2333. /** Installs a custom exception handler that
  2334. overrides the handleException() method. */
  2335. public static void setExceptionHandler(ExceptionHandler handler) {
  2336. exceptionHandler = handler;
  2337. }
  2338. public interface ExceptionHandler {
  2339. public void handle(Throwable e);
  2340. }
  2341. static ExceptionHandler exceptionHandler;
  2342. public static void addEventListener(IJEventListener listener) {
  2343. eventListeners.addElement(listener);
  2344. }
  2345. public static void removeEventListener(IJEventListener listener) {
  2346. eventListeners.removeElement(listener);
  2347. }
  2348. public static void notifyEventListeners(int eventID) {
  2349. synchronized (eventListeners) {
  2350. for (int i=0; i<eventListeners.size(); i++) {
  2351. IJEventListener listener = (IJEventListener)eventListeners.elementAt(i);
  2352. listener.eventOccurred(eventID);
  2353. }
  2354. }
  2355. }
  2356. /** Adds a key-value pair to IJ.properties. The key
  2357. * and value are removed if 'value' is null.
  2358. */
  2359. public static void setProperty(String key, Object value) {
  2360. if (properties==null)
  2361. properties = new Properties();
  2362. if (value==null)
  2363. properties.remove(key);
  2364. else
  2365. properties.put(key, value);
  2366. }
  2367. /** Returns the object in IJ.properties associated
  2368. * with 'key', or null if 'key' is not found.
  2369. */
  2370. public static Object getProperty(String key) {
  2371. if (properties==null)
  2372. return null;
  2373. else
  2374. return properties.get(key);
  2375. }
  2376. public static boolean statusBarProtected() {
  2377. return protectStatusBar;
  2378. }
  2379. public static void protectStatusBar(boolean protect) {
  2380. protectStatusBar = protect;
  2381. if (!protectStatusBar)
  2382. statusBarThread = null;
  2383. }
  2384. }