Search in sources :

Example 46 with Project

use of ini.trakem2.Project in project TrakEM2 by trakem2.

the class FSLoader method importStackAsPatches.

/**
 * Returns the last Patch.
 */
protected Patch importStackAsPatches(final Project project, final Layer first_layer, final double x, final double y, final ImagePlus imp_stack, final boolean as_copy, final String filepath) {
    Utils.log2("FSLoader.importStackAsPatches filepath=" + filepath);
    String target_dir = null;
    if (as_copy) {
        DirectoryChooser dc = new DirectoryChooser("Folder to save images");
        target_dir = dc.getDirectory();
        // user canceled dialog
        if (null == target_dir)
            return null;
        if (IJ.isWindows())
            target_dir = target_dir.replace('\\', '/');
        if (target_dir.length() - 1 != target_dir.lastIndexOf('/')) {
            target_dir += "/";
        }
    }
    // Double.MAX_VALUE is a flag to indicate "add centered"
    double pos_x = Double.MAX_VALUE != x ? x : first_layer.getLayerWidth() / 2 - imp_stack.getWidth() / 2;
    double pos_y = Double.MAX_VALUE != y ? y : first_layer.getLayerHeight() / 2 - imp_stack.getHeight() / 2;
    final double thickness = first_layer.getThickness();
    final String title = Utils.removeExtension(imp_stack.getTitle()).replace(' ', '_');
    Utils.showProgress(0);
    Patch previous_patch = null;
    final int n = imp_stack.getStackSize();
    final ImageStack stack = imp_stack.getStack();
    final boolean virtual = stack.isVirtual();
    final VirtualStack vs = virtual ? (VirtualStack) stack : null;
    for (int i = 1; i <= n; i++) {
        Layer layer = first_layer;
        double z = first_layer.getZ() + (i - 1) * thickness;
        // will create new layer if not found
        if (i > 1)
            layer = first_layer.getParent().getLayer(z, thickness, true);
        if (null == layer) {
            Utils.log("Display.importStack: could not create new layers.");
            return null;
        }
        String patch_path = null;
        ImagePlus imp_patch_i = null;
        if (virtual) {
            // because we love inefficiency, every time all this is done again
            // VirtualStack vs = (VirtualStack)imp_stack.getStack();
            String vs_dir = vs.getDirectory().replace('\\', '/');
            if (!vs_dir.endsWith("/"))
                vs_dir += "/";
            String iname = vs.getFileName(i);
            patch_path = vs_dir + iname;
            Utils.log2("virtual stack: patch path is " + patch_path);
            releaseToFit(new File(patch_path).length() * 3);
            Utils.log2(i + " : " + patch_path);
            imp_patch_i = openImage(patch_path);
        } else {
            ImageProcessor ip = stack.getProcessor(i);
            if (as_copy)
                ip = ip.duplicate();
            imp_patch_i = new ImagePlus(title + "__slice=" + i, ip);
        }
        String label = stack.getSliceLabel(i);
        if (null == label)
            label = "";
        Patch patch = null;
        if (as_copy) {
            patch_path = target_dir + cleanSlashes(imp_patch_i.getTitle()) + ".zip";
            ini.trakem2.io.ImageSaver.saveAsZip(imp_patch_i, patch_path);
            patch = new Patch(project, label + " " + title + " " + i, pos_x, pos_y, imp_patch_i);
        } else if (virtual) {
            patch = new Patch(project, label, pos_x, pos_y, imp_patch_i);
        } else {
            patch_path = filepath + "-----#slice=" + i;
            // Utils.log2("path is "+ patch_path);
            final AffineTransform atp = new AffineTransform();
            atp.translate(pos_x, pos_y);
            patch = new Patch(project, getNextId(), label + " " + title + " " + i, imp_stack.getWidth(), imp_stack.getHeight(), imp_stack.getWidth(), imp_stack.getHeight(), imp_stack.getType(), false, imp_stack.getProcessor().getMin(), imp_stack.getProcessor().getMax(), atp);
            patch.addToDatabase();
        // Utils.log2("type is " + imp_stack.getType());
        }
        Utils.log2("B: " + i + " : " + patch_path);
        addedPatchFrom(patch_path, patch);
        if (!as_copy && !virtual) {
            if (// each slice separately
            virtual)
                // each slice separately
                cache(patch, imp_patch_i);
            else
                // uses the entire stack, shared among all Patch instances
                cache(patch, imp_stack);
        }
        // submit for regeneration
        if (isMipMapsRegenerationEnabled())
            regenerateMipMaps(patch);
        if (null != previous_patch)
            patch.link(previous_patch);
        layer.add(patch);
        previous_patch = patch;
        Utils.showProgress(i * (1.0 / n));
    }
    Utils.showProgress(1.0);
    // return the last patch
    return previous_patch;
}
Also used : ImageStack(ij.ImageStack) Layer(ini.trakem2.display.Layer) ImagePlus(ij.ImagePlus) FloatImagePlus(net.imglib2.img.imageplus.FloatImagePlus) ImageProcessor(ij.process.ImageProcessor) VirtualStack(ij.VirtualStack) AffineTransform(java.awt.geom.AffineTransform) Patch(ini.trakem2.display.Patch) File(java.io.File) DirectoryChooser(ij.io.DirectoryChooser)

Example 47 with Project

use of ini.trakem2.Project in project TrakEM2 by trakem2.

the class FSLoader method deleteStaleFiles.

/**
 * Delete stale files under the {@link FSLoader#unuid} folder.
 * These include "*.ct" files (for {@link CoordinateTransform})
 * and "*.zip" files (for alpha mask images) that are not referenced from any {@link Patch}.
 */
@Override
public boolean deleteStaleFiles(boolean coordinate_transforms, boolean alpha_masks) {
    boolean b = true;
    final Project project = Project.findProject(this);
    if (coordinate_transforms)
        b = b && StaleFiles.deleteCoordinateTransforms(project);
    if (alpha_masks)
        b = b && StaleFiles.deleteAlphaMasks(project);
    return b;
}
Also used : Project(ini.trakem2.Project)

Example 48 with Project

use of ini.trakem2.Project in project TrakEM2 by trakem2.

the class FSLoader method saveAs.

/**
 * Meant for programmatic access, such as calls to project.saveAs(path, overwrite) which call exactly this method.
 */
@Override
public String saveAs(final String path, final XMLOptions options) {
    if (null == path) {
        Utils.log("Cannot save on null path.");
        return null;
    }
    String path2 = path;
    String extension = ".xml";
    if (// all fine
    path2.endsWith(extension)) // all fine
    {
    } else if (path2.endsWith(".xml.gz"))
        extension = ".xml.gz";
    else {
        // neither matches, add the default ".xml"
        path2 += extension;
    }
    File fxml = new File(path2);
    if (!fxml.canWrite()) {
        // write to storage folder instead
        String path3 = path2;
        path2 = getStorageFolder() + fxml.getName();
        Utils.logAll("WARNING can't write to " + path3 + "\n  --> will write instead to " + path2);
        fxml = new File(path2);
    }
    if (!options.overwriteXMLFile) {
        int i = 1;
        while (fxml.exists()) {
            String parent = fxml.getParent().replace('\\', '/');
            if (!parent.endsWith("/"))
                parent += "/";
            String name = fxml.getName();
            name = name.substring(0, name.length() - 4);
            path2 = parent + name + "-" + i + extension;
            fxml = new File(path2);
            i++;
        }
    }
    Project project = Project.findProject(this);
    path2 = super.saveAs(project, path2, options);
    if (null != path2) {
        project_file_path = path2;
        Utils.logAll("After saveAs, new xml path is: " + path2);
        ControlWindow.updateTitle(project);
        touched_mipmaps.clear();
    }
    return path2;
}
Also used : Project(ini.trakem2.Project) File(java.io.File)

Example 49 with Project

use of ini.trakem2.Project in project TrakEM2 by trakem2.

the class FilePathRepair method fixPath.

private static void fixPath(final JTable table, final PathTableModel data, final int row, final boolean fix_similar, final boolean fix_all, final boolean update_mipmaps) throws Exception {
    synchronized (projects) {
        final Patch patch = data.vp.get(row);
        if (null == patch)
            return;
        final String old_path = patch.getImageFilePath();
        final File f = new File(old_path);
        if (f.exists()) {
            Utils.log("File exists for " + patch + " at " + f.getAbsolutePath() + "\n  --> not updating path.");
            data.remove(row);
            return;
        }
        // Else, pop up file dialog
        OpenDialog od = new OpenDialog("Select image file", OpenDialog.getDefaultDirectory(), null);
        String dir = od.getDirectory();
        final String filename = od.getFileName();
        // dialog was canceled
        if (null == dir)
            return;
        if (IJ.isWindows())
            dir = dir.replace('\\', '/');
        if (!dir.endsWith("/"))
            dir += "/";
        // Compare filenames
        if (!filename.equals(f.getName())) {
            YesNoDialog yn = new YesNoDialog(projects.get(patch.getProject()).frame, "WARNING", "Different file names!\n  old: " + f.getName() + "\n  new: " + filename + "\nSet to new file name?");
            if (!yn.yesPressed())
                return;
            // Remove mipmaps: would not be found with the new name and the old ones would remain behind unused
            if (!f.getName().equals(new File(old_path).getName())) {
                // remove mipmaps: the name wouldn't match otherwise
                patch.getProject().getLoader().removeMipMaps(patch);
            }
        }
        // 
        String wrong_parent_path = new File(data.vpath.get(row)).getParent();
        wrong_parent_path = wrong_parent_path.replace('\\', '/');
        // not File.separatorChar, TrakEM2 uses '/' as folder separator
        if (!wrong_parent_path.endsWith("/"))
            wrong_parent_path = new StringBuilder(wrong_parent_path).append('/').toString();
        final String path = new StringBuilder(dir).append(filename).toString();
        // keep track of fixed slices to avoid calling n_slices * n_slices times!
        final HashSet<Patch> fixed = new HashSet<Patch>();
        int n_fixed = 0;
        if (-1 == patch.getFilePath().lastIndexOf("-----#slice=")) {
            if (!fixPatchPath(patch, path, update_mipmaps)) {
                return;
            }
            data.remove(patch);
            fixed.add(patch);
            n_fixed += 1;
        } else {
            int n = fixStack(data, fixed, patch.getStackPatches(), old_path, path, update_mipmaps);
            if (0 == n) {
                // some error ocurred, no paths fixed
                return;
            }
            n_fixed += n;
        // data already cleared of removed patches by fixStack
        }
        String good_parent_path = dir;
        // not File.separatorChar, TrakEM2 uses '/' as folder separator
        if (!dir.endsWith("/"))
            good_parent_path = new StringBuilder(good_parent_path).append('/').toString();
        // Check for similar parent paths and see if they can be fixed
        if (fix_similar) {
            for (int i = data.vp.size() - 1; i > -1; i--) {
                final String wrong_path = data.vpath.get(i);
                final Patch p = data.vp.get(i);
                if (wrong_path.startsWith(wrong_parent_path)) {
                    // try to fix as well
                    final File file = new File(new StringBuilder(good_parent_path).append(wrong_path.substring(wrong_parent_path.length())).toString());
                    if (file.exists()) {
                        if (-1 == p.getFilePath().lastIndexOf("-----#slice=")) {
                            if (!fixed.contains(p) && fixPatchPath(p, file.getAbsolutePath(), update_mipmaps)) {
                                // not by 'i' but by Patch, since if some fail the order is not the same
                                data.remove(p);
                                n_fixed++;
                                fixed.add(p);
                            }
                        } else {
                            if (fixed.contains(p))
                                continue;
                            n_fixed += fixStack(data, fixed, p.getStackPatches(), wrong_path, file.getAbsolutePath(), update_mipmaps);
                        }
                    }
                }
            }
        }
        if (fix_all) {
            // traverse all Patch from the entire project, minus those already fixed
            for (final Displayable d : patch.getLayerSet().getDisplayables(Patch.class)) {
                final Patch p = (Patch) d;
                final String wrong_path = p.getImageFilePath();
                if (wrong_path.startsWith(wrong_parent_path)) {
                    File file = new File(new StringBuilder(good_parent_path).append(wrong_path.substring(wrong_parent_path.length())).toString());
                    if (file.exists()) {
                        if (-1 == p.getFilePath().lastIndexOf("-----#slice=")) {
                            if (!fixed.contains(p) && fixPatchPath(p, file.getAbsolutePath(), update_mipmaps)) {
                                // not by 'i' but by Patch, since if some fail the order is not the same
                                data.remove(p);
                                n_fixed++;
                                fixed.add(p);
                            }
                        } else {
                            if (fixed.contains(p))
                                continue;
                            n_fixed += fixStack(data, fixed, p.getStackPatches(), wrong_path, file.getAbsolutePath(), update_mipmaps);
                        }
                    }
                }
            }
        }
        // if table is empty, close
        if (0 == data.vp.size()) {
            FilePathRepair fpr = projects.remove(patch.getProject());
            fpr.frame.dispose();
        }
        Utils.logAll("Fixed " + n_fixed + " image file path" + (n_fixed > 1 ? "s" : ""));
    }
}
Also used : Displayable(ini.trakem2.display.Displayable) YesNoDialog(ini.trakem2.display.YesNoDialog) Patch(ini.trakem2.display.Patch) File(java.io.File) OpenDialog(ij.io.OpenDialog) HashSet(java.util.HashSet)

Example 50 with Project

use of ini.trakem2.Project in project TrakEM2 by trakem2.

the class Utils method addPlugIns.

/**
 * Returns null if none to add.
 */
public static final JMenu addPlugIns(final String menu, final Project project, final Callable<Displayable> active) {
    final Map<String, TPlugIn> plugins = project.getPlugins(menu);
    if (0 == plugins.size())
        return null;
    Displayable d = null;
    try {
        d = active.call();
    } catch (final Exception e) {
        IJError.print(e);
    }
    final JMenu m = new JMenu("Plugins");
    JMenuItem item;
    int count = 0;
    for (final Map.Entry<String, TPlugIn> e : plugins.entrySet()) {
        item = new JMenuItem(e.getKey());
        item.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent ae) {
                Bureaucrat.createAndStart(new Worker.Task(e.getKey()) {

                    @Override
                    public void exec() {
                        try {
                            e.getValue().invoke(active.call());
                        } catch (final Exception e) {
                            IJError.print(e);
                        }
                    }
                }, project);
            }
        });
        item.setEnabled(e.getValue().applies(d));
        if (count < 9) {
            item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1 + count, Utils.getControlModifier(), true));
        }
        m.add(item);
        count++;
    }
    if (0 == m.getItemCount())
        return null;
    m.addSeparator();
    // Now all the "Setup " + name
    for (final Map.Entry<String, TPlugIn> e : plugins.entrySet()) {
        item = new JMenuItem("Setup " + e.getKey());
        item.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent ae) {
                Bureaucrat.createAndStart(new Worker.Task(e.getKey()) {

                    @Override
                    public void exec() {
                        try {
                            e.getValue().setup(active.call());
                        } catch (final Exception e) {
                            IJError.print(e);
                        }
                    }
                }, project);
            }
        });
        m.add(item);
    }
    return m;
}
Also used : Displayable(ini.trakem2.display.Displayable) ActionEvent(java.awt.event.ActionEvent) IOException(java.io.IOException) TPlugIn(ini.trakem2.plugin.TPlugIn) ActionListener(java.awt.event.ActionListener) JMenuItem(javax.swing.JMenuItem) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) JMenu(javax.swing.JMenu)

Aggregations

ArrayList (java.util.ArrayList)33 Project (ini.trakem2.Project)26 HashMap (java.util.HashMap)25 Layer (ini.trakem2.display.Layer)21 Displayable (ini.trakem2.display.Displayable)19 Patch (ini.trakem2.display.Patch)18 File (java.io.File)18 HashSet (java.util.HashSet)18 ZDisplayable (ini.trakem2.display.ZDisplayable)17 ImagePlus (ij.ImagePlus)16 ProjectThing (ini.trakem2.tree.ProjectThing)16 Worker (ini.trakem2.utils.Worker)16 TemplateThing (ini.trakem2.tree.TemplateThing)15 Map (java.util.Map)15 LayerSet (ini.trakem2.display.LayerSet)14 ResultSet (java.sql.ResultSet)13 DBObject (ini.trakem2.persistence.DBObject)12 AffineTransform (java.awt.geom.AffineTransform)11 TreeMap (java.util.TreeMap)11 FSLoader (ini.trakem2.persistence.FSLoader)10