use of ini.trakem2.display.LayerSet in project TrakEM2 by trakem2.
the class Project method openDBProject.
/**
* Open a TrakEM2 project from the database. Queries the database for existing projects and if more than one, asks which one to open.
*/
public static Project openDBProject() {
if (Utils.wrongImageJVersion())
return null;
DBLoader loader = new DBLoader();
if (!loader.isReady())
return null;
// check connection
if (!loader.isConnected()) {
Utils.showMessage("Can't talk to database.");
loader.destroy();
return null;
}
// query the database for existing projects
Project[] projects = loader.getProjects();
if (null == projects) {
Utils.showMessage("Can't talk to database (null list of projects).");
loader.destroy();
return null;
}
Project project = null;
if (0 == projects.length) {
Utils.showMessage("No projects in this database.");
loader.destroy();
return null;
} else if (1 == projects.length) {
project = projects[0];
} else {
// ask to choose one
String[] titles = new String[projects.length];
for (int i = 0; i < projects.length; i++) {
titles[i] = projects[i].title;
}
GenericDialog gd = new GenericDialog("Choose");
gd.addMessage("Choose project to open:");
gd.addChoice("project: ", titles, titles[titles.length - 1]);
gd.showDialog();
if (gd.wasCanceled()) {
loader.destroy();
return null;
}
project = projects[gd.getNextChoiceIndex()];
}
// check if the selected project is open already
for (final Project p : al_open_projects) {
if (loader.isIdenticalProjectSource(p.loader) && p.id == project.id && p.title.equals(project.title)) {
Utils.showMessage("A project with title " + p.title + " and id " + p.id + " from the same database is already open.");
loader.destroy();
return null;
}
}
// now, open the selected project
// assign loader
project.loader = loader;
// grab the XML template
TemplateThing template_root = loader.getTemplateRoot(project);
if (null == template_root) {
Utils.showMessage("Failed to retrieve the template tree.");
project.destroy();
return null;
}
project.template_tree = new TemplateTree(project, template_root);
synchronized (project.ht_unique_tt) {
project.ht_unique_tt.clear();
project.ht_unique_tt.putAll(template_root.getUniqueTypes(new HashMap<String, TemplateThing>()));
}
// create the project Thing, to be root of the whole user Thing tree (and load all its objects)
// to collect all created displayables, and then reassign to the proper layers.
HashMap<Long, Displayable> hs_d = new HashMap<Long, Displayable>();
try {
// create a template for the project Thing
TemplateThing project_template = new TemplateThing("project");
project.ht_unique_tt.put("project", project_template);
project_template.addChild(template_root);
project.root_pt = loader.getRootProjectThing(project, template_root, project_template, hs_d);
// restore parent/child and attribute ownership and values (now that all Things exist)
project.root_pt.setup();
} catch (Exception e) {
Utils.showMessage("Failed to retrieve the Thing tree for the project.");
IJError.print(e);
project.destroy();
return null;
}
// create the user objects tree
project.project_tree = new ProjectTree(project, project.root_pt);
// restore the expanded state of each node
loader.restoreNodesExpandedState(project);
// create the layers templates
project.createLayerTemplates();
// fetch the root layer thing and the root layer set (will load all layers and layer sets, with minimal contents of patches; gets the basic objects -profile, pipe, etc.- from the project.root_pt). Will open all existing displays for each layer.
LayerThing root_layer_thing = null;
try {
root_layer_thing = loader.getRootLayerThing(project, project.root_pt, Project.layer_set_template, Project.layer_template);
if (null == root_layer_thing) {
project.destroy();
Utils.showMessage("Could not retrieve the root layer thing.");
return null;
}
// set the child/parent relationships now that everything exists
root_layer_thing.setup();
project.layer_set = (LayerSet) root_layer_thing.getObject();
if (null == project.layer_set) {
project.destroy();
Utils.showMessage("Could not retrieve the root layer set.");
return null;
}
// set the active layer to each ZDisplayable
project.layer_set.setup();
// debug:
// Utils.log2("$$$ root_lt: " + root_layer_thing + " ob: " + root_layer_thing.getObject().getClass().getName() + "\n children: " + ((LayerSet)root_layer_thing.getObject()).getLayers().size());
project.layer_tree = new LayerTree(project, root_layer_thing);
project.root_lt = root_layer_thing;
} catch (Exception e) {
Utils.showMessage("Failed to retrieve the Layer tree for the project.");
IJError.print(e);
project.destroy();
return null;
}
// 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);
// now open the displays that were stored for later, if any:
Display.openLater();
return project;
}
use of ini.trakem2.display.LayerSet in project TrakEM2 by trakem2.
the class Project method createSubproject.
/**
* Create a new subproject for the given layer range and ROI.
* Create a new Project using the given project as template. This means the DTD of the given project is copied, as well as the storage and mipmaps folders; everything else is empty in the new project.
*/
public Project createSubproject(final Rectangle roi, final Layer first, final Layer last, final boolean ignore_hidden_patches) {
try {
// The order matters.
final Project pr = new Project(new FSLoader(this.getLoader().getStorageFolder()));
pr.id = this.id;
// copy properties
pr.title = this.title;
pr.ht_props.putAll(this.ht_props);
// copy template
pr.root_tt = this.root_tt.clone(pr, true);
pr.template_tree = new TemplateTree(pr, pr.root_tt);
synchronized (pr.ht_unique_tt) {
pr.ht_unique_tt.clear();
pr.ht_unique_tt.putAll(root_tt.getUniqueTypes(new HashMap<String, TemplateThing>()));
}
TemplateThing project_template = new TemplateThing("project");
project_template.addChild(pr.root_tt);
pr.ht_unique_tt.put("project", project_template);
// create the layers templates
pr.createLayerTemplates();
// copy LayerSet and all involved Displayable objects
// (A two-step process to provide the layer_set pointer and all Layer pointers to the ZDisplayable to copy and crop.)
pr.layer_set = (LayerSet) this.layer_set.clone(pr, first, last, roi, false, true, ignore_hidden_patches);
LayerSet.cloneInto(this.layer_set, first, last, pr, pr.layer_set, roi, true);
// create layer tree
pr.root_lt = new LayerThing(Project.layer_set_template, pr, pr.layer_set);
pr.layer_tree = new LayerTree(pr, pr.root_lt);
// add layer nodes to the layer tree (solving chicken-and-egg problem)
pr.layer_set.updateLayerTree();
// copy project tree
pr.root_pt = this.root_pt.subclone(pr);
pr.project_tree = new ProjectTree(pr, pr.root_pt);
// not copying node expanded state.
// register
al_open_projects.add(pr);
// add to gui:
ControlWindow.add(pr, pr.template_tree, pr.project_tree, pr.layer_tree);
// Above, the id of each object is preserved from this project into the subproject.
// The abstract structure should be copied in full regardless, without the basic objects
// included if they intersect the roi.
// Regenerate mipmaps (blocks GUI from interaction other than navigation)
pr.loader.regenerateMipMaps(pr.layer_set.getDisplayables(Patch.class));
pr.restartAutosaving();
return pr;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
use of ini.trakem2.display.LayerSet 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;
}
use of ini.trakem2.display.LayerSet in project TrakEM2 by trakem2.
the class Loader method startLargeUpdate.
public void startLargeUpdate() {
final LayerSet ls = Project.findProject(this).getRootLayerSet();
temp_snapshots_mode = ls.getSnapshotsMode();
// disable repainting snapshots
if (2 != temp_snapshots_mode)
ls.setSnapshotsMode(2);
}
use of ini.trakem2.display.LayerSet 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;
}
Aggregations