1 package org.simantics.district.region.ui;
3 import java.awt.geom.Rectangle2D;
6 import org.eclipse.core.runtime.IProgressMonitor;
7 import org.eclipse.core.runtime.IStatus;
8 import org.eclipse.core.runtime.Status;
9 import org.eclipse.e4.core.di.annotations.CanExecute;
10 import org.eclipse.e4.core.di.annotations.Execute;
11 import org.eclipse.e4.ui.workbench.modeling.ESelectionService;
12 import org.eclipse.jface.dialogs.InputDialog;
13 import org.eclipse.jface.window.Window;
14 import org.eclipse.ui.IEditorPart;
15 import org.eclipse.ui.progress.UIJob;
16 import org.simantics.Simantics;
17 import org.simantics.db.Resource;
18 import org.simantics.db.WriteGraph;
19 import org.simantics.db.exception.DatabaseException;
20 import org.simantics.db.request.Write;
21 import org.simantics.diagram.ui.DiagramModelHints;
22 import org.simantics.district.region.DiagramRegions;
23 import org.simantics.g2d.canvas.ICanvasContext;
24 import org.simantics.g2d.diagram.IDiagram;
25 import org.simantics.g2d.diagram.participant.Selection;
26 import org.simantics.g2d.element.ElementUtils;
27 import org.simantics.g2d.element.IElement;
28 import org.simantics.utils.ui.workbench.WorkbenchUtils;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
32 public class CreateRegionFromSelection {
34 private static final Logger LOGGER = LoggerFactory.getLogger(CreateRegionFromSelection.class);
37 public boolean canExecute(ESelectionService selectionService) {
38 return selectionService.getSelection() != null;
42 public void createRegionFromSelection() {
43 IEditorPart activeEditor = WorkbenchUtils.getActiveEditor();
44 ICanvasContext context = activeEditor.getAdapter(ICanvasContext.class);
45 if (context != null) {
46 IDiagram diagram = activeEditor.getAdapter(IDiagram.class);
47 if (diagram != null) {
48 Resource diagramResource = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
49 Selection selection = context.getAtMostOneItemOfClass(Selection.class);
50 Set<IElement> allSelections = selection.getAllSelections();
51 Rectangle2D surroundingElementBoundsOnDiagram = ElementUtils.getSurroundingElementBoundsOnDiagram(allSelections);
52 double[] coordinates = DiagramRegions.shapeToCoordinates(surroundingElementBoundsOnDiagram);
54 UIJob job = new UIJob("Creating new region for diagram") {
57 public IStatus runInUIThread(IProgressMonitor monitor) {
58 InputDialog d = new InputDialog(getDisplay().getActiveShell(), "Enter label for region", "Enter region label", "", null);
59 int status = d.open();
60 if (status == Window.OK) {
61 String label = d.getValue();
62 Simantics.getSession().asyncRequest(new Write() {
65 public void perform(WriteGraph graph) throws DatabaseException {
66 DiagramRegions.createRegionForDiagram(graph, diagramResource, label, coordinates);
72 return Status.OK_STATUS;
78 LOGGER.warn("No diagram available for active editor {}", activeEditor);
81 LOGGER.warn("No CanvasContext available for active editor {}", activeEditor);