1 /*******************************************************************************
2 * Copyright (c) 2007, 2013 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 * Semantum Oy - issue #4384
12 *******************************************************************************/
13 package org.simantics.modeling.ui.diagramEditor.e4;
15 import java.awt.Color;
16 import java.awt.dnd.DnDConstants;
17 import java.util.Collections;
19 import java.util.concurrent.TimeUnit;
20 import java.util.function.Supplier;
22 import org.eclipse.core.runtime.Assert;
23 import org.eclipse.core.runtime.IAdaptable;
24 import org.eclipse.core.runtime.IProgressMonitor;
25 import org.eclipse.core.runtime.SubMonitor;
26 import org.eclipse.core.runtime.jobs.Job;
27 import org.eclipse.e4.ui.model.application.ui.basic.MPart;
28 import org.eclipse.e4.ui.services.EContextService;
29 import org.eclipse.jface.action.IStatusLineManager;
30 import org.eclipse.jface.resource.JFaceResources;
31 import org.eclipse.jface.resource.LocalResourceManager;
32 import org.eclipse.swt.widgets.Composite;
33 import org.eclipse.swt.widgets.Display;
34 import org.eclipse.swt.widgets.Shell;
35 import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
36 import org.simantics.Simantics;
37 import org.simantics.browsing.ui.model.browsecontexts.BrowseContext;
38 import org.simantics.db.ReadGraph;
39 import org.simantics.db.Resource;
40 import org.simantics.db.Session;
41 import org.simantics.db.WriteGraph;
42 import org.simantics.db.common.primitiverequest.PossibleAdapter;
43 import org.simantics.db.common.procedure.adapter.ListenerDelegate;
44 import org.simantics.db.common.procedure.adapter.ListenerSupport;
45 import org.simantics.db.common.request.ParametrizedRead;
46 import org.simantics.db.common.request.WriteRequest;
47 import org.simantics.db.common.utils.CommonDBUtils;
48 import org.simantics.db.common.utils.TagUtil;
49 import org.simantics.db.exception.DatabaseException;
50 import org.simantics.db.layer0.request.combinations.Combinators;
51 import org.simantics.db.management.ISessionContext;
52 import org.simantics.db.management.ISessionContextProvider;
53 import org.simantics.db.request.Read;
54 import org.simantics.diagram.DiagramTypeUtils;
55 import org.simantics.diagram.adapter.FlagClassFactory;
56 import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;
57 import org.simantics.diagram.adapter.IDiagramLoader;
58 import org.simantics.diagram.connection.ModelledConnectionAdvisor;
59 import org.simantics.diagram.handler.ConnectionCommandHandler;
60 import org.simantics.diagram.handler.CopyPasteStrategy;
61 import org.simantics.diagram.handler.DefaultCopyPasteStrategy;
62 import org.simantics.diagram.handler.DeleteHandler;
63 import org.simantics.diagram.handler.ExpandSelectionHandler;
64 import org.simantics.diagram.handler.SimpleElementTransformHandler;
65 import org.simantics.diagram.handler.e4.CopyPasteHandler;
66 import org.simantics.diagram.layer.ILayersViewPage;
67 import org.simantics.diagram.participant.PointerInteractor2;
68 import org.simantics.diagram.participant.SGFocusParticipant;
69 import org.simantics.diagram.participant.e4.ContextUtil;
70 import org.simantics.diagram.query.DiagramRequests;
71 import org.simantics.diagram.runtime.RuntimeDiagramManager;
72 import org.simantics.diagram.stubs.DiagramResource;
73 import org.simantics.diagram.symbolcontribution.SymbolProviderFactory;
74 import org.simantics.diagram.synchronization.CopyAdvisor;
75 import org.simantics.diagram.synchronization.IModifiableSynchronizationContext;
76 import org.simantics.diagram.synchronization.SynchronizationHints;
77 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
78 import org.simantics.diagram.ui.DiagramModelHints;
79 import org.simantics.diagram.ui.SWTPopupMenuParticipant;
80 import org.simantics.diagram.ui.WorkbenchSelectionProvider;
81 import org.simantics.g2d.canvas.Hints;
82 import org.simantics.g2d.canvas.ICanvasContext;
83 import org.simantics.g2d.canvas.ICanvasParticipant;
84 import org.simantics.g2d.canvas.impl.CanvasContext;
85 import org.simantics.g2d.chassis.AWTChassis;
86 import org.simantics.g2d.chassis.ICanvasChassis;
87 import org.simantics.g2d.chassis.IChassisListener;
88 import org.simantics.g2d.chassis.SWTChassis;
89 import org.simantics.g2d.connection.IConnectionAdvisor;
90 import org.simantics.g2d.diagram.DiagramClass;
91 import org.simantics.g2d.diagram.DiagramHints;
92 import org.simantics.g2d.diagram.IDiagram;
93 import org.simantics.g2d.diagram.handler.PickRequest.PickFilter;
94 import org.simantics.g2d.diagram.impl.Diagram;
95 import org.simantics.g2d.diagram.participant.DelayedBatchElementPainter;
96 import org.simantics.g2d.diagram.participant.DiagramParticipant;
97 import org.simantics.g2d.diagram.participant.ElementInteractor;
98 import org.simantics.g2d.diagram.participant.ElementPainter;
99 import org.simantics.g2d.diagram.participant.Selection;
100 import org.simantics.g2d.diagram.participant.TerminalPainter;
101 import org.simantics.g2d.diagram.participant.ZOrderHandler;
102 import org.simantics.g2d.diagram.participant.pointertool.PointerInteractor;
103 import org.simantics.g2d.element.ElementClassProviders;
104 import org.simantics.g2d.element.ElementClasses;
105 import org.simantics.g2d.element.IElement;
106 import org.simantics.g2d.element.IElementClassProvider;
107 import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;
108 import org.simantics.g2d.elementclass.connection.ConnectionClass;
109 import org.simantics.g2d.page.DiagramDesc;
110 import org.simantics.g2d.participant.BackgroundPainter;
111 import org.simantics.g2d.participant.CanvasBoundsParticipant;
112 import org.simantics.g2d.participant.CanvasGrab;
113 import org.simantics.g2d.participant.GridPainter;
114 import org.simantics.g2d.participant.KeyUtil;
115 import org.simantics.g2d.participant.MouseUtil;
116 import org.simantics.g2d.participant.Notifications;
117 import org.simantics.g2d.participant.PageBorderParticipant;
118 import org.simantics.g2d.participant.PanZoomRotateHandler;
119 import org.simantics.g2d.participant.PointerPainter;
120 import org.simantics.g2d.participant.RenderingQualityInteractor;
121 import org.simantics.g2d.participant.RulerPainter;
122 import org.simantics.g2d.participant.SymbolUtil;
123 import org.simantics.g2d.participant.TimeParticipant;
124 import org.simantics.g2d.participant.TransformUtil;
125 import org.simantics.g2d.participant.WorkbenchStatusLine;
126 import org.simantics.g2d.participant.ZoomToAreaHandler;
127 import org.simantics.g2d.tooltip.TerminalTooltipParticipant;
128 import org.simantics.g2d.utils.CanvasUtils;
129 import org.simantics.layer0.utils.triggers.IActivation;
130 import org.simantics.layer0.utils.triggers.IActivationManager;
131 import org.simantics.modeling.ModelingResources;
132 import org.simantics.modeling.mapping.ComponentCopyAdvisor;
133 import org.simantics.modeling.mapping.ElementCopyAdvisor;
134 import org.simantics.modeling.mapping.MappedElementCopyAdvisor;
135 import org.simantics.modeling.mapping.ModelingSynchronizationHints;
136 import org.simantics.modeling.ui.diagramEditor.DiagramEditorStates;
137 import org.simantics.modeling.ui.diagramEditor.DiagramLayersPage;
138 import org.simantics.modeling.ui.diagramEditor.DiagramOutlinePage;
139 import org.simantics.modeling.ui.diagramEditor.EditorState;
140 import org.simantics.modeling.ui.diagramEditor.PopulateElementMonitorDropParticipant;
141 import org.simantics.modeling.ui.diagramEditor.handlers.e4.LinkBrowsingHandler;
142 import org.simantics.modeling.ui.diagramEditor.handlers.e4.StructuralBrowsingHandler;
143 import org.simantics.modeling.ui.preferences.DiagramPreferenceUtil;
144 import org.simantics.modeling.ui.preferences.DiagramPreferences;
145 import org.simantics.project.ontology.ProjectResource;
146 import org.simantics.scenegraph.INode;
147 import org.simantics.scenegraph.g2d.snap.GridSnapAdvisor;
148 import org.simantics.scenegraph.utils.NodeUtil;
149 import org.simantics.structural.stubs.StructuralResource2;
150 import org.simantics.structural2.modelingRules.IModelingRules;
151 import org.simantics.ui.SimanticsUI;
152 import org.simantics.ui.jobs.SessionGarbageCollectorJob;
153 import org.simantics.ui.workbench.IPropertyPage;
154 import org.simantics.ui.workbench.IResourceEditorInput;
155 import org.simantics.ui.workbench.IResourceEditorInput2;
156 import org.simantics.ui.workbench.TitleRequest;
157 import org.simantics.ui.workbench.TitleUpdater;
158 import org.simantics.ui.workbench.ToolTipRequest;
159 import org.simantics.ui.workbench.editor.input.InputValidationCombinators;
160 import org.simantics.utils.DataContainer;
161 import org.simantics.utils.datastructures.Callback;
162 import org.simantics.utils.datastructures.hints.HintContext;
163 import org.simantics.utils.datastructures.hints.HintListenerAdapter;
164 import org.simantics.utils.datastructures.hints.IHintContext;
165 import org.simantics.utils.datastructures.hints.IHintContext.Key;
166 import org.simantics.utils.datastructures.hints.IHintListener;
167 import org.simantics.utils.datastructures.hints.IHintObservable;
168 import org.simantics.utils.threads.AWTThread;
169 import org.simantics.utils.threads.IThreadWorkQueue;
170 import org.simantics.utils.threads.SWTThread;
171 import org.simantics.utils.threads.ThreadUtils;
172 import org.simantics.utils.ui.ErrorLogger;
173 import org.simantics.utils.ui.ExceptionUtils;
174 import org.simantics.utils.ui.workbench.WorkbenchUtils;
176 import com.kitfox.svg.SVGCache;
179 * @author Toni Kalajainen
180 * @author Tuukka Lehtonen
182 public class DiagramViewer
183 //extends EditorPart implements IResourceEditorPart2,
184 implements ListenerSupport, IAdaptable {
186 public interface DiagramViewerHost {
187 void doSetPartName(String name);
188 void doSetTitleToolTip(String name);
191 public static final String DIAGRAMMING_CONTEXT = "org.simantics.modeling.ui.diagramming";
192 private static final String PREFERENCE_VIRTUAL_GRAPH = "preferences";
194 private static final boolean PROFILE = false;
196 ParametrizedRead<IResourceEditorInput, Boolean> INPUT_VALIDATOR =
198 InputValidationCombinators.or(
199 // Normal configuration diagrams of a model
201 InputValidationCombinators.hasURI(),
202 InputValidationCombinators.partialFunction(ModelingResources.URIs.DiagramToComposite)
204 // Configuration diagrams of a component type
206 InputValidationCombinators.hasURI(),
208 InputValidationCombinators.partialFunction(StructuralResource2.URIs.Defines),
209 InputValidationCombinators.partialFunction(ModelingResources.URIs.DiagramToComposite)
213 InputValidationCombinators.extractInputResource()
216 protected EditorState editorState;
218 protected boolean disposed = false;
219 protected IThreadWorkQueue swt;
220 protected IStatusLineManager statusLineManager;
221 protected Display display;
222 protected LocalResourceManager resourceManager;
223 protected SWTChassis c;
224 protected IDiagram sourceDiagram;
225 protected DataContainer<IDiagram> sourceDiagramContainer = new DataContainer<IDiagram>();
226 protected CanvasContext canvasContext;
227 protected ISessionContextProvider sessionContextProvider;
228 protected ISessionContext sessionContext;
229 protected Resource diagramResource;
230 protected GraphToDiagramSynchronizer synchronizer;
231 protected IActivation activation;
232 protected ContextUtil contextUtil;
233 protected SWTPopupMenuParticipant popupMenuParticipant;
235 protected DiagramPreferences diagramPreferences;
236 protected DiagramDesc diagramDesc;
237 protected GridSnapAdvisor snapAdvisor;
239 private RuntimeDiagramManager runtimeDiagramManager;
241 protected WorkbenchSelectionProvider selectionProvider;
243 public Resource getRuntime() {
244 RuntimeDiagramManager rtdm = runtimeDiagramManager;
245 return (rtdm == null) ? null : rtdm.getRuntimeDiagram();
248 public ParametrizedRead<IResourceEditorInput, Boolean> getInputValidator() {
249 return INPUT_VALIDATOR;
252 protected void addDropParticipants(ICanvasContext ctx) {
253 ctx.getDefaultHintContext().setHint(Hints.KEY_ALLOWED_DRAG_ACTIONS, DnDConstants.ACTION_COPY);
255 ctx.add(new PopulateElementDropParticipant(synchronizer, getPart()));
256 ctx.add(new PopulateElementMonitorDropParticipant(synchronizer, 0.5, 0.5));
259 protected CopyPasteStrategy getCopyPasteStrategy() {
261 CopyPasteStrategy cpStrategy = Simantics.getSession().syncRequest(new PossibleAdapter<CopyPasteStrategy>(getResourceEditorInput().getResource(), CopyPasteStrategy.class));
262 if(cpStrategy != null) return cpStrategy;
263 } catch (DatabaseException e) {
265 return new DefaultCopyPasteStrategy();
268 protected CopyAdvisor getCopyAdvisor() {
270 CopyAdvisor advisor = Simantics.getSession().syncRequest(new PossibleAdapter<CopyAdvisor>(getResourceEditorInput().getResource(), CopyAdvisor.class));
271 if(advisor != null) return advisor;
272 } catch (DatabaseException e) {
274 return new MappedElementCopyAdvisor(new ElementCopyAdvisor(), new ComponentCopyAdvisor());
279 * TODO: change argument from CanvasContext to ICanvasContext
281 protected void addKeyBindingParticipants(CanvasContext ctx) {
282 //ctx.add( new KeyToCommand( CommandKeyBinding.DEFAULT_BINDINGS ) );
283 ctx.add(new DeleteHandler(statusLineManager));
284 ctx.add(new CopyPasteHandler(getCopyPasteStrategy(), statusLineManager).setWorkbenchSite(getPart()));
285 ctx.add(new ConnectionCommandHandler());
288 protected void addPopupmenu(ICanvasContext ctx) {
289 ctx.add(popupMenuParticipant);
292 protected void addWorkbenchSelectionProvider(ICanvasContext ctx) {
293 ctx.add(selectionProvider);
296 protected void addViewManipulationParticipants(CanvasContext ctx) {
297 ctx.add(new PanZoomRotateHandler());
298 //ctx.add(new MousePanZoomInteractor());
299 //ctx.add(new MultitouchPanZoomRotateInteractor());
300 // ctx.add( new OrientationRestorer() );
301 ctx.add(new ZoomToAreaHandler());
304 protected void addDiagramParticipants(ICanvasContext ctx) {
305 ctx.add(new ZOrderHandler());
306 ctx.add(getPointerInteractor());
307 ctx.add(new ElementInteractor());
308 ctx.add(new Selection());
309 ctx.add(new DiagramParticipant());
310 ctx.add(new ElementPainter());
311 //ctx.add(new ElementHeartbeater());
312 //ctx.add(new ZoomTransitionParticipant(TransitionFunction.SIGMOID));
313 //ctx.add(new TooltipParticipant());
314 ctx.add(new TerminalTooltipParticipant());
317 protected void addPainterParticipants(ICanvasContext ctx) {
318 ctx.add(new RenderingQualityInteractor());
319 ctx.add(new TerminalPainter(true, true, false, true));
320 ctx.add(new DelayedBatchElementPainter(PickFilter.FILTER_MONITORS, 500, TimeUnit.MILLISECONDS));
323 protected void addStructureParticipants(ICanvasContext ctx) {
324 addWorkbenchSelectionProvider(ctx);
325 // Add visual browsing capabilities for structural models
326 ctx.add(new StructuralBrowsingHandler(sessionContext, getPart(), getResourceEditorInput()));
327 ctx.add(new LinkBrowsingHandler(this, sessionContext));
331 * Override to add any diagram/canvas participants to the canvas context
332 * initialized for the editor.
336 protected void addOtherParticipants(CanvasContext ctx) {
339 public static Set<String> defaultPropertyBrowseContexts = Collections.singleton(ProjectResource.URIs.ProjectBrowseContext);
341 protected Set<String> getPropertyPageContexts() {
343 return BrowseContext.getBrowseContextClosure(SimanticsUI.getSession(), defaultPropertyBrowseContexts);
344 } catch (DatabaseException e) {
345 ExceptionUtils.logAndShowError("Failed to load modeled browse contexts for property page, see exception for details.", e);
346 return defaultPropertyBrowseContexts;
350 protected IPropertyPage createPropertyPage(MPart part, Set<String> contexts) {
351 // #TODO Finish this when we are going to use full E4 workbench
352 // return new StandardPropertyPage(part, contexts);
356 protected String getPopupId() {
357 return "#ModelingDiagramPopup";
360 protected void getPreferences() {
361 this.diagramPreferences = DiagramPreferenceUtil.getPreferences();
364 protected void initSession() {
365 sessionContextProvider = SimanticsUI.getSessionContextProvider();
366 sessionContext = sessionContextProvider.getSessionContext();
369 protected void readNames() {
370 String name = getResourceEditorInput().getName();
371 host.doSetPartName(name);
372 host.doSetTitleToolTip(name);
375 class ChassisListener implements IChassisListener {
377 public void chassisClosed(ICanvasChassis sender) {
378 // Prevent deadlock while disposing which using syncExec would result in.
379 final ICanvasContext ctx = canvasContext;
380 ThreadUtils.asyncExec(ctx.getThreadAccess(), new Runnable() {
384 saveEditorState(ctx);
385 ctx.getHintStack().removeKeyHintListener(GridPainter.KEY_GRID_ENABLED, canvasHintListener);
386 ctx.getHintStack().removeKeyHintListener(RulerPainter.KEY_RULER_ENABLED, canvasHintListener);
387 final AWTChassis awtChassis = c.getAWTComponent();
388 if (awtChassis != null)
389 awtChassis.setCanvasContext(null);
393 sourceDiagramContainer.set(null);
394 sourceDiagramContainer = null;
396 if (sourceDiagram != null)
397 sourceDiagram.dispose();
399 if(synchronizer != null) {
400 synchronizer.dispose();
405 if (runtimeDiagramManager != null) {
406 runtimeDiagramManager.dispose();
407 runtimeDiagramManager = null;
411 c.removeChassisListener(ChassisListener.this);
415 protected void createChassis(Composite parent) {
416 resourceManager = new LocalResourceManager(JFaceResources.getResources(), parent);
417 c = new SWTChassis(parent, 0);
419 Object task = BEGIN("DV.precreateParticipants");
420 createCustomParticipants();
423 c.populate(component -> {
425 c.addChassisListener(new ChassisListener());
431 protected void beforeSetCanvasContext(ICanvasContext canvasContext2) {
435 * Invoke this only from the AWT thread.
438 protected void setCanvasContext(ICanvasContext context) {
439 // Cannot directly invoke SWTChassis.setCanvasContext only because it
440 // needs to be invoked in the SWT thread and AWTChassis.setCanvasContext in the
441 // AWT thread, but directly invoking SWTChassis.setCanvasContext would call both
442 // in the SWT thread which would cause synchronous scheduling of AWT
443 // runnables which is always a potential source of deadlocks.
444 c.getAWTComponent().setCanvasContext(canvasContext);
445 swt.asyncExec(new Runnable() {
449 // For AWT, this is a no-operation.
450 c.setCanvasContext(canvasContext);
455 public void createPartControl(Composite parent) {
456 //ProfileObserver.begin = System.nanoTime();
457 display = parent.getDisplay();
458 swt = SWTThread.getThreadAccess(display);
459 statusLineManager = WorkbenchUtils.getStatusLine(WorkbenchUtils.getActiveWorkbenchPart());
461 Object task = BEGIN("DV.initSession");
465 diagramResource = getResourceEditorInput().getResource();
469 // DiagramViewerSelectionProvider MUST be created and attached to the
472 // 2. here before returning from createPartControl
473 selectionProvider = createSelectionProvider();
476 this.runtimeDiagramManager = RuntimeDiagramManager.track(sessionContext.getSession(), diagramResource, getResourceEditorInput(), this);
478 // Create the canvas context here before finishing createPartControl
479 // to give DiagramViewerActionContributor a chance to work.
480 // The context can be created in SWT thread without scheduling
481 // to the context thread and having potential deadlocks.
482 IThreadWorkQueue thread = AWTThread.getThreadAccess();
483 this.canvasContext = new CanvasContext(thread);
484 this.canvasContext.setLocked(true);
486 task = BEGIN("DV.createChassis");
487 createChassis(parent);
489 } catch (DatabaseException e) {
490 ErrorLogger.defaultLogError(e);
497 protected WorkbenchSelectionProvider createSelectionProvider() {
498 // #TODO Finish this when we are going to use full E4 workbench
499 // return new DiagramViewerSelectionProvider(swt, getPart(), sourceDiagramContainer);
504 * A method invoked before chassis construction for creating such
505 * {@link ICanvasParticipant}s that need to be constructed in the SWT
508 * Use it for creating any such canvas participants during the viewer
509 * construction and add them to the {@link ICanvasContext} later on from
512 protected void createCustomParticipants() {
513 // #TODO Finish this when we are going to use full E4 workbench
514 // popupMenuParticipant = new SWTPopupMenuParticipant(getPart(), c, display, getPopupId());
518 * Invoke this only from the AWT thread.
520 protected void initializeCanvas() {
521 Object canvasInit = BEGIN("DV.canvasInitialization");
523 Object task = BEGIN("DV.createViewerCanvas");
524 initializeCanvasContext(canvasContext);
527 beforeSetCanvasContext(canvasContext);
528 //FullscreenUtils.addFullScreenHandler(canvasContext, s, canvasProvider);
530 // Without this all diagram participants will crash like there's no tomorrow.
531 // Just trying to keep the behavior a bit more sane in case of
532 // errors instead of flooding the console with exceptions.
533 canvasContext.getDefaultHintContext().setHint(DiagramHints.KEY_DIAGRAM, Diagram.spawnNew(DiagramClass.DEFAULT));
535 // Changes in ruler/grid activity shall be written as
536 // workspace-persistent diagram-specific preferences.
537 canvasContext.getHintStack().addKeyHintListener(GridPainter.KEY_GRID_ENABLED, canvasHintListener);
538 canvasContext.getHintStack().addKeyHintListener(RulerPainter.KEY_RULER_ENABLED, canvasHintListener);
540 task = BEGIN("DV.setCanvasContext");
541 setCanvasContext(canvasContext);
544 // Finish loading in a worker thread because it may be a time consuming
545 // process to load a large diagram and we don't want unnecessary AWT
546 // thread contention.
547 Job loadJob = new DiagramViewerLoadJob(this);
553 protected void activateUiContexts(ContextUtil util) {
554 util.activate(DIAGRAMMING_CONTEXT);
558 * @param monitor the progress monitor to use for reporting progress to the
559 * user. It is the caller's responsibility to call done() on the
560 * given monitor. Accepts <code>null</code>, indicating that no
561 * progress should be reported and that the operation cannot be
564 protected void performActivation(IProgressMonitor monitor) {
565 SubMonitor progress = SubMonitor.convert(monitor, "Activate Mapping", 100);
566 IActivationManager activationManager = sessionContext.getSession().peekService(IActivationManager.class);
567 if (activationManager != null) {
568 activation = activationManager.activate(diagramResource);
570 progress.worked(100);
573 protected void onCreated() {
579 protected void scheduleZoomToFit(IDiagram diagram) {
581 throw new IllegalStateException("diagram is null");
583 CanvasUtils.scheduleZoomToFit(swt, () -> disposed, canvasContext, diagram);
587 * Subclasses may override but should always invoke super.
590 * @param initialHints
591 * @throws DatabaseException
593 protected void fillInitialDiagramHints(Resource diagram, IHintContext initialHints) throws DatabaseException {
594 IModelingRules modelingRules = sessionContext.getSession().syncRequest(
595 DiagramRequests.getModelingRules(diagram, null));
596 if (modelingRules != null) {
597 initialHints.setHint(DiagramModelHints.KEY_MODELING_RULES, modelingRules);
598 initialHints.setHint(DiagramHints.CONNECTION_ADVISOR,
599 getConnectionAdvisor(modelingRules, sessionContext.getSession()));
602 initialHints.setHint(SynchronizationHints.COPY_ADVISOR, getCopyAdvisor());
603 initialHints.setHint(DiagramHints.KEY_USE_CONNECTION_FLAGS, Boolean.TRUE);
604 initialHints.setHint(DiagramHints.KEY_ALLOW_CONNECTION_BRANCHING, Boolean.TRUE);
605 initialHints.setHint(DiagramHints.KEY_ALLOW_ROUTE_POINTS, Boolean.TRUE);
609 * @param monitor the progress monitor to use for reporting progress to the
610 * user. It is the caller's responsibility to call done() on the
611 * given monitor. Accepts <code>null</code>, indicating that no
612 * progress should be reported and that the operation cannot be
616 * @throws DatabaseException
618 protected IDiagram loadDiagram(IProgressMonitor monitor, final Resource r) throws DatabaseException {
619 // Pre-load modeling rules and possibly other hints too since they are
620 // needed already while loading the diagram contents.
621 IHintContext initialHints = new HintContext();
622 fillInitialDiagramHints(r, initialHints);
623 IDiagram d = loadDiagram(monitor, r, initialHints);
628 * @param monitor the progress monitor to use for reporting progress to the
629 * user. It is the caller's responsibility to call done() on the
630 * given monitor. Accepts <code>null</code>, indicating that no
631 * progress should be reported and that the operation cannot be
634 * @param initialHints
636 * @throws DatabaseException
638 protected IDiagram loadDiagram(IProgressMonitor monitor, Resource diagram, IHintContext initialHints) throws DatabaseException {
639 RuntimeDiagramManager rtdm = runtimeDiagramManager;
640 Resource runtimeDiagram = rtdm != null ? rtdm.getRuntimeDiagram() : null;
641 IDiagramLoader loader = synchronizer;
642 if (rtdm == null || runtimeDiagram == null || loader == null)
644 IDiagram d = sessionContext.getSession().syncRequest(
645 DiagramRequests.loadDiagram(monitor, getResourceEditorInput().getModel(null), diagram,
646 runtimeDiagram, null, loader, initialHints));
650 protected void beforeSetDiagram(IDiagram diagram) {
653 protected PointerInteractor getPointerInteractor() {
654 return new PointerInteractor2(true, true, true, false, true, false, synchronizer.getElementClassProvider());
657 protected IConnectionAdvisor getConnectionAdvisor(IModelingRules modelingRules, Session session) {
658 return new ModelledConnectionAdvisor(modelingRules, sessionContext.getSession());
661 protected GraphToDiagramSynchronizer createSynchronizer(final ICanvasContext ctx, final ISessionContext sessionContext) {
663 return sessionContext.getSession().syncRequest(new Read<GraphToDiagramSynchronizer>() {
665 public GraphToDiagramSynchronizer perform(ReadGraph graph) throws DatabaseException {
666 GraphToDiagramSynchronizer sync = new GraphToDiagramSynchronizer(graph, ctx, createElementClassProvider(graph));
667 initializeSynchronizationContext(graph, sync);
671 } catch (DatabaseException e) {
672 throw new UnsupportedOperationException("Failed to initialize data model synchronizer", e);
676 protected void initializeSynchronizationContext(ReadGraph graph, IModifiableSynchronizationContext context) {
677 context.set(ModelingSynchronizationHints.MODELING_RESOURCE, ModelingResources.getInstance(graph));
680 protected IElementClassProvider createElementClassProvider(ReadGraph graph) {
681 DiagramResource dr = DiagramResource.getInstance(graph);
682 return ElementClassProviders.mappedProvider(
683 ElementClasses.CONNECTION, ConnectionClass.CLASS.newClassWith(new StaticObjectAdapter(dr.RouteGraphConnection)),
684 ElementClasses.FLAG, FlagClassFactory.createFlagClass(dr.Flag, dr.Flag_Terminal)
688 protected SimpleElementTransformHandler getTransformHandler() {
689 return new SimpleElementTransformHandler(true, true, true);
692 public void initializeCanvasContext(CanvasContext ctx) {
693 IHintContext h = ctx.getDefaultHintContext();
695 // The canvas context should not be painted until it is ready to avoid
696 // unnecessary visual glitches.
697 h.setHint(Hints.KEY_DISABLE_PAINTING, Boolean.TRUE);
699 Object task = BEGIN("createSynchronizer");
700 this.synchronizer = createSynchronizer(ctx, sessionContext);
703 EContextService contextService = getPart().getContext().get(EContextService.class);
704 contextUtil = new ContextUtil(contextService, swt);
706 // Support & Util Participants
707 ctx.add(new TransformUtil());
708 ctx.add(new MouseUtil());
709 ctx.add(new KeyUtil());
710 ctx.add(contextUtil);
711 ctx.add(new WorkbenchStatusLine(statusLineManager));
712 ctx.add(new CanvasGrab());
713 ctx.add(new SymbolUtil());
714 ctx.add(new TimeParticipant());
715 ctx.add(new CanvasBoundsParticipant());
716 ctx.add(new Notifications());
718 ctx.add(new SGFocusParticipant(c, DIAGRAMMING_CONTEXT));
720 // Debug participant(s)
721 // ctx.add( new PointerPainter() );
722 // ctx.add( new HandPainter() );
723 h.setHint(PointerPainter.KEY_PAINT_POINTER, true);
725 // Pan & Zoom & Rotate
726 addViewManipulationParticipants(ctx);
728 ctx.add(getTransformHandler());
729 ctx.add(new ExpandSelectionHandler(statusLineManager));
732 addKeyBindingParticipants(ctx);
734 // Grid & Ruler & Background
735 ctx.add(new GridPainter());
736 ctx.add(new RulerPainter());
737 ctx.add(new BackgroundPainter());
739 h.setHint(Hints.KEY_DISPLAY_PAGE, diagramPreferences.get(DiagramPreferences.P_DISPLAY_PAGE_SIZE));
740 h.setHint(Hints.KEY_DISPLAY_MARGINS, diagramPreferences.get(DiagramPreferences.P_DISPLAY_MARGINS));
741 ctx.add(new PageBorderParticipant());
743 // h.setHint(Hints.KEY_GRID_COLOR, new Color(0.9f, 0.9f, 0.9f));
744 // h.setHint(Hints.KEY_BACKGROUND_COLOR, Color.LIGHT_GRAY);
745 h.setHint(Hints.KEY_GRID_COLOR, new Color(0.9f, 0.9f, 0.9f));
746 h.setHint(Hints.KEY_BACKGROUND_COLOR, Color.WHITE);
747 h.setHint(RulerPainter.KEY_RULER_BACKGROUND_COLOR, new Color(0.9f, 0.9f, 0.9f, 0.75f));
748 h.setHint(RulerPainter.KEY_RULER_TEXT_COLOR, Color.BLACK);
750 ////// Diagram Participants //////
751 addDiagramParticipants(ctx);
752 addPainterParticipants(ctx);
754 /////// D'n'D ///////
755 addDropParticipants(ctx);
757 h.setHint(ElementPainter.KEY_SELECTION_FRAME_COLOR, Color.MAGENTA);
758 h.setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
760 h.setHint(PanZoomRotateHandler.KEY_ZOOM_IN_LIMIT, 100000.0);
761 h.setHint(PanZoomRotateHandler.KEY_ZOOM_OUT_LIMIT, 10.0);
763 Double snapResolution = diagramPreferences.get(DiagramPreferences.P_SNAP_GRID_SIZE);
764 this.snapAdvisor = new GridSnapAdvisor(snapResolution);
765 h.setHint(DiagramHints.SNAP_ADVISOR, this.snapAdvisor);
766 h.setHint(GridPainter.KEY_GRID_SIZE, snapResolution);
767 h.setHint(GridPainter.KEY_GRID_ENABLED, Boolean.FALSE);
769 // Workbench selection provider
770 addStructureParticipants(ctx);
775 // Load page frame description settings
776 loadPageSettings(ctx);
778 addOtherParticipants(ctx);
780 ctx.assertParticipantDependencies();
781 ctx.setLocked(false);
784 protected void loadPageSettings(ICanvasContext ctx) {
785 DiagramDesc diagramDesc = null;
787 // load diagram page configuration
788 if (diagramResource != null) {
790 diagramDesc = sessionContext.getSession().syncRequest(DiagramRequests.getDiagramDesc(diagramResource));
791 } catch (DatabaseException e) {
792 ErrorLogger.defaultLogError(e);
796 if (diagramDesc == null) {
797 // Take page description from the preferences if nothing else is available.
798 final DiagramDesc desc = diagramDesc = diagramPreferences.getDiagramDesc();
800 // Write page configuration to graph
801 sessionContext.getSession().asyncRequest(new WriteRequest() {
803 public void perform(WriteGraph graph) throws DatabaseException {
804 CommonDBUtils.selectClusterSet(graph, diagramResource);
805 DiagramGraphUtil.setDiagramDesc(graph, diagramResource, desc);
807 }, new Callback<DatabaseException>() {
809 public void run(DatabaseException parameter) {
810 if (parameter != null)
811 ErrorLogger.defaultLogError("Failed to write default diagram page description to database, see exception for details", parameter);
816 setDiagramDesc(ctx, diagramDesc);
818 // Create a listener to react to page setting changes.
819 sessionContext.getSession().asyncRequest(DiagramRequests.getDiagramDesc(diagramResource),
820 new ListenerDelegate<DiagramDesc>(this) {
822 public void execute(final DiagramDesc result) {
823 if (result != null && canvasContext != null) {
824 ThreadUtils.asyncExec(canvasContext.getThreadAccess(), new Runnable() {
828 setDiagramDesc(canvasContext, result);
836 protected void setDiagramDesc(ICanvasContext ctx, DiagramDesc diagramDesc) {
837 if (diagramDesc == null)
838 throw new NullPointerException("null diagram desc");
840 if (diagramDesc.equals(this.diagramDesc))
843 this.diagramDesc = diagramDesc;
844 IHintContext hints = ctx.getDefaultHintContext();
845 hints.setHint(Hints.KEY_PAGE_DESC, diagramDesc.getPageDesc());
846 hints.setHint(Hints.KEY_DISPLAY_PAGE, diagramDesc.isPageBordersVisible());
847 hints.setHint(Hints.KEY_DISPLAY_MARGINS, diagramDesc.isMarginsVisible());
848 hints.setHint(GridPainter.KEY_GRID_ENABLED, diagramDesc.isGridVisible());
849 hints.setHint(RulerPainter.KEY_RULER_ENABLED, diagramDesc.isRulerVisible());
850 snapAdvisor.setResolution(diagramDesc.getGridSize());
851 hints.setHint(GridPainter.KEY_GRID_SIZE, diagramDesc.getGridSize());
855 * Must be invoked from the AWT thread only.
860 protected void applyEditorState(final EditorState state, final ICanvasContext ctx) {
861 final IDiagram diagram = ctx.getHintStack().getHint(DiagramHints.KEY_DIAGRAM);
863 if (state.viewTransform != null && state.viewTransform.getDeterminant() != 0) {
864 for (PanZoomRotateHandler h : ctx.getItemsByClass(PanZoomRotateHandler.class)) {
865 h.setTransform(state.viewTransform);
869 if (diagram != null) {
870 if (state.viewTransform != null)
871 diagram.removeHint(DiagramHints.KEY_INITIAL_ZOOM_TO_FIT);
873 if (state.toolMode != null)
874 ctx.getDefaultHintContext().setHint(Hints.KEY_TOOL, state.toToolMode());
876 ctx.getDefaultHintContext().setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
878 final Set<IElement> selected = DiagramEditorStates.toElements(state.selection, diagram);
879 if (!selected.isEmpty()) {
880 for (Selection s : ctx.getItemsByClass(Selection.class)) {
881 s.setSelection(0, selected);
887 protected EditorState getSavedEditorState(ICanvasContext ctx) {
888 return DiagramEditorStates.toEditorState(ctx, true, true, true);
891 protected void saveEditorState(ICanvasContext ctx) {
892 DiagramEditorStates.saveEditorState(PREFERENCE_VIRTUAL_GRAPH, diagramResource, getSavedEditorState(ctx) , DiagramViewer.this);
895 private boolean firstFocus = true;
897 public void setFocus() {
903 // This is a workaround for using the symbol viewer in multi-page
904 // editors which causes the first zoom-to-fit scheduling to happen
905 // already before the controls have been laid out properly.
914 protected void firstTimeSetFocus() {
915 // [Tuukka@2010-02-11]
916 // Removed since this is actually a workaround for multi-page editors.
917 //scheduleZoomToFit();
920 public void dispose() {
921 // Deactivate all contexts here because after this the context service
922 // in question will not be available.
923 if (contextUtil != null) {
924 contextUtil.deactivateAll();
928 if (activation != null) {
929 activation.deactivate();
933 if (resourceManager != null) {
934 resourceManager.dispose();
935 resourceManager = null;
940 // protected Resource getInputResource() {
941 // return getResourceInput().getResource();
944 // public IResourceEditorInput getResourceInput() {
945 // return (IResourceEditorInput) getEditorInput();
948 // public IResourceEditorInput2 getResourceInput2() {
949 // return (IResourceEditorInput2) getEditorInput();
952 public void init(DiagramViewerHost _host, MPart part, IResourceEditorInput2 input) {
954 if (!(input instanceof IResourceEditorInput))
955 throw new RuntimeException("Invalid input: must be IResourceEditorInput");
959 setResourceEditorInput(input);
961 // Set initial part name according to the name given by IEditorInput
962 host.doSetPartName(getResourceEditorInput().getName());
964 Session session = SimanticsUI.peekSession();
965 if (session != null) {
966 Supplier<Boolean> disposedCallback = () -> disposed;
967 Display display = part.getContext().get(Shell.class).getDisplay();
968 session.asyncRequest(
969 new TitleRequest(part.getElementId(), getResourceEditorInput()),
970 new TitleUpdater(display, host::doSetPartName, disposedCallback));
971 session.asyncRequest(
972 new ToolTipRequest(part.getElementId(), getResourceEditorInput()),
973 new TitleUpdater(display, host::doSetTitleToolTip, disposedCallback));
977 // Read previous editor state from the database
978 editorState = DiagramEditorStates.readEditorState(getResourceEditorInput().getResource());
979 } catch (DatabaseException e) {
984 @SuppressWarnings("rawtypes")
986 public Object getAdapter(Class adapter) {
987 // System.out.println("diagramViewer getAdapter " + adapter);
988 // Property view support
989 if (adapter == IPropertyPage.class)
990 return createPropertyPage(getPart(), getPropertyPageContexts());
991 // Provide symbols for the editor
992 if (adapter == SymbolProviderFactory.class) {
994 return DiagramTypeUtils.readSymbolProviderFactory(sessionContext.getSession(), diagramResource);
995 } catch (DatabaseException e) {
996 ErrorLogger.defaultLogError(getClass() + " failed to adapt to SymbolProviderFactory, see exception for details.", e);
1000 // Outline view support
1001 if (adapter == IContentOutlinePage.class)
1002 return new DiagramOutlinePage(sessionContextProvider, getResourceEditorInput());
1003 // Role view support
1004 if (adapter == ILayersViewPage.class)
1005 return new DiagramLayersPage(sourceDiagram, canvasContext);
1006 // Support external steering of the diagram canvas, zooming etc.
1007 if (adapter == ICanvasContext.class)
1008 return canvasContext;
1009 // Support scene graph debugger view
1010 if (adapter == INode.class) {
1011 if (canvasContext != null) {
1012 INode node = canvasContext.getCanvasNode();
1014 return NodeUtil.getRootNode(node);
1018 // Support retrieval of the current diagram.
1019 if (adapter == IDiagram.class)
1020 return sourceDiagram;
1021 // Why is this here ??
1022 if (adapter == Session.class)
1023 return sessionContext.getSession();
1024 if(adapter == RuntimeDiagramManager.class)
1025 return runtimeDiagramManager;
1026 if (adapter == Resource.class)
1027 return getRuntime();
1028 if (adapter == ICanvasChassis.class)
1034 //-------------------------------------------------------------------------
1037 protected static Object BEGIN(String name) {
1039 //return ThreadLog.BEGIN(name);
1044 protected static void END(Object task) {
1046 //((Task) task).end();
1050 //-------------------------------------------------------------------------
1051 // implement ListenerSupport
1054 public void exception(Throwable t) {
1055 ErrorLogger.defaultLogError(t);
1059 public boolean isDisposed() {
1063 protected void collectGarbage() {
1064 SessionGarbageCollectorJob.getInstance().schedule(0);
1065 AWTThread.getThreadAccess().asyncExec(new Runnable() {
1068 //System.out.println("BEFORE CLEAR: " + SVGCache.getSVGUniverse().report());
1069 SVGCache.getSVGUniverse().clearUnreferenced();
1070 //System.out.println("AFTER CLEAR: " + SVGCache.getSVGUniverse().report());
1075 //-------------------------------------------------------------------------
1076 // Listener for certain canvas context hint changes
1078 IHintListener canvasHintListener = new HintListenerAdapter() {
1080 public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
1081 if (key == GridPainter.KEY_GRID_ENABLED) {
1082 boolean v = Boolean.TRUE.equals(newValue);
1083 if (diagramDesc.isGridVisible() != v)
1084 setGlobalPreference(DiagramResource.URIs.DisplayGrid, v);
1085 } else if (key == RulerPainter.KEY_RULER_ENABLED) {
1086 boolean v = Boolean.TRUE.equals(newValue);
1087 if (diagramDesc.isRulerVisible() != v)
1088 setGlobalPreference(DiagramResource.URIs.DisplayRuler, v);
1093 private <T> void setGlobalPreference(final String preferenceURI, boolean value) {
1094 TagUtil.execute(Simantics.getSession(), PREFERENCE_VIRTUAL_GRAPH, preferenceURI, value, Simantics.getProjectResource());
1098 * --------------------------------------------------------------------
1099 * Changes related to removal of EditorPart extension from here on down
1100 * --------------------------------------------------------------------
1104 private DiagramViewerHost host;
1105 private IResourceEditorInput2 resourceEditorInput = null;
1107 public MPart getPart() {
1111 // public IEditorSite getEditorSite() {
1112 // return (IEditorSite) getSite();
1115 // public IEditorInput getEditorInput() {
1116 // return editorInput;
1119 // protected void setPartName(String partName) {
1120 //// if (compatibilityTitleListener != null) {
1121 //// removePropertyListener(compatibilityTitleListener);
1122 //// compatibilityTitleListener = null;
1125 //// super.setPartName(partName);
1128 // protected void setTitleToolTip(String toolTip) {
1129 //// toolTip = Util.safeString(toolTip);
1130 //// //Do not send changes if they are the same
1131 //// if (Util.equals(this.toolTip, toolTip)) {
1134 //// this.toolTip = toolTip;
1135 //// firePropertyChange(IWorkbenchPart.PROP_TITLE);
1138 protected void setHost(DiagramViewerHost host) {
1142 protected void setPart(MPart part) {
1146 protected void setResourceEditorInput(IResourceEditorInput2 input) {
1147 Assert.isLegal(input != null);
1148 resourceEditorInput = input;
1151 public IResourceEditorInput2 getResourceEditorInput() {
1152 return resourceEditorInput;
1155 public Composite getComposite() {