Search in sources :

Example 26 with Bureaucrat

use of ini.trakem2.utils.Bureaucrat in project TrakEM2 by trakem2.

the class Display method importNextImage.

protected Bureaucrat importNextImage() {
    final Worker worker = new // / all this verbosity is what happens when functions are not first class citizens. I could abstract it away by passing a string name "importImage" and invoking it with reflection, but that is an even bigger PAIN
    Worker(// / all this verbosity is what happens when functions are not first class citizens. I could abstract it away by passing a string name "importImage" and invoking it with reflection, but that is an even bigger PAIN
    "Import image") {

        @Override
        public void run() {
            startedWorking();
            try {
                final Rectangle srcRect = canvas.getSrcRect();
                // - imp.getWidth() / 2;
                final int x = srcRect.x + srcRect.width / 2;
                // - imp.getHeight()/ 2;
                final int y = srcRect.y + srcRect.height / 2;
                final Patch p = project.getLoader().importNextImage(project, x, y);
                if (null == p) {
                    Utils.showMessage("Could not open next image.");
                    finishedWorking();
                    return;
                }
                Display.this.getLayerSet().addLayerContentStep(layer);
                // will add it to the proper Displays
                layer.add(p);
                Display.this.getLayerSet().addLayerContentStep(layer);
            } catch (final Exception e) {
                IJError.print(e);
            }
            finishedWorking();
        }
    };
    return Bureaucrat.createAndStart(worker, getProject());
}
Also used : Rectangle(java.awt.Rectangle) Worker(ini.trakem2.utils.Worker) Point(java.awt.Point) NoninvertibleTransformException(java.awt.geom.NoninvertibleTransformException)

Example 27 with Bureaucrat

use of ini.trakem2.utils.Bureaucrat 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 28 with Bureaucrat

use of ini.trakem2.utils.Bureaucrat in project TrakEM2 by trakem2.

the class Loader method getJobsPopup.

public JPopupMenu getJobsPopup(final Display display) {
    synchronized (jobs) {
        this.popup_jobs = new JPopupMenu("Cancel jobs:");
        int i = 1;
        for (final Bureaucrat burro : jobs) {
            final JMenuItem item = new JMenuItem("Job " + i + ": " + burro.getTaskName());
            item.addActionListener(display);
            popup_jobs.add(item);
            i++;
        }
    }
    return popup_jobs;
}
Also used : Bureaucrat(ini.trakem2.utils.Bureaucrat) JMenuItem(javax.swing.JMenuItem) JPopupMenu(javax.swing.JPopupMenu)

Example 29 with Bureaucrat

use of ini.trakem2.utils.Bureaucrat in project TrakEM2 by trakem2.

the class Loader method importGrid.

/**
 * Import a grid of images and put them in the layer. If the directory (@param dir) is null, it'll be asked for.
 */
public Bureaucrat importGrid(final Layer layer, String dir) {
    try {
        String file = null;
        if (null == dir) {
            final String[] dn = Utils.selectFile("Select first image");
            if (null == dn)
                return null;
            dir = dn[0];
            file = dn[1];
        }
        // char digit digit
        String convention = "cdd";
        boolean chars_are_columns = true;
        // examine file name
        /*
		if (file.matches("\\A[a-zA-Z]\\d\\d.*")) { // one letter, 2 numbers
			//means:
			//	\A		- beggining of input
			//	[a-zA-Z]	- any letter upper or lower case
			//	\d\d		- two consecutive digits
			//	.*		- any row of chars
			ini_grid_convention = true;
		}
		*/
        // ask for chars->rows, numbers->columns or viceversa
        final GenericDialog gd = new GenericDialog("Conventions");
        gd.addStringField("file_name_contains:", "");
        gd.addNumericField("base_x: ", 0, 3);
        gd.addNumericField("base_y: ", 0, 3);
        gd.addMessage("Use: x(any), c(haracter), d(igit)");
        gd.addStringField("convention: ", convention);
        final String[] cr = new String[] { "columns", "rows" };
        gd.addChoice("characters are: ", cr, cr[0]);
        gd.addMessage("[File extension ignored]");
        // as asked by Joachim Walter
        gd.addNumericField("bottom-top overlap: ", 0, 3);
        gd.addNumericField("left-right overlap: ", 0, 3);
        gd.addCheckbox("link_images", false);
        gd.addCheckbox("montage with phase correlation", false);
        gd.addCheckbox("homogenize_contrast", true);
        final Component[] c = { (Component) gd.getSliders().get(gd.getSliders().size() - 2), (Component) gd.getNumericFields().get(gd.getNumericFields().size() - 2), (Component) gd.getSliders().get(gd.getSliders().size() - 1), (Component) gd.getNumericFields().get(gd.getNumericFields().size() - 1), (Component) gd.getChoices().get(gd.getChoices().size() - 1) };
        // enable the checkbox to control the slider and its associated numeric field:
        Utils.addEnablerListener((Checkbox) gd.getCheckboxes().get(gd.getCheckboxes().size() - 1), c, null);
        // gd.addCheckbox("Apply non-linear deformation", false);
        gd.showDialog();
        if (gd.wasCanceled()) {
            return null;
        }
        // collect data
        // filter away files not containing this tag
        final String regex = gd.getNextString();
        // the base x,y of the whole grid
        final double bx = gd.getNextNumber();
        final double by = gd.getNextNumber();
        // if (!ini_grid_convention) {
        convention = gd.getNextString().toLowerCase();
        // }
        if (/*!ini_grid_convention && */
        (null == convention || convention.equals("") || -1 == convention.indexOf('c') || -1 == convention.indexOf('d'))) {
            // TODO check that the convention has only 'cdx' chars and also that there is an island of 'c's and of 'd's only.
            Utils.showMessage("Convention '" + convention + "' needs both c(haracters) and d(igits), optionally 'x', and nothing else!");
            return null;
        }
        chars_are_columns = (0 == gd.getNextChoiceIndex());
        final double bt_overlap = gd.getNextNumber();
        final double lr_overlap = gd.getNextNumber();
        final boolean link_images = gd.getNextBoolean();
        final boolean stitch_tiles = gd.getNextBoolean();
        final boolean homogenize_contrast = gd.getNextBoolean();
        // start magic
        // get ImageJ-openable files that comply with the convention
        final File images_dir = new File(dir);
        if (!(images_dir.exists() && images_dir.isDirectory())) {
            Utils.showMessage("Something went wrong:\n\tCan't find directory " + dir);
            return null;
        }
        final String[] file_names = images_dir.list(new ImageFileFilter(regex, convention));
        if (null == file && file_names.length > 0) {
            // the 'selected' file
            file = file_names[0];
        }
        Utils.showStatus("Adding " + file_names.length + " patches.", false);
        if (0 == file_names.length) {
            Utils.log("Zero files match the convention '" + convention + "'");
            return null;
        }
        // How to: select all files, and order their names in a double array as they should be placed in the Display. Then place them, displacing by offset, and resizing if necessary.
        // gather image files:
        final Montage montage = new Montage(convention, chars_are_columns);
        montage.addAll(file_names);
        // an array of Object[] arrays, of unequal length maybe, each containing a column of image file names
        final ArrayList<String[]> cols = montage.getCols();
        // !@#$%^&*
        final String dir_ = dir;
        final double bt_overlap_ = bt_overlap;
        final double lr_overlap_ = lr_overlap;
        final String file_ = file;
        return Bureaucrat.createAndStart(new Worker.Task("Insert grid", true) {

            @Override
            public void exec() {
                StitchingTEM.PhaseCorrelationParam pc_param = null;
                if (stitch_tiles) {
                    pc_param = new StitchingTEM.PhaseCorrelationParam();
                    pc_param.setup(layer);
                }
                insertGrid(layer, dir_, file_, file_names.length, cols, bx, by, bt_overlap_, lr_overlap_, link_images, stitch_tiles, homogenize_contrast, pc_param, this);
            }
        }, layer.getProject());
    } catch (final Exception e) {
        IJError.print(e);
    }
    return null;
}
Also used : ImageFileFilter(ini.trakem2.io.ImageFileFilter) IOException(java.io.IOException) FormatException(loci.formats.FormatException) GenericDialog(ij.gui.GenericDialog) Montage(ini.trakem2.utils.Montage) Worker(ini.trakem2.utils.Worker) Component(java.awt.Component) File(java.io.File)

Example 30 with Bureaucrat

use of ini.trakem2.utils.Bureaucrat in project TrakEM2 by trakem2.

the class DistortionCorrectionTask method correctDistortionFromSelection.

public static final Bureaucrat correctDistortionFromSelection(final Selection selection) {
    final List<Patch> patches = new ArrayList<Patch>();
    for (final Displayable d : Display.getFront().getSelection().getSelected()) if (d instanceof Patch)
        patches.add((Patch) d);
    if (patches.size() < 2) {
        Utils.log("No images in the selection.");
        return null;
    }
    final Worker worker = new Worker("Lens correction") {

        @Override
        public final void run() {
            try {
                startedWorking();
                if (!correctDistortionFromSelectionParam.setup(selection))
                    return;
                DistortionCorrectionTask.run(correctDistortionFromSelectionParam.clone(), patches, selection.getActive(), selection.getLayer(), null);
                Display.repaint();
            } catch (final Exception e) {
                IJError.print(e);
            } finally {
                finishedWorking();
            }
        }
    };
    return Bureaucrat.createAndStart(worker, selection.getProject());
}
Also used : Displayable(ini.trakem2.display.Displayable) ArrayList(java.util.ArrayList) Worker(ini.trakem2.utils.Worker) Patch(ini.trakem2.display.Patch)

Aggregations

Worker (ini.trakem2.utils.Worker)26 ArrayList (java.util.ArrayList)12 GenericDialog (ij.gui.GenericDialog)11 File (java.io.File)11 ImagePlus (ij.ImagePlus)10 Bureaucrat (ini.trakem2.utils.Bureaucrat)8 Rectangle (java.awt.Rectangle)8 Patch (ini.trakem2.display.Patch)7 NoninvertibleTransformException (java.awt.geom.NoninvertibleTransformException)7 IOException (java.io.IOException)7 HashSet (java.util.HashSet)7 Project (ini.trakem2.Project)6 FormatException (loci.formats.FormatException)6 DirectoryChooser (ij.io.DirectoryChooser)5 Layer (ini.trakem2.display.Layer)5 Point (java.awt.Point)5 TreeMap (java.util.TreeMap)5 Future (java.util.concurrent.Future)5 Displayable (ini.trakem2.display.Displayable)4 DBObject (ini.trakem2.persistence.DBObject)4