Search in sources :

Example 21 with Loader

use of ini.trakem2.persistence.Loader in project TrakEM2 by trakem2.

the class Project method openFSProject.

/**
 * Opens a project from an .xml file. If the path is null it'll be asked for.
 *  Only one project may be opened at a time.
 */
@SuppressWarnings("unchecked")
public static synchronized Project openFSProject(final String path, final boolean open_displays) {
    if (Utils.wrongImageJVersion())
        return null;
    final FSLoader loader = new FSLoader();
    final Object[] data = loader.openFSProject(path, open_displays);
    if (null == data) {
        loader.destroy();
        return null;
    }
    final TemplateThing root_tt = (TemplateThing) data[0];
    final ProjectThing root_pt = (ProjectThing) data[1];
    final LayerThing root_lt = (LayerThing) data[2];
    final HashMap<ProjectThing, Boolean> ht_pt_expanded = (HashMap<ProjectThing, Boolean>) data[3];
    final Project project = (Project) root_pt.getObject();
    project.createLayerTemplates();
    project.template_tree = new TemplateTree(project, root_tt);
    project.root_tt = root_tt;
    project.root_pt = root_pt;
    project.project_tree = new ProjectTree(project, project.root_pt);
    project.layer_tree = new LayerTree(project, root_lt);
    project.root_lt = root_lt;
    project.layer_set = (LayerSet) root_lt.getObject();
    // if all when well, register as open:
    al_open_projects.add(project);
    // create the project control window, containing the trees in a double JSplitPane
    ControlWindow.add(project, project.template_tree, project.project_tree, project.layer_tree);
    // set ProjectThing nodes expanded state, now that the trees exist
    try {
        java.lang.reflect.Field f = JTree.class.getDeclaredField("expandedState");
        f.setAccessible(true);
        Hashtable<Object, Object> ht_exp = (Hashtable<Object, Object>) f.get(project.project_tree);
        for (Map.Entry<ProjectThing, Boolean> entry : ht_pt_expanded.entrySet()) {
            ProjectThing pt = entry.getKey();
            Boolean expanded = entry.getValue();
            // project.project_tree.expandPath(new TreePath(project.project_tree.findNode(pt, project.project_tree).getPath()));
            // WARNING the above is wrong in that it will expand the whole thing, not just set the state of the node!!
            // So the ONLY way to do it is to start from the child-most leafs of the tree, and apply the expanding to them upward. This is RIDICULOUS, how can it be so broken
            // so, hackerous:
            DefaultMutableTreeNode nd = DNDTree.findNode(pt, project.project_tree);
            // else Utils.log2("path: " + new TreePath(nd.getPath()));
            if (null == nd) {
                Utils.log2("Can't find node for " + pt);
            } else {
                ht_exp.put(new TreePath(nd.getPath()), expanded);
            }
        }
        // very important!!
        project.project_tree.updateUILater();
    } catch (Exception e) {
        IJError.print(e);
    }
    // open any stored displays
    if (open_displays) {
        final Bureaucrat burro = Display.openLater();
        if (null != burro) {
            final Runnable ru = new Runnable() {

                public void run() {
                    // wait until the Bureaucrat finishes
                    try {
                        burro.join();
                    } catch (InterruptedException ie) {
                    }
                    // restore to non-changes (crude, but works)
                    project.loader.setChanged(false);
                    Utils.log2("C set to false");
                }
            };
            new Thread() {

                public void run() {
                    setPriority(Thread.NORM_PRIORITY);
                    // avoiding "can't call invokeAndWait from the EventDispatch thread" error
                    try {
                        javax.swing.SwingUtilities.invokeAndWait(ru);
                    } catch (Exception e) {
                        Utils.log2("ERROR: " + e);
                    }
                }
            }.start();
            // SO: WAIT TILL THE END OF TIME!
            new Thread() {

                public void run() {
                    try {
                        // ah, the pain in my veins. I can't take this shitty setup anymore.
                        Thread.sleep(4000);
                        javax.swing.SwingUtilities.invokeAndWait(new Runnable() {

                            public void run() {
                                project.getLoader().setChanged(false);
                                Utils.log2("D set to false");
                            }
                        });
                        // repainting to fix gross errors in tree rendering
                        project.getTemplateTree().updateUILater();
                        // idem
                        project.getProjectTree().updateUILater();
                    } catch (Exception ie) {
                    }
                }
            }.start();
        } else {
            // help the helpless users
            Display.createDisplay(project, project.layer_set.getLayer(0));
        }
    }
    project.restartAutosaving();
    return project;
}
Also used : DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) HashMap(java.util.HashMap) TemplateTree(ini.trakem2.tree.TemplateTree) Bureaucrat(ini.trakem2.utils.Bureaucrat) ProjectTree(ini.trakem2.tree.ProjectTree) LayerTree(ini.trakem2.tree.LayerTree) ProjectThing(ini.trakem2.tree.ProjectThing) LayerThing(ini.trakem2.tree.LayerThing) Hashtable(java.util.Hashtable) FSLoader(ini.trakem2.persistence.FSLoader) TreePath(javax.swing.tree.TreePath) TemplateThing(ini.trakem2.tree.TemplateThing) DBObject(ini.trakem2.persistence.DBObject) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap)

Example 22 with Loader

use of ini.trakem2.persistence.Loader in project TrakEM2 by trakem2.

the class TMLHandler method startElement.

public void startElement(String namespace_URI, String local_name, String qualified_name, Attributes attributes) throws SAXException {
    if (null == loader)
        return;
    // Utils.log2("startElement: " + qualified_name);
    this.counter++;
    if (0 == counter % 100) {
        // davi-experimenting: don't talk so much when you have > 600,000 patches to load!
        Utils.showStatus("Loading " + counter, false);
    }
    try {
        // failsafe:
        qualified_name = qualified_name.toLowerCase();
        final HashMap<String, String> ht_attributes = new HashMap<String, String>();
        for (int i = attributes.getLength() - 1; i > -1; i--) {
            ht_attributes.put(attributes.getQName(i).toLowerCase(), attributes.getValue(i));
        }
        // get the id, which whenever possible it's the id of the encapsulating Thing object. The encapsulated object id is the oid
        // The type is specified by the qualified_name
        Thing thing = null;
        if (0 == qualified_name.indexOf("t2_")) {
            if (qualified_name.equals("t2_display")) {
                // store for later, until the layers exist
                if (open_displays)
                    al_displays.add(ht_attributes);
            } else {
                // a Layer, LayerSet or Displayable object
                thing = makeLayerThing(qualified_name, ht_attributes);
                if (null != thing) {
                    if (null == root_lt && thing.getObject() instanceof LayerSet) {
                        root_lt = (LayerThing) thing;
                    }
                }
            }
        } else if (qualified_name.equals("project")) {
            if (null != this.root_pt) {
                Utils.log("WARNING: more than one project definitions.");
                return;
            }
            // Create the project
            this.project = new Project(Long.parseLong(ht_attributes.remove("id")), ht_attributes.remove("title"));
            // temp, but will be the same anyway
            this.project.setTempLoader(this.loader);
            this.project.parseXMLOptions(ht_attributes);
            // register id
            this.project.addToDatabase();
            String title = ht_attributes.get("title");
            if (null != title)
                this.project.setTitle(title);
            // Add all unique TemplateThing types to the project
            for (Iterator<TemplateThing> it = root_tt.getUniqueTypes(new HashMap<String, TemplateThing>()).values().iterator(); it.hasNext(); ) {
                this.project.addUniqueType(it.next());
            }
            this.project.addUniqueType(this.project_tt);
            this.root_pt = new ProjectThing(this.project_tt, this.project, this.project);
            // Add a project pointer to all template things
            this.root_tt.addToDatabase(this.project);
            thing = root_pt;
        } else if (qualified_name.startsWith("ict_transform") || qualified_name.startsWith("iict_transform")) {
            makeCoordinateTransform(qualified_name, ht_attributes);
        } else if (!qualified_name.equals("trakem2")) {
            // Any abstract object
            thing = makeProjectThing(qualified_name, ht_attributes);
        }
        if (null != thing) {
            // get the previously open thing and add this new_thing to it as a child
            int size = al_open.size();
            if (size > 0) {
                Thing parent = al_open.get(size - 1);
                parent.addChild(thing);
            // Utils.log2("Adding child " + thing + " to parent " + parent);
            }
            // add the new thing as open
            al_open.add(thing);
        }
    } catch (Exception e) {
        IJError.print(e);
        skip = true;
    }
}
Also used : Project(ini.trakem2.Project) HashMap(java.util.HashMap) LayerSet(ini.trakem2.display.LayerSet) Iterator(java.util.Iterator) LayerThing(ini.trakem2.tree.LayerThing) TemplateThing(ini.trakem2.tree.TemplateThing) ProjectThing(ini.trakem2.tree.ProjectThing) Thing(ini.trakem2.tree.Thing) ProjectThing(ini.trakem2.tree.ProjectThing) SAXException(org.xml.sax.SAXException) SAXParseException(org.xml.sax.SAXParseException)

Example 23 with Loader

use of ini.trakem2.persistence.Loader in project TrakEM2 by trakem2.

the class DBLoader method fetchLayer.

/**
 * Load all objects into the Layer: Profile and Pipe from the hs_pt (full of ProjectThing wrapping them), and Patch, LayerSet, DLabel, etc from the database.
 */
private Layer fetchLayer(Project project, long id, HashMap hs_pt) throws Exception {
    ResultSet r = connection.prepareStatement("SELECT * FROM ab_layers WHERE id=" + id).executeQuery();
    Layer layer = null;
    if (r.next()) {
        long layer_id = r.getLong("id");
        layer = new Layer(project, layer_id, r.getDouble("z"), r.getDouble("thickness"));
        // find the Layer's parent
        long parent_id = r.getLong("layer_set_id");
        Object set = hs_pt.get(new Long(parent_id));
        if (null != set) {
            ((LayerSet) set).addSilently(layer);
        } else {
            Utils.log("Loader.fetchLayer: WARNING no parent for layer " + layer);
        }
        // add the displayables from hs_pt that correspond to this layer (and all other objects that belong to the layer)
        HashMap hs_d = new HashMap();
        ResultSet rd = connection.prepareStatement("SELECT ab_displayables.id, ab_profiles.id, layer_id, stack_index FROM ab_displayables,ab_profiles WHERE ab_displayables.id=ab_profiles.id AND layer_id=" + layer_id).executeQuery();
        while (rd.next()) {
            Long idd = new Long(rd.getLong("id"));
            Object ob = hs_pt.get(idd);
            // Utils.log("Found profile with id=" + idd + " and ob = " + ob);
            if (null != ob) {
                hs_d.put(new Integer(rd.getInt("stack_index")), ob);
            }
        }
        rd.close();
        // fetch LayerSet objects (which are also Displayable), and put them in the hs_pt (this is hackerous)
        ResultSet rls = connection.prepareStatement("SELECT * FROM ab_layer_sets, ab_displayables WHERE ab_layer_sets.id=ab_displayables.id AND ab_layer_sets.parent_layer_id=" + id).executeQuery();
        while (rls.next()) {
            long ls_id = rls.getLong("id");
            LayerSet layer_set = new LayerSet(project, ls_id, rls.getString("title"), (float) rls.getDouble("width"), (float) rls.getDouble("height"), rls.getDouble("rot_x"), rls.getDouble("rot_y"), rls.getDouble("rot_z"), (float) rls.getDouble("layer_width"), (float) rls.getDouble("layer_height"), rls.getBoolean("locked"), rls.getInt("snapshots_mode"), new AffineTransform(rls.getDouble("m00"), rls.getDouble("m10"), rls.getDouble("m01"), rls.getDouble("m11"), rls.getDouble("m02"), rls.getDouble("m12")));
            hs_pt.put(new Long(ls_id), layer_set);
            hs_d.put(new Integer(rls.getInt("stack_index")), layer_set);
            layer_set.setLayer(layer, false);
            // find the pipes (or other possible ZDisplayable objects) in the hs_pt that belong to this LayerSet and add them silently
            ResultSet rpi = connection.prepareStatement("SELECT ab_displayables.id, ab_zdisplayables.id, layer_id, layer_set_id, stack_index FROM ab_displayables,ab_zdisplayables WHERE ab_displayables.id=ab_zdisplayables.id AND layer_set_id=" + ls_id + " ORDER BY stack_index ASC").executeQuery();
            while (rpi.next()) {
                Long idd = new Long(rpi.getLong("id"));
                Object ob = hs_pt.get(idd);
                if (null != ob && ob instanceof ZDisplayable) {
                    layer_set.addSilently((ZDisplayable) ob);
                } else {
                    Utils.log("fetchLayer: failed to add a ZDisplayable to the layer_set. zdispl id = " + idd);
                }
            }
            rpi.close();
        }
        rls.close();
        // add Patch objects from ab_patches joint-called with ab_displayables
        ResultSet rp = connection.prepareStatement("SELECT ab_patches.id, ab_displayables.id, layer_id, title, width, height, stack_index, imp_type, locked, min, max, m00, m10, m01, m11, m02, m12 FROM ab_patches,ab_displayables WHERE ab_patches.id=ab_displayables.id AND ab_displayables.layer_id=" + layer_id).executeQuery();
        while (rp.next()) {
            long patch_id = rp.getLong("id");
            Patch patch = new Patch(project, patch_id, rp.getString("title"), (float) rp.getDouble("width"), (float) rp.getDouble("height"), rp.getInt("o_width"), rp.getInt("o_height"), rp.getInt("imp_type"), rp.getBoolean("locked"), rp.getDouble("min"), rp.getDouble("max"), new AffineTransform(rp.getDouble("m00"), rp.getDouble("m10"), rp.getDouble("m01"), rp.getDouble("m11"), rp.getDouble("m02"), rp.getDouble("m12")));
            // collecting all Displayable objects to reconstruct links
            hs_pt.put(new Long(patch_id), patch);
            hs_d.put(new Integer(rp.getInt("stack_index")), patch);
        }
        rp.close();
        // add DLabel objects
        ResultSet rl = connection.prepareStatement("SELECT ab_labels.id, ab_displayables.id, layer_id, title, width, height, m00, m10, m01, m11, m02, m12, stack_index, font_name, font_style, font_size, ab_labels.type, locked FROM ab_labels,ab_displayables WHERE ab_labels.id=ab_displayables.id AND ab_displayables.layer_id=" + layer_id).executeQuery();
        while (rl.next()) {
            long label_id = rl.getLong("id");
            DLabel label = new DLabel(project, label_id, rl.getString("title"), (float) rl.getDouble("width"), (float) rl.getDouble("height"), rl.getInt("type"), rl.getString("font_name"), rl.getInt("font_style"), rl.getInt("font_size"), rl.getBoolean("locked"), new AffineTransform(rl.getDouble("m00"), rl.getDouble("m10"), rl.getDouble("m01"), rl.getDouble("m11"), rl.getDouble("m02"), rl.getDouble("m12")));
            // collecting all Displayable objects to reconstruct links
            hs_pt.put(new Long(label_id), label);
            hs_d.put(new Integer(rl.getInt("stack_index")), label);
        }
        rl.close();
        // Add silently to the Layer ordered by stack index
        Set e = hs_d.keySet();
        Object[] si = new Object[hs_d.size()];
        si = e.toArray(si);
        // will it sort an array of integers correctly? Who knows!
        Arrays.sort(si);
        for (int i = 0; i < si.length; i++) {
            // Utils.log("Loader layer.addSilently: adding " + (DBObject)hs_d.get(si[i]));
            layer.addSilently((DBObject) hs_d.get(si[i]));
        }
        // find displays and open later, when fully loaded.
        ResultSet rdi = connection.prepareStatement("SELECT * FROM ab_displays WHERE layer_id=" + layer.getId()).executeQuery();
        while (rdi.next()) {
            fetchDisplay(rdi, layer);
        }
        rdi.close();
    }
    r.close();
    return layer;
}
Also used : ResultSet(java.sql.ResultSet) Set(java.util.Set) LayerSet(ini.trakem2.display.LayerSet) LayerSet(ini.trakem2.display.LayerSet) HashMap(java.util.HashMap) Layer(ini.trakem2.display.Layer) Point(java.awt.Point) PGpoint(org.postgresql.geometric.PGpoint) ZDisplayable(ini.trakem2.display.ZDisplayable) DLabel(ini.trakem2.display.DLabel) ResultSet(java.sql.ResultSet) AffineTransform(java.awt.geom.AffineTransform) Patch(ini.trakem2.display.Patch)

Example 24 with Loader

use of ini.trakem2.persistence.Loader in project TrakEM2 by trakem2.

the class FilePathRepair method fixStack.

private static int fixStack(final PathTableModel data, final Set<Patch> fixed, final Collection<Patch> slices, final String wrong_path, final String new_path, final boolean update_mipmaps) {
    int n_fixed = 0;
    Dimension dim = null;
    Loader loader = null;
    for (final Patch ps : slices) {
        if (fixed.contains(ps))
            continue;
        final String slicepath = ps.getFilePath();
        final int isl = slicepath.lastIndexOf("-----#slice=");
        if (-1 == isl) {
            Utils.log2("Not a stack path: " + slicepath);
            // someone linked an image...
            continue;
        }
        // same: // ps.getImageFilePath();
        final String ps_path = slicepath.substring(0, isl);
        if (!ps_path.substring(0, isl).equals(wrong_path)) {
            Utils.log2("Not the same stack path:\n  i=" + ps_path + "\n  ref=" + wrong_path);
            // not the same stack!
            continue;
        }
        if (null == dim) {
            loader = ps.getProject().getLoader();
            loader.releaseToFit(Math.max(Loader.MIN_FREE_BYTES, ps.getOWidth() * ps.getOHeight() * 10));
            dim = loader.getDimensions(new_path);
            if (null == dim) {
                // preserving backslashes
                Utils.log(new StringBuilder("ERROR: could not open image at ").append(new_path).toString());
                return n_fixed;
            }
            // Check dimensions
            if (dim.width != ps.getOWidth() || dim.height != ps.getOHeight()) {
                Utils.log("ERROR different o_width,o_height for patch " + ps + "\n  at new path " + new_path + "\nold o_width,o_height: " + ps.getOWidth() + "," + ps.getOHeight() + "\nnew o_width,o_height: " + dim.width + "," + dim.height);
                return n_fixed;
            }
        }
        // flag as good
        fixed.add(ps);
        loader.removeFromUnloadable(ps);
        // Assign new image path with slice info appended
        loader.addedPatchFrom(new_path + slicepath.substring(isl), ps);
        // submit job to regenerate mipmaps in the background
        if (update_mipmaps)
            loader.regenerateMipMaps(ps);
        // 
        data.remove(ps);
        n_fixed++;
    }
    return n_fixed;
}
Also used : Dimension(java.awt.Dimension) Patch(ini.trakem2.display.Patch)

Example 25 with Loader

use of ini.trakem2.persistence.Loader in project TrakEM2 by trakem2.

the class PatchStack method resetNonActive.

/**
 * Reset temporary changes such as from dragging B&amp;C sliders and so on, in the current slice (the current Patch).
 */
public void resetNonActive() {
    Utils.log2("PatchStack: calling reset");
    // remake the awt for the patch, flush the previous awt
    Loader loader = patch[currentSlice - 1].getProject().getLoader();
    for (int i = 0; i < patch.length; i++) {
        if (currentSlice - 1 == i || !called[i])
            continue;
        called[i] = false;
        ImagePlus imp = loader.fetchImagePlus(patch[i]);
        ImageProcessor ip = imp.getProcessor();
        switch(// as in ij.plugin.frame.ContrastAdjuster.reset(ImagePlus, ImageProcessor)
        imp.getType()) {
            case ImagePlus.COLOR_RGB:
                ip.reset();
                break;
            case ImagePlus.GRAY16:
            case ImagePlus.GRAY32:
                ip.resetMinAndMax();
                break;
        }
        patch[i].setMinAndMax(ip.getMin(), ip.getMax());
        patch[i].getProject().getLoader().decacheAWT(patch[i].getId());
        Display.repaint(patch[i].getLayer(), patch[i], null, 0, true);
    }
}
Also used : ImageProcessor(ij.process.ImageProcessor) Loader(ini.trakem2.persistence.Loader) ImagePlus(ij.ImagePlus)

Aggregations

Loader (ini.trakem2.persistence.Loader)20 ImagePlus (ij.ImagePlus)13 Patch (ini.trakem2.display.Patch)11 FSLoader (ini.trakem2.persistence.FSLoader)11 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 LayerThing (ini.trakem2.tree.LayerThing)6 Rectangle (java.awt.Rectangle)6 ImageProcessor (ij.process.ImageProcessor)5 Layer (ini.trakem2.display.Layer)5 TemplateThing (ini.trakem2.tree.TemplateThing)5 ZDisplayable (ini.trakem2.display.ZDisplayable)4 ProjectThing (ini.trakem2.tree.ProjectThing)4 IllDefinedDataPointsException (mpicbg.models.IllDefinedDataPointsException)4 NotEnoughDataPointsException (mpicbg.models.NotEnoughDataPointsException)4 ImageStack (ij.ImageStack)3 GenericDialog (ij.gui.GenericDialog)3 Displayable (ini.trakem2.display.Displayable)3 LayerSet (ini.trakem2.display.LayerSet)3 LayerTree (ini.trakem2.tree.LayerTree)3