Search in sources :

Example 11 with LayerThing

use of ini.trakem2.tree.LayerThing 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 12 with LayerThing

use of ini.trakem2.tree.LayerThing in project TrakEM2 by trakem2.

the class ProjectTiler method createRetiledSibling.

/**
 * Take a {@link Project}, a size for the image tiles, and a target directory,
 * and create a new copy of the current project in that folder but with the underlying
 * images converted to tiles with a translation-only transform (saved as zipped TIFFs,
 * with extension ".tif.zip").
 * The new, returned {@link Project} represents the given project but with much
 * simpler transformations (just translation) for the images and a defined size for
 * the latter, which helps a lot regarding storage space of the XML (and parsing and
 * saving time) and performance when browsing layers (keep in mind that, for a 32k x 32k image,
 * at 100% zoom one would have to load a 32k x 32k image and render just a tiny bit
 * of it). The copied Project preserves the ID of the {@link Layer}s of the original
 * {@link Project}, as well as the dimensions; this means the copy is a sibling of
 * the original, and it is possible to send segmentations from one to the other "as is"
 * (directly, without having to transform along with the images which would not be possible).
 *
 * Image files are stored as
 *
 * The non-image objects of the given project are copied into the new project as well.
 *
 * @param srcProject The project to create a sibling of.
 * @param targetDirectory The directory in which to create all the necessary data and mipmap folders for the new Project.
 * @param tileWidth The width of the tiles to create for the data of the new project.
 * @param tileHeight The height of the tiles.
 * @param exportImageType Any of {@link ImagePlus#GRAY8}, {@link ImagePlus#GRAY16} or {@link ImagePlus#COLOR_RGB}, otherwise an {@link IllegalArgumentException} is thrown.
 * @param onlyVisibleImages Whether to consider visible images only.
 * @param nExportThreads Number of layers to export in parallel. Use a small number when original images are huge (such as larger than 4096 x 4096 pixels).
 * @param createMipMaps Whether to generate the mipmaps when done or not.
 *
 * @throws Exception IllegalArgumentException When {@code exportImageType} is not {@link ImagePlus#GRAY16} or {@link ImagePlus#COLOR_RGB}, or when the directory exists and cannot be written to.
 */
public static final Project createRetiledSibling(final Project srcProject, final String targetDirectory, final int tileWidth, final int tileHeight, final int exportImageType, final boolean onlyVisibleImages, final int nExportThreads, final boolean createMipMaps) throws Exception {
    // Validate exportImageType
    switch(exportImageType) {
        case ImagePlus.GRAY8:
        case ImagePlus.GRAY16:
        case ImagePlus.COLOR_RGB:
            break;
        default:
            throw new IllegalArgumentException("Can only accept GRAY8, GRAY16 or COLOR_RGB as values for 'exportImageType'!");
    }
    // Validate targetDirectory
    final File fdir = new File(targetDirectory);
    if (fdir.exists()) {
        if (!fdir.isDirectory() || !fdir.canWrite())
            throw new IllegalArgumentException("Invalid directory: not a directory or cannot write to: " + targetDirectory);
    } else {
        if (!fdir.mkdirs()) {
            throw new IllegalArgumentException("Cannot create directory at: " + targetDirectory);
        }
    }
    final String targetDir = Utils.fixDir(targetDirectory);
    // Create "data" directory
    final String dataDir = new StringBuilder(targetDir).append("data/").toString();
    final File fDataDir = new File(dataDir);
    if (fDataDir.exists() && (!fDataDir.isDirectory() || !fDataDir.canWrite())) {
        throw new IllegalArgumentException("Cannot create or write to 'data' directory in the targetDirectory at: " + targetDir);
    } else {
        fDataDir.mkdir();
    }
    // Create new Project, plain, without any automatic creation of a Layer or a Display
    final Project newProject = Project.newFSProject("blank", null, targetDir, false);
    final LayerSet newLayerSet = newProject.getRootLayerSet();
    newLayerSet.setCalibration(srcProject.getRootLayerSet().getCalibrationCopy());
    if (!createMipMaps) {
        Utils.log("MipMaps are DISABLED:\n --> When done, right-click and choose 'Display - Properties...' and enable mipmaps,\n     and then run 'Project - Regenerate all mipmaps'\n");
        newProject.getLoader().setMipMapsRegeneration(false);
        Utils.log("mipmaps enabled? " + newProject.getLoader().isMipMapsRegenerationEnabled());
    }
    // Copy the Template Tree of types
    newProject.resetRootTemplateThing(srcProject.getRootTemplateThing().clone(newProject, true), null);
    for (final TemplateThing tt : newProject.getRootTemplateThing().getUniqueTypes(new HashMap<String, TemplateThing>()).values()) {
        newProject.addUniqueType(tt);
    }
    // Clone layers with the exact same IDs, so that the two projects are siblings at the layer-level:
    // (Being siblings allows for treelines, arealists, etc. to be transferred from one to another "as is").
    final List<Layer> srcLayers = srcProject.getRootLayerSet().getLayers();
    final List<Layer> newLayers = new ArrayList<Layer>();
    for (final Layer srcLayer : srcLayers) {
        final Layer newLayer = new Layer(newProject, srcLayer.getId(), srcLayer.getZ(), srcLayer.getThickness());
        // to update the ID generator in FSLoader
        newLayer.addToDatabase();
        newLayerSet.add(newLayer);
        newLayers.add(newLayer);
        newProject.getRootLayerThing().addChild(new LayerThing(newProject.getRootLayerThing().getChildTemplate("layer"), newProject, newLayer));
    }
    newProject.getLayerTree().rebuild();
    // Update the LayerSet
    newLayerSet.setDimensions(srcProject.getRootLayerSet().getLayerWidth(), srcProject.getRootLayerSet().getLayerHeight(), LayerSet.NORTHWEST);
    Display.updateLayerScroller(newLayerSet);
    Display.update(newLayerSet);
    // Copy template from the src Project
    // (It's done after creating layers so the IDs will not collide with those of the Layers)
    newProject.resetRootTemplateThing(srcProject.getRootTemplateThing().clone(newProject, false), null);
    // Export tiles as new Patch instances, creating new image files in disk
    final int numThreads = Math.max(1, Math.min(nExportThreads, Runtime.getRuntime().availableProcessors()));
    int i = 0;
    for (final Layer srcLayer : srcLayers) {
        Utils.log("Processing layer " + (i + 1) + "/" + srcLayers.size() + " -- " + new Date());
        final int layerIndex = i++;
        // Create subDirectory
        final String dir = dataDir + "/" + layerIndex + "/";
        new File(dir).mkdir();
        // Create a new Layer with the same Z and thickness
        final Layer newLayer = newLayers.get(layerIndex);
        // Export layer tiles
        final ArrayList<Patch> patches = new ArrayList<Patch>();
        if (ImagePlus.GRAY16 == exportImageType) {
            Process.progressive(ExportUnsignedShort.exportTiles(srcLayer, tileWidth, tileHeight, onlyVisibleImages), new CountingTaskFactory<Callable<ExportedTile>, Patch>() {

                public Patch process(final Callable<ExportedTile> c, final int index) {
                    try {
                        // Create the tile
                        final ExportedTile t = c.call();
                        // Store the file
                        final String title = layerIndex + "-" + index;
                        final String path = dir + title + ".tif.zip";
                        final ImagePlus imp = new ImagePlus(title, t.sp);
                        if (!new FileSaver(imp).saveAsZip(path)) {
                            throw new Exception("Could not save tile: " + path);
                        }
                        // Create a Patch
                        final Patch patch = new Patch(newProject, title, t.x, t.y, imp);
                        patch.setLocked(true);
                        newProject.getLoader().addedPatchFrom(path, patch);
                        return patch;
                    } catch (Exception e) {
                        IJError.print(e);
                        return null;
                    }
                }
            }, patches, numThreads);
        } else {
            // GRAY8 or COLOR_RGB: created from mipmaps
            Process.progressive(tileSequence(srcLayer, tileWidth, tileHeight, onlyVisibleImages), new CountingTaskFactory<Rectangle, Patch>() {

                @Override
                public Patch process(final Rectangle bounds, final int index) {
                    try {
                        // Create the tile
                        final ImagePlus imp = srcLayer.getProject().getLoader().getFlatImage(srcLayer, bounds, 1.0, -1, exportImageType, Patch.class, null, false, Color.black);
                        final String title = layerIndex + "-" + index;
                        imp.setTitle(title);
                        final String path = dir + title + ".tif.zip";
                        if (!new FileSaver(imp).saveAsZip(path)) {
                            throw new Exception("Could not save tile: " + path);
                        }
                        // Create a Patch
                        final Patch patch = new Patch(newProject, title, bounds.x, bounds.y, imp);
                        patch.setLocked(true);
                        newProject.getLoader().addedPatchFrom(path, patch);
                        return patch;
                    } catch (Exception e) {
                        IJError.print(e);
                        return null;
                    }
                }
            }, patches, numThreads);
        }
        // Add all Patches to the new Layer
        for (final Patch p : patches) {
            newLayer.add(p);
        }
    }
    // Copy all segmentations "As is"
    final ProjectThing root = srcProject.getRootProjectThing();
    if (null != root.getChildren() && !root.getChildren().isEmpty()) {
        final ProjectThing source_pt = srcProject.getRootProjectThing().getChildren().get(0);
        // "As is"
        final int transfer_mode = 0;
        final ProjectThing landing_parent = newProject.getRootProjectThing();
        srcProject.getProjectTree().rawSendToSiblingProject(source_pt, transfer_mode, newProject, landing_parent);
    }
    // Copy all floating text labels
    i = 0;
    for (final Layer srcLayer : srcLayers) {
        for (final DLabel srcLabel : srcLayer.getAll(DLabel.class)) {
            newLayers.get(i++).add(srcLabel.clone(newProject, false));
        }
    }
    if (createMipMaps) {
        final LinkedList<Future<?>> fus = new LinkedList<Future<?>>();
        final int batch = Runtime.getRuntime().availableProcessors();
        for (final Layer newLayer : newLayers) {
            for (final Patch p : newLayer.getAll(Patch.class)) {
                fus.add(p.updateMipMaps());
                // Don't build-up too much
                if (fus.size() > batch * 3) {
                    while (fus.size() > batch) {
                        try {
                            fus.removeFirst().get();
                        } catch (Exception e) {
                            IJError.print(e);
                        }
                    }
                }
            }
        }
        Utils.wait(fus);
    }
    // Save:
    newProject.saveAs(targetDir + "exported.xml", false);
    return newProject;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Rectangle(java.awt.Rectangle) Callable(java.util.concurrent.Callable) FileSaver(ij.io.FileSaver) ProjectThing(ini.trakem2.tree.ProjectThing) LayerSet(ini.trakem2.display.LayerSet) LayerThing(ini.trakem2.tree.LayerThing) Layer(ini.trakem2.display.Layer) ImagePlus(ij.ImagePlus) Date(java.util.Date) LinkedList(java.util.LinkedList) Project(ini.trakem2.Project) DLabel(ini.trakem2.display.DLabel) TemplateThing(ini.trakem2.tree.TemplateThing) Future(java.util.concurrent.Future) File(java.io.File) Patch(ini.trakem2.display.Patch) ExportedTile(mpicbg.trakem2.transform.ExportedTile)

Example 13 with LayerThing

use of ini.trakem2.tree.LayerThing in project TrakEM2 by trakem2.

the class TMLHandler method makeLayerThing.

private LayerThing makeLayerThing(String type, final HashMap<String, String> ht_attributes) {
    try {
        type = type.toLowerCase();
        if (0 == type.indexOf("t2_")) {
            type = type.substring(3);
        }
        // long id = -1;
        // final String sid = ht_attributes.get("id");
        // if (null != sid) id = Long.parseLong(sid);
        long oid = -1;
        final String soid = ht_attributes.get("oid");
        if (null != soid)
            oid = Long.parseLong(soid);
        if (type.equals("node")) {
            if (null == last_tree) {
                throw new NullPointerException("Can't create a node for null last_tree!");
            }
            final Node<?> node = last_tree.newNode(ht_attributes);
            taggables.add(node);
            // Put node into the list of nodes with that layer id, to update to proper Layer pointer later
            final long ndlid = Long.parseLong(ht_attributes.get("lid"));
            List<Node<?>> list = node_layer_table.get(ndlid);
            if (null == list) {
                list = new ArrayList<Node<?>>();
                node_layer_table.put(ndlid, list);
            }
            list.add(node);
            // Set node as root node or add as child to last node in the stack
            if (null == last_root_node) {
                last_root_node = node;
            } else {
                final String sconf = ht_attributes.get("c");
                nodes.getLast().add((Node) node, null == sconf ? Node.MAX_EDGE_CONFIDENCE : Byte.parseByte(sconf));
            }
            // color?
            final String scolor = ht_attributes.get("color");
            if (null != scolor) {
                final Color color = Utils.getRGBColorFromHex(scolor);
                Collection<Node<?>> nodes = node_colors.get(color);
                if (null == nodes) {
                    nodes = new ArrayList<Node<?>>();
                    node_colors.put(color, nodes);
                }
                nodes.add(node);
            }
            // Put node into stack of nodes (to be removed on closing the tag)
            nodes.add(node);
        } else if (type.equals("profile")) {
            Profile profile = new Profile(this.project, oid, ht_attributes, ht_links);
            profile.addToDatabase();
            ht_displayables.put(oid, profile);
            addToLastOpenLayer(profile);
            last_displayable = profile;
            return null;
        } else if (type.equals("pipe")) {
            Pipe pipe = new Pipe(this.project, oid, ht_attributes, ht_links);
            pipe.addToDatabase();
            ht_displayables.put(new Long(oid), pipe);
            ht_zdispl.put(new Long(oid), pipe);
            last_displayable = pipe;
            addToLastOpenLayerSet(pipe);
            return null;
        } else if (type.equals("polyline")) {
            Polyline pline = new Polyline(this.project, oid, ht_attributes, ht_links);
            pline.addToDatabase();
            last_displayable = pline;
            ht_displayables.put(new Long(oid), pline);
            ht_zdispl.put(new Long(oid), pline);
            addToLastOpenLayerSet(pline);
            return null;
        } else if (type.equals("connector")) {
            final Connector con = new Connector(this.project, oid, ht_attributes, ht_links);
            if (ht_attributes.containsKey("origin")) {
                legacy.add(new Runnable() {

                    public void run() {
                        con.readLegacyXML(al_layer_sets.get(al_layer_sets.size() - 1), ht_attributes, ht_links);
                    }
                });
            }
            con.addToDatabase();
            last_connector = con;
            last_tree = con;
            last_displayable = con;
            ht_displayables.put(new Long(oid), con);
            ht_zdispl.put(new Long(oid), con);
            addToLastOpenLayerSet(con);
            return null;
        } else if (type.equals("path")) {
            if (null != reca) {
                reca.add(ht_attributes.get("d"));
                return null;
            }
            return null;
        } else if (type.equals("area")) {
            reca = new ReconstructArea();
            if (null != last_area_list) {
                last_area_list_layer_id = Long.parseLong(ht_attributes.get("layer_id"));
            }
            return null;
        } else if (type.equals("area_list")) {
            AreaList area = new AreaList(this.project, oid, ht_attributes, ht_links);
            // why? This looks like an onion
            area.addToDatabase();
            last_area_list = area;
            last_displayable = area;
            ht_displayables.put(new Long(oid), area);
            ht_zdispl.put(new Long(oid), area);
            addToLastOpenLayerSet(area);
            return null;
        } else if (type.equals("tag")) {
            Taggable t = taggables.getLast();
            if (null != t) {
                Object ob = ht_attributes.get("key");
                // defaults to 't'
                int keyCode = KeyEvent.VK_T;
                // KeyEvent.VK_U is char U, not u
                if (null != ob)
                    keyCode = (int) ((String) ob).toUpperCase().charAt(0);
                Tag tag = al_layer_sets.get(al_layer_sets.size() - 1).putTag(ht_attributes.get("name"), keyCode);
                // could be null if name is not found
                if (null != tag)
                    t.addTag(tag);
            }
        } else if (type.equals("ball_ob")) {
            // add a ball to the last open Ball
            if (null != last_ball) {
                last_ball.addBall(Double.parseDouble(ht_attributes.get("x")), Double.parseDouble(ht_attributes.get("y")), Double.parseDouble(ht_attributes.get("r")), Long.parseLong(ht_attributes.get("layer_id")));
            }
            return null;
        } else if (type.equals("ball")) {
            Ball ball = new Ball(this.project, oid, ht_attributes, ht_links);
            ball.addToDatabase();
            last_ball = ball;
            last_displayable = ball;
            ht_displayables.put(new Long(oid), ball);
            ht_zdispl.put(new Long(oid), ball);
            addToLastOpenLayerSet(ball);
            return null;
        } else if (type.equals("stack")) {
            Stack stack = new Stack(this.project, oid, ht_attributes, ht_links);
            stack.addToDatabase();
            last_stack = stack;
            last_displayable = stack;
            ht_displayables.put(new Long(oid), stack);
            ht_zdispl.put(new Long(oid), stack);
            addToLastOpenLayerSet(stack);
        } else if (type.equals("treeline")) {
            Treeline tline = new Treeline(this.project, oid, ht_attributes, ht_links);
            tline.addToDatabase();
            last_treeline = tline;
            last_tree = tline;
            last_treeline_data = new StringBuilder();
            last_displayable = tline;
            ht_displayables.put(oid, tline);
            ht_zdispl.put(oid, tline);
            addToLastOpenLayerSet(tline);
        } else if (type.equals("areatree")) {
            AreaTree art = new AreaTree(this.project, oid, ht_attributes, ht_links);
            art.addToDatabase();
            last_areatree = art;
            last_tree = art;
            last_displayable = art;
            ht_displayables.put(oid, art);
            ht_zdispl.put(oid, art);
            addToLastOpenLayerSet(art);
        } else if (type.equals("dd_item")) {
            if (null != last_dissector) {
                last_dissector.addItem(Integer.parseInt(ht_attributes.get("tag")), Integer.parseInt(ht_attributes.get("radius")), ht_attributes.get("points"));
            }
        } else if (type.equals("label")) {
            DLabel label = new DLabel(project, oid, ht_attributes, ht_links);
            label.addToDatabase();
            ht_displayables.put(new Long(oid), label);
            addToLastOpenLayer(label);
            last_displayable = label;
            return null;
        } else if (type.equals("annot")) {
            last_annotation = new StringBuilder();
            return null;
        } else if (type.equals("patch")) {
            Patch patch = new Patch(project, oid, ht_attributes, ht_links);
            patch.addToDatabase();
            ht_displayables.put(new Long(oid), patch);
            addToLastOpenLayer(patch);
            last_patch = patch;
            last_displayable = patch;
            checkAlphaMasks(patch);
            return null;
        } else if (type.equals("filter")) {
            last_patch_filters.add(newFilter(ht_attributes));
        } else if (type.equals("dissector")) {
            Dissector dissector = new Dissector(this.project, oid, ht_attributes, ht_links);
            dissector.addToDatabase();
            last_dissector = dissector;
            last_displayable = dissector;
            ht_displayables.put(new Long(oid), dissector);
            ht_zdispl.put(new Long(oid), dissector);
            addToLastOpenLayerSet(dissector);
        } else if (type.equals("layer")) {
            // find last open LayerSet, if any
            for (int i = al_layer_sets.size() - 1; i > -1; ) {
                LayerSet set = al_layer_sets.get(i);
                Layer layer = new Layer(project, oid, ht_attributes);
                layer.addToDatabase();
                set.addSilently(layer);
                al_layers.add(layer);
                Object ot = ht_attributes.get("title");
                return new LayerThing(template_layer_thing, project, -1, (null == ot ? null : (String) ot), layer, null);
            }
        } else if (type.equals("layer_set")) {
            LayerSet set = new LayerSet(project, oid, ht_attributes, ht_links);
            last_displayable = set;
            set.addToDatabase();
            ht_displayables.put(new Long(oid), set);
            al_layer_sets.add(set);
            addToLastOpenLayer(set);
            Object ot = ht_attributes.get("title");
            return new LayerThing(template_layer_set_thing, project, -1, (null == ot ? null : (String) ot), set, null);
        } else if (type.equals("calibration")) {
            // find last open LayerSet if any
            for (int i = al_layer_sets.size() - 1; i > -1; ) {
                LayerSet set = al_layer_sets.get(i);
                set.restoreCalibration(ht_attributes);
                return null;
            }
        } else if (type.equals("prop")) {
            // Add property to last created Displayable
            if (null != last_displayable) {
                last_displayable.setProperty(ht_attributes.get("key"), ht_attributes.get("value"));
            }
        } else if (type.equals("linked_prop")) {
            // Add linked property to last created Displayable. Has to wait until the Displayable ids have been resolved to instances.
            if (null != last_displayable) {
                putLinkedProperty(last_displayable, ht_attributes);
            }
        } else {
            Utils.log2("TMLHandler Unknown type: " + type);
        }
    } catch (Exception e) {
        IJError.print(e);
    }
    // default:
    return null;
}
Also used : Ball(ini.trakem2.display.Ball) Connector(ini.trakem2.display.Connector) Node(ini.trakem2.display.Node) Profile(ini.trakem2.display.Profile) AreaTree(ini.trakem2.display.AreaTree) ReconstructArea(ini.trakem2.utils.ReconstructArea) Dissector(ini.trakem2.display.Dissector) LayerSet(ini.trakem2.display.LayerSet) LayerThing(ini.trakem2.tree.LayerThing) Color(java.awt.Color) Pipe(ini.trakem2.display.Pipe) AreaList(ini.trakem2.display.AreaList) Layer(ini.trakem2.display.Layer) SAXException(org.xml.sax.SAXException) SAXParseException(org.xml.sax.SAXParseException) Stack(ini.trakem2.display.Stack) Treeline(ini.trakem2.display.Treeline) DLabel(ini.trakem2.display.DLabel) Polyline(ini.trakem2.display.Polyline) Tag(ini.trakem2.display.Tag) Taggable(ini.trakem2.display.Taggable) Patch(ini.trakem2.display.Patch)

Example 14 with LayerThing

use of ini.trakem2.tree.LayerThing 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 15 with LayerThing

use of ini.trakem2.tree.LayerThing in project TrakEM2 by trakem2.

the class LayerThing method addChild.

public boolean addChild(Thing child) {
    if (!template.canHaveAsChild(child)) {
        return false;
    }
    if (null == al_children)
        al_children = new ArrayList<LayerThing>();
    synchronized (al_children) {
        if (null != child.getObject() && child.getObject() instanceof Layer) {
            // this is a patch, but hey, do you want to redesign the events, which are based on layer titles and toString() contents? TODO ...
            Layer l = (Layer) child.getObject();
            int i = l.getParent().indexOf(l);
            // Utils.log2("al_children.size(): " + al_children.size() + ",  i=" + i);
            if (i >= al_children.size()) {
                // TODO happens when importing a stack
                al_children.add((LayerThing) child);
            } else {
                try {
                    al_children.add(i, (LayerThing) child);
                } catch (Exception e) {
                    Utils.log2("LayerThing.addChild: " + e);
                    // at the end
                    al_children.add((LayerThing) child);
                }
            }
        } else {
            al_children.add((LayerThing) child);
        }
    }
    child.setParent(this);
    return true;
}
Also used : ArrayList(java.util.ArrayList) Layer(ini.trakem2.display.Layer)

Aggregations

LayerThing (ini.trakem2.tree.LayerThing)13 Layer (ini.trakem2.display.Layer)8 HashMap (java.util.HashMap)8 LayerSet (ini.trakem2.display.LayerSet)7 TemplateThing (ini.trakem2.tree.TemplateThing)7 ProjectThing (ini.trakem2.tree.ProjectThing)5 DBObject (ini.trakem2.persistence.DBObject)4 LayerTree (ini.trakem2.tree.LayerTree)4 ProjectTree (ini.trakem2.tree.ProjectTree)4 TemplateTree (ini.trakem2.tree.TemplateTree)4 ArrayList (java.util.ArrayList)4 TreePath (javax.swing.tree.TreePath)4 Displayable (ini.trakem2.display.Displayable)3 Patch (ini.trakem2.display.Patch)3 DefaultMutableTreeNode (javax.swing.tree.DefaultMutableTreeNode)3 GenericDialog (ij.gui.GenericDialog)2 Project (ini.trakem2.Project)2 AreaTree (ini.trakem2.display.AreaTree)2 DLabel (ini.trakem2.display.DLabel)2 Display (ini.trakem2.display.Display)2