]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/diagramEditor/handlers/LinkBrowsingHandler.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / diagramEditor / handlers / LinkBrowsingHandler.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.modeling.ui.diagramEditor.handlers;
13
14 import java.awt.Shape;
15 import java.awt.geom.AffineTransform;
16 import java.awt.geom.Rectangle2D;
17 import java.util.Collection;
18 import java.util.HashSet;
19 import java.util.Set;
20 import java.util.function.Consumer;
21
22 import org.eclipse.ui.IEditorPart;
23 import org.eclipse.ui.IWorkbenchPartSite;
24 import org.eclipse.ui.PartInitException;
25 import org.simantics.db.ReadGraph;
26 import org.simantics.db.Resource;
27 import org.simantics.db.common.ResourceArray;
28 import org.simantics.db.common.request.ReadRequest;
29 import org.simantics.db.common.utils.OrderedSetUtils;
30 import org.simantics.db.exception.DatabaseException;
31 import org.simantics.db.management.ISessionContext;
32 import org.simantics.diagram.stubs.DiagramResource;
33 import org.simantics.g2d.canvas.ICanvasContext;
34 import org.simantics.g2d.canvas.impl.AbstractCanvasParticipant;
35 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
36 import org.simantics.g2d.diagram.DiagramHints;
37 import org.simantics.g2d.diagram.IDiagram;
38 import org.simantics.g2d.diagram.handler.DataElementMap;
39 import org.simantics.g2d.diagram.participant.Selection;
40 import org.simantics.g2d.element.ElementHints;
41 import org.simantics.g2d.element.ElementUtils;
42 import org.simantics.g2d.element.IElement;
43 import org.simantics.g2d.participant.CanvasBoundsParticipant;
44 import org.simantics.g2d.participant.TransformUtil;
45 import org.simantics.g2d.utils.GeometryUtils;
46 import org.simantics.modeling.ModelingResources;
47 import org.simantics.modeling.ui.diagramEditor.DiagramViewer;
48 import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;
49 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseDoubleClickedEvent;
50 import org.simantics.structural.stubs.StructuralResource2;
51 import org.simantics.ui.workbench.ResourceEditorInput;
52 import org.simantics.utils.page.MarginUtils;
53 import org.simantics.utils.threads.ThreadUtils;
54 import org.simantics.utils.ui.ErrorLogger;
55 import org.simantics.utils.ui.workbench.WorkbenchUtils;
56
57 /**
58  * StructuralBrowsingHandler supports visual browsing into subcomponents through
59  * mouse events.
60  * 
61  * @author Tuukka Lehtonen
62  */
63 public class LinkBrowsingHandler extends AbstractCanvasParticipant {
64
65     @Dependency
66     CanvasBoundsParticipant canvasBounds;
67     @Dependency
68     Selection               selection;
69
70     IWorkbenchPartSite      site;
71     DiagramViewer           viewer;
72     ISessionContext         sessionContext;
73
74     public LinkBrowsingHandler(IWorkbenchPartSite site, DiagramViewer viewer, ISessionContext context) {
75
76         assert site != null;
77
78 //              System.out.println("LinkBrowsingHandler " + viewer + " " + viewer.structuralPath);
79
80         this.site = site;
81         this.viewer = viewer;
82         this.sessionContext = context;
83
84     }
85
86     public static Runnable editorActivator(final IEditorPart part, final ResourceArray input, final Consumer<IEditorPart> successCallback) {
87         String sourcePartId = part.getSite().getId();
88         return editorActivator(sourcePartId, input, successCallback);
89     }
90
91     public Runnable elementSelectorZoomer(final ICanvasContext canvas, final Collection<Object> elementObjects, final boolean keepZoom) {
92         return new Runnable() {
93             @Override
94             public void run() {
95                 IDiagram diagram = canvas.getHintStack().getHint(DiagramHints.KEY_DIAGRAM);
96                 assert diagram != null;
97                 if (!zoomToSelection(canvas, diagram, selectElement(canvas, diagram, elementObjects), keepZoom)) {
98                     // Reschedule for later.
99                     ThreadUtils.asyncExec(canvas.getThreadAccess(), this);
100                 }
101             }
102         };
103     }
104
105     public static Set<IElement> selectElement(final ICanvasContext canvas, final IDiagram diagram, final Collection<Object> elementObjects) {
106         // Select element
107         Set<IElement> selection = new HashSet<IElement>();
108         DataElementMap dataMap = diagram.getDiagramClass().getSingleItem(DataElementMap.class);
109         for (Object obj : elementObjects) {
110             IElement element = dataMap.getElement(diagram, obj);
111             if (element == null) {
112                 ErrorLogger.defaultLogWarning("No element to select for object " + obj, new Exception());
113             } else {
114                 selection.add(element);
115             }
116         }
117         for (Selection s : canvas.getItemsByClass(Selection.class)) {
118             s.setSelection(0, selection);
119         }
120         return selection;
121     }
122
123     public boolean zoomToSelection(final ICanvasContext canvas, final IDiagram diagram, Set<IElement> selection, boolean keepZoom) {
124         TransformUtil util = canvas.getSingleItem(TransformUtil.class);
125         Rectangle2D controlBounds = canvasBounds.getControlBounds();
126         if (controlBounds == null)
127             return false;
128
129         Shape shp = ElementUtils.getElementBoundsOnDiagram(selection);
130         if (shp == null)
131             return false;
132
133         Rectangle2D diagramRect = shp.getBounds2D();
134         if (keepZoom) {
135             double scaleFactor = GeometryUtils.getScale(util.getTransform());
136             double cwh = controlBounds.getWidth() / (scaleFactor*2);
137             double chh = controlBounds.getHeight() / (scaleFactor*2);
138
139             AffineTransform view = new AffineTransform();
140             view.scale(scaleFactor, scaleFactor);
141             view.translate(-diagramRect.getCenterX()+cwh, -diagramRect.getCenterY()+chh);
142
143             util.setTransform(view);
144         } else {
145             MarginUtils.Margin margin = MarginUtils.marginOf(40, 0, 0);
146             MarginUtils.Margins margins = new MarginUtils.Margins(margin, margin, margin, margin);
147             util.fitArea(controlBounds, diagramRect, margins);
148         }
149         return true;
150     }
151
152     public static Runnable editorActivator(String editorPartId, ResourceArray input, Consumer<IEditorPart> successCallback) {
153         return new Runnable() {
154             @Override
155             public void run() {
156                 try {
157                     // open and activate new editor
158                     IEditorPart newPart = WorkbenchUtils.openEditor(editorPartId, new ResourceEditorInput(editorPartId, input));
159                     newPart.getSite().getPage().activate(newPart);
160                     successCallback.accept(newPart);
161                 } catch (PartInitException e) {
162                     // TODO: handle properly
163                     e.printStackTrace();
164                 }
165             }
166         };
167     }
168
169     public static Resource getOwnerList(ReadGraph g, Resource listElement) throws DatabaseException {
170         return OrderedSetUtils.getSingleOwnerList(g, listElement, DiagramResource.getInstance(g).Composite);
171     }
172
173     @EventHandler(priority = 0)
174     public boolean handleDoubleClick(MouseDoubleClickedEvent me) {
175
176         //System.out.println("LinkBrowsingHandler");
177
178         if (sessionContext == null)
179             return false;
180
181         Set<IElement> sel = selection.getSelection(0);
182
183         if (sel.size() == 1) {
184             IElement e = sel.iterator().next();
185             Object data = e.getHint(ElementHints.KEY_OBJECT);
186             if (data instanceof Resource) {
187                 final Resource element = (Resource) data;
188                 sessionContext.getSession().asyncRequest(new ReadRequest() {
189                     @Override
190                     public void run(ReadGraph graph) throws DatabaseException {
191
192                         //System.out.println("LinkBrowsingHandler0");
193
194                         ModelingResources mr = ModelingResources.getInstance(graph);
195                         DiagramResource dr = DiagramResource.getInstance(graph);
196                         StructuralResource2 sr = StructuralResource2.getInstance(graph);
197
198                         if (graph.isInstanceOf(element, dr.UpwardLink)) {
199
200 //                            Resource component = viewer.structuralPath.resources[0];
201 //                            Resource element = graph.getPossibleObject(component, mr.ComponentToElement);
202 //                            Resource diagram = getOwnerList(graph, element);
203 //
204 //                            IEditorPart thisEditor = (IEditorPart) site.getPart();
205 //                            site.getWorkbenchWindow().getShell().getDisplay().asyncExec(
206 //                                    editorActivator(thisEditor, viewer.structuralPath.removeFromBeginning(1).prepended(diagram), new Callback<IEditorPart>() {
207 //                                        @Override
208 //                                        public void run(IEditorPart part) {
209 //                                        }
210 //                                    }));
211
212                         } else if (graph.isInstanceOf(element, dr.Link)) {
213
214                             //System.out.println("LinkBrowsingHandler2");
215
216 //                                                      ContextMap parameters = new ContextMap();
217 //                                                      parameters.put(ModelingOperationConstants.WORKBENCH_WINDOW, site.getWorkbenchWindow());
218 //                                                      parameters.put(ModelingOperationConstants.WORKBENCH_PART, site.getPart());
219 //                                                      parameters.put(IOperation.SUBJECT, element);
220
221                             Resource thisDiagram = getOwnerList(graph, element);
222                             if (thisDiagram == null) return;
223
224                             final Resource target = graph.getPossibleObject(element, dr.HasLinkTarget);
225                             if (target == null) return;
226
227                             final Resource otherDiagram = getOwnerList(graph, target);
228                             if (otherDiagram == null)
229                                 return;
230
231                             final Resource component = graph.getPossibleObject(target, mr.ElementToComponent);
232                             if (component == null)
233                                 return;
234
235                             Resource type = graph.getSingleType(component, sr.Component);
236                             if (type == null)
237                                 return;
238
239                             Resource definedBy = graph.getPossibleObject(type, sr.IsDefinedBy);
240                             if (definedBy == null)
241                                 return;
242
243                             final Resource diagram = graph.getPossibleObject(definedBy, mr.CompositeToDiagram);
244                             if (diagram == null)
245                                 return;
246
247 //                              PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
248 //                                  @Override
249 //                                  public void run() {
250 //                                      try {
251 //                                          WorkbenchUtils.openEditor(site.getId(), new ResourceEditorInput(site.getId(), parentStructuralPath.prepended(diagram, component)));
252 //                                      } catch (PartInitException e) {
253 //                                          // TODO Auto-generated catch block
254 //                                          e.printStackTrace();
255 //                                      }
256 //                                  }
257 //                              });
258
259 //                            IEditorPart thisEditor = (IEditorPart) site.getPart();
260 //                            ResourceArray input = viewer.structuralPath.prepended(diagram, component);
261 //                            System.out.println("Browsing link " + input);
262 //                            site.getWorkbenchWindow().getShell().getDisplay().asyncExec(
263 //                                    editorActivator(thisEditor, input, new Callback<IEditorPart>() {
264 //                                        @Override
265 //                                        public void run(IEditorPart part) {
266 ////                                                                                    final ICanvasContext openedCanvas = (ICanvasContext) part.getAdapter(ICanvasContext.class);
267 ////                                                                                    assert openedCanvas != null;
268 ////                                                                                    IDiagram diagram = (IDiagram) part.getAdapter(IDiagram.class);
269 ////                                                                                    assert diagram != null;
270 //                                            // Disable automatic-zoom-to-fit
271 ////                                                                                    diagram.removeHint(DiagramHints.KEY_INITIAL_ZOOM_TO_FIT);
272 ////                                                                                    ThreadUtils.asyncExec(openedCanvas.getThreadAccess(),
273 ////                                                                                                    elementSelectorZoomer(openedCanvas, Collections.singleton((Object) target), false));
274 //                                        }
275 //                                    }));
276
277
278
279 //                                                      System.out.println("LinkBrowsingHandler3");
280 //
281 //                                                      if (!thisDiagram.equals(otherDiagram)) {
282 //
283 //                                                              System.out.println("LinkBrowsingHandler4");
284 //
285 //                                                              // Find the structural path
286 //                                                              Resource ownerComposite = graph.getPossibleObject(otherDiagram, mr.DiagramToComposite);
287 //                                                              if (ownerComposite == null)
288 //                                                                      return;
289 //
290 //                                                              Collection<ResourceArray> inputs = ComponentUtils.formInputs(graph, ownerComposite);
291 //
292 //
293 //                                                              for (final ResourceArray input : inputs) {
294 //                                                              }
295 //                                                      }
296 //                                                      return;
297
298                         }
299
300                         return;
301
302                     }
303
304                 });
305
306
307             }
308
309         }
310         return false;
311     }
312
313 }