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"; //$NON-NLS-1$
191 private static final String PREFERENCE_VIRTUAL_GRAPH = "preferences"; //$NON-NLS-1$
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 HasDiagramSourceListener hasDiagramSourceListener;
243 * {@link #init(DiagramViewerHost, IEditorSite, IEditorInput, DataContainer, WorkbenchSelectionProvider)}
246 protected WorkbenchSelectionProvider selectionProvider;
248 public Resource getRuntime() {
249 RuntimeDiagramManager rtdm = runtimeDiagramManager;
250 return (rtdm == null) ? null : rtdm.getRuntimeDiagram();
253 public ParametrizedRead<IResourceEditorInput, Boolean> getInputValidator() {
254 return INPUT_VALIDATOR;
257 protected void addDropParticipants(ICanvasContext ctx) {
258 ctx.getDefaultHintContext().setHint(Hints.KEY_ALLOWED_DRAG_ACTIONS, DnDConstants.ACTION_COPY);
260 ctx.add(new PopulateElementDropParticipant(synchronizer, getSite()));
261 ctx.add(new PopulateElementMonitorDropParticipant(synchronizer, 0.5, 0.5));
264 protected CopyPasteStrategy getCopyPasteStrategy() {
266 CopyPasteStrategy cpStrategy = Simantics.getSession().syncRequest(new PossibleAdapter<CopyPasteStrategy>(getInputResource(), CopyPasteStrategy.class));
267 if(cpStrategy != null) return cpStrategy;
268 } catch (DatabaseException e) {
270 return getDefaultCopyPasteStrategy();
273 protected CopyPasteStrategy getDefaultCopyPasteStrategy() {
274 return new DefaultCopyPasteStrategy();
277 protected CopyAdvisor getCopyAdvisor() {
279 CopyAdvisor advisor = Simantics.getSession().syncRequest(new PossibleAdapter<CopyAdvisor>(getInputResource(), CopyAdvisor.class));
280 if(advisor != null) return advisor;
281 } catch (DatabaseException e) {
283 return new MappedElementCopyAdvisor(new ElementCopyAdvisor(), new ComponentCopyAdvisor());
288 * TODO: change argument from CanvasContext to ICanvasContext
290 protected void addKeyBindingParticipants(CanvasContext ctx) {
291 //ctx.add( new KeyToCommand( CommandKeyBinding.DEFAULT_BINDINGS ) );
292 ctx.add(new DeleteHandler(statusLineManager));
293 ctx.add(new CopyPasteHandler(getCopyPasteStrategy(), statusLineManager).setWorkbenchSite(getEditorSite()));
294 ctx.add(new ConnectionCommandHandler());
297 protected void addPopupmenu(ICanvasContext ctx) {
298 ctx.add(popupMenuParticipant);
301 protected void addWorkbenchSelectionProvider(ICanvasContext ctx) {
302 if (selectionProvider != null)
303 ctx.add(selectionProvider);
306 protected void addViewManipulationParticipants(CanvasContext ctx) {
307 ctx.add(new PanZoomRotateHandler());
308 //ctx.add(new MousePanZoomInteractor());
309 //ctx.add(new MultitouchPanZoomRotateInteractor());
310 // ctx.add( new OrientationRestorer() );
311 ctx.add(new ZoomToAreaHandler());
314 protected void addDiagramParticipants(ICanvasContext ctx) {
315 ctx.add(new ZOrderHandler());
316 ctx.add(getPointerInteractor());
317 ctx.add(new ElementInteractor());
318 ctx.add(new Selection());
319 ctx.add(new DiagramParticipant());
320 ctx.add(new ElementPainter());
321 //ctx.add(new ElementHeartbeater());
322 //ctx.add(new ZoomTransitionParticipant(TransitionFunction.SIGMOID));
323 //ctx.add(new TooltipParticipant());
324 ctx.add(new TerminalTooltipParticipant());
327 protected void addPainterParticipants(ICanvasContext ctx) {
328 ctx.add(new RenderingQualityInteractor());
329 ctx.add(new TerminalPainter(true, true, false, true));
330 ctx.add(new DelayedBatchElementPainter(PickFilter.FILTER_MONITORS, 500, TimeUnit.MILLISECONDS));
333 protected void addStructureParticipants(ICanvasContext ctx) {
334 addWorkbenchSelectionProvider(ctx);
335 // Add visual browsing capabilities for structural models
336 ctx.add(new StructuralBrowsingHandler(getSite(), sessionContext, getResourceInput2()));
337 ctx.add(new LinkBrowsingHandler(getSite(), this, sessionContext));
341 * Override to add any diagram/canvas participants to the canvas context
342 * initialized for the editor.
346 protected void addOtherParticipants(CanvasContext ctx) {
349 public static Set<String> defaultPropertyBrowseContexts = Collections.singleton(ProjectResource.URIs.ProjectBrowseContext);
351 protected Set<String> getPropertyPageContexts() {
353 return BrowseContext.getBrowseContextClosure(Simantics.getSession(), defaultPropertyBrowseContexts);
354 } catch (DatabaseException e) {
355 ExceptionUtils.logAndShowError(Messages.DiagramViewer_FailedtoLoadModeled, e);
356 return defaultPropertyBrowseContexts;
360 protected IPropertyPage createPropertyPage(IWorkbenchPartSite site, Set<String> contexts) {
361 return new StandardPropertyPage(site, contexts);
364 protected String getPopupId() {
365 return "#ModelingDiagramPopup"; //$NON-NLS-1$
368 protected void getPreferences() {
369 this.diagramPreferences = DiagramPreferenceUtil.getPreferences();
372 protected void initSession() {
373 sessionContextProvider = Simantics.getSessionContextProvider();
374 sessionContext = sessionContextProvider.getSessionContext();
377 protected void readNames() {
378 String name = getEditorInput().getName();
379 host.doSetPartName(name);
380 host.doSetTitleToolTip(name);
383 class ChassisListener implements IChassisListener {
385 public void chassisClosed(ICanvasChassis sender) {
386 // Prevent deadlock while disposing which using syncExec would result in.
387 final ICanvasContext ctx = canvasContext;
388 ThreadUtils.asyncExec(ctx.getThreadAccess(), new Runnable() {
392 saveEditorState(ctx);
393 ctx.getHintStack().removeKeyHintListener(GridPainter.KEY_GRID_ENABLED, canvasHintListener);
394 ctx.getHintStack().removeKeyHintListener(RulerPainter.KEY_RULER_ENABLED, canvasHintListener);
395 final AWTChassis awtChassis = c.getAWTComponent();
396 if (awtChassis != null)
397 awtChassis.setCanvasContext(null);
401 if (sourceDiagramContainer != null) {
402 sourceDiagramContainer.set(null);
403 sourceDiagramContainer = null;
406 if (sourceDiagram != null)
407 sourceDiagram.dispose();
409 if(synchronizer != null) {
410 synchronizer.dispose();
415 if (runtimeDiagramManager != null) {
416 runtimeDiagramManager.dispose();
417 runtimeDiagramManager = null;
421 c.removeChassisListener(ChassisListener.this);
425 protected void createChassis(Composite parent) {
426 resourceManager = new LocalResourceManager(JFaceResources.getResources(), parent);
427 c = new SWTChassis(parent, 0);
429 Object task = BEGIN("DV.precreateParticipants"); //$NON-NLS-1$
430 createCustomParticipants();
433 c.populate(component -> {
435 c.addChassisListener(new ChassisListener());
441 protected void beforeSetCanvasContext(ICanvasContext canvasContext2) {
445 * Invoke this only from the AWT thread.
448 protected void setCanvasContext(ICanvasContext context) {
449 // Cannot directly invoke SWTChassis.setCanvasContext only because it
450 // needs to be invoked in the SWT thread and AWTChassis.setCanvasContext in the
451 // AWT thread, but directly invoking SWTChassis.setCanvasContext would call both
452 // in the SWT thread which would cause synchronous scheduling of AWT
453 // runnables which is always a potential source of deadlocks.
454 c.getAWTComponent().setCanvasContext(canvasContext);
455 swt.asyncExec(new Runnable() {
459 // For AWT, this is a no-operation.
460 c.setCanvasContext(canvasContext);
465 public void createPartControl(Composite parent) {
466 //ProfileObserver.begin = System.nanoTime();
467 display = parent.getDisplay();
468 swt = SWTThread.getThreadAccess(display);
469 statusLineManager = getEditorSite().getActionBars().getStatusLineManager();
471 Object task = BEGIN("DV.initSession"); //$NON-NLS-1$
475 diagramResource = getInputResource();
480 this.runtimeDiagramManager = RuntimeDiagramManager.track(sessionContext.getSession(), diagramResource, getEditorInput(), this);
482 // Create the canvas context here before finishing createPartControl
483 // to give DiagramViewerActionContributor a chance to work.
484 // The context can be created in SWT thread without scheduling
485 // to the context thread and having potential deadlocks.
486 IThreadWorkQueue thread = AWTThread.getThreadAccess();
487 this.canvasContext = new CanvasContext(thread);
488 this.canvasContext.setLocked(true);
490 task = BEGIN("DV.createChassis"); //$NON-NLS-1$
491 createChassis(parent);
493 } catch (DatabaseException e) {
494 ErrorLogger.defaultLogError(e);
500 * A method invoked before chassis construction for creating such
501 * {@link ICanvasParticipant}s that need to be constructed in the SWT
504 * Use it for creating any such canvas participants during the viewer
505 * construction and add them to the {@link ICanvasContext} later on from
508 protected void createCustomParticipants() {
509 if (SimanticsUI.isLinuxGTK()) {
510 popupMenuParticipant = new SWTPopupMenuParticipantAwt(getSite(), c, display, getPopupId());
512 popupMenuParticipant = new SWTPopupMenuParticipant(getSite(), c, display, getPopupId());
517 * Invoke this only from the AWT thread.
519 protected void initializeCanvas() {
520 Object canvasInit = BEGIN("DV.canvasInitialization"); //$NON-NLS-1$
522 Object task = BEGIN("DV.createViewerCanvas"); //$NON-NLS-1$
523 initializeCanvasContext(canvasContext);
526 beforeSetCanvasContext(canvasContext);
527 //FullscreenUtils.addFullScreenHandler(canvasContext, s, canvasProvider);
529 // Without this all diagram participants will crash like there's no tomorrow.
530 // Just trying to keep the behavior a bit more sane in case of
531 // errors instead of flooding the console with exceptions.
532 canvasContext.getDefaultHintContext().setHint(DiagramHints.KEY_DIAGRAM, Diagram.spawnNew(DiagramClass.DEFAULT));
534 // Changes in ruler/grid activity shall be written as
535 // workspace-persistent diagram-specific preferences.
536 canvasContext.getHintStack().addKeyHintListener(GridPainter.KEY_GRID_ENABLED, canvasHintListener);
537 canvasContext.getHintStack().addKeyHintListener(RulerPainter.KEY_RULER_ENABLED, canvasHintListener);
539 task = BEGIN("DV.setCanvasContext"); //$NON-NLS-1$
540 setCanvasContext(canvasContext);
543 // Finish loading in a worker thread because it may be a time consuming
544 // process to load a large diagram and we don't want unnecessary AWT
545 // thread contention.
546 Job loadJob = new DiagramViewerLoadJob(this);
552 protected void activateUiContexts(ContextUtil util) {
553 util.activate(DIAGRAMMING_CONTEXT);
557 * @param monitor the progress monitor to use for reporting progress to the
558 * user. It is the caller's responsibility to call done() on the
559 * given monitor. Accepts <code>null</code>, indicating that no
560 * progress should be reported and that the operation cannot be
563 protected void performActivation(IProgressMonitor monitor) {
564 SubMonitor progress = SubMonitor.convert(monitor, Messages.DiagramViewer_MonitorActivateMapping, 100);
565 IActivationManager activationManager = sessionContext.getSession().peekService(IActivationManager.class);
566 if (activationManager != null) {
567 activation = activationManager.activate(diagramResource);
569 progress.worked(100);
572 protected void onCreated() {
578 protected void scheduleZoomToFit(IDiagram diagram) {
580 throw new IllegalStateException("diagram is null"); //$NON-NLS-1$
582 CanvasUtils.scheduleZoomToFit(swt, () -> disposed, canvasContext, diagram);
586 * Subclasses may override but should always invoke super.
589 * @param initialHints
590 * @throws DatabaseException
592 protected void fillInitialDiagramHints(Resource diagram, IHintContext initialHints) throws DatabaseException {
593 IModelingRules modelingRules = sessionContext.getSession().syncRequest(
594 DiagramRequests.getModelingRules(diagram, null));
595 if (modelingRules != null) {
596 initialHints.setHint(DiagramModelHints.KEY_MODELING_RULES, modelingRules);
597 initialHints.setHint(DiagramHints.CONNECTION_ADVISOR,
598 getConnectionAdvisor(modelingRules, sessionContext.getSession()));
601 initialHints.setHint(SynchronizationHints.COPY_ADVISOR, getCopyAdvisor());
602 initialHints.setHint(DiagramHints.KEY_USE_CONNECTION_FLAGS, Boolean.TRUE);
603 initialHints.setHint(DiagramHints.KEY_ALLOW_CONNECTION_BRANCHING, Boolean.TRUE);
604 initialHints.setHint(DiagramHints.KEY_ALLOW_ROUTE_POINTS, Boolean.TRUE);
608 * @param monitor the progress monitor to use for reporting progress to the
609 * user. It is the caller's responsibility to call done() on the
610 * given monitor. Accepts <code>null</code>, indicating that no
611 * progress should be reported and that the operation cannot be
615 * @throws DatabaseException
617 protected IDiagram loadDiagram(IProgressMonitor monitor, final Resource r) throws DatabaseException {
618 // Pre-load modeling rules and possibly other hints too since they are
619 // needed already while loading the diagram contents.
620 IHintContext initialHints = new HintContext();
621 fillInitialDiagramHints(r, initialHints);
622 IDiagram d = loadDiagram(monitor, r, initialHints);
627 * @param monitor the progress monitor to use for reporting progress to the
628 * user. It is the caller's responsibility to call done() on the
629 * given monitor. Accepts <code>null</code>, indicating that no
630 * progress should be reported and that the operation cannot be
633 * @param initialHints
635 * @throws DatabaseException
637 protected IDiagram loadDiagram(IProgressMonitor monitor, Resource diagram, IHintContext initialHints) throws DatabaseException {
638 RuntimeDiagramManager rtdm = runtimeDiagramManager;
639 Resource runtimeDiagram = rtdm != null ? rtdm.getRuntimeDiagram() : null;
640 IDiagramLoader loader = synchronizer;
641 if (rtdm == null || runtimeDiagram == null || loader == null)
643 IDiagram d = sessionContext.getSession().syncRequest((Read<IDiagram>) graph -> {
644 IDiagram result = DiagramRequests.loadDiagram(monitor, getResourceInput2().getModel(null), diagram,
645 runtimeDiagram, null, loader, initialHints).perform(graph);
647 // #399: Enable certain PropertyTester implementation without database transactions
648 ModelingResources MOD = ModelingResources.getInstance(graph);
649 Resource composite = graph.getPossibleObject(diagram, MOD.DiagramToComposite);
651 DiagramModelHints.KEY_DIAGRAM_RESOURCE_TYPE_URIS,
652 graph.syncRequest(new TypeURIs(diagram)));
654 DiagramModelHints.KEY_MAPPED_COMPOSITE_RESOURCE_TYPE_URIS,
655 composite != null ? graph.syncRequest(new TypeURIs(composite)) : Collections.emptySet());
657 Resource diagramSource = graph.syncRequest(
658 new PossibleObject(diagram, MOD.HasDiagramSource),
659 hasDiagramSourceListener = new HasDiagramSourceListener(sourceDiagramContainer));
660 ElementUtils.setOrRemoveHint(
662 DiagramModelHints.KEY_HAS_DIAGRAM_SOURCE,
670 protected void beforeSetDiagram(IDiagram diagram) {
673 protected PointerInteractor getPointerInteractor() {
674 return new PointerInteractor2(true, true, true, false, true, false, synchronizer.getElementClassProvider());
677 protected IConnectionAdvisor getConnectionAdvisor(IModelingRules modelingRules, Session session) {
678 return new ModelledConnectionAdvisor(modelingRules, sessionContext.getSession());
681 protected GraphToDiagramSynchronizer createSynchronizer(final ICanvasContext ctx, final ISessionContext sessionContext) {
683 return sessionContext.getSession().syncRequest(new Read<GraphToDiagramSynchronizer>() {
685 public GraphToDiagramSynchronizer perform(ReadGraph graph) throws DatabaseException {
686 GraphToDiagramSynchronizer sync = new GraphToDiagramSynchronizer(graph, ctx, createElementClassProvider(graph));
687 initializeSynchronizationContext(graph, sync);
691 } catch (DatabaseException e) {
692 throw new UnsupportedOperationException("Failed to initialize data model synchronizer", e); //$NON-NLS-1$
696 protected void initializeSynchronizationContext(ReadGraph graph, IModifiableSynchronizationContext context) {
697 context.set(ModelingSynchronizationHints.MODELING_RESOURCE, ModelingResources.getInstance(graph));
700 protected IElementClassProvider createElementClassProvider(ReadGraph graph) {
701 DiagramResource dr = DiagramResource.getInstance(graph);
702 return ElementClassProviders.mappedProvider(
703 ElementClasses.CONNECTION, ConnectionClass.CLASS.newClassWith(new StaticObjectAdapter(dr.RouteGraphConnection)),
704 ElementClasses.FLAG, FlagClassFactory.createFlagClass(dr.Flag, dr.Flag_Terminal)
708 protected SimpleElementTransformHandler getTransformHandler() {
709 return new SimpleElementTransformHandler(true, true, true);
712 public void initializeCanvasContext(CanvasContext ctx) {
713 IHintContext h = ctx.getDefaultHintContext();
715 // The canvas context should not be painted until it is ready to avoid
716 // unnecessary visual glitches.
717 h.setHint(Hints.KEY_DISABLE_PAINTING, Boolean.TRUE);
719 Object task = BEGIN("createSynchronizer"); //$NON-NLS-1$
720 this.synchronizer = createSynchronizer(ctx, sessionContext);
723 IContextService contextService = (IContextService) getSite().getService(IContextService.class);
724 contextUtil = new ContextUtil(contextService, swt);
726 // Support & Util Participants
727 ctx.add(new TransformUtil());
728 ctx.add(new MouseUtil());
729 ctx.add(new KeyUtil());
730 ctx.add(contextUtil);
731 ctx.add(new WorkbenchStatusLine(statusLineManager));
732 ctx.add(new CanvasGrab());
733 ctx.add(new SymbolUtil());
734 ctx.add(new TimeParticipant());
735 ctx.add(new CanvasBoundsParticipant());
736 ctx.add(new Notifications());
738 ctx.add(new SGFocusParticipant(c, DIAGRAMMING_CONTEXT));
740 // Debug participant(s)
741 // ctx.add( new PointerPainter() );
742 // ctx.add( new HandPainter() );
743 h.setHint(PointerPainter.KEY_PAINT_POINTER, true);
745 // Pan & Zoom & Rotate
746 addViewManipulationParticipants(ctx);
748 ctx.add(getTransformHandler());
749 ctx.add(new ExpandSelectionHandler(getEditorSite().getActionBars().getStatusLineManager()));
752 addKeyBindingParticipants(ctx);
754 // Grid & Ruler & Background
755 addGridRulerBackgroundParticipants(ctx);
757 h.setHint(Hints.KEY_DISPLAY_PAGE, diagramPreferences.get(DiagramPreferences.P_DISPLAY_PAGE_SIZE));
758 h.setHint(Hints.KEY_DISPLAY_MARGINS, diagramPreferences.get(DiagramPreferences.P_DISPLAY_MARGINS));
759 ctx.add(new PageBorderParticipant());
761 // h.setHint(Hints.KEY_GRID_COLOR, new Color(0.9f, 0.9f, 0.9f));
762 // h.setHint(Hints.KEY_BACKGROUND_COLOR, Color.LIGHT_GRAY);
763 h.setHint(Hints.KEY_GRID_COLOR, new Color(0.9f, 0.9f, 0.9f));
764 h.setHint(Hints.KEY_BACKGROUND_COLOR, Color.WHITE);
765 h.setHint(RulerPainter.KEY_RULER_BACKGROUND_COLOR, new Color(0.9f, 0.9f, 0.9f, 0.75f));
766 h.setHint(RulerPainter.KEY_RULER_TEXT_COLOR, Color.BLACK);
768 ////// Diagram Participants //////
769 addDiagramParticipants(ctx);
770 addPainterParticipants(ctx);
772 /////// D'n'D ///////
773 addDropParticipants(ctx);
775 h.setHint(ElementPainter.KEY_SELECTION_FRAME_COLOR, Color.MAGENTA);
776 h.setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
778 h.setHint(PanZoomRotateHandler.KEY_ZOOM_IN_LIMIT, 100000.0);
779 h.setHint(PanZoomRotateHandler.KEY_ZOOM_OUT_LIMIT, 10.0);
781 Double snapResolution = diagramPreferences.get(DiagramPreferences.P_SNAP_GRID_SIZE);
782 this.snapAdvisor = new GridSnapAdvisor(snapResolution);
783 h.setHint(DiagramHints.SNAP_ADVISOR, this.snapAdvisor);
784 h.setHint(GridPainter.KEY_GRID_SIZE, snapResolution);
785 h.setHint(GridPainter.KEY_GRID_ENABLED, Boolean.FALSE);
787 // Workbench selection provider
788 addStructureParticipants(ctx);
793 // Load page frame description settings
794 loadPageSettings(ctx);
796 addOtherParticipants(ctx);
798 ctx.assertParticipantDependencies();
799 ctx.setLocked(false);
802 protected void addGridRulerBackgroundParticipants(CanvasContext ctx) {
803 ctx.add(new GridPainter());
804 ctx.add(new RulerPainter());
805 ctx.add(new BackgroundPainter());
808 protected void loadPageSettings(ICanvasContext ctx) {
809 DiagramDesc diagramDesc = null;
811 // load diagram page configuration
812 if (diagramResource != null) {
814 diagramDesc = sessionContext.getSession().syncRequest(DiagramRequests.getDiagramDesc(diagramResource));
815 } catch (DatabaseException e) {
816 ErrorLogger.defaultLogError(e);
820 if (diagramDesc == null) {
821 // Take page description from the preferences if nothing else is available.
822 final DiagramDesc desc = diagramDesc = diagramPreferences.getDiagramDesc();
824 // Write page configuration to graph
825 sessionContext.getSession().asyncRequest(new WriteRequest() {
827 public void perform(WriteGraph graph) throws DatabaseException {
828 if (graph.isImmutable(diagramResource))
830 CommonDBUtils.selectClusterSet(graph, diagramResource);
831 DiagramGraphUtil.setDiagramDesc(graph, diagramResource, desc);
834 if (parameter != null)
835 ErrorLogger.defaultLogError("Failed to write default diagram page description to database, see exception for details", parameter); //$NON-NLS-1$
839 setDiagramDesc(ctx, diagramDesc);
841 // Create a listener to react to page setting changes.
842 sessionContext.getSession().asyncRequest(DiagramRequests.getDiagramDesc(diagramResource),
843 new ListenerDelegate<DiagramDesc>(this) {
845 public void execute(final DiagramDesc result) {
846 if (result != null && canvasContext != null) {
847 ThreadUtils.asyncExec(canvasContext.getThreadAccess(), new Runnable() {
851 setDiagramDesc(canvasContext, result);
859 protected void setDiagramDesc(ICanvasContext ctx, DiagramDesc diagramDesc) {
860 if (diagramDesc == null)
861 throw new NullPointerException("null diagram desc"); //$NON-NLS-1$
863 if (diagramDesc.equals(this.diagramDesc))
866 this.diagramDesc = diagramDesc;
867 IHintContext hints = ctx.getDefaultHintContext();
868 hints.setHint(Hints.KEY_PAGE_DESC, diagramDesc.getPageDesc());
869 hints.setHint(Hints.KEY_DISPLAY_PAGE, diagramDesc.isPageBordersVisible());
870 hints.setHint(Hints.KEY_DISPLAY_MARGINS, diagramDesc.isMarginsVisible());
871 hints.setHint(GridPainter.KEY_GRID_ENABLED, diagramDesc.isGridVisible());
872 hints.setHint(RulerPainter.KEY_RULER_ENABLED, diagramDesc.isRulerVisible());
873 snapAdvisor.setResolution(diagramDesc.getGridSize());
874 hints.setHint(GridPainter.KEY_GRID_SIZE, diagramDesc.getGridSize());
878 * Must be invoked from the AWT thread only.
883 protected void applyEditorState(final EditorState state, final ICanvasContext ctx) {
884 final IDiagram diagram = ctx.getHintStack().getHint(DiagramHints.KEY_DIAGRAM);
886 if (state.viewTransform != null && state.viewTransform.getDeterminant() != 0) {
887 for (PanZoomRotateHandler h : ctx.getItemsByClass(PanZoomRotateHandler.class)) {
888 h.setTransform(state.viewTransform);
892 if (diagram != null) {
893 if (state.viewTransform != null)
894 diagram.removeHint(DiagramHints.KEY_INITIAL_ZOOM_TO_FIT);
896 if (state.toolMode != null)
897 ctx.getDefaultHintContext().setHint(Hints.KEY_TOOL, state.toToolMode());
899 ctx.getDefaultHintContext().setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
901 final Set<IElement> selected = DiagramEditorStates.toElements(state.selection, diagram);
902 if (!selected.isEmpty()) {
903 for (Selection s : ctx.getItemsByClass(Selection.class)) {
904 s.setSelection(0, selected);
910 protected EditorState getSavedEditorState(ICanvasContext ctx) {
911 return DiagramEditorStates.toEditorState(ctx, true, true, true);
914 protected void saveEditorState(ICanvasContext ctx) {
915 DiagramEditorStates.saveEditorState(PREFERENCE_VIRTUAL_GRAPH, diagramResource, getSavedEditorState(ctx) , DiagramViewer.this);
918 private boolean firstFocus = true;
920 public void setFocus() {
926 // This is a workaround for using the symbol viewer in multi-page
927 // editors which causes the first zoom-to-fit scheduling to happen
928 // already before the controls have been laid out properly.
937 protected void firstTimeSetFocus() {
938 // [Tuukka@2010-02-11]
939 // Removed since this is actually a workaround for multi-page editors.
940 //scheduleZoomToFit();
943 public void dispose() {
944 // Deactivate all contexts here because after this the context service
945 // in question will not be available.
946 if (contextUtil != null) {
947 contextUtil.deactivateAll();
952 if (hasDiagramSourceListener != null) {
953 hasDiagramSourceListener.dispose();
954 hasDiagramSourceListener = null;
957 if (activation != null) {
958 activation.deactivate();
962 if (resourceManager != null) {
963 resourceManager.dispose();
964 resourceManager = null;
969 protected Resource getInputResource() {
970 return getResourceInput().getResource();
973 public IResourceEditorInput getResourceInput() {
974 return (IResourceEditorInput) getEditorInput();
977 public IResourceEditorInput2 getResourceInput2() {
978 return (IResourceEditorInput2) getEditorInput();
981 public void init(DiagramViewerHost _host, IEditorSite site, IEditorInput input, DataContainer<IDiagram> diagramContainer, WorkbenchSelectionProvider selectionProvider) {
982 if (!(input instanceof IResourceEditorInput))
983 throw new RuntimeException("Invalid input: must be IResourceEditorInput"); //$NON-NLS-1$
988 this.sourceDiagramContainer = diagramContainer;
989 this.selectionProvider = selectionProvider;
991 // Set initial part name according to the name given by IEditorInput
992 host.doSetPartName(getEditorInput().getName());
994 Session session = Simantics.peekSession();
995 if (session != null) {
996 Supplier<Boolean> disposedCallback = () -> disposed;
997 session.asyncRequest(
998 new TitleRequest(site.getId(), getResourceInput()),
999 new TitleUpdater(site.getShell().getDisplay(), host::doSetPartName, disposedCallback));
1000 session.asyncRequest(
1001 new ToolTipRequest(site.getId(), getResourceInput()),
1002 new TitleUpdater(site.getShell().getDisplay(), host::doSetTitleToolTip, disposedCallback));
1006 // Read previous editor state from the database
1007 editorState = DiagramEditorStates.readEditorState(getInputResource());
1008 } catch (DatabaseException e) {
1013 @SuppressWarnings("unchecked")
1015 public <T> T getAdapter(Class<T> adapter) {
1016 // System.out.println("diagramViewer getAdapter " + adapter);
1017 // Property view support
1018 if (adapter == IPropertyPage.class)
1019 return (T) createPropertyPage(getSite(), getPropertyPageContexts());
1020 // Provide symbols for the editor
1021 if (adapter == SymbolProviderFactory.class) {
1023 return (T) DiagramTypeUtils.readSymbolProviderFactory(sessionContext.getSession(), diagramResource);
1024 } catch (DatabaseException e) {
1025 ErrorLogger.defaultLogError(getClass() + " failed to adapt to SymbolProviderFactory, see exception for details.", e); //$NON-NLS-1$
1029 // Outline view support
1030 if (adapter == IContentOutlinePage.class)
1031 return (T) new DiagramOutlinePage(sessionContextProvider, getResourceInput2());
1032 // Role view support
1033 if (adapter == ILayersViewPage.class)
1034 return (T) new DiagramLayersPage(sourceDiagram, canvasContext);
1035 // Support external steering of the diagram canvas, zooming etc.
1036 if (adapter == ICanvasContext.class)
1037 return (T) canvasContext;
1038 // Support scene graph debugger view
1039 if (adapter == INode.class) {
1040 if (canvasContext != null) {
1041 INode node = canvasContext.getCanvasNode();
1043 return (T) NodeUtil.getRootNode(node);
1047 // Support retrieval of the current diagram.
1048 if (adapter == IDiagram.class)
1049 return (T) sourceDiagram;
1050 // Why is this here ??
1051 if (adapter == Session.class)
1052 return (T) sessionContext.getSession();
1053 if(adapter == RuntimeDiagramManager.class)
1054 return (T) runtimeDiagramManager;
1055 if (adapter == Resource.class)
1056 return (T) getRuntime();
1057 if (adapter == ICanvasChassis.class)
1063 //-------------------------------------------------------------------------
1066 protected static Object BEGIN(String name) {
1068 //return ThreadLog.BEGIN(name);
1073 protected static void END(Object task) {
1075 //((Task) task).end();
1079 //-------------------------------------------------------------------------
1080 // implement ListenerSupport
1083 public void exception(Throwable t) {
1084 ErrorLogger.defaultLogError(t);
1088 public boolean isDisposed() {
1092 protected void collectGarbage() {
1093 SessionGarbageCollectorJob.getInstance().schedule(0);
1094 AWTThread.getThreadAccess().asyncExec(new Runnable() {
1097 //System.out.println("BEFORE CLEAR: " + SVGCache.getSVGUniverse().report());
1098 SVGCache.getSVGUniverse().clearUnreferenced();
1099 //System.out.println("AFTER CLEAR: " + SVGCache.getSVGUniverse().report());
1104 //-------------------------------------------------------------------------
1105 // Listener for certain canvas context hint changes
1107 IHintListener canvasHintListener = new HintListenerAdapter() {
1109 public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
1110 if (key == GridPainter.KEY_GRID_ENABLED) {
1111 boolean v = Boolean.TRUE.equals(newValue);
1112 if (diagramDesc.isGridVisible() != v)
1113 setGlobalPreference(DiagramResource.URIs.DisplayGrid, v);
1114 } else if (key == RulerPainter.KEY_RULER_ENABLED) {
1115 boolean v = Boolean.TRUE.equals(newValue);
1116 if (diagramDesc.isRulerVisible() != v)
1117 setGlobalPreference(DiagramResource.URIs.DisplayRuler, v);
1122 private <T> void setGlobalPreference(final String preferenceURI, boolean value) {
1123 TagUtil.execute(Simantics.getSession(), PREFERENCE_VIRTUAL_GRAPH, preferenceURI, value, Simantics.getProjectResource());
1127 * --------------------------------------------------------------------
1128 * Changes related to removal of EditorPart extension from here on down
1129 * --------------------------------------------------------------------
1132 private IWorkbenchPartSite partSite;
1133 private DiagramViewerHost host;
1134 private IEditorInput editorInput = null;
1137 * Method declared on IWorkbenchPart.
1139 public IWorkbenchPartSite getSite() {
1143 public IEditorSite getEditorSite() {
1144 return (IEditorSite) getSite();
1147 public IEditorInput getEditorInput() {
1151 // protected void setPartName(String partName) {
1152 //// if (compatibilityTitleListener != null) {
1153 //// removePropertyListener(compatibilityTitleListener);
1154 //// compatibilityTitleListener = null;
1157 //// super.setPartName(partName);
1160 // protected void setTitleToolTip(String toolTip) {
1161 //// toolTip = Util.safeString(toolTip);
1162 //// //Do not send changes if they are the same
1163 //// if (Util.equals(this.toolTip, toolTip)) {
1166 //// this.toolTip = toolTip;
1167 //// firePropertyChange(IWorkbenchPart.PROP_TITLE);
1170 protected void setHost(DiagramViewerHost host) {
1174 protected void setSite(IWorkbenchPartSite site) {
1175 this.partSite = site;
1178 protected void setInput(IEditorInput input) {
1179 Assert.isLegal(input != null);
1180 editorInput = input;
1183 public Composite getComposite() {