private void openDirectory(File f, String path) { if (path == null) return; if (!(path.endsWith(File.separator) || path.endsWith("/"))) path += File.separator; String[] names = f.list(); names = (new FolderOpener()).trimFileList(names); if (names == null) return; String msg = "Open all " + names.length + " images in \"" + f.getName() + "\" as a stack?"; GenericDialog gd = new GenericDialog("Open Folder"); gd.setInsets(10, 5, 0); gd.addMessage(msg); gd.setInsets(15, 35, 0); gd.addCheckbox("Convert to RGB", convertToRGB); gd.setInsets(0, 35, 0); gd.addCheckbox("Use Virtual Stack", virtualStack); gd.enableYesNoCancel(); gd.showDialog(); if (gd.wasCanceled()) return; if (gd.wasOKed()) { convertToRGB = gd.getNextBoolean(); virtualStack = gd.getNextBoolean(); String options = " sort"; if (convertToRGB) options += " convert_to_rgb"; if (virtualStack) options += " use"; IJ.run("Image Sequence...", "open=[" + path + "]" + options); DirectoryChooser.setDefaultDirectory(path); } else { for (int k = 0; k < names.length; k++) { IJ.redirectErrorMessages(); if (!names[k].startsWith(".")) (new Opener()).open(path + names[k]); } } IJ.register(DragAndDrop.class); }
private ImagePlus openImage(String directory, String name, String path) { Object o = tryOpen(directory, name, path); // if an image was returned, assume success if (o instanceof ImagePlus) return (ImagePlus) o; // try opening the file with LOCI Bio-Formats plugin - always check this last! // Do not call Bio-Formats if File>Import>Image Sequence is opening this file. if (o == null && (IJ.getVersion().compareTo("1.38j") < 0 || !IJ.redirectingErrorMessages()) && (new File(path).exists())) { Object loci = IJ.runPlugIn("loci.plugins.LociImporter", path); if (loci != null) { // plugin exists and was launched try { // check whether plugin was successful Class c = loci.getClass(); boolean success = c.getField("success").getBoolean(loci); boolean canceled = c.getField("canceled").getBoolean(loci); if (success || canceled) { width = IMAGE_OPENED; return null; } } catch (Exception exc) { } } } return null; } // openImage
/** Called by ImageJ when the user selects Quit. */ public void quit() { quitMacro = IJ.macroRunning(); Thread thread = new Thread(this, "Quit"); thread.setPriority(Thread.NORM_PRIORITY); thread.start(); IJ.wait(10); }
/** Handle menu events. */ public void actionPerformed(ActionEvent e) { if ((e.getSource() instanceof MenuItem)) { MenuItem item = (MenuItem) e.getSource(); String cmd = e.getActionCommand(); commandName = cmd; ImagePlus imp = null; if (item.getParent() == Menus.getOpenRecentMenu()) { new RecentOpener(cmd); // open image in separate thread return; } else if (item.getParent() == Menus.getPopupMenu()) { Object parent = Menus.getPopupMenu().getParent(); if (parent instanceof ImageCanvas) imp = ((ImageCanvas) parent).getImage(); } int flags = e.getModifiers(); hotkey = false; actionPerformedTime = System.currentTimeMillis(); long ellapsedTime = actionPerformedTime - keyPressedTime; if (cmd != null && (ellapsedTime >= 200L || !cmd.equals(lastKeyCommand))) { if ((flags & Event.ALT_MASK) != 0) IJ.setKeyDown(KeyEvent.VK_ALT); if ((flags & Event.SHIFT_MASK) != 0) IJ.setKeyDown(KeyEvent.VK_SHIFT); new Executer(cmd, imp); } lastKeyCommand = null; if (IJ.debugMode) IJ.log("actionPerformed: time=" + ellapsedTime + ", " + e); } }
public Zipper<Map<Integer, MZipper<RoiContainer>>> exec( Zipper<Map<Integer, MZipper<RoiContainer>>> z, int frame) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(WindowManager.getCurrentWindow().getCanvas()); Map<Integer, MZipper<RoiContainer>> newRois; if (returnVal == JFileChooser.APPROVE_OPTION) { try { FileInputStream f = new FileInputStream(fc.getSelectedFile().getCanonicalPath()); MroiLisp parser = new MroiLisp(f); parser.ReInit(f); newRois = parser.roiFile(); // z.rights.clear(); // z.rights.add(newRois); // z = z.right(); // return z; return z.insertAndStep(newRois); } catch (IOException e) { IJ.error("Couldn't open from " + fc.getSelectedFile().getName() + ": " + e.getMessage()); } catch (mroi.ParseException e) { IJ.error("Failed in parsing: " + e.getMessage()); } catch (Exception e) { IJ.error("Malformed input file: " + e.getMessage()); } } return z; }
/** Called from io/Opener.java. */ public void run(String path) { if (path.equals("")) return; File theFile = new File(path); String directory = theFile.getParent(); String fileName = theFile.getName(); if (directory == null) directory = ""; // Try and recognise file type and load the file if recognised ImagePlus imp = openImage(directory, fileName, path); if (imp == null) { IJ.showStatus(""); return; // failed to load file or plugin has opened and displayed it } ImageStack stack = imp.getStack(); // get the title from the stack (falling back to the fileName) String title = imp.getTitle().equals("") ? fileName : imp.getTitle(); // set the stack of this HandleExtraFileTypes object // to that attached to the ImagePlus object returned by openImage() setStack(title, stack); // copy over the calibration info since it doesn't come with the ImageProcessor setCalibration(imp.getCalibration()); // also copy the Show Info field over if it exists if (imp.getProperty("Info") != null) setProperty("Info", imp.getProperty("Info")); // copy the FileInfo setFileInfo(imp.getOriginalFileInfo()); // copy dimensions if (IJ.getVersion().compareTo("1.38s") >= 0) setDimensions(imp.getNChannels(), imp.getNSlices(), imp.getNFrames()); if (IJ.getVersion().compareTo("1.41o") >= 0) setOpenAsHyperStack(imp.getOpenAsHyperStack()); }
void write16BitStack(OutputStream out, Object[] stack) throws IOException { showProgressBar = false; for (int i = 0; i < fi.nImages; i++) { IJ.showStatus("Writing: " + (i + 1) + "/" + fi.nImages); write16BitImage(out, (short[]) stack[i]); IJ.showProgress((double) (i + 1) / fi.nImages); } }
public void dragOver(DropTargetDragEvent e) { if (IJ.debugMode) IJ.log("DragOver: " + e.getLocation()); Point loc = e.getLocation(); int buttonSize = Toolbar.getButtonSize(); int width = IJ.getInstance().getSize().width; openAsVirtualStack = width - loc.x <= buttonSize; if (openAsVirtualStack) IJ.showStatus("<<Open as Virtual Stack>>"); else IJ.showStatus("<<Drag and Drop>>"); }
void write16BitVirtualStack(OutputStream out, VirtualStack virtualStack) throws IOException { showProgressBar = false; boolean flip = "FlipTheseImages".equals(fi.fileName); for (int i = 1; i <= fi.nImages; i++) { IJ.showStatus("Writing: " + i + "/" + fi.nImages); ImageProcessor ip = virtualStack.getProcessor(i); if (flip) ip.flipVertical(); short[] pixels = (short[]) ip.getPixels(); write16BitImage(out, pixels); IJ.showProgress((double) i / fi.nImages); } }
/** Quit using a separate thread, hopefully avoiding thread deadlocks. */ public void run() { quitting = true; boolean changes = false; int[] wList = WindowManager.getIDList(); if (wList != null) { for (int i = 0; i < wList.length; i++) { ImagePlus imp = WindowManager.getImage(wList[i]); if (imp != null && imp.changes == true) { changes = true; break; } } } Frame[] frames = WindowManager.getNonImageWindows(); if (frames != null) { for (int i = 0; i < frames.length; i++) { if (frames[i] != null && (frames[i] instanceof Editor)) { if (((Editor) frames[i]).fileChanged()) { changes = true; break; } } } } if (windowClosed && !changes && Menus.window.getItemCount() > Menus.WINDOW_MENU_ITEMS && !(IJ.macroRunning() && WindowManager.getImageCount() == 0)) { GenericDialog gd = new GenericDialog("ImageJ", this); gd.addMessage("Are you sure you want to quit ImageJ?"); gd.showDialog(); quitting = !gd.wasCanceled(); windowClosed = false; } if (!quitting) return; if (!WindowManager.closeAllWindows()) { quitting = false; return; } // IJ.log("savePreferences"); if (applet == null) { saveWindowLocations(); Prefs.savePreferences(); } IJ.cleanup(); // setVisible(false); // IJ.log("dispose"); dispose(); if (exitWhenQuitting) System.exit(0); }
public void drop(DropTargetDropEvent dtde) { dtde.acceptDrop(DnDConstants.ACTION_COPY); DataFlavor[] flavors = null; try { Transferable t = dtde.getTransferable(); iterator = null; flavors = t.getTransferDataFlavors(); if (IJ.debugMode) IJ.log("DragAndDrop.drop: " + flavors.length + " flavors"); for (int i = 0; i < flavors.length; i++) { if (IJ.debugMode) IJ.log(" flavor[" + i + "]: " + flavors[i].getMimeType()); if (flavors[i].isFlavorJavaFileListType()) { Object data = t.getTransferData(DataFlavor.javaFileListFlavor); iterator = ((List) data).iterator(); break; } else if (flavors[i].isFlavorTextType()) { Object ob = t.getTransferData(flavors[i]); if (!(ob instanceof String)) continue; String s = ob.toString().trim(); if (IJ.isLinux() && s.length() > 1 && (int) s.charAt(1) == 0) s = fixLinuxString(s); ArrayList list = new ArrayList(); if (s.indexOf("href=\"") != -1 || s.indexOf("src=\"") != -1) { s = parseHTML(s); if (IJ.debugMode) IJ.log(" url: " + s); list.add(s); this.iterator = list.iterator(); break; } BufferedReader br = new BufferedReader(new StringReader(s)); String tmp; while (null != (tmp = br.readLine())) { tmp = java.net.URLDecoder.decode(tmp.replaceAll("\\+", "%2b"), "UTF-8"); if (tmp.startsWith("file://")) tmp = tmp.substring(7); if (IJ.debugMode) IJ.log(" content: " + tmp); if (tmp.startsWith("http://")) list.add(s); else list.add(new File(tmp)); } this.iterator = list.iterator(); break; } } if (iterator != null) { Thread thread = new Thread(this, "DrawAndDrop"); thread.setPriority(Math.max(thread.getPriority() - 1, Thread.MIN_PRIORITY)); thread.start(); } } catch (Exception e) { dtde.dropComplete(false); return; } dtde.dropComplete(true); if (flavors == null || flavors.length == 0) { if (IJ.isMacOSX()) IJ.error( "First drag and drop ignored. Please try again. You can avoid this\n" + "problem by dragging to the toolbar instead of the status bar."); else IJ.error("Drag and drop failed"); } }
public void run(String arg) { ImageJ ij = IJ.getInstance(); ij.setDropTarget(null); new DropTarget(ij, this); new DropTarget(Toolbar.getInstance(), this); new DropTarget(ij.getStatusBar(), this); }
void updateMenus() { if (IJ.debugMode) { long start = System.currentTimeMillis(); Menus.updateImageJMenus(); IJ.log("Refresh Menus: " + (System.currentTimeMillis() - start) + " ms"); } else Menus.updateImageJMenus(); }
/** Opens a stack of images. */ ImagePlus openStack(ColorModel cm, boolean show) { ImageStack stack = new ImageStack(fi.width, fi.height, cm); long skip = fi.getOffset(); Object pixels; try { ImageReader reader = new ImageReader(fi); InputStream is = createInputStream(fi); if (is == null) return null; IJ.resetEscape(); for (int i = 1; i <= fi.nImages; i++) { if (!silentMode) IJ.showStatus("Reading: " + i + "/" + fi.nImages); if (IJ.escapePressed()) { IJ.beep(); IJ.showProgress(1.0); silentMode = false; return null; } pixels = reader.readPixels(is, skip); if (pixels == null) break; stack.addSlice(null, pixels); skip = fi.gapBetweenImages; if (!silentMode) IJ.showProgress(i, fi.nImages); } is.close(); } catch (Exception e) { IJ.log("" + e); } catch (OutOfMemoryError e) { IJ.outOfMemory(fi.fileName); stack.trim(); } if (!silentMode) IJ.showProgress(1.0); if (stack.getSize() == 0) return null; if (fi.sliceLabels != null && fi.sliceLabels.length <= stack.getSize()) { for (int i = 0; i < fi.sliceLabels.length; i++) stack.setSliceLabel(fi.sliceLabels[i], i + 1); } ImagePlus imp = new ImagePlus(fi.fileName, stack); if (fi.info != null) imp.setProperty("Info", fi.info); if (show) imp.show(); imp.setFileInfo(fi); setCalibration(imp); ImageProcessor ip = imp.getProcessor(); if (ip.getMin() == ip.getMax()) // find stack min and max if first slice is blank setStackDisplayRange(imp); if (!silentMode) IJ.showProgress(1.0); silentMode = false; return imp; }
/** * Reads the image from a URL and returns the pixel array (byte, short, int or float). Returns * null if there was an IO exception. */ public Object readPixels(String url) { java.net.URL theURL; InputStream is; try { theURL = new URL(url); } catch (MalformedURLException e) { IJ.log("" + e); return null; } try { is = theURL.openStream(); } catch (IOException e) { IJ.log("" + e); return null; } return readPixels(is); }
public FileOpener(FileInfo fi) { this.fi = fi; if (fi != null) { width = fi.width; height = fi.height; } if (IJ.debugMode) IJ.log("FileInfo: " + fi); }
public String getInfo() { return version() + System.getProperty("os.name") + " " + System.getProperty("os.version") + "; " + IJ.freeMemory(); }
byte[] getJar(String address) { // System.out.println("getJar: "+address); byte[] data; try { URL url = new URL(address); IJ.showStatus("Connecting to " + IJ.URL); URLConnection uc = url.openConnection(); int len = uc.getContentLength(); if (IJ.debugMode) IJ.log("Updater (url): " + address + " " + len); if (len <= 0) return null; String name = address.contains("wsr") ? "daily build (" : "ij.jar ("; IJ.showStatus("Downloading " + name + IJ.d2s((double) len / 1048576, 1) + "MB)"); InputStream in = uc.getInputStream(); data = new byte[len]; int n = 0; while (n < len) { int count = in.read(data, n, len - n); if (count < 0) throw new EOFException(); n += count; IJ.showProgress(n, len); } in.close(); } catch (IOException e) { if (IJ.debugMode) IJ.log("" + e); return null; } if (IJ.debugMode) IJ.wait(6000); return data; }
private String version() { return "ImageJ " + VERSION + BUILD + "; " + "Java " + System.getProperty("java.version") + (IJ.is64Bit() ? " [64-bit]; " : " [32-bit]; "); }
byte[] download(File f) { if (!f.exists()) { IJ.error("Plugin Installer", "File not found: " + f); return null; } byte[] data = null; try { int len = (int) f.length(); InputStream in = new BufferedInputStream(new FileInputStream(f)); DataInputStream dis = new DataInputStream(in); data = new byte[len]; dis.readFully(data); dis.close(); } catch (Exception e) { IJ.error("Plugin Installer", "" + e); data = null; } return data; }
short[] readCompressed16bitImage(InputStream in) throws IOException { if (IJ.debugMode) IJ.log("ImageReader.read16bit, offset=" + fi.stripOffsets[0]); short[] pixels = new short[nPixels]; int base = 0; short last = 0; for (int k = 0; k < fi.stripOffsets.length; k++) { // IJ.log("seek: "+fi.stripOffsets[k]+" "+fi.stripLengths[k]+" "+(in instanceof // RandomAccessStream)); if (in instanceof RandomAccessStream) ((RandomAccessStream) in).seek(fi.stripOffsets[k]); else if (k > 0) { long skip = (fi.stripOffsets[k] & 0xffffffffL) - (fi.stripOffsets[k - 1] & 0xffffffffL) - fi.stripLengths[k - 1]; if (skip > 0L) in.skip(skip); } byte[] byteArray = new byte[fi.stripLengths[k]]; int read = 0, left = byteArray.length; while (left > 0) { int r = in.read(byteArray, read, left); if (r == -1) { eofError(); break; } read += r; left -= r; } byteArray = uncompress(byteArray); int pixelsRead = byteArray.length / bytesPerPixel; pixelsRead = pixelsRead - (pixelsRead % fi.width); int pmax = base + pixelsRead; if (pmax > nPixels) pmax = nPixels; if (fi.intelByteOrder) { for (int i = base, j = 0; i < pmax; i++, j += 2) pixels[i] = (short) (((byteArray[j + 1] & 0xff) << 8) | (byteArray[j] & 0xff)); } else { for (int i = base, j = 0; i < pmax; i++, j += 2) pixels[i] = (short) (((byteArray[j] & 0xff) << 8) | (byteArray[j + 1] & 0xff)); } if (fi.compression == FileInfo.LZW_WITH_DIFFERENCING) { for (int b = base; b < pmax; b++) { pixels[b] += last; last = b % fi.width == fi.width - 1 ? 0 : pixels[b]; } } base += pixelsRead; showProgress(k + 1, fi.stripOffsets.length); } if (fi.fileType == FileInfo.GRAY16_SIGNED) { // convert to unsigned for (int i = 0; i < nPixels; i++) pixels[i] = (short) (pixels[i] + 32768); } return pixels; }
boolean savePlugin(File f, byte[] data) { try { FileOutputStream out = new FileOutputStream(f); out.write(data, 0, data.length); out.close(); } catch (IOException e) { IJ.error("Plugin Installer", "" + e); return false; } return true; }
String[] openUrlAsList(String address) { IJ.showStatus("Connecting to " + IJ.URL); Vector v = new Vector(); try { URL url = new URL(address); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while (true) { line = br.readLine(); if (line == null) break; if (!line.equals("")) v.addElement(line); } br.close(); } catch (Exception e) { } String[] lines = new String[v.size()]; v.copyInto((String[]) lines); IJ.showStatus(""); return lines; }
public void run(String arg) { OpenDialog od = new OpenDialog("Install Plugin, Macro or Script...", arg); String directory = od.getDirectory(); String name = od.getFileName(); if (name == null) return; if (!validExtension(name)) { IJ.error("Plugin Installer", errorMessage()); return; } String path = directory + name; install(path); }
void abortPluginOrMacro(ImagePlus imp) { if (imp != null) { ImageWindow win = imp.getWindow(); if (win != null) { win.running = false; win.running2 = false; } } Macro.abort(); Interpreter.abort(); if (Interpreter.getInstance() != null) IJ.beep(); }
/** * Open a file. If it's a directory, ask to open all images as a sequence in a stack or * individually. */ public void openFile(File f) { if (IJ.debugMode) IJ.log("DragAndDrop.openFile: " + f); try { if (null == f) return; String path = f.getCanonicalPath(); if (f.exists()) { if (f.isDirectory()) openDirectory(f, path); else { if (openAsVirtualStack && (path.endsWith(".tif") || path.endsWith(".TIF"))) (new FileInfoVirtualStack()).run(path); else (new Opener()).openAndAddToRecent(path); OpenDialog.setLastDirectory(f.getParent() + File.separator); OpenDialog.setLastName(f.getName()); } } else { IJ.log("File not found: " + path); } } catch (Throwable e) { if (!Macro.MACRO_CANCELED.equals(e.getMessage())) IJ.handleException(e); } }
public void run(String arg) { if (IJ.versionLessThan("1.49d")) return; if (!showDialog()) return; SaveDialog sd = new SaveDialog("Save as Bricks...", "", ""); basename = sd.getFileName(); directory = sd.getDirectory(); if (basename == null || directory == null) return; build_bricks(); }
public void run(ImageProcessor ip) { dimz = stack.getSize(); dimy = stack.getWidth(); dimx = stack.getHeight(); SaveDialog sd = new SaveDialog("Save Measurements as Text...", "res", ".dat"); String name = sd.getFileName(); if (name == null) return; String directory = sd.getDirectory(); nb = calculnb(stack); // -1; IJ.showStatus("Measure parameters for the " + nb + " objects ..."); if (nb < 1) { IJ.showMessage("volume must be labeled"); } else { double[] volume_m = new double[nb]; int[] volume_p = new int[nb]; double[] surface = new double[nb]; double[] surfacenb = new double[nb]; double[][][] I = new double[3][3][nb]; double[][] J = new double[3][nb]; double[][][] dir = new double[3][3][nb]; double[] xg = new double[nb]; double[] yg = new double[nb]; double[] zg = new double[nb]; byte[] bord = new byte[nb]; // double[] a = new double[nb]; // double[] b = new double[nb]; // double[] c = new double[nb]; // double[] Fab = new double[nb]; // double[] Fac = new double[nb]; // double[] Fbc = new double[nb]; // double[] sp = new double[nb]; double[][] lmin = new double[nb][3]; double[][] lmax = new double[nb][3]; IJ.showStatus("Measure surfaces ..."); calculmarchsurfstack(stack, nb, surface, volume_m); calculmarchsurfstacknb(stack, nb, surfacenb); // calculvolumestack(stack,nb,volume_p); IJ.showStatus("Measure volumes and inertia ..."); calculcgstack(stack, nb, volume_p, xg, yg, zg); calculinertiestack(stack, nb, xg, yg, zg, I); inertie(nb, I, J, dir); IJ.showStatus("Measure bounding boxes ..."); boitestack(stack, nb, xg, yg, zg, dir, lmin, lmax); borderstack(stack, nb, bord); IJ.showStatus("Save results ..."); sauvegarde( volume_p, volume_m, surface, surfacenb, xg, yg, zg, J, dir, nb, bord, lmin, lmax, directory, name); volume_m = null; volume_p = null; surface = null; xg = null; yg = null; zg = null; } }
/** * Attempts to open the specified path with the given plugin. If the plugin extends the ImagePlus * class (e.g., BioRad_Reader), set extendsImagePlus to true, otherwise (e.g., LSM_Reader) set it * to false. * * @return A reference to the plugin, if it was successful. */ private Object tryPlugIn(String className, String path) { Object o = IJ.runPlugIn(className, path); if (o instanceof ImagePlus) { // plugin extends ImagePlus class ImagePlus imp = (ImagePlus) o; if (imp.getWidth() == 0) o = null; // invalid image else width = IMAGE_OPENED; // success } else { // plugin does not extend ImagePlus; assume success width = IMAGE_OPENED; } return o; }
private String parseHTML(String s) { if (IJ.debugMode) IJ.log("parseHTML:\n" + s); int index1 = s.indexOf("src=\""); if (index1 >= 0) { int index2 = s.indexOf("\"", index1 + 5); if (index2 > 0) return s.substring(index1 + 5, index2); } index1 = s.indexOf("href=\""); if (index1 >= 0) { int index2 = s.indexOf("\"", index1 + 6); if (index2 > 0) return s.substring(index1 + 6, index2); } return s; }