]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/sg/DiagramSceneGraphProvider.java
Configurable connection crossing styles
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / sg / DiagramSceneGraphProvider.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.sg;
13
14 import java.awt.Color;
15 import java.awt.event.AWTEventListener;
16
17 import org.eclipse.core.runtime.NullProgressMonitor;
18 import org.simantics.Simantics;
19 import org.simantics.databoard.Bindings;
20 import org.simantics.db.ReadGraph;
21 import org.simantics.db.Resource;
22 import org.simantics.db.common.ResourceArray;
23 import org.simantics.db.common.primitiverequest.PossibleAdapter;
24 import org.simantics.db.exception.DatabaseException;
25 import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
26 import org.simantics.db.exception.NoSingleResultException;
27 import org.simantics.db.exception.ServiceException;
28 import org.simantics.db.management.ISessionContext;
29 import org.simantics.db.request.Read;
30 import org.simantics.diagram.adapter.DefaultConnectionClassFactory;
31 import org.simantics.diagram.adapter.FlagClassFactory;
32 import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;
33 import org.simantics.diagram.handler.CopyPasteHandler;
34 import org.simantics.diagram.handler.CopyPasteStrategy;
35 import org.simantics.diagram.handler.DefaultCopyPasteStrategy;
36 import org.simantics.diagram.handler.DeleteHandler;
37 import org.simantics.diagram.handler.SimpleElementTransformHandler;
38 import org.simantics.diagram.participant.ConnectionCrossingsParticipant;
39 import org.simantics.diagram.query.DiagramRequests;
40 import org.simantics.diagram.runtime.RuntimeDiagramManager;
41 import org.simantics.diagram.stubs.DiagramResource;
42 import org.simantics.diagram.synchronization.CopyAdvisor;
43 import org.simantics.diagram.synchronization.SynchronizationHints;
44 import org.simantics.diagram.ui.DiagramModelHints;
45 import org.simantics.g2d.canvas.Hints;
46 import org.simantics.g2d.canvas.ICanvasContext;
47 import org.simantics.g2d.canvas.impl.CanvasContext;
48 import org.simantics.g2d.diagram.DiagramHints;
49 import org.simantics.g2d.diagram.IDiagram;
50 import org.simantics.g2d.diagram.participant.DiagramParticipant;
51 import org.simantics.g2d.diagram.participant.ElementInteractor;
52 import org.simantics.g2d.diagram.participant.ElementPainter;
53 import org.simantics.g2d.diagram.participant.Selection;
54 import org.simantics.g2d.diagram.participant.ZOrderHandler;
55 import org.simantics.g2d.diagram.participant.pointertool.PointerInteractor;
56 import org.simantics.g2d.element.ElementClassProviders;
57 import org.simantics.g2d.element.ElementClasses;
58 import org.simantics.g2d.element.IElementClassProvider;
59 import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;
60 import org.simantics.g2d.multileveldiagram.TransitionFunction;
61 import org.simantics.g2d.multileveldiagram.ZoomTransitionParticipant;
62 import org.simantics.g2d.page.DiagramDesc;
63 import org.simantics.g2d.participant.BackgroundPainter;
64 import org.simantics.g2d.participant.CanvasBoundsParticipant;
65 import org.simantics.g2d.participant.CanvasGrab;
66 import org.simantics.g2d.participant.GridPainter;
67 import org.simantics.g2d.participant.KeyToCommand;
68 import org.simantics.g2d.participant.KeyUtil;
69 import org.simantics.g2d.participant.MouseUtil;
70 import org.simantics.g2d.participant.MultitouchPanZoomRotateInteractor;
71 import org.simantics.g2d.participant.Notifications;
72 import org.simantics.g2d.participant.PageBorderParticipant;
73 import org.simantics.g2d.participant.PanZoomRotateHandler;
74 import org.simantics.g2d.participant.PointerPainter;
75 import org.simantics.g2d.participant.RulerPainter;
76 import org.simantics.g2d.participant.SymbolUtil;
77 import org.simantics.g2d.participant.TimeParticipant;
78 import org.simantics.g2d.participant.TransformUtil;
79 import org.simantics.g2d.participant.ZoomToAreaHandler;
80 import org.simantics.g2d.scenegraph.ICanvasSceneGraphProvider;
81 import org.simantics.modeling.ModelingResources;
82 import org.simantics.modeling.mapping.ComponentCopyAdvisor;
83 import org.simantics.modeling.mapping.ElementCopyAdvisor;
84 import org.simantics.modeling.mapping.MappedElementCopyAdvisor;
85 import org.simantics.modeling.mapping.ModelingSynchronizationHints;
86 import org.simantics.modeling.ui.diagramEditor.PopulateElementDropParticipant;
87 import org.simantics.modeling.ui.diagramEditor.PopulateElementMonitorDropParticipant;
88 import org.simantics.modeling.ui.diagramEditor.handlers.HeadlessStructuralBrowsingHandler;
89 import org.simantics.modeling.ui.diagramEditor.handlers.HeadlessStructuralBrowsingHandler.IDiagramUpdateSupport;
90 import org.simantics.scenegraph.g2d.G2DSceneGraph;
91 import org.simantics.scenegraph.g2d.events.adapter.AWTRemoteEventAdapter;
92 import org.simantics.scenegraph.g2d.events.command.CommandKeyBinding;
93 import org.simantics.structural.stubs.StructuralResource2;
94 import org.simantics.structural2.modelingRules.IModelingRules;
95 import org.simantics.utils.datastructures.hints.HintContext;
96 import org.simantics.utils.datastructures.hints.IHintContext;
97 import org.simantics.utils.page.PageDesc;
98 import org.simantics.utils.page.PageOrientation;
99 import org.simantics.utils.threads.AWTThread;
100 import org.simantics.utils.threads.IThreadWorkQueue;
101 import org.simantics.utils.ui.ErrorLogger;
102
103
104 /**
105  * ISceneGraphProvider implementation for diagrams.
106  * TODO: decide if this should be stateless or stateful class
107  * 
108  * @author J-P Laine
109  *
110  */
111 public class DiagramSceneGraphProvider implements ICanvasSceneGraphProvider, IDiagramUpdateSupport {
112
113         protected boolean isSymbol = false;
114     protected Resource resource;
115     protected ResourceArray structuralPath = null;
116     protected IDiagram diagram = null;
117     protected CanvasContext ctx = null;
118     protected boolean ownsContext = false;
119     protected GraphToDiagramSynchronizer synchronizer = null;
120     protected String view = null;
121     protected Boolean navigation = null;
122
123     protected AWTRemoteEventAdapter listener = null;
124
125     final IHintContext initialHints = new HintContext();
126
127     public DiagramSceneGraphProvider(ReadGraph g, final Resource diagramOrComposite) {
128         this.structuralPath = new ResourceArray();
129         try {
130
131             StructuralResource2 sr = StructuralResource2.getInstance(g);
132                 DiagramResource DIA = DiagramResource.getInstance(g);
133                 
134                 Resource diagram = diagramOrComposite;
135                 if(!g.isInstanceOf(diagram, DIA.Composite)) {
136                         
137                 ModelingResources mr = ModelingResources.getInstance(g);
138                         diagram = g.getPossibleObject(diagramOrComposite, mr.CompositeToDiagram);
139                         if(diagram == null) {
140                     // looks like we have a component without direct relation to composite.. try to solve this
141                     // FIXME: use adapter to get composite directly from resource
142                     final Resource type = g.getSingleType(diagramOrComposite, sr.Component);
143                     if (type == null)
144                         return;
145
146                     final Resource definedBy = g.getPossibleObject(type, sr.IsDefinedBy);
147                     if (definedBy == null)
148                         return;
149
150                     this.structuralPath = new ResourceArray(diagramOrComposite);
151                     diagram =  g.getPossibleObject(definedBy, mr.CompositeToDiagram);
152                         }
153                         
154                 } else {
155                         
156                         Resource possibleSymbol = g.getPossibleObject(diagram, sr.Defines);
157                         if(possibleSymbol != null && g.isInstanceOf(possibleSymbol, DIA.ElementClass)) isSymbol = true;
158                         
159                 }
160                 
161                         this.resource = diagram;
162                 
163         } catch (ManyObjectsForFunctionalRelationException e) {
164             // TODO Auto-generated catch block
165             e.printStackTrace();
166         } catch (ServiceException e) {
167             // TODO Auto-generated catch block
168             e.printStackTrace();
169         } catch (NoSingleResultException e) {
170             // TODO Auto-generated catch block
171             e.printStackTrace();
172         }
173     }
174
175     public GraphToDiagramSynchronizer getGraphToDiagramSynchronizer() {
176         return synchronizer;
177     }
178
179     protected CopyPasteStrategy getCopyPasteStrategy() {
180                 try {
181                         CopyPasteStrategy cpStrategy = Simantics.getSession().syncRequest(new PossibleAdapter<CopyPasteStrategy>(resource, CopyPasteStrategy.class));
182                         if(cpStrategy != null) return cpStrategy;
183                 } catch (DatabaseException e) {
184                 }
185                 return new DefaultCopyPasteStrategy();
186     }
187     
188     protected CopyAdvisor getCopyAdvisor() {
189                 try {
190                         CopyAdvisor advisor = Simantics.getSession().syncRequest(new PossibleAdapter<CopyAdvisor>(resource, CopyAdvisor.class));
191                         if(advisor != null) return advisor;
192                 } catch (DatabaseException e) {
193                 }
194                 return new MappedElementCopyAdvisor(new ElementCopyAdvisor(), new ComponentCopyAdvisor());
195     }
196     
197     protected void initContext(CanvasContext ctx) {
198         boolean unlock = false;
199         if (!ctx.isLocked()) {
200             ctx.setLocked(true);
201             unlock = true;
202         }
203
204         IHintContext h = ctx.getDefaultHintContext();
205
206         // Support & Util Participants
207         ctx.add( new TransformUtil() );
208         ctx.add( new MouseUtil() );
209         ctx.add( new KeyUtil() );
210         ctx.add( new CanvasGrab() );
211         ctx.add( new SymbolUtil() );
212         ctx.add( new TimeParticipant() );
213         ctx.add( new CanvasBoundsParticipant() );
214         ctx.add( new Notifications() );
215
216         // SGFocusParticipant does not work for remote viewer at the moment.
217         //ctx.add( new SGFocusParticipant() );
218
219         h.setHint(PointerPainter.KEY_PAINT_POINTER, true);
220
221         ctx.add( new PanZoomRotateHandler(navigation == null || navigation == true) );
222         ctx.add( new MultitouchPanZoomRotateInteractor() );
223         ctx.add( new ZoomToAreaHandler() );
224         ctx.add( new SimpleElementTransformHandler() );
225         
226         // Key bindings
227         if(navigation == null || navigation == true)
228             ctx.add( new KeyToCommand( CommandKeyBinding.DEFAULT_BINDINGS ) );
229
230         // Grid & Ruler & Background
231         h.setHint(RulerPainter.KEY_RULER_ENABLED, false);
232         h.setHint(GridPainter.KEY_GRID_ENABLED, false);
233
234         ctx.add( new GridPainter() );
235         ctx.add( new RulerPainter() );
236         ctx.add( new BackgroundPainter() );
237         
238         h.setHint(Hints.KEY_DISPLAY_PAGE, Boolean.FALSE);
239         h.setHint(Hints.KEY_DISPLAY_MARGINS, Boolean.TRUE);
240         ctx.add( new PageBorderParticipant() );
241
242         h.setHint(Hints.KEY_GRID_COLOR, new Color(0.95f, 0.95f, 0.95f));
243         h.setHint(Hints.KEY_BACKGROUND_COLOR, Color.WHITE);
244         h.setHint(RulerPainter.KEY_RULER_BACKGROUND_COLOR, new Color(0.9f, 0.9f, 0.9f, 0.75f));
245         h.setHint(RulerPainter.KEY_RULER_TEXT_COLOR, Color.BLACK);
246
247         ////// Diagram Participants //////
248         ctx.add( new PointerInteractor(false, false, false, false, true, true, synchronizer.getElementClassProvider(), null) );
249         ctx.add( new ElementInteractor() );
250         ctx.add( new Selection() );
251         ctx.add( new DiagramParticipant() );
252         ctx.add( new ElementPainter(true) );
253         ctx.add( new ConnectionCrossingsParticipant(resource));
254
255         //ctx.add( new ElementHeartbeater() );
256         ctx.add( new ZOrderHandler() );
257         ctx.add( new ZoomTransitionParticipant(TransitionFunction.SIGMOID) );
258
259         /////// D'n'D ///////
260         ctx.add(new PopulateElementDropParticipant(synchronizer));
261         ctx.add(new PopulateElementMonitorDropParticipant(synchronizer, 0.5, 0.5));
262
263         h.setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
264
265         h.setHint(PanZoomRotateHandler.KEY_ZOOM_IN_LIMIT, 1000.0);
266         h.setHint(PanZoomRotateHandler.KEY_ZOOM_OUT_LIMIT, 10.0);
267
268         // Add visual browsing capabilities for structural models
269         ISessionContext sessionContext = Simantics.getSessionContext();
270         ctx.add(new HeadlessStructuralBrowsingHandler(this, sessionContext, structuralPath));
271
272         // Page settings
273         PageDesc pageDesc = PageDesc.DEFAULT.withOrientation(PageOrientation.Landscape);
274         // TODO: load page desc from graph
275         h.setHint(Hints.KEY_PAGE_DESC, pageDesc);
276
277         ctx.add(new CopyPasteHandler(getCopyPasteStrategy()));
278         ctx.add(new DeleteHandler(null));
279
280         if (resource != null)
281             loadPageSettings(ctx, resource);
282
283         ctx.assertParticipantDependencies();
284         if (unlock)
285             ctx.setLocked(false);
286     }
287
288     protected void loadPageSettings(ICanvasContext ctx, Resource diagramResource) {
289         try {
290             DiagramDesc diagramDesc = Simantics.getSession().syncRequest(DiagramRequests.getDiagramDesc(diagramResource));
291             if (diagramDesc != null)
292                 setDiagramDesc(ctx, diagramDesc);
293         } catch (DatabaseException e) {
294             ErrorLogger.defaultLogError(e);
295         }
296     }
297
298     protected void setDiagramDesc(ICanvasContext ctx, DiagramDesc diagramDesc) {
299         IHintContext hints = ctx.getDefaultHintContext();
300         hints.setHint(Hints.KEY_PAGE_DESC, diagramDesc.getPageDesc());
301         //hints.setHint(Hints.KEY_DISPLAY_PAGE, diagramDesc.isPageBordersVisible());
302         hints.setHint(Hints.KEY_DISPLAY_MARGINS, diagramDesc.isMarginsVisible());
303     }
304
305     @Override
306     public G2DSceneGraph initializeSceneGraph(G2DSceneGraph sg) {
307         return initializeSceneGraph(sg, null);
308     }
309
310     @Override
311     public G2DSceneGraph initializeSceneGraph(G2DSceneGraph sg, String view) {
312         return initializeSceneGraph(sg, "", "", view);
313     }
314
315     @Override
316     public G2DSceneGraph initializeSceneGraph(G2DSceneGraph sg, String modelURI, String RVI) {
317         return initializeSceneGraph(sg, modelURI, RVI, "");
318     }
319
320     @Override
321     public G2DSceneGraph initializeSceneGraph(ICanvasContext context, String modelURI, String RVI) {
322         G2DSceneGraph sg = context.getSceneGraph();
323         return initializeSceneGraph(context, sg, modelURI, RVI, "");
324     }
325
326     /**
327      * @param sg
328      * @param view
329      * @param initialHints
330      * @return
331      */
332     private G2DSceneGraph initializeSceneGraph(G2DSceneGraph sg, String modelURI, String RVI, String view) {
333         IThreadWorkQueue thread = AWTThread.getThreadAccess();
334         ctx = new CanvasContext(thread, sg); // By giving the scene graph instance as parameter, we can use external serializer
335         return initializeSceneGraph(ctx, sg, modelURI, RVI, view);
336     }
337
338     /**
339      * @param sg
340      * @param view
341      * @param initialHints
342      * @return
343      */
344     private G2DSceneGraph initializeSceneGraph(ICanvasContext context, G2DSceneGraph sg, String modelURI, String RVI, String view) {
345         this.ctx = (CanvasContext) context;
346         this.view = view;
347         if(view != null) {
348             //System.out.println("using layer '"+view+"'");
349             initialHints.setHint(DiagramHints.KEY_FIXED_LAYERS, new String[] { view });
350         }
351
352         try {
353                 fillInitialDiagramHints(initialHints);
354             
355             final RuntimeDiagramManager runtimeDiagramManager = RuntimeDiagramManager.create(Simantics.getSession(), resource, modelURI, RVI);
356             
357             synchronizer = Simantics.getSession().syncRequest(new Read<GraphToDiagramSynchronizer>() {
358                 @Override
359                 public GraphToDiagramSynchronizer perform(ReadGraph graph) throws DatabaseException {
360                     DiagramResource dr = DiagramResource.getInstance(graph);
361                     Boolean val = graph.getPossibleRelatedValue(resource, dr.NavigationEnabled, Bindings.BOOLEAN);
362                     if(val != null && navigation == null) { // Set only if navigation has not been set manually
363                         navigation = val;
364                     }
365                     GraphToDiagramSynchronizer sync = new GraphToDiagramSynchronizer(graph, ctx,createElementClassProvider(graph));
366                     
367                     sync.set(ModelingSynchronizationHints.MODELING_RESOURCE, ModelingResources.getInstance(graph));
368                     diagram = sync.loadDiagram(new NullProgressMonitor(), graph, null, resource, runtimeDiagramManager.getRuntimeDiagram(), structuralPath, initialHints); // FIXME
369                     return sync;
370                 }
371             });
372             
373         } catch (DatabaseException e) {
374             // TODO Auto-generated catch block
375             e.printStackTrace();
376         }
377         ctx.getDefaultHintContext().setHint(DiagramHints.KEY_DIAGRAM, diagram);
378
379         initContext(ctx);
380
381         return ctx.getSceneGraph();
382     }
383     
384     protected void fillInitialDiagramHints(IHintContext initialHints) throws DatabaseException {
385           IModelingRules modelingRules = Simantics.getSession().syncRequest(DiagramRequests.getModelingRules(resource, null));
386           if (modelingRules != null) {
387               initialHints.setHint(DiagramModelHints.KEY_MODELING_RULES, modelingRules);
388           }
389           
390           initialHints.setHint(SynchronizationHints.COPY_ADVISOR, getCopyAdvisor());
391     }
392     
393     protected IElementClassProvider createElementClassProvider(ReadGraph graph) throws DatabaseException {
394         DiagramResource dr = DiagramResource.getInstance(graph);
395         return ElementClassProviders.mappedProvider(
396                   ElementClasses.CONNECTION, DefaultConnectionClassFactory.CLASS.newClassWith(new StaticObjectAdapter(dr.Connection)),
397                   ElementClasses.FLAG, FlagClassFactory.createFlagClass(dr.Flag, dr.Flag_Terminal)
398         );
399         
400     }
401
402     @Override
403     public void dispose() {
404         if(ctx != null) {
405             if (ownsContext)
406                 ctx.dispose();
407             ctx = null;
408         }
409         if (synchronizer != null) {
410             synchronizer.dispose();
411             synchronizer = null;
412         }
413         if (diagram != null) {
414             diagram.dispose();
415             diagram = null;
416         }
417     }
418
419     /**
420      * Hack for returning canvasContext for some special cases
421      * this method brakes the interface, but this is not intended to be used in production context
422      * @return
423      */
424     @Override
425     public ICanvasContext getCanvasContext() {
426         return ctx;
427     }
428
429     @Override
430     public AWTEventListener getEventListener() {
431         if(ctx == null) return null;
432         if(listener == null) {
433             listener = new AWTRemoteEventAdapter(ctx, ctx.getEventQueue());
434         }
435         return listener;
436     }
437
438     @Override
439     public void updateDiagram(final ResourceArray structuralPath) {
440         final IHintContext hints = new HintContext();
441         if(view != null) {
442             System.out.println("using layer '"+view+"'");
443             hints.setHint(DiagramHints.KEY_FIXED_LAYERS, new String[] { view });
444         }
445
446         try {
447             // FIXME: I have no idea if this works or not..
448             diagram = Simantics.getSession().syncRequest(new Read<IDiagram>() {
449                 @Override
450                 public IDiagram perform(ReadGraph graph) throws DatabaseException {
451                     IDiagram d = synchronizer.loadDiagram(new NullProgressMonitor(), graph, null, structuralPath.resources[0], null, structuralPath.removeFromBeginning(0), hints);
452                     return d;
453                 }
454             });
455             ctx.getDefaultHintContext().setHint(DiagramHints.KEY_DIAGRAM, diagram);
456         } catch (DatabaseException e) {
457             // TODO Auto-generated catch block
458             e.printStackTrace();
459         }
460     }
461
462     public void setExperiment(ReadGraph g, String identifier) {
463         if(diagram == null) return;
464         diagram.setHint(DiagramModelHints.KEY_ACTIVE_EXPERIMENT, identifier);
465         initialHints.setHint(DiagramModelHints.KEY_ACTIVE_EXPERIMENT, identifier);
466
467 //              try {
468 //                      DiagramExperiment.setActiveExperiment(g, diagram, (String)identifier);
469 //              } catch (DatabaseException e) {
470 //                      // TODO Auto-generated catch block
471 //                      e.printStackTrace();
472 //              }
473
474     }
475
476     /**
477      * Supported keys:
478      *     DiagramModelHints.KEY_SESSION_ID
479      *     DiagramHints.KEY_NAVIGATION_ENABLED
480      */
481     @Override
482     public void setHint(Object key, Object value) {
483         if(DiagramModelHints.KEY_SESSION_ID.equals(key)) {
484             if(diagram != null)
485                 diagram.setHint(DiagramModelHints.KEY_SESSION_ID, value);
486             initialHints.setHint(DiagramModelHints.KEY_SESSION_ID, value);
487         } else if(DiagramModelHints.KEY_ACTIVE_EXPERIMENT.equals(key)) {
488             if(diagram != null)
489                 diagram.setHint(DiagramModelHints.KEY_ACTIVE_EXPERIMENT, value);
490             initialHints.setHint(DiagramModelHints.KEY_ACTIVE_EXPERIMENT, value);
491         } else if(DiagramHints.KEY_NAVIGATION_ENABLED.equals(key)) {
492             navigation = (Boolean)value;
493         }
494     }
495 }