1 /*******************************************************************************
2 * Copyright (c) 2007, 2019 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, gitlab #399
12 *******************************************************************************/
13 package org.simantics.modeling.ui.diagramEditor;
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.jface.action.IStatusLineManager;
28 import org.eclipse.jface.resource.JFaceResources;
29 import org.eclipse.jface.resource.LocalResourceManager;
30 import org.eclipse.swt.widgets.Composite;
31 import org.eclipse.swt.widgets.Display;
32 import org.eclipse.ui.IEditorInput;
33 import org.eclipse.ui.IEditorSite;
34 import org.eclipse.ui.IWorkbenchPartSite;
35 import org.eclipse.ui.contexts.IContextService;
36 import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
37 import org.simantics.Simantics;
38 import org.simantics.browsing.ui.model.browsecontexts.BrowseContext;
39 import org.simantics.db.ReadGraph;
40 import org.simantics.db.Resource;
41 import org.simantics.db.Session;
42 import org.simantics.db.WriteGraph;
43 import org.simantics.db.common.primitiverequest.PossibleAdapter;
44 import org.simantics.db.common.primitiverequest.PossibleObject;
45 import org.simantics.db.common.procedure.adapter.ListenerDelegate;
46 import org.simantics.db.common.procedure.adapter.ListenerSupport;
47 import org.simantics.db.common.request.ParametrizedRead;
48 import org.simantics.db.common.request.TypeURIs;
49 import org.simantics.db.common.request.WriteRequest;
50 import org.simantics.db.common.utils.CommonDBUtils;
51 import org.simantics.db.common.utils.TagUtil;
52 import org.simantics.db.exception.DatabaseException;
53 import org.simantics.db.layer0.request.combinations.Combinators;
54 import org.simantics.db.management.ISessionContext;
55 import org.simantics.db.management.ISessionContextProvider;
56 import org.simantics.db.request.Read;
57 import org.simantics.diagram.DiagramTypeUtils;
58 import org.simantics.diagram.adapter.FlagClassFactory;
59 import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;
60 import org.simantics.diagram.adapter.IDiagramLoader;
61 import org.simantics.diagram.connection.ModelledConnectionAdvisor;
62 import org.simantics.diagram.handler.ConnectionCommandHandler;
63 import org.simantics.diagram.handler.CopyPasteHandler;
64 import org.simantics.diagram.handler.CopyPasteStrategy;
65 import org.simantics.diagram.handler.DefaultCopyPasteStrategy;
66 import org.simantics.diagram.handler.DeleteHandler;
67 import org.simantics.diagram.handler.ExpandSelectionHandler;
68 import org.simantics.diagram.handler.SimpleElementTransformHandler;
69 import org.simantics.diagram.layer.ILayersViewPage;
70 import org.simantics.diagram.participant.ContextUtil;
71 import org.simantics.diagram.participant.PointerInteractor2;
72 import org.simantics.diagram.participant.SGFocusParticipant;
73 import org.simantics.diagram.query.DiagramRequests;
74 import org.simantics.diagram.runtime.RuntimeDiagramManager;
75 import org.simantics.diagram.stubs.DiagramResource;
76 import org.simantics.diagram.symbolcontribution.SymbolProviderFactory;
77 import org.simantics.diagram.synchronization.CopyAdvisor;
78 import org.simantics.diagram.synchronization.IModifiableSynchronizationContext;
79 import org.simantics.diagram.synchronization.SynchronizationHints;
80 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
81 import org.simantics.diagram.ui.DiagramModelHints;
82 import org.simantics.diagram.ui.SWTPopupMenuParticipant;
83 import org.simantics.diagram.ui.SWTPopupMenuParticipantAwt;
84 import org.simantics.diagram.ui.WorkbenchSelectionProvider;
85 import org.simantics.g2d.canvas.Hints;
86 import org.simantics.g2d.canvas.ICanvasContext;
87 import org.simantics.g2d.canvas.ICanvasParticipant;
88 import org.simantics.g2d.canvas.impl.CanvasContext;
89 import org.simantics.g2d.chassis.AWTChassis;
90 import org.simantics.g2d.chassis.ICanvasChassis;
91 import org.simantics.g2d.chassis.IChassisListener;
92 import org.simantics.g2d.chassis.SWTChassis;
93 import org.simantics.g2d.connection.IConnectionAdvisor;
94 import org.simantics.g2d.diagram.DiagramClass;
95 import org.simantics.g2d.diagram.DiagramHints;
96 import org.simantics.g2d.diagram.IDiagram;
97 import org.simantics.g2d.diagram.handler.PickRequest.PickFilter;
98 import org.simantics.g2d.diagram.impl.Diagram;
99 import org.simantics.g2d.diagram.participant.DelayedBatchElementPainter;
100 import org.simantics.g2d.diagram.participant.DiagramParticipant;
101 import org.simantics.g2d.diagram.participant.ElementInteractor;
102 import org.simantics.g2d.diagram.participant.ElementPainter;
103 import org.simantics.g2d.diagram.participant.Selection;
104 import org.simantics.g2d.diagram.participant.TerminalPainter;
105 import org.simantics.g2d.diagram.participant.ZOrderHandler;
106 import org.simantics.g2d.diagram.participant.pointertool.PointerInteractor;
107 import org.simantics.g2d.element.ElementClassProviders;
108 import org.simantics.g2d.element.ElementClasses;
109 import org.simantics.g2d.element.ElementUtils;
110 import org.simantics.g2d.element.IElement;
111 import org.simantics.g2d.element.IElementClassProvider;
112 import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;
113 import org.simantics.g2d.elementclass.connection.ConnectionClass;
114 import org.simantics.g2d.page.DiagramDesc;
115 import org.simantics.g2d.participant.BackgroundPainter;
116 import org.simantics.g2d.participant.CanvasBoundsParticipant;
117 import org.simantics.g2d.participant.CanvasGrab;
118 import org.simantics.g2d.participant.GridPainter;
119 import org.simantics.g2d.participant.KeyUtil;
120 import org.simantics.g2d.participant.MouseUtil;
121 import org.simantics.g2d.participant.Notifications;
122 import org.simantics.g2d.participant.PageBorderParticipant;
123 import org.simantics.g2d.participant.PanZoomRotateHandler;
124 import org.simantics.g2d.participant.PointerPainter;
125 import org.simantics.g2d.participant.RenderingQualityInteractor;
126 import org.simantics.g2d.participant.RulerPainter;
127 import org.simantics.g2d.participant.SymbolUtil;
128 import org.simantics.g2d.participant.TimeParticipant;
129 import org.simantics.g2d.participant.TransformUtil;
130 import org.simantics.g2d.participant.WorkbenchStatusLine;
131 import org.simantics.g2d.participant.ZoomToAreaHandler;
132 import org.simantics.g2d.tooltip.TerminalTooltipParticipant;
133 import org.simantics.g2d.utils.CanvasUtils;
134 import org.simantics.layer0.utils.triggers.IActivation;
135 import org.simantics.layer0.utils.triggers.IActivationManager;
136 import org.simantics.modeling.ModelingResources;
137 import org.simantics.modeling.mapping.ComponentCopyAdvisor;
138 import org.simantics.modeling.mapping.ElementCopyAdvisor;
139 import org.simantics.modeling.mapping.MappedElementCopyAdvisor;
140 import org.simantics.modeling.mapping.ModelingSynchronizationHints;
141 import org.simantics.modeling.ui.diagramEditor.handlers.LinkBrowsingHandler;
142 import org.simantics.modeling.ui.diagramEditor.handlers.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.selectionview.StandardPropertyPage;
150 import org.simantics.structural.stubs.StructuralResource2;
151 import org.simantics.structural2.modelingRules.IModelingRules;
152 import org.simantics.ui.SimanticsUI;
153 import org.simantics.ui.jobs.SessionGarbageCollectorJob;
154 import org.simantics.ui.workbench.IPropertyPage;
155 import org.simantics.ui.workbench.IResourceEditorInput;
156 import org.simantics.ui.workbench.IResourceEditorInput2;
157 import org.simantics.ui.workbench.TitleRequest;
158 import org.simantics.ui.workbench.TitleUpdater;
159 import org.simantics.ui.workbench.ToolTipRequest;
160 import org.simantics.ui.workbench.editor.input.InputValidationCombinators;
161 import org.simantics.utils.DataContainer;
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;
175 import com.kitfox.svg.SVGCache;
178 * @author Toni Kalajainen
179 * @author Tuukka Lehtonen
181 public class DiagramViewer
182 //extends EditorPart implements IResourceEditorPart2,
183 implements ListenerSupport, IAdaptable {
185 public interface DiagramViewerHost {
186 void doSetPartName(String name);
187 void doSetTitleToolTip(String name);
190 public static final String DIAGRAMMING_CONTEXT = "org.simantics.modeling.ui.diagramming";
191 private static final String PREFERENCE_VIRTUAL_GRAPH = "preferences";
193 private static final boolean PROFILE = false;
195 ParametrizedRead<IResourceEditorInput, Boolean> INPUT_VALIDATOR =
197 InputValidationCombinators.or(
198 // Normal configuration diagrams of a model
200 InputValidationCombinators.hasURI(),
201 InputValidationCombinators.partialFunction(ModelingResources.URIs.DiagramToComposite)
203 // Configuration diagrams of a component type
205 InputValidationCombinators.hasURI(),
207 InputValidationCombinators.partialFunction(StructuralResource2.URIs.Defines),
208 InputValidationCombinators.partialFunction(ModelingResources.URIs.DiagramToComposite)
212 InputValidationCombinators.extractInputResource()
215 protected EditorState editorState;
217 protected boolean disposed = false;
218 protected IThreadWorkQueue swt;
219 protected IStatusLineManager statusLineManager;
220 protected Display display;
221 protected LocalResourceManager resourceManager;
222 protected SWTChassis c;
223 protected IDiagram sourceDiagram;
224 protected DataContainer<IDiagram> sourceDiagramContainer;
225 protected CanvasContext canvasContext;
226 protected ISessionContextProvider sessionContextProvider;
227 protected ISessionContext sessionContext;
228 protected Resource diagramResource;
229 protected GraphToDiagramSynchronizer synchronizer;
230 protected IActivation activation;
231 protected ContextUtil contextUtil;
232 protected SWTPopupMenuParticipant popupMenuParticipant;
234 protected DiagramPreferences diagramPreferences;
235 protected DiagramDesc diagramDesc;
236 protected GridSnapAdvisor snapAdvisor;
238 private RuntimeDiagramManager runtimeDiagramManager;
239 private Resource runtimeDiagramResourceCache;
240 private HasDiagramSourceListener hasDiagramSourceListener;
244 * {@link #init(DiagramViewerHost, IEditorSite, IEditorInput, DataContainer, WorkbenchSelectionProvider)}
247 protected WorkbenchSelectionProvider selectionProvider;
249 protected Resource getRuntimeFromManager() {
250 RuntimeDiagramManager rtdm = runtimeDiagramManager;
251 return (rtdm == null) ? null : rtdm.getRuntimeDiagram();
254 public Resource getRuntime() {
255 if (runtimeDiagramResourceCache != null)
256 return runtimeDiagramResourceCache;
257 runtimeDiagramResourceCache = getRuntimeFromManager();
258 return runtimeDiagramResourceCache;
261 public ParametrizedRead<IResourceEditorInput, Boolean> getInputValidator() {
262 return INPUT_VALIDATOR;
265 protected void addDropParticipants(ICanvasContext ctx) {
266 ctx.getDefaultHintContext().setHint(Hints.KEY_ALLOWED_DRAG_ACTIONS, DnDConstants.ACTION_COPY);
268 ctx.add(new PopulateElementDropParticipant(synchronizer, getSite()));
269 ctx.add(new PopulateElementMonitorDropParticipant(synchronizer, 0.5, 0.5));
272 protected CopyPasteStrategy getCopyPasteStrategy() {
274 CopyPasteStrategy cpStrategy = Simantics.getSession().syncRequest(new PossibleAdapter<CopyPasteStrategy>(getInputResource(), CopyPasteStrategy.class));
275 if(cpStrategy != null) return cpStrategy;
276 } catch (DatabaseException e) {
278 return getDefaultCopyPasteStrategy();
281 protected CopyPasteStrategy getDefaultCopyPasteStrategy() {
282 return new DefaultCopyPasteStrategy();
285 protected CopyAdvisor getCopyAdvisor() {
287 CopyAdvisor advisor = Simantics.getSession().syncRequest(new PossibleAdapter<CopyAdvisor>(getInputResource(), CopyAdvisor.class));
288 if(advisor != null) return advisor;
289 } catch (DatabaseException e) {
291 return new MappedElementCopyAdvisor(new ElementCopyAdvisor(), new ComponentCopyAdvisor());
296 * TODO: change argument from CanvasContext to ICanvasContext
298 protected void addKeyBindingParticipants(CanvasContext ctx) {
299 //ctx.add( new KeyToCommand( CommandKeyBinding.DEFAULT_BINDINGS ) );
300 ctx.add(new DeleteHandler(statusLineManager));
301 ctx.add(new CopyPasteHandler(getCopyPasteStrategy(), statusLineManager).setWorkbenchSite(getEditorSite()));
302 ctx.add(new ConnectionCommandHandler());
305 protected void addPopupmenu(ICanvasContext ctx) {
306 ctx.add(popupMenuParticipant);
309 protected void addWorkbenchSelectionProvider(ICanvasContext ctx) {
310 if (selectionProvider != null)
311 ctx.add(selectionProvider);
314 protected void addViewManipulationParticipants(CanvasContext ctx) {
315 ctx.add(new PanZoomRotateHandler());
316 //ctx.add(new MousePanZoomInteractor());
317 //ctx.add(new MultitouchPanZoomRotateInteractor());
318 // ctx.add( new OrientationRestorer() );
319 ctx.add(new ZoomToAreaHandler());
322 protected void addDiagramParticipants(ICanvasContext ctx) {
323 ctx.add(new ZOrderHandler());
324 ctx.add(getPointerInteractor());
325 ctx.add(new ElementInteractor());
326 ctx.add(new Selection());
327 ctx.add(new DiagramParticipant());
328 ctx.add(new ElementPainter());
329 //ctx.add(new ElementHeartbeater());
330 //ctx.add(new ZoomTransitionParticipant(TransitionFunction.SIGMOID));
331 //ctx.add(new TooltipParticipant());
332 ctx.add(new TerminalTooltipParticipant());
335 protected void addPainterParticipants(ICanvasContext ctx) {
336 ctx.add(new RenderingQualityInteractor());
337 ctx.add(new TerminalPainter(true, true, false, true));
338 ctx.add(new DelayedBatchElementPainter(PickFilter.FILTER_MONITORS, 500, TimeUnit.MILLISECONDS));
341 protected void addStructureParticipants(ICanvasContext ctx) {
342 addWorkbenchSelectionProvider(ctx);
343 // Add visual browsing capabilities for structural models
344 ctx.add(new StructuralBrowsingHandler(getSite(), sessionContext, getResourceInput2()));
345 ctx.add(new LinkBrowsingHandler(getSite(), this, sessionContext));
349 * Override to add any diagram/canvas participants to the canvas context
350 * initialized for the editor.
354 protected void addOtherParticipants(CanvasContext ctx) {
357 public static Set<String> defaultPropertyBrowseContexts = Collections.singleton(ProjectResource.URIs.ProjectBrowseContext);
359 protected Set<String> getPropertyPageContexts() {
361 return BrowseContext.getBrowseContextClosure(SimanticsUI.getSession(), defaultPropertyBrowseContexts);
362 } catch (DatabaseException e) {
363 ExceptionUtils.logAndShowError("Failed to load modeled browse contexts for property page, see exception for details.", e);
364 return defaultPropertyBrowseContexts;
368 protected IPropertyPage createPropertyPage(IWorkbenchPartSite site, Set<String> contexts) {
369 return new StandardPropertyPage(site, contexts);
372 protected String getPopupId() {
373 return "#ModelingDiagramPopup";
376 protected void getPreferences() {
377 this.diagramPreferences = DiagramPreferenceUtil.getPreferences();
380 protected void initSession() {
381 sessionContextProvider = SimanticsUI.getSessionContextProvider();
382 sessionContext = sessionContextProvider.getSessionContext();
385 protected void readNames() {
386 String name = getEditorInput().getName();
387 host.doSetPartName(name);
388 host.doSetTitleToolTip(name);
391 class ChassisListener implements IChassisListener {
393 public void chassisClosed(ICanvasChassis sender) {
394 // Prevent deadlock while disposing which using syncExec would result in.
395 final ICanvasContext ctx = canvasContext;
396 ThreadUtils.asyncExec(ctx.getThreadAccess(), new Runnable() {
400 saveEditorState(ctx);
401 ctx.getHintStack().removeKeyHintListener(GridPainter.KEY_GRID_ENABLED, canvasHintListener);
402 ctx.getHintStack().removeKeyHintListener(RulerPainter.KEY_RULER_ENABLED, canvasHintListener);
403 final AWTChassis awtChassis = c.getAWTComponent();
404 if (awtChassis != null)
405 awtChassis.setCanvasContext(null);
409 if (sourceDiagramContainer != null) {
410 sourceDiagramContainer.set(null);
411 sourceDiagramContainer = null;
414 if (sourceDiagram != null)
415 sourceDiagram.dispose();
417 if(synchronizer != null) {
418 synchronizer.dispose();
423 if (runtimeDiagramManager != null) {
424 runtimeDiagramManager.dispose();
425 runtimeDiagramManager = null;
429 c.removeChassisListener(ChassisListener.this);
433 protected void createChassis(Composite parent) {
434 resourceManager = new LocalResourceManager(JFaceResources.getResources(), parent);
435 c = new SWTChassis(parent, 0);
437 Object task = BEGIN("DV.precreateParticipants");
438 createCustomParticipants();
441 c.populate(component -> {
443 c.addChassisListener(new ChassisListener());
449 protected void beforeSetCanvasContext(ICanvasContext canvasContext2) {
453 * Invoke this only from the AWT thread.
456 protected void setCanvasContext(ICanvasContext context) {
457 // Cannot directly invoke SWTChassis.setCanvasContext only because it
458 // needs to be invoked in the SWT thread and AWTChassis.setCanvasContext in the
459 // AWT thread, but directly invoking SWTChassis.setCanvasContext would call both
460 // in the SWT thread which would cause synchronous scheduling of AWT
461 // runnables which is always a potential source of deadlocks.
462 c.getAWTComponent().setCanvasContext(canvasContext);
463 swt.asyncExec(new Runnable() {
467 // For AWT, this is a no-operation.
468 c.setCanvasContext(canvasContext);
473 public void createPartControl(Composite parent) {
474 //ProfileObserver.begin = System.nanoTime();
475 display = parent.getDisplay();
476 swt = SWTThread.getThreadAccess(display);
477 statusLineManager = getEditorSite().getActionBars().getStatusLineManager();
479 Object task = BEGIN("DV.initSession");
483 diagramResource = getInputResource();
488 this.runtimeDiagramManager = RuntimeDiagramManager.track(sessionContext.getSession(), diagramResource, getEditorInput(), this);
490 // Create the canvas context here before finishing createPartControl
491 // to give DiagramViewerActionContributor a chance to work.
492 // The context can be created in SWT thread without scheduling
493 // to the context thread and having potential deadlocks.
494 IThreadWorkQueue thread = AWTThread.getThreadAccess();
495 this.canvasContext = new CanvasContext(thread);
496 this.canvasContext.setLocked(true);
498 task = BEGIN("DV.createChassis");
499 createChassis(parent);
501 } catch (DatabaseException e) {
502 ErrorLogger.defaultLogError(e);
508 * A method invoked before chassis construction for creating such
509 * {@link ICanvasParticipant}s that need to be constructed in the SWT
512 * Use it for creating any such canvas participants during the viewer
513 * construction and add them to the {@link ICanvasContext} later on from
516 protected void createCustomParticipants() {
517 if (SimanticsUI.isLinuxGTK()) {
518 popupMenuParticipant = new SWTPopupMenuParticipantAwt(getSite(), c, display, getPopupId());
520 popupMenuParticipant = new SWTPopupMenuParticipant(getSite(), c, display, getPopupId());
525 * Invoke this only from the AWT thread.
527 protected void initializeCanvas() {
528 Object canvasInit = BEGIN("DV.canvasInitialization");
530 Object task = BEGIN("DV.createViewerCanvas");
531 initializeCanvasContext(canvasContext);
534 beforeSetCanvasContext(canvasContext);
535 //FullscreenUtils.addFullScreenHandler(canvasContext, s, canvasProvider);
537 // Without this all diagram participants will crash like there's no tomorrow.
538 // Just trying to keep the behavior a bit more sane in case of
539 // errors instead of flooding the console with exceptions.
540 canvasContext.getDefaultHintContext().setHint(DiagramHints.KEY_DIAGRAM, Diagram.spawnNew(DiagramClass.DEFAULT));
542 // Changes in ruler/grid activity shall be written as
543 // workspace-persistent diagram-specific preferences.
544 canvasContext.getHintStack().addKeyHintListener(GridPainter.KEY_GRID_ENABLED, canvasHintListener);
545 canvasContext.getHintStack().addKeyHintListener(RulerPainter.KEY_RULER_ENABLED, canvasHintListener);
547 task = BEGIN("DV.setCanvasContext");
548 setCanvasContext(canvasContext);
551 // Finish loading in a worker thread because it may be a time consuming
552 // process to load a large diagram and we don't want unnecessary AWT
553 // thread contention.
554 Job loadJob = new DiagramViewerLoadJob(this);
560 protected void activateUiContexts(ContextUtil util) {
561 util.activate(DIAGRAMMING_CONTEXT);
565 * @param monitor the progress monitor to use for reporting progress to the
566 * user. It is the caller's responsibility to call done() on the
567 * given monitor. Accepts <code>null</code>, indicating that no
568 * progress should be reported and that the operation cannot be
571 protected void performActivation(IProgressMonitor monitor) {
572 SubMonitor progress = SubMonitor.convert(monitor, "Activate Mapping", 100);
573 IActivationManager activationManager = sessionContext.getSession().peekService(IActivationManager.class);
574 if (activationManager != null) {
575 activation = activationManager.activate(diagramResource);
577 progress.worked(100);
580 protected void onCreated() {
586 protected void scheduleZoomToFit(IDiagram diagram) {
588 throw new IllegalStateException("diagram is null");
590 CanvasUtils.scheduleZoomToFit(swt, () -> disposed, canvasContext, diagram);
594 * Subclasses may override but should always invoke super.
597 * @param initialHints
598 * @throws DatabaseException
600 protected void fillInitialDiagramHints(Resource diagram, IHintContext initialHints) throws DatabaseException {
601 IModelingRules modelingRules = sessionContext.getSession().syncRequest(
602 DiagramRequests.getModelingRules(diagram, null));
603 if (modelingRules != null) {
604 initialHints.setHint(DiagramModelHints.KEY_MODELING_RULES, modelingRules);
605 initialHints.setHint(DiagramHints.CONNECTION_ADVISOR,
606 getConnectionAdvisor(modelingRules, sessionContext.getSession()));
609 initialHints.setHint(SynchronizationHints.COPY_ADVISOR, getCopyAdvisor());
610 initialHints.setHint(DiagramHints.KEY_USE_CONNECTION_FLAGS, Boolean.TRUE);
611 initialHints.setHint(DiagramHints.KEY_ALLOW_CONNECTION_BRANCHING, Boolean.TRUE);
612 initialHints.setHint(DiagramHints.KEY_ALLOW_ROUTE_POINTS, Boolean.TRUE);
616 * @param monitor the progress monitor to use for reporting progress to the
617 * user. It is the caller's responsibility to call done() on the
618 * given monitor. Accepts <code>null</code>, indicating that no
619 * progress should be reported and that the operation cannot be
623 * @throws DatabaseException
625 protected IDiagram loadDiagram(IProgressMonitor monitor, final Resource r) throws DatabaseException {
626 // Pre-load modeling rules and possibly other hints too since they are
627 // needed already while loading the diagram contents.
628 IHintContext initialHints = new HintContext();
629 fillInitialDiagramHints(r, initialHints);
630 IDiagram d = loadDiagram(monitor, r, initialHints);
635 * @param monitor the progress monitor to use for reporting progress to the
636 * user. It is the caller's responsibility to call done() on the
637 * given monitor. Accepts <code>null</code>, indicating that no
638 * progress should be reported and that the operation cannot be
641 * @param initialHints
643 * @throws DatabaseException
645 protected IDiagram loadDiagram(IProgressMonitor monitor, Resource diagram, IHintContext initialHints) throws DatabaseException {
646 RuntimeDiagramManager rtdm = runtimeDiagramManager;
647 Resource runtimeDiagram = rtdm != null ? rtdm.getRuntimeDiagram() : null;
648 IDiagramLoader loader = synchronizer;
649 if (rtdm == null || runtimeDiagram == null || loader == null)
651 IDiagram d = sessionContext.getSession().syncRequest((Read<IDiagram>) graph -> {
652 IDiagram result = DiagramRequests.loadDiagram(monitor, getResourceInput2().getModel(null), diagram,
653 runtimeDiagram, null, loader, initialHints).perform(graph);
655 // #399: Enable certain PropertyTester implementation without database transactions
656 ModelingResources MOD = ModelingResources.getInstance(graph);
657 Resource composite = graph.getPossibleObject(diagram, MOD.DiagramToComposite);
659 DiagramModelHints.KEY_DIAGRAM_RESOURCE_TYPE_URIS,
660 graph.syncRequest(new TypeURIs(diagram)));
662 DiagramModelHints.KEY_MAPPED_COMPOSITE_RESOURCE_TYPE_URIS,
663 composite != null ? graph.syncRequest(new TypeURIs(composite)) : Collections.emptySet());
665 Resource diagramSource = graph.syncRequest(
666 new PossibleObject(diagram, MOD.HasDiagramSource),
667 hasDiagramSourceListener = new HasDiagramSourceListener(sourceDiagramContainer));
668 ElementUtils.setOrRemoveHint(
670 DiagramModelHints.KEY_HAS_DIAGRAM_SOURCE,
678 protected void beforeSetDiagram(IDiagram diagram) {
681 protected PointerInteractor getPointerInteractor() {
682 return new PointerInteractor2(true, true, true, false, true, false, synchronizer.getElementClassProvider());
685 protected IConnectionAdvisor getConnectionAdvisor(IModelingRules modelingRules, Session session) {
686 return new ModelledConnectionAdvisor(modelingRules, sessionContext.getSession());
689 protected GraphToDiagramSynchronizer createSynchronizer(final ICanvasContext ctx, final ISessionContext sessionContext) {
691 return sessionContext.getSession().syncRequest(new Read<GraphToDiagramSynchronizer>() {
693 public GraphToDiagramSynchronizer perform(ReadGraph graph) throws DatabaseException {
694 GraphToDiagramSynchronizer sync = new GraphToDiagramSynchronizer(graph, ctx, createElementClassProvider(graph));
695 initializeSynchronizationContext(graph, sync);
699 } catch (DatabaseException e) {
700 throw new UnsupportedOperationException("Failed to initialize data model synchronizer", e);
704 protected void initializeSynchronizationContext(ReadGraph graph, IModifiableSynchronizationContext context) {
705 context.set(ModelingSynchronizationHints.MODELING_RESOURCE, ModelingResources.getInstance(graph));
708 protected IElementClassProvider createElementClassProvider(ReadGraph graph) {
709 DiagramResource dr = DiagramResource.getInstance(graph);
710 return ElementClassProviders.mappedProvider(
711 ElementClasses.CONNECTION, ConnectionClass.CLASS.newClassWith(new StaticObjectAdapter(dr.RouteGraphConnection)),
712 ElementClasses.FLAG, FlagClassFactory.createFlagClass(dr.Flag, dr.Flag_Terminal)
716 protected SimpleElementTransformHandler getTransformHandler() {
717 return new SimpleElementTransformHandler(true, true, true);
720 public void initializeCanvasContext(CanvasContext ctx) {
721 IHintContext h = ctx.getDefaultHintContext();
723 // The canvas context should not be painted until it is ready to avoid
724 // unnecessary visual glitches.
725 h.setHint(Hints.KEY_DISABLE_PAINTING, Boolean.TRUE);
727 Object task = BEGIN("createSynchronizer");
728 this.synchronizer = createSynchronizer(ctx, sessionContext);
731 IContextService contextService = (IContextService) getSite().getService(IContextService.class);
732 contextUtil = new ContextUtil(contextService, swt);
734 // Support & Util Participants
735 ctx.add(new TransformUtil());
736 ctx.add(new MouseUtil());
737 ctx.add(new KeyUtil());
738 ctx.add(contextUtil);
739 ctx.add(new WorkbenchStatusLine(statusLineManager));
740 ctx.add(new CanvasGrab());
741 ctx.add(new SymbolUtil());
742 ctx.add(new TimeParticipant());
743 ctx.add(new CanvasBoundsParticipant());
744 ctx.add(new Notifications());
746 ctx.add(new SGFocusParticipant(c, DIAGRAMMING_CONTEXT));
748 // Debug participant(s)
749 // ctx.add( new PointerPainter() );
750 // ctx.add( new HandPainter() );
751 h.setHint(PointerPainter.KEY_PAINT_POINTER, true);
753 // Pan & Zoom & Rotate
754 addViewManipulationParticipants(ctx);
756 ctx.add(getTransformHandler());
757 ctx.add(new ExpandSelectionHandler(getEditorSite().getActionBars().getStatusLineManager()));
760 addKeyBindingParticipants(ctx);
762 // Grid & Ruler & Background
763 addGridRulerBackgroundParticipants(ctx);
765 h.setHint(Hints.KEY_DISPLAY_PAGE, diagramPreferences.get(DiagramPreferences.P_DISPLAY_PAGE_SIZE));
766 h.setHint(Hints.KEY_DISPLAY_MARGINS, diagramPreferences.get(DiagramPreferences.P_DISPLAY_MARGINS));
767 ctx.add(new PageBorderParticipant());
769 // h.setHint(Hints.KEY_GRID_COLOR, new Color(0.9f, 0.9f, 0.9f));
770 // h.setHint(Hints.KEY_BACKGROUND_COLOR, Color.LIGHT_GRAY);
771 h.setHint(Hints.KEY_GRID_COLOR, new Color(0.9f, 0.9f, 0.9f));
772 h.setHint(Hints.KEY_BACKGROUND_COLOR, Color.WHITE);
773 h.setHint(RulerPainter.KEY_RULER_BACKGROUND_COLOR, new Color(0.9f, 0.9f, 0.9f, 0.75f));
774 h.setHint(RulerPainter.KEY_RULER_TEXT_COLOR, Color.BLACK);
776 ////// Diagram Participants //////
777 addDiagramParticipants(ctx);
778 addPainterParticipants(ctx);
780 /////// D'n'D ///////
781 addDropParticipants(ctx);
783 h.setHint(ElementPainter.KEY_SELECTION_FRAME_COLOR, Color.MAGENTA);
784 h.setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
786 h.setHint(PanZoomRotateHandler.KEY_ZOOM_IN_LIMIT, 100000.0);
787 h.setHint(PanZoomRotateHandler.KEY_ZOOM_OUT_LIMIT, 10.0);
789 Double snapResolution = diagramPreferences.get(DiagramPreferences.P_SNAP_GRID_SIZE);
790 this.snapAdvisor = new GridSnapAdvisor(snapResolution);
791 h.setHint(DiagramHints.SNAP_ADVISOR, this.snapAdvisor);
792 h.setHint(GridPainter.KEY_GRID_SIZE, snapResolution);
793 h.setHint(GridPainter.KEY_GRID_ENABLED, Boolean.FALSE);
795 // Workbench selection provider
796 addStructureParticipants(ctx);
801 // Load page frame description settings
802 loadPageSettings(ctx);
804 addOtherParticipants(ctx);
806 ctx.assertParticipantDependencies();
807 ctx.setLocked(false);
810 protected void addGridRulerBackgroundParticipants(CanvasContext ctx) {
811 ctx.add(new GridPainter());
812 ctx.add(new RulerPainter());
813 ctx.add(new BackgroundPainter());
816 protected void loadPageSettings(ICanvasContext ctx) {
817 DiagramDesc diagramDesc = null;
819 // load diagram page configuration
820 if (diagramResource != null) {
822 diagramDesc = sessionContext.getSession().syncRequest(DiagramRequests.getDiagramDesc(diagramResource));
823 } catch (DatabaseException e) {
824 ErrorLogger.defaultLogError(e);
828 if (diagramDesc == null) {
829 // Take page description from the preferences if nothing else is available.
830 final DiagramDesc desc = diagramDesc = diagramPreferences.getDiagramDesc();
832 // Write page configuration to graph
833 sessionContext.getSession().asyncRequest(new WriteRequest() {
835 public void perform(WriteGraph graph) throws DatabaseException {
836 if (graph.isImmutable(diagramResource))
838 CommonDBUtils.selectClusterSet(graph, diagramResource);
839 DiagramGraphUtil.setDiagramDesc(graph, diagramResource, desc);
842 if (parameter != null)
843 ErrorLogger.defaultLogError("Failed to write default diagram page description to database, see exception for details", parameter);
847 setDiagramDesc(ctx, diagramDesc);
849 // Create a listener to react to page setting changes.
850 sessionContext.getSession().asyncRequest(DiagramRequests.getDiagramDesc(diagramResource),
851 new ListenerDelegate<DiagramDesc>(this) {
853 public void execute(final DiagramDesc result) {
854 if (result != null && canvasContext != null) {
855 ThreadUtils.asyncExec(canvasContext.getThreadAccess(), new Runnable() {
859 setDiagramDesc(canvasContext, result);
867 protected void setDiagramDesc(ICanvasContext ctx, DiagramDesc diagramDesc) {
868 if (diagramDesc == null)
869 throw new NullPointerException("null diagram desc");
871 if (diagramDesc.equals(this.diagramDesc))
874 this.diagramDesc = diagramDesc;
875 IHintContext hints = ctx.getDefaultHintContext();
876 hints.setHint(Hints.KEY_PAGE_DESC, diagramDesc.getPageDesc());
877 hints.setHint(Hints.KEY_DISPLAY_PAGE, diagramDesc.isPageBordersVisible());
878 hints.setHint(Hints.KEY_DISPLAY_MARGINS, diagramDesc.isMarginsVisible());
879 hints.setHint(GridPainter.KEY_GRID_ENABLED, diagramDesc.isGridVisible());
880 hints.setHint(RulerPainter.KEY_RULER_ENABLED, diagramDesc.isRulerVisible());
881 snapAdvisor.setResolution(diagramDesc.getGridSize());
882 hints.setHint(GridPainter.KEY_GRID_SIZE, diagramDesc.getGridSize());
886 * Must be invoked from the AWT thread only.
891 protected void applyEditorState(final EditorState state, final ICanvasContext ctx) {
892 final IDiagram diagram = ctx.getHintStack().getHint(DiagramHints.KEY_DIAGRAM);
894 if (state.viewTransform != null && state.viewTransform.getDeterminant() != 0) {
895 for (PanZoomRotateHandler h : ctx.getItemsByClass(PanZoomRotateHandler.class)) {
896 h.setTransform(state.viewTransform);
900 if (diagram != null) {
901 if (state.viewTransform != null)
902 diagram.removeHint(DiagramHints.KEY_INITIAL_ZOOM_TO_FIT);
904 if (state.toolMode != null)
905 ctx.getDefaultHintContext().setHint(Hints.KEY_TOOL, state.toToolMode());
907 ctx.getDefaultHintContext().setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
909 final Set<IElement> selected = DiagramEditorStates.toElements(state.selection, diagram);
910 if (!selected.isEmpty()) {
911 for (Selection s : ctx.getItemsByClass(Selection.class)) {
912 s.setSelection(0, selected);
918 protected EditorState getSavedEditorState(ICanvasContext ctx) {
919 return DiagramEditorStates.toEditorState(ctx, true, true, true);
922 protected void saveEditorState(ICanvasContext ctx) {
923 DiagramEditorStates.saveEditorState(PREFERENCE_VIRTUAL_GRAPH, diagramResource, getSavedEditorState(ctx) , DiagramViewer.this);
926 private boolean firstFocus = true;
928 public void setFocus() {
934 // This is a workaround for using the symbol viewer in multi-page
935 // editors which causes the first zoom-to-fit scheduling to happen
936 // already before the controls have been laid out properly.
945 protected void firstTimeSetFocus() {
946 // [Tuukka@2010-02-11]
947 // Removed since this is actually a workaround for multi-page editors.
948 //scheduleZoomToFit();
951 public void dispose() {
952 // Deactivate all contexts here because after this the context service
953 // in question will not be available.
954 if (contextUtil != null) {
955 contextUtil.deactivateAll();
960 if (hasDiagramSourceListener != null) {
961 hasDiagramSourceListener.dispose();
962 hasDiagramSourceListener = null;
965 if (activation != null) {
966 activation.deactivate();
970 if (resourceManager != null) {
971 resourceManager.dispose();
972 resourceManager = null;
977 protected Resource getInputResource() {
978 return getResourceInput().getResource();
981 public IResourceEditorInput getResourceInput() {
982 return (IResourceEditorInput) getEditorInput();
985 public IResourceEditorInput2 getResourceInput2() {
986 return (IResourceEditorInput2) getEditorInput();
989 public void init(DiagramViewerHost _host, IEditorSite site, IEditorInput input, DataContainer<IDiagram> diagramContainer, WorkbenchSelectionProvider selectionProvider) {
990 if (!(input instanceof IResourceEditorInput))
991 throw new RuntimeException("Invalid input: must be IResourceEditorInput");
996 this.sourceDiagramContainer = diagramContainer;
997 this.selectionProvider = selectionProvider;
999 // Set initial part name according to the name given by IEditorInput
1000 host.doSetPartName(getEditorInput().getName());
1002 Session session = SimanticsUI.peekSession();
1003 if (session != null) {
1004 Supplier<Boolean> disposedCallback = () -> disposed;
1005 session.asyncRequest(
1006 new TitleRequest(site.getId(), getResourceInput()),
1007 new TitleUpdater(site.getShell().getDisplay(), host::doSetPartName, disposedCallback));
1008 session.asyncRequest(
1009 new ToolTipRequest(site.getId(), getResourceInput()),
1010 new TitleUpdater(site.getShell().getDisplay(), host::doSetTitleToolTip, disposedCallback));
1014 // Read previous editor state from the database
1015 editorState = DiagramEditorStates.readEditorState(getInputResource());
1016 } catch (DatabaseException e) {
1021 @SuppressWarnings("unchecked")
1023 public <T> T getAdapter(Class<T> adapter) {
1024 // System.out.println("diagramViewer getAdapter " + adapter);
1025 // Property view support
1026 if (adapter == IPropertyPage.class)
1027 return (T) createPropertyPage(getSite(), getPropertyPageContexts());
1028 // Provide symbols for the editor
1029 if (adapter == SymbolProviderFactory.class) {
1031 return (T) DiagramTypeUtils.readSymbolProviderFactory(sessionContext.getSession(), diagramResource);
1032 } catch (DatabaseException e) {
1033 ErrorLogger.defaultLogError(getClass() + " failed to adapt to SymbolProviderFactory, see exception for details.", e);
1037 // Outline view support
1038 if (adapter == IContentOutlinePage.class)
1039 return (T) new DiagramOutlinePage(sessionContextProvider, getResourceInput2());
1040 // Role view support
1041 if (adapter == ILayersViewPage.class)
1042 return (T) new DiagramLayersPage(sourceDiagram, canvasContext);
1043 // Support external steering of the diagram canvas, zooming etc.
1044 if (adapter == ICanvasContext.class)
1045 return (T) canvasContext;
1046 // Support scene graph debugger view
1047 if (adapter == INode.class) {
1048 if (canvasContext != null) {
1049 INode node = canvasContext.getCanvasNode();
1051 return (T) NodeUtil.getRootNode(node);
1055 // Support retrieval of the current diagram.
1056 if (adapter == IDiagram.class)
1057 return (T) sourceDiagram;
1058 // Why is this here ??
1059 if (adapter == Session.class)
1060 return (T) sessionContext.getSession();
1061 if(adapter == RuntimeDiagramManager.class)
1062 return (T) runtimeDiagramManager;
1063 if (adapter == Resource.class)
1064 return (T) getRuntime();
1065 if (adapter == ICanvasChassis.class)
1071 //-------------------------------------------------------------------------
1074 protected static Object BEGIN(String name) {
1076 //return ThreadLog.BEGIN(name);
1081 protected static void END(Object task) {
1083 //((Task) task).end();
1087 //-------------------------------------------------------------------------
1088 // implement ListenerSupport
1091 public void exception(Throwable t) {
1092 ErrorLogger.defaultLogError(t);
1096 public boolean isDisposed() {
1100 protected void collectGarbage() {
1101 SessionGarbageCollectorJob.getInstance().schedule(0);
1102 AWTThread.getThreadAccess().asyncExec(new Runnable() {
1105 //System.out.println("BEFORE CLEAR: " + SVGCache.getSVGUniverse().report());
1106 SVGCache.getSVGUniverse().clearUnreferenced();
1107 //System.out.println("AFTER CLEAR: " + SVGCache.getSVGUniverse().report());
1112 //-------------------------------------------------------------------------
1113 // Listener for certain canvas context hint changes
1115 IHintListener canvasHintListener = new HintListenerAdapter() {
1117 public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
1118 if (key == GridPainter.KEY_GRID_ENABLED) {
1119 boolean v = Boolean.TRUE.equals(newValue);
1120 if (diagramDesc.isGridVisible() != v)
1121 setGlobalPreference(DiagramResource.URIs.DisplayGrid, v);
1122 } else if (key == RulerPainter.KEY_RULER_ENABLED) {
1123 boolean v = Boolean.TRUE.equals(newValue);
1124 if (diagramDesc.isRulerVisible() != v)
1125 setGlobalPreference(DiagramResource.URIs.DisplayRuler, v);
1130 private <T> void setGlobalPreference(final String preferenceURI, boolean value) {
1131 TagUtil.execute(Simantics.getSession(), PREFERENCE_VIRTUAL_GRAPH, preferenceURI, value, Simantics.getProjectResource());
1135 * --------------------------------------------------------------------
1136 * Changes related to removal of EditorPart extension from here on down
1137 * --------------------------------------------------------------------
1140 private IWorkbenchPartSite partSite;
1141 private DiagramViewerHost host;
1142 private IEditorInput editorInput = null;
1145 * Method declared on IWorkbenchPart.
1147 public IWorkbenchPartSite getSite() {
1151 public IEditorSite getEditorSite() {
1152 return (IEditorSite) getSite();
1155 public IEditorInput getEditorInput() {
1159 // protected void setPartName(String partName) {
1160 //// if (compatibilityTitleListener != null) {
1161 //// removePropertyListener(compatibilityTitleListener);
1162 //// compatibilityTitleListener = null;
1165 //// super.setPartName(partName);
1168 // protected void setTitleToolTip(String toolTip) {
1169 //// toolTip = Util.safeString(toolTip);
1170 //// //Do not send changes if they are the same
1171 //// if (Util.equals(this.toolTip, toolTip)) {
1174 //// this.toolTip = toolTip;
1175 //// firePropertyChange(IWorkbenchPart.PROP_TITLE);
1178 protected void setHost(DiagramViewerHost host) {
1182 protected void setSite(IWorkbenchPartSite site) {
1183 this.partSite = site;
1186 protected void setInput(IEditorInput input) {
1187 Assert.isLegal(input != null);
1188 editorInput = input;
1191 public Composite getComposite() {