PageRenderTime 71ms CodeModel.GetById 31ms RepoModel.GetById 1ms 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

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

  1. package ij;
  2. import ij.gui.*;
  3. import ij.process.*;
  4. import ij.text.*;
  5. import ij.io.*;
  6. import ij.plugin.*;
  7. import ij.plugin.filter.*;
  8. import ij.util.Tools;
  9. import ij.plugin.frame.Recorder;
  10. import ij.plugin.frame.ThresholdAdjuster;
  11. import ij.macro.Interpreter;
  12. import ij.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. */

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