1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.modeling.ui.sg;
14 import java.awt.Color;
15 import java.awt.event.AWTEventListener;
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.VirtualGraph;
23 import org.simantics.db.common.ResourceArray;
24 import org.simantics.db.common.primitiverequest.PossibleAdapter;
25 import org.simantics.db.exception.DatabaseException;
26 import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
27 import org.simantics.db.exception.NoSingleResultException;
28 import org.simantics.db.exception.ServiceException;
29 import org.simantics.db.management.ISessionContext;
30 import org.simantics.db.procedure.Listener;
31 import org.simantics.db.request.Read;
32 import org.simantics.db.service.VirtualGraphSupport;
33 import org.simantics.diagram.adapter.DefaultConnectionClassFactory;
34 import org.simantics.diagram.adapter.FlagClassFactory;
35 import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;
36 import org.simantics.diagram.handler.CopyPasteHandler;
37 import org.simantics.diagram.handler.CopyPasteStrategy;
38 import org.simantics.diagram.handler.DefaultCopyPasteStrategy;
39 import org.simantics.diagram.handler.DeleteHandler;
40 import org.simantics.diagram.handler.SimpleElementTransformHandler;
41 import org.simantics.diagram.participant.ConnectionCrossingsParticipant;
42 import org.simantics.diagram.query.DiagramRequests;
43 import org.simantics.diagram.runtime.RuntimeDiagramManager;
44 import org.simantics.diagram.stubs.DiagramResource;
45 import org.simantics.diagram.synchronization.CopyAdvisor;
46 import org.simantics.diagram.synchronization.SynchronizationHints;
47 import org.simantics.diagram.ui.DiagramModelHints;
48 import org.simantics.g2d.canvas.Hints;
49 import org.simantics.g2d.canvas.ICanvasContext;
50 import org.simantics.g2d.canvas.impl.CanvasContext;
51 import org.simantics.g2d.diagram.DiagramHints;
52 import org.simantics.g2d.diagram.IDiagram;
53 import org.simantics.g2d.diagram.participant.DiagramParticipant;
54 import org.simantics.g2d.diagram.participant.ElementInteractor;
55 import org.simantics.g2d.diagram.participant.ElementPainter;
56 import org.simantics.g2d.diagram.participant.Selection;
57 import org.simantics.g2d.diagram.participant.ZOrderHandler;
58 import org.simantics.g2d.diagram.participant.pointertool.PointerInteractor;
59 import org.simantics.g2d.element.ElementClassProviders;
60 import org.simantics.g2d.element.ElementClasses;
61 import org.simantics.g2d.element.IElementClassProvider;
62 import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;
63 import org.simantics.g2d.multileveldiagram.TransitionFunction;
64 import org.simantics.g2d.multileveldiagram.ZoomTransitionParticipant;
65 import org.simantics.g2d.page.DiagramDesc;
66 import org.simantics.g2d.participant.BackgroundPainter;
67 import org.simantics.g2d.participant.CanvasBoundsParticipant;
68 import org.simantics.g2d.participant.CanvasGrab;
69 import org.simantics.g2d.participant.GridPainter;
70 import org.simantics.g2d.participant.KeyToCommand;
71 import org.simantics.g2d.participant.KeyUtil;
72 import org.simantics.g2d.participant.MouseUtil;
73 import org.simantics.g2d.participant.MultitouchPanZoomRotateInteractor;
74 import org.simantics.g2d.participant.Notifications;
75 import org.simantics.g2d.participant.PageBorderParticipant;
76 import org.simantics.g2d.participant.PanZoomRotateHandler;
77 import org.simantics.g2d.participant.PointerPainter;
78 import org.simantics.g2d.participant.RulerPainter;
79 import org.simantics.g2d.participant.SymbolUtil;
80 import org.simantics.g2d.participant.TimeParticipant;
81 import org.simantics.g2d.participant.TransformUtil;
82 import org.simantics.g2d.participant.ZoomToAreaHandler;
83 import org.simantics.g2d.scenegraph.ICanvasSceneGraphProvider;
84 import org.simantics.modeling.ModelingResources;
85 import org.simantics.modeling.mapping.ComponentCopyAdvisor;
86 import org.simantics.modeling.mapping.ElementCopyAdvisor;
87 import org.simantics.modeling.mapping.MappedElementCopyAdvisor;
88 import org.simantics.modeling.mapping.ModelingSynchronizationHints;
89 import org.simantics.modeling.ui.diagramEditor.PopulateElementDropParticipant;
90 import org.simantics.modeling.ui.diagramEditor.PopulateElementMonitorDropParticipant;
91 import org.simantics.modeling.ui.diagramEditor.handlers.HeadlessStructuralBrowsingHandler;
92 import org.simantics.modeling.ui.diagramEditor.handlers.HeadlessStructuralBrowsingHandler.IDiagramUpdateSupport;
93 import org.simantics.scenegraph.g2d.G2DSceneGraph;
94 import org.simantics.scenegraph.g2d.events.adapter.AWTRemoteEventAdapter;
95 import org.simantics.scenegraph.g2d.events.command.CommandKeyBinding;
96 import org.simantics.structural.stubs.StructuralResource2;
97 import org.simantics.structural2.modelingRules.IModelingRules;
98 import org.simantics.utils.datastructures.hints.HintContext;
99 import org.simantics.utils.datastructures.hints.IHintContext;
100 import org.simantics.utils.page.PageDesc;
101 import org.simantics.utils.page.PageOrientation;
102 import org.simantics.utils.threads.AWTThread;
103 import org.simantics.utils.threads.IThreadWorkQueue;
104 import org.simantics.utils.threads.ThreadUtils;
105 import org.simantics.utils.ui.ErrorLogger;
109 * ISceneGraphProvider implementation for diagrams.
110 * TODO: decide if this should be stateless or stateful class
115 public class DiagramSceneGraphProvider implements ICanvasSceneGraphProvider, IDiagramUpdateSupport {
117 protected boolean isSymbol = false;
118 protected Resource resource;
119 protected ResourceArray structuralPath = null;
120 protected IDiagram diagram = null;
121 protected CanvasContext ctx = null;
122 protected boolean ownsContext = false;
123 protected GraphToDiagramSynchronizer synchronizer = null;
124 protected String view = null;
125 protected Boolean navigation = null;
127 protected AWTRemoteEventAdapter listener = null;
129 final IHintContext initialHints = new HintContext();
131 public DiagramSceneGraphProvider(ReadGraph g, final Resource diagramOrComposite) {
132 this.structuralPath = new ResourceArray();
135 StructuralResource2 sr = StructuralResource2.getInstance(g);
136 DiagramResource DIA = DiagramResource.getInstance(g);
138 Resource diagram = diagramOrComposite;
139 if(!g.isInstanceOf(diagram, DIA.Composite)) {
141 ModelingResources mr = ModelingResources.getInstance(g);
142 diagram = g.getPossibleObject(diagramOrComposite, mr.CompositeToDiagram);
143 if(diagram == null) {
144 // looks like we have a component without direct relation to composite.. try to solve this
145 // FIXME: use adapter to get composite directly from resource
146 final Resource type = g.getSingleType(diagramOrComposite, sr.Component);
150 final Resource definedBy = g.getPossibleObject(type, sr.IsDefinedBy);
151 if (definedBy == null)
154 this.structuralPath = new ResourceArray(diagramOrComposite);
155 diagram = g.getPossibleObject(definedBy, mr.CompositeToDiagram);
160 Resource possibleSymbol = g.getPossibleObject(diagram, sr.Defines);
161 if(possibleSymbol != null && g.isInstanceOf(possibleSymbol, DIA.ElementClass)) isSymbol = true;
165 this.resource = diagram;
167 } catch (ManyObjectsForFunctionalRelationException e) {
168 // TODO Auto-generated catch block
170 } catch (ServiceException e) {
171 // TODO Auto-generated catch block
173 } catch (NoSingleResultException e) {
174 // TODO Auto-generated catch block
179 public GraphToDiagramSynchronizer getGraphToDiagramSynchronizer() {
183 protected CopyPasteStrategy getCopyPasteStrategy() {
185 CopyPasteStrategy cpStrategy = Simantics.getSession().syncRequest(new PossibleAdapter<CopyPasteStrategy>(resource, CopyPasteStrategy.class));
186 if(cpStrategy != null) return cpStrategy;
187 } catch (DatabaseException e) {
189 return new DefaultCopyPasteStrategy();
192 protected CopyAdvisor getCopyAdvisor() {
194 CopyAdvisor advisor = Simantics.getSession().syncRequest(new PossibleAdapter<CopyAdvisor>(resource, CopyAdvisor.class));
195 if(advisor != null) return advisor;
196 } catch (DatabaseException e) {
198 return new MappedElementCopyAdvisor(new ElementCopyAdvisor(), new ComponentCopyAdvisor());
201 protected void initContext(CanvasContext ctx) {
202 boolean unlock = false;
203 if (!ctx.isLocked()) {
208 IHintContext h = ctx.getDefaultHintContext();
210 // Support & Util Participants
211 ctx.add( new TransformUtil() );
212 ctx.add( new MouseUtil() );
213 ctx.add( new KeyUtil() );
214 ctx.add( new CanvasGrab() );
215 ctx.add( new SymbolUtil() );
216 ctx.add( new TimeParticipant() );
217 ctx.add( new CanvasBoundsParticipant() );
218 ctx.add( new Notifications() );
220 // SGFocusParticipant does not work for remote viewer at the moment.
221 //ctx.add( new SGFocusParticipant() );
223 h.setHint(PointerPainter.KEY_PAINT_POINTER, true);
225 ctx.add( new PanZoomRotateHandler(navigation == null || navigation == true) );
226 ctx.add( new MultitouchPanZoomRotateInteractor() );
227 ctx.add( new ZoomToAreaHandler() );
228 ctx.add( new SimpleElementTransformHandler() );
231 if(navigation == null || navigation == true)
232 ctx.add( new KeyToCommand( CommandKeyBinding.DEFAULT_BINDINGS ) );
234 // Grid & Ruler & Background
235 h.setHint(RulerPainter.KEY_RULER_ENABLED, false);
236 h.setHint(GridPainter.KEY_GRID_ENABLED, false);
238 ctx.add( new GridPainter() );
239 ctx.add( new RulerPainter() );
240 ctx.add( new BackgroundPainter() );
242 h.setHint(Hints.KEY_DISPLAY_PAGE, Boolean.FALSE);
243 h.setHint(Hints.KEY_DISPLAY_MARGINS, Boolean.TRUE);
244 ctx.add( new PageBorderParticipant() );
246 h.setHint(Hints.KEY_GRID_COLOR, new Color(0.95f, 0.95f, 0.95f));
247 h.setHint(Hints.KEY_BACKGROUND_COLOR, Color.WHITE);
248 h.setHint(RulerPainter.KEY_RULER_BACKGROUND_COLOR, new Color(0.9f, 0.9f, 0.9f, 0.75f));
249 h.setHint(RulerPainter.KEY_RULER_TEXT_COLOR, Color.BLACK);
251 ////// Diagram Participants //////
252 ctx.add( new PointerInteractor(false, false, false, false, true, true, synchronizer.getElementClassProvider(), null) );
253 ctx.add( new ElementInteractor() );
254 ctx.add( new Selection() );
255 ctx.add( new DiagramParticipant() );
256 ctx.add( new ElementPainter(true) );
257 ctx.add( new ConnectionCrossingsParticipant(resource));
259 //ctx.add( new ElementHeartbeater() );
260 ctx.add( new ZOrderHandler() );
261 ctx.add( new ZoomTransitionParticipant(TransitionFunction.SIGMOID) );
263 /////// D'n'D ///////
264 ctx.add(new PopulateElementDropParticipant(synchronizer));
265 ctx.add(new PopulateElementMonitorDropParticipant(synchronizer, 0.5, 0.5));
267 h.setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
269 h.setHint(PanZoomRotateHandler.KEY_ZOOM_IN_LIMIT, 1000.0);
270 h.setHint(PanZoomRotateHandler.KEY_ZOOM_OUT_LIMIT, 10.0);
272 // Add visual browsing capabilities for structural models
273 ISessionContext sessionContext = Simantics.getSessionContext();
274 ctx.add(new HeadlessStructuralBrowsingHandler(this, sessionContext, structuralPath));
277 PageDesc pageDesc = PageDesc.DEFAULT.withOrientation(PageOrientation.Landscape);
278 // TODO: load page desc from graph
279 h.setHint(Hints.KEY_PAGE_DESC, pageDesc);
281 ctx.add(new CopyPasteHandler(getCopyPasteStrategy()));
282 ctx.add(new DeleteHandler(null));
284 if (resource != null)
285 loadPageSettings(ctx, resource);
287 ctx.assertParticipantDependencies();
289 ctx.setLocked(false);
292 protected void loadPageSettings(ICanvasContext ctx, Resource diagramResource) {
294 DiagramDesc diagramDesc = Simantics.getSession().syncRequest(DiagramRequests.getDiagramDesc(diagramResource));
295 if (diagramDesc != null)
296 setDiagramDesc(ctx, diagramDesc);
298 // Create a listener to react to page setting changes.
299 Simantics.getSession().asyncRequest(DiagramRequests.getDiagramDesc(diagramResource), new Listener<DiagramDesc>() {
301 public void execute(DiagramDesc result) {
302 if (result != null && ctx != null) {
303 ThreadUtils.asyncExec(ctx.getThreadAccess(), () -> {
305 setDiagramDesc(ctx, result);
312 public void exception(Throwable t) {
313 ErrorLogger.defaultLogError(t);
317 public boolean isDisposed() {
318 return DiagramSceneGraphProvider.this.ctx == null;
321 } catch (DatabaseException e) {
322 ErrorLogger.defaultLogError(e);
326 protected void setDiagramDesc(ICanvasContext ctx, DiagramDesc diagramDesc) {
327 IHintContext hints = ctx.getDefaultHintContext();
328 hints.setHint(Hints.KEY_PAGE_DESC, diagramDesc.getPageDesc());
329 hints.setHint(Hints.KEY_DISPLAY_PAGE, diagramDesc.isPageBordersVisible());
330 hints.setHint(Hints.KEY_DISPLAY_MARGINS, diagramDesc.isMarginsVisible());
334 public G2DSceneGraph initializeSceneGraph(G2DSceneGraph sg) {
335 return initializeSceneGraph(sg, null);
339 public G2DSceneGraph initializeSceneGraph(G2DSceneGraph sg, String view) {
340 return initializeSceneGraph(sg, "", "", view);
344 public G2DSceneGraph initializeSceneGraph(G2DSceneGraph sg, String modelURI, String RVI) {
345 return initializeSceneGraph(sg, modelURI, RVI, "");
349 public G2DSceneGraph initializeSceneGraph(ICanvasContext context, String modelURI, String RVI) {
350 G2DSceneGraph sg = context.getSceneGraph();
351 return initializeSceneGraph(context, sg, modelURI, RVI, "");
357 * @param initialHints
360 private G2DSceneGraph initializeSceneGraph(G2DSceneGraph sg, String modelURI, String RVI, String view) {
361 IThreadWorkQueue thread = AWTThread.getThreadAccess();
362 ctx = new CanvasContext(thread, sg); // By giving the scene graph instance as parameter, we can use external serializer
363 return initializeSceneGraph(ctx, sg, modelURI, RVI, view);
369 * @param initialHints
372 private G2DSceneGraph initializeSceneGraph(ICanvasContext context, G2DSceneGraph sg, String modelURI, String RVI, String view) {
373 this.ctx = (CanvasContext) context;
376 //System.out.println("using layer '"+view+"'");
377 initialHints.setHint(DiagramHints.KEY_FIXED_LAYERS, new String[] { view });
381 fillInitialDiagramHints(initialHints);
383 final RuntimeDiagramManager runtimeDiagramManager = RuntimeDiagramManager.create(Simantics.getSession(), resource, modelURI, RVI);
384 VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
386 synchronizer = Simantics.getSession().syncRequest(new Read<GraphToDiagramSynchronizer>() {
388 public GraphToDiagramSynchronizer perform(ReadGraph graph) throws DatabaseException {
389 DiagramResource dr = DiagramResource.getInstance(graph);
390 Boolean val = graph.getPossibleRelatedValue(resource, dr.NavigationEnabled, Bindings.BOOLEAN);
391 if(val != null && navigation == null) { // Set only if navigation has not been set manually
394 VirtualGraph virtualGraph = support.getGraph(graph, resource);
395 GraphToDiagramSynchronizer sync;
396 if (virtualGraph != null) {
397 sync = new GraphToDiagramSynchronizer(graph, ctx,createElementClassProvider(graph), virtualGraph);
399 sync = new GraphToDiagramSynchronizer(graph, ctx,createElementClassProvider(graph));
402 sync.set(ModelingSynchronizationHints.MODELING_RESOURCE, ModelingResources.getInstance(graph));
403 diagram = sync.loadDiagram(new NullProgressMonitor(), graph, null, resource, runtimeDiagramManager.getRuntimeDiagram(), structuralPath, initialHints); // FIXME
408 } catch (DatabaseException e) {
409 // TODO Auto-generated catch block
412 ctx.getDefaultHintContext().setHint(DiagramHints.KEY_DIAGRAM, diagram);
416 return ctx.getSceneGraph();
419 protected void fillInitialDiagramHints(IHintContext initialHints) throws DatabaseException {
420 IModelingRules modelingRules = Simantics.getSession().syncRequest(DiagramRequests.getModelingRules(resource, null));
421 if (modelingRules != null) {
422 initialHints.setHint(DiagramModelHints.KEY_MODELING_RULES, modelingRules);
425 initialHints.setHint(SynchronizationHints.COPY_ADVISOR, getCopyAdvisor());
428 protected IElementClassProvider createElementClassProvider(ReadGraph graph) throws DatabaseException {
429 DiagramResource dr = DiagramResource.getInstance(graph);
430 return ElementClassProviders.mappedProvider(
431 ElementClasses.CONNECTION, DefaultConnectionClassFactory.CLASS.newClassWith(new StaticObjectAdapter(dr.Connection)),
432 ElementClasses.FLAG, FlagClassFactory.createFlagClass(dr.Flag, dr.Flag_Terminal)
438 public void dispose() {
444 if (synchronizer != null) {
445 synchronizer.dispose();
448 if (diagram != null) {
455 * Hack for returning canvasContext for some special cases
456 * this method brakes the interface, but this is not intended to be used in production context
460 public ICanvasContext getCanvasContext() {
465 public AWTEventListener getEventListener() {
466 if(ctx == null) return null;
467 if(listener == null) {
468 listener = new AWTRemoteEventAdapter(ctx, ctx.getEventQueue());
474 public void updateDiagram(final ResourceArray structuralPath) {
475 final IHintContext hints = new HintContext();
477 System.out.println("using layer '"+view+"'");
478 hints.setHint(DiagramHints.KEY_FIXED_LAYERS, new String[] { view });
482 // FIXME: I have no idea if this works or not..
483 diagram = Simantics.getSession().syncRequest(new Read<IDiagram>() {
485 public IDiagram perform(ReadGraph graph) throws DatabaseException {
486 IDiagram d = synchronizer.loadDiagram(new NullProgressMonitor(), graph, null, structuralPath.resources[0], null, structuralPath.removeFromBeginning(0), hints);
490 ctx.getDefaultHintContext().setHint(DiagramHints.KEY_DIAGRAM, diagram);
491 } catch (DatabaseException e) {
492 // TODO Auto-generated catch block
497 public void setExperiment(ReadGraph g, String identifier) {
498 if(diagram == null) return;
499 diagram.setHint(DiagramModelHints.KEY_ACTIVE_EXPERIMENT, identifier);
500 initialHints.setHint(DiagramModelHints.KEY_ACTIVE_EXPERIMENT, identifier);
503 // DiagramExperiment.setActiveExperiment(g, diagram, (String)identifier);
504 // } catch (DatabaseException e) {
505 // // TODO Auto-generated catch block
506 // e.printStackTrace();
513 * DiagramModelHints.KEY_SESSION_ID
514 * DiagramHints.KEY_NAVIGATION_ENABLED
517 public void setHint(Object key, Object value) {
518 if(DiagramModelHints.KEY_SESSION_ID.equals(key)) {
520 diagram.setHint(DiagramModelHints.KEY_SESSION_ID, value);
521 initialHints.setHint(DiagramModelHints.KEY_SESSION_ID, value);
522 } else if(DiagramModelHints.KEY_ACTIVE_EXPERIMENT.equals(key)) {
524 diagram.setHint(DiagramModelHints.KEY_ACTIVE_EXPERIMENT, value);
525 initialHints.setHint(DiagramModelHints.KEY_ACTIVE_EXPERIMENT, value);
526 } else if(DiagramHints.KEY_NAVIGATION_ENABLED.equals(key)) {
527 navigation = (Boolean)value;