Search in sources :

Example 6 with DBObject

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

the class LayerTree method mousePressed.

public void mousePressed(MouseEvent me) {
    Object source = me.getSource();
    if (!source.equals(this) || !project.isInputEnabled()) {
        return;
    }
    // ignore if doing multiple selection
    if (!Utils.isPopupTrigger(me) && (me.isShiftDown() || (!ij.IJ.isMacOSX() && me.isControlDown()))) {
        return;
    }
    int x = me.getX();
    int y = me.getY();
    // check if there is a multiple selection
    TreePath[] paths = this.getSelectionPaths();
    if (null != paths && paths.length > 1) {
        if (Utils.isPopupTrigger(me)) {
            // check that all items are of the same type
            String type_first = ((LayerThing) ((DefaultMutableTreeNode) paths[0].getLastPathComponent()).getUserObject()).getType();
            for (int i = 1; i < paths.length; i++) {
                String type = ((LayerThing) ((DefaultMutableTreeNode) paths[i].getLastPathComponent()).getUserObject()).getType();
                if (!type.equals(type_first)) {
                    Utils.showMessage("All selected items must be of the same type for operations on multiple items.");
                    return;
                }
            }
            // prepare popup menu
            JPopupMenu popup = new JPopupMenu();
            JMenuItem item = null;
            if (type_first.equals("layer")) {
                item = new JMenuItem("Reverse layer Z coords");
                item.addActionListener(this);
                popup.add(item);
                item = new JMenuItem("Translate layers in Z...");
                item.addActionListener(this);
                popup.add(item);
                item = new JMenuItem("Scale Z and thickness...");
                item.addActionListener(this);
                popup.add(item);
                item = new JMenuItem("Delete...");
                item.addActionListener(this);
                popup.add(item);
            }
            if (popup.getSubElements().length > 0) {
                popup.show(this, x, y);
            }
        }
        // disable commands depending upon a single node being selected
        selected_node = null;
        return;
    }
    // find the node and set it selected
    TreePath path = getPathForLocation(x, y);
    if (null == path) {
        return;
    }
    setSelectionPath(path);
    selected_node = (DefaultMutableTreeNode) path.getLastPathComponent();
    if (2 == me.getClickCount() && !Utils.isPopupTrigger(me) && MouseEvent.BUTTON1 == me.getButton()) {
        // create a new Display
        LayerThing thing = (LayerThing) selected_node.getUserObject();
        DBObject ob = (DBObject) thing.getObject();
        if (thing.getType().toLowerCase().replace('_', ' ').equals("layer set") && null == ((LayerSet) ob).getParent()) {
            // the top level LayerSet
            return;
        }
        // new Display(ob.getProject(), thing.getType().toLowerCase().equals("layer") ? (Layer)ob : ((LayerSet)ob).getParent());
        Display.createDisplay(ob.getProject(), thing.getType().toLowerCase().equals("layer") ? (Layer) ob : ((LayerSet) ob).getParent());
        return;
    } else if (Utils.isPopupTrigger(me)) {
        JPopupMenu popup = getPopupMenu(selected_node);
        if (null == popup)
            return;
        popup.show(this, x, y);
        return;
    }
}
Also used : TreePath(javax.swing.tree.TreePath) LayerSet(ini.trakem2.display.LayerSet) DBObject(ini.trakem2.persistence.DBObject) JMenuItem(javax.swing.JMenuItem) DBObject(ini.trakem2.persistence.DBObject) Layer(ini.trakem2.display.Layer) JPopupMenu(javax.swing.JPopupMenu)

Example 7 with DBObject

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

the class LayerTree method actionPerformed.

public void actionPerformed(ActionEvent ae) {
    try {
        String command = ae.getActionCommand();
        // commands for multiple selections:
        TreePath[] paths = this.getSelectionPaths();
        if (null != paths && paths.length > 1) {
            if (command.equals("Reverse layer Z coords")) {
                // check that all layers belong to the same layer set
                // just do it
                Layer[] layer = new Layer[paths.length];
                LayerSet ls = null;
                for (int i = 0; i < paths.length; i++) {
                    layer[i] = (Layer) ((LayerThing) ((DefaultMutableTreeNode) paths[i].getLastPathComponent()).getUserObject()).getObject();
                    if (null == ls)
                        ls = layer[i].getParent();
                    else if (!ls.equals(layer[i].getParent())) {
                        Utils.showMessage("To reverse, all layers must belong to the same layer set");
                        return;
                    }
                }
                final ArrayList<Layer> al = new ArrayList<Layer>();
                for (int i = 0; i < layer.length; i++) al.add(layer[i]);
                ls.addLayerEditedStep(al);
                // ASSSUMING layers are already Z ordered! CHECK
                for (int i = 0, j = layer.length - 1; i < layer.length / 2; i++, j--) {
                    double z = layer[i].getZ();
                    layer[i].setZ(layer[j].getZ());
                    layer[j].setZ(z);
                }
                updateList(ls);
                ls.addLayerEditedStep(al);
                Display.updateLayerScroller(ls);
            } else if (command.equals("Translate layers in Z...")) {
                GenericDialog gd = ControlWindow.makeGenericDialog("Range");
                gd.addMessage("Translate selected range in the Z axis:");
                gd.addNumericField("by: ", 0, 4);
                gd.showDialog();
                if (gd.wasCanceled())
                    return;
                // else, displace
                double dz = gd.getNextNumber();
                if (Double.isNaN(dz)) {
                    Utils.showMessage("Invalid number");
                    return;
                }
                HashSet<LayerSet> hs_parents = new HashSet<LayerSet>();
                for (int i = 0; i < paths.length; i++) {
                    Layer layer = (Layer) ((LayerThing) ((DefaultMutableTreeNode) paths[i].getLastPathComponent()).getUserObject()).getObject();
                    layer.setZ(layer.getZ() + dz);
                    hs_parents.add(layer.getParent());
                }
                for (LayerSet ls : hs_parents) {
                    updateList(ls);
                }
                // now update all profile's Z ordering in the ProjectTree
                ProjectThing root_pt = project.getRootProjectThing();
                for (final ProjectThing pt : root_pt.findChildrenOfType("profile_list")) {
                    pt.fixZOrdering();
                    project.getProjectTree().updateList(pt);
                }
                project.getProjectTree().updateUILater();
            // Display.updateLayerScroller((LayerSet)((DefaultMutableTreeNode)getModel().getRoot()).getUserObject());
            } else if (command.equals("Delete...")) {
                if (!Utils.check("Really remove all selected layers?"))
                    return;
                for (int i = 0; i < paths.length; i++) {
                    DefaultMutableTreeNode lnode = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
                    LayerThing lt = (LayerThing) lnode.getUserObject();
                    Layer layer = (Layer) lt.getObject();
                    if (!layer.remove(false)) {
                        Utils.showMessage("Could not delete layer " + layer);
                        this.updateUILater();
                        return;
                    }
                    if (lt.remove(false)) {
                        ((DefaultTreeModel) this.getModel()).removeNodeFromParent(lnode);
                    }
                }
                this.updateUILater();
            } else if (command.equals("Scale Z and thickness...")) {
                GenericDialog gd = new GenericDialog("Scale Z");
                gd.addNumericField("scale: ", 1.0, 2);
                gd.showDialog();
                double scale = gd.getNextNumber();
                if (Double.isNaN(scale) || 0 == scale) {
                    Utils.showMessage("Imvalid scaling factor: " + scale);
                    return;
                }
                for (int i = 0; i < paths.length; i++) {
                    DefaultMutableTreeNode lnode = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
                    LayerThing lt = (LayerThing) lnode.getUserObject();
                    Layer layer = (Layer) lt.getObject();
                    layer.setZ(layer.getZ() * scale);
                    layer.setThickness(layer.getThickness() * scale);
                }
                this.updateUILater();
            } else {
                Utils.showMessage("Don't know what to do with command " + command + " for multiple selected nodes");
            }
            return;
        }
        // commands for single selection:
        if (null == selected_node)
            return;
        LayerThing thing = (LayerThing) selected_node.getUserObject();
        LayerThing new_thing = null;
        TemplateThing tt = null;
        Object ob = null;
        int i_position = -1;
        if (command.startsWith("new ")) {
            String name = command.substring(4).toLowerCase();
            if (name.equals("layer")) {
                // Create new Layer and add it to the selected node
                LayerSet set = (LayerSet) thing.getObject();
                Layer new_layer = Layer.create(thing.getProject(), set);
                if (null == new_layer)
                    return;
                tt = thing.getChildTemplate("layer");
                ob = new_layer;
                Display.updateTitle(set);
            } else if (name.equals("layer set")) {
                // with space in the middle
                // Create a new LayerSet and add it in the middle
                Layer layer = (Layer) thing.getObject();
                LayerSet new_set = layer.getParent().create(layer);
                if (null == new_set)
                    return;
                layer.add(new_set);
                // add it at the end of the list
                // with space, not underscore
                tt = thing.getChildTemplate("layer set");
                ob = new_set;
                i_position = selected_node.getChildCount();
                Display.update(layer);
            } else {
                Utils.log("LayerTree.actionPerformed: don't know what to do with the command: " + command);
                return;
            }
        } else if (command.equals("many new layers...")) {
            LayerSet set = (LayerSet) thing.getObject();
            List<Layer> layers = Layer.createMany(set.getProject(), set);
            // add them to the tree as LayerThing
            if (null == layers)
                return;
            for (Layer la : layers) {
                // null layers will be skipped
                addLayer(set, la);
            }
            Display.updateTitle(set);
            return;
        } else if (command.equals("Show")) {
            // create a new Display
            DBObject dbo = (DBObject) thing.getObject();
            // the top level LayerSet
            if (thing.getType().equals("layer_set") && null == ((LayerSet) dbo).getParent())
                return;
            Display.createDisplay(dbo.getProject(), thing.getType().equals("layer") ? (Layer) dbo : ((LayerSet) dbo).getParent());
            return;
        } else if (command.equals("Show centered in Display")) {
            LayerSet ls = (LayerSet) thing.getObject();
            Display.showCentered(ls.getParent(), ls, false, false);
        } else if (command.equals("Delete...")) {
            remove(true, thing, selected_node);
            return;
        } else if (command.equals("Import stack...")) {
            if (thing.getObject() instanceof LayerSet) {
                LayerSet set = (LayerSet) thing.getObject();
                Layer layer = null;
                if (0 == set.getLayers().size()) {
                    layer = Layer.create(set.getProject(), set);
                    if (null == layer)
                        return;
                    tt = thing.getChildTemplate("Layer");
                    ob = layer;
                } else
                    // click on a desired, existing layer.
                    return;
                layer.getProject().getLoader().importStack(layer, null, true);
            } else if (thing.getObject() instanceof Layer) {
                Layer layer = (Layer) thing.getObject();
                layer.getProject().getLoader().importStack(layer, null, true);
                return;
            }
        } else if (command.equals("Import grid...")) {
            if (thing.getObject() instanceof Layer) {
                Layer layer = (Layer) thing.getObject();
                layer.getProject().getLoader().importGrid(layer);
            }
        } else if (command.equals("Import sequence as grid...")) {
            if (thing.getObject() instanceof Layer) {
                Layer layer = (Layer) thing.getObject();
                layer.getProject().getLoader().importSequenceAsGrid(layer);
            }
        } else if (command.equals("Import from text file...")) {
            if (thing.getObject() instanceof Layer) {
                Layer layer = (Layer) thing.getObject();
                layer.getProject().getLoader().importImages(layer);
            }
        } else if (command.equals("Resize LayerSet...")) {
            if (thing.getObject() instanceof LayerSet) {
                LayerSet ls = (LayerSet) thing.getObject();
                ij.gui.GenericDialog gd = ControlWindow.makeGenericDialog("Resize LayerSet");
                gd.addNumericField("new width: ", ls.getLayerWidth(), 3);
                gd.addNumericField("new height: ", ls.getLayerHeight(), 3);
                gd.addChoice("Anchor: ", LayerSet.ANCHORS, LayerSet.ANCHORS[0]);
                gd.showDialog();
                if (gd.wasCanceled())
                    return;
                float new_width = (float) gd.getNextNumber(), new_height = (float) gd.getNextNumber();
                // will complain and prevent cropping existing Displayable objects
                ls.setDimensions(new_width, new_height, gd.getNextChoiceIndex());
            }
        } else if (command.equals("Autoresize LayerSet")) {
            if (thing.getObject() instanceof LayerSet) {
                LayerSet ls = (LayerSet) thing.getObject();
                ls.setMinimumDimensions();
            }
        } else if (command.equals("Adjust...")) {
            if (thing.getObject() instanceof Layer) {
                Layer layer = (Layer) thing.getObject();
                ij.gui.GenericDialog gd = ControlWindow.makeGenericDialog("Adjust Layer");
                gd.addNumericField("new z: ", layer.getZ(), 4);
                gd.addNumericField("new thickness: ", layer.getThickness(), 4);
                gd.showDialog();
                if (gd.wasCanceled())
                    return;
                double new_z = gd.getNextNumber();
                layer.setThickness(gd.getNextNumber());
                if (new_z != layer.getZ()) {
                    layer.setZ(new_z);
                    // move in the tree
                    /*
						DefaultMutableTreeNode child = findNode(thing, this);
						DefaultMutableTreeNode parent = (DefaultMutableTreeNode)child.getParent();
						parent.remove(child);
						// reinsert
						int n = parent.getChildCount();
						int i = 0;
						for (; i < n; i++) {
							DefaultMutableTreeNode child_node = (DefaultMutableTreeNode)parent.getChildAt(i);
							LayerThing child_thing = (LayerThing)child_node.getUserObject();
							if (!child_thing.getType().equals("Layer")) continue;
							double iz = ((Layer)child_thing.getObject()).getZ();
							if (iz < new_z) continue;
							// else, add the layer here, after this one
							break;
						}
						((DefaultTreeModel)this.getModel()).insertNodeInto(child, parent, i);
						*/
                    // fix tree crappiness (empty slot ?!?)
                    /* // the fix doesn't work. ARGH TODO
						Enumeration e = parent.children();
						parent.removeAllChildren();
						i = 0;
						while (e.hasMoreElements()) {
							//parent.add((DefaultMutableTreeNode)e.nextElement());
							((DefaultTreeModel)this.getModel()).insertNodeInto(child, parent, i);
							i++;
						}*/
                    // easier and correct: overkill
                    updateList(layer.getParent());
                    // set selected
                    DefaultMutableTreeNode child = findNode(thing, this);
                    TreePath treePath = new TreePath(child.getPath());
                    this.scrollPathToVisible(treePath);
                    this.setSelectionPath(treePath);
                }
            }
            return;
        } else if (command.equals("Rename...")) {
            GenericDialog gd = ControlWindow.makeGenericDialog("Rename");
            gd.addStringField("new name: ", thing.getTitle());
            gd.showDialog();
            if (gd.wasCanceled())
                return;
            project.getRootLayerSet().addUndoStep(new RenameThingStep(thing));
            thing.setTitle(gd.getNextString());
            project.getRootLayerSet().addUndoStep(new RenameThingStep(thing));
        } else if (command.equals("Translate layers in Z...")) {
            // / TODO: this method should use multiple selections directly on the tree
            if (thing.getObject() instanceof LayerSet) {
                LayerSet ls = (LayerSet) thing.getObject();
                ArrayList<Layer> al_layers = ls.getLayers();
                String[] layer_names = new String[al_layers.size()];
                for (int i = 0; i < layer_names.length; i++) {
                    layer_names[i] = ls.getProject().findLayerThing(al_layers.get(i)).toString();
                }
                GenericDialog gd = ControlWindow.makeGenericDialog("Range");
                gd.addMessage("Translate selected range in the Z axis:");
                gd.addChoice("from: ", layer_names, layer_names[0]);
                gd.addChoice("to: ", layer_names, layer_names[layer_names.length - 1]);
                gd.addNumericField("by: ", 0, 4);
                gd.showDialog();
                if (gd.wasCanceled())
                    return;
                // else, displace
                double dz = gd.getNextNumber();
                if (Double.isNaN(dz)) {
                    Utils.showMessage("Invalid number");
                    return;
                }
                int i_start = gd.getNextChoiceIndex();
                int i_end = gd.getNextChoiceIndex();
                for (int i = i_start; i <= i_end; i++) {
                    Layer layer = (Layer) al_layers.get(i);
                    layer.setZ(layer.getZ() + dz);
                }
                // update node labels and position
                updateList(ls);
            }
        } else if (command.equals("Reverse layer Z coords...")) {
            // / TODO: this method should use multiple selections directly on the tree
            if (thing.getObject() instanceof LayerSet) {
                LayerSet ls = (LayerSet) thing.getObject();
                ArrayList<Layer> al_layers = ls.getLayers();
                String[] layer_names = new String[al_layers.size()];
                for (int i = 0; i < layer_names.length; i++) {
                    layer_names[i] = ls.getProject().findLayerThing(al_layers.get(i)).toString();
                }
                GenericDialog gd = ControlWindow.makeGenericDialog("Range");
                gd.addMessage("Reverse Z coordinates of selected range:");
                gd.addChoice("from: ", layer_names, layer_names[0]);
                gd.addChoice("to: ", layer_names, layer_names[layer_names.length - 1]);
                gd.showDialog();
                if (gd.wasCanceled())
                    return;
                int i_start = gd.getNextChoiceIndex();
                int i_end = gd.getNextChoiceIndex();
                for (int i = i_start, j = i_end; i < i_end / 2; i++, j--) {
                    Layer layer1 = (Layer) al_layers.get(i);
                    double z1 = layer1.getZ();
                    Layer layer2 = (Layer) al_layers.get(j);
                    layer1.setZ(layer2.getZ());
                    layer2.setZ(z1);
                }
                // update node labels and position
                updateList(ls);
            }
        } else if (command.equals("Search...")) {
            Search.showWindow();
        } else if (command.equals("Reset layer Z and thickness")) {
            LayerSet ls = ((LayerSet) thing.getObject());
            List<Layer> layers = ls.getLayers();
            ls.addLayerEditedStep(layers);
            int i = 0;
            for (final Layer la : ls.getLayers()) {
                la.setZ(i++);
                la.setThickness(1);
            }
            ls.addLayerEditedStep(layers);
        } else {
            Utils.log("LayerTree.actionPerformed: don't know what to do with the command: " + command);
            return;
        }
        if (null == tt)
            return;
        new_thing = new LayerThing(tt, thing.getProject(), ob);
        if (-1 == i_position && new_thing.getType().equals("layer")) {
            // find the node whose 'z' is larger than z, and add the Layer before that.
            // (just because there could be objects other than LayerThing with a Layer in it in the future, so set.getLayers().indexOf(layer) may not be useful)
            double z = ((Layer) ob).getZ();
            int n = selected_node.getChildCount();
            int i = 0;
            for (; i < n; i++) {
                DefaultMutableTreeNode child_node = (DefaultMutableTreeNode) selected_node.getChildAt(i);
                LayerThing child_thing = (LayerThing) child_node.getUserObject();
                if (!child_thing.getType().equals("layer")) {
                    continue;
                }
                double iz = ((Layer) child_thing.getObject()).getZ();
                if (iz < z) {
                    continue;
                }
                // else, add the layer here, after this one
                break;
            }
            i_position = i;
        }
        thing.addChild(new_thing);
        DefaultMutableTreeNode new_node = new DefaultMutableTreeNode(new_thing);
        ((DefaultTreeModel) this.getModel()).insertNodeInto(new_node, selected_node, i_position);
        TreePath treePath = new TreePath(new_node.getPath());
        this.scrollPathToVisible(treePath);
        this.setSelectionPath(treePath);
        if (new_thing.getType().equals("layer set")) {
            // add the first layer to it, and open it in a Display
            LayerSet newls = (LayerSet) new_thing.getObject();
            Layer la = new Layer(newls.getProject(), 0, 1, newls);
            addLayer(newls, la);
            new Display(newls.getProject(), la);
        }
    } catch (Exception e) {
        IJError.print(e);
    }
}
Also used : DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) ArrayList(java.util.ArrayList) DBObject(ini.trakem2.persistence.DBObject) GenericDialog(ij.gui.GenericDialog) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) LayerSet(ini.trakem2.display.LayerSet) DefaultTreeModel(javax.swing.tree.DefaultTreeModel) Layer(ini.trakem2.display.Layer) TreePath(javax.swing.tree.TreePath) DBObject(ini.trakem2.persistence.DBObject) Display(ini.trakem2.display.Display)

Example 8 with DBObject

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

the class ProjectThing method subclone.

/**
 * Implicit id copying; assumes the ids of the object are also the same in the given project; the object, if it is a DBObject, is retrieved from the given project by matching its id.
 */
public ProjectThing subclone(final Project pr) {
    Object ob = null;
    if (null != this.object) {
        if (this.object instanceof DBObject)
            ob = pr.getRootLayerSet().findById(((DBObject) this.object).getId());
        else
            // String is a final class: no copy protection needed.
            ob = this.object;
    }
    final ProjectThing copy = new ProjectThing(pr.getTemplateThing(this.template.getType()), pr, this.id, ob, new ArrayList<ProjectThing>());
    if (null != this.al_children) {
        copy.al_children = new ArrayList<ProjectThing>();
        synchronized (al_children) {
            for (ProjectThing child : this.al_children) {
                ProjectThing cc = child.subclone(pr);
                // don't add: the object was not cloned and thus not found.
                if (child.object instanceof DBObject && null == cc.object)
                    continue;
                cc.setParent(this);
                copy.al_children.add(cc);
            }
        }
    }
    return copy;
}
Also used : DBObject(ini.trakem2.persistence.DBObject) DBObject(ini.trakem2.persistence.DBObject)

Example 9 with DBObject

use of ini.trakem2.persistence.DBObject 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 10 with DBObject

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

the class Search method executeSearch.

private void executeSearch() {
    final Project project = Project.getProjects().get(projects.getSelectedIndex());
    if (null == project) {
        // Should not happen
        return;
    }
    Bureaucrat.createAndStart(new Worker.Task("Searching") {

        public void exec() {
            String pattern = search_field.getText();
            if (null == pattern || 0 == pattern.length()) {
                return;
            }
            // fix pattern
            final String typed_pattern = pattern;
            // I hate java
            final StringBuilder sb = new StringBuilder();
            if (!pattern.startsWith("^"))
                sb.append("^.*");
            for (int i = 0; i < pattern.length(); i++) {
                sb.append(pattern.charAt(i));
            }
            if (!pattern.endsWith("$"))
                sb.append(".*$");
            pattern = sb.toString();
            final Pattern pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
            // Utils.log2("pattern after: " + pattern);
            final ArrayList<DBObject> al = new ArrayList<DBObject>();
            // Utils.log("types[pulldown] = " +
            // types[pulldown.getSelectedIndex()]);
            find(project.getRootLayerSet(), al, types[pulldown.getSelectedIndex()]);
            // Utils.log2("found labels: " + al.size());
            if (0 == al.size())
                return;
            final Vector<DBObject> v_obs = new Vector<DBObject>();
            final Vector<String> v_txt = new Vector<String>();
            final Vector<Coordinate<?>> v_co = new Vector<Coordinate<?>>();
            Coordinate<?> co = null;
            for (final DBObject dbo : al) {
                if (Thread.currentThread().isInterrupted()) {
                    return;
                }
                boolean matched = false;
                // Search in its title
                Displayable d = null;
                if (dbo instanceof Displayable) {
                    d = (Displayable) dbo;
                }
                String txt;
                String meaningful_title = null;
                if (null == d || Patch.class == d.getClass())
                    txt = dbo.getTitle();
                else {
                    txt = meaningful_title = dbo.getProject().getMeaningfulTitle(d);
                }
                if (null == txt || 0 == txt.trim().length())
                    continue;
                matched = pat.matcher(txt).matches();
                if (!matched && null != d) {
                    // Search also in its annotation
                    txt = d.getAnnotation();
                    if (null != txt)
                        matched = pat.matcher(txt).matches();
                }
                if (!matched) {
                    // Search also in its toString()
                    txt = dbo.toString();
                    matched = pat.matcher(txt).matches();
                }
                if (!matched) {
                    // Search also in its id
                    txt = Long.toString(dbo.getId());
                    matched = pat.matcher(txt).matches();
                    if (matched)
                        txt = "id: #" + txt;
                }
                if (!matched && null != d) {
                    // Search also in its properties
                    Map<String, String> props = d.getProperties();
                    if (null != props) {
                        for (final Map.Entry<String, String> e : props.entrySet()) {
                            if (pat.matcher(e.getKey()).matches() || pat.matcher(e.getValue()).matches()) {
                                matched = true;
                                txt = e.getKey() + " => " + e.getValue() + " [property]";
                                break;
                            }
                        }
                    }
                    if (!matched) {
                        Map<Displayable, Map<String, String>> linked_props = ((Displayable) dbo).getLinkedProperties();
                        if (null != linked_props) {
                            for (final Map.Entry<Displayable, Map<String, String>> e : linked_props.entrySet()) {
                                for (final Map.Entry<String, String> ee : e.getValue().entrySet()) {
                                    if (pat.matcher(ee.getKey()).matches() || pat.matcher(ee.getValue()).matches()) {
                                        matched = true;
                                        txt = ee.getKey() + " => " + e.getValue() + " [linked property]";
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                if (!matched && dbo instanceof Tree<?>) {
                    // search Node tags
                    Node<?> root = ((Tree<?>) dbo).getRoot();
                    if (null == root)
                        continue;
                    for (final Node<?> nd : root.getSubtreeNodes()) {
                        Set<Tag> tags = nd.getTags();
                        if (null == tags)
                            continue;
                        for (final Tag tag : tags) {
                            if (pat.matcher(tag.toString()).matches()) {
                                v_obs.add(dbo);
                                v_txt.add(new StringBuilder(tag.toString()).append(" (").append(null == meaningful_title ? dbo.toString() : meaningful_title).append(')').toString());
                                v_co.add(createCoordinate((Tree<?>) dbo, nd));
                            }
                        }
                    }
                    // all added if any
                    continue;
                }
                if (!matched)
                    continue;
                // txt = txt.length() > 30 ? txt.substring(0, 27) + "..." :
                // txt;
                v_obs.add(dbo);
                v_txt.add(txt);
                v_co.add(co);
            }
            if (0 == v_obs.size()) {
                Utils.showMessage("Nothing found.");
                return;
            }
            final JPanel result = new JPanel();
            GridBagLayout gb = new GridBagLayout();
            result.setLayout(gb);
            GridBagConstraints c = new GridBagConstraints();
            c.anchor = GridBagConstraints.NORTHWEST;
            c.fill = GridBagConstraints.HORIZONTAL;
            c.insets = new Insets(5, 10, 5, 10);
            String xml = "";
            if (project.getLoader() instanceof FSLoader) {
                String path = ((FSLoader) project.getLoader()).getProjectXMLPath();
                if (null != path) {
                    xml = " [" + new File(path).getName() + "]";
                }
            }
            JLabel projectTitle = new JLabel(project.getTitle() + xml);
            gb.setConstraints(projectTitle, c);
            result.add(projectTitle);
            c.insets = new Insets(0, 0, 0, 0);
            JPanel padding = new JPanel();
            c.weightx = 1;
            gb.setConstraints(padding, c);
            result.add(padding);
            c.gridy = 1;
            c.gridwidth = 2;
            c.fill = GridBagConstraints.BOTH;
            c.weighty = 1;
            JScrollPane jsp = makeTable(new DisplayableTableModel(v_obs, v_txt, v_co), project);
            gb.setConstraints(jsp, c);
            result.add(jsp);
            search_tabs.addTab(typed_pattern, result);
            search_tabs.setSelectedComponent(result);
            synchronized (tabMap) {
                List<JPanel> cs = tabMap.get(project);
                if (null == cs) {
                    cs = new ArrayList<JPanel>();
                    tabMap.put(project, cs);
                }
                cs.add(result);
            }
        }
    }, project);
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Set(java.util.Set) HashSet(java.util.HashSet) LayerSet(ini.trakem2.display.LayerSet) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) Node(ini.trakem2.display.Node) ArrayList(java.util.ArrayList) DBObject(ini.trakem2.persistence.DBObject) AreaTree(ini.trakem2.display.AreaTree) Tree(ini.trakem2.display.Tree) AreaList(ini.trakem2.display.AreaList) List(java.util.List) ArrayList(java.util.ArrayList) Vector(java.util.Vector) JScrollPane(javax.swing.JScrollPane) Pattern(java.util.regex.Pattern) Displayable(ini.trakem2.display.Displayable) ZDisplayable(ini.trakem2.display.ZDisplayable) JLabel(javax.swing.JLabel) Project(ini.trakem2.Project) FSLoader(ini.trakem2.persistence.FSLoader) Coordinate(ini.trakem2.display.Coordinate) Tag(ini.trakem2.display.Tag) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File)

Aggregations

DBObject (ini.trakem2.persistence.DBObject)9 Layer (ini.trakem2.display.Layer)6 LayerSet (ini.trakem2.display.LayerSet)4 Patch (ini.trakem2.display.Patch)4 Displayable (ini.trakem2.display.Displayable)3 ZDisplayable (ini.trakem2.display.ZDisplayable)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 GenericDialog (ij.gui.GenericDialog)2 AffineTransform (java.awt.geom.AffineTransform)2 HashSet (java.util.HashSet)2 Iterator (java.util.Iterator)2 List (java.util.List)2 Map (java.util.Map)2 Set (java.util.Set)2 TreePath (javax.swing.tree.TreePath)2 Project (ini.trakem2.Project)1 AreaList (ini.trakem2.display.AreaList)1 AreaTree (ini.trakem2.display.AreaTree)1 Coordinate (ini.trakem2.display.Coordinate)1