]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/diagramEditor/DiagramViewer.java
Re-enabled CTRL+SHIFT+R resource search dialog in org.simantics.debug.ui
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / diagramEditor / DiagramViewer.java
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2013 Association for Decentralized Information Management\r
3  * in Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *     Semantum Oy - issue #4384\r
12  *******************************************************************************/\r
13 package org.simantics.modeling.ui.diagramEditor;\r
14 \r
15 import java.awt.Color;\r
16 import java.awt.dnd.DnDConstants;\r
17 import java.util.Collections;\r
18 import java.util.Set;\r
19 import java.util.concurrent.TimeUnit;\r
20 import java.util.function.Supplier;\r
21 \r
22 import org.eclipse.core.runtime.Assert;\r
23 import org.eclipse.core.runtime.IAdaptable;\r
24 import org.eclipse.core.runtime.IProgressMonitor;\r
25 import org.eclipse.core.runtime.SubMonitor;\r
26 import org.eclipse.core.runtime.jobs.Job;\r
27 import org.eclipse.jface.action.IStatusLineManager;\r
28 import org.eclipse.jface.resource.JFaceResources;\r
29 import org.eclipse.jface.resource.LocalResourceManager;\r
30 import org.eclipse.swt.widgets.Composite;\r
31 import org.eclipse.swt.widgets.Display;\r
32 import org.eclipse.ui.IEditorInput;\r
33 import org.eclipse.ui.IEditorSite;\r
34 import org.eclipse.ui.IWorkbenchPartSite;\r
35 import org.eclipse.ui.contexts.IContextService;\r
36 import org.eclipse.ui.views.contentoutline.IContentOutlinePage;\r
37 import org.simantics.Simantics;\r
38 import org.simantics.browsing.ui.model.browsecontexts.BrowseContext;\r
39 import org.simantics.db.ReadGraph;\r
40 import org.simantics.db.Resource;\r
41 import org.simantics.db.Session;\r
42 import org.simantics.db.WriteGraph;\r
43 import org.simantics.db.common.primitiverequest.PossibleAdapter;\r
44 import org.simantics.db.common.procedure.adapter.ListenerDelegate;\r
45 import org.simantics.db.common.procedure.adapter.ListenerSupport;\r
46 import org.simantics.db.common.request.ParametrizedRead;\r
47 import org.simantics.db.common.request.WriteRequest;\r
48 import org.simantics.db.common.utils.CommonDBUtils;\r
49 import org.simantics.db.common.utils.TagUtil;\r
50 import org.simantics.db.exception.DatabaseException;\r
51 import org.simantics.db.layer0.request.combinations.Combinators;\r
52 import org.simantics.db.management.ISessionContext;\r
53 import org.simantics.db.management.ISessionContextProvider;\r
54 import org.simantics.db.request.Read;\r
55 import org.simantics.diagram.DiagramTypeUtils;\r
56 import org.simantics.diagram.adapter.FlagClassFactory;\r
57 import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;\r
58 import org.simantics.diagram.adapter.IDiagramLoader;\r
59 import org.simantics.diagram.connection.ModelledConnectionAdvisor;\r
60 import org.simantics.diagram.handler.ConnectionCommandHandler;\r
61 import org.simantics.diagram.handler.CopyPasteHandler;\r
62 import org.simantics.diagram.handler.CopyPasteStrategy;\r
63 import org.simantics.diagram.handler.DefaultCopyPasteStrategy;\r
64 import org.simantics.diagram.handler.DeleteHandler;\r
65 import org.simantics.diagram.handler.ExpandSelectionHandler;\r
66 import org.simantics.diagram.handler.SimpleElementTransformHandler;\r
67 import org.simantics.diagram.layer.ILayersViewPage;\r
68 import org.simantics.diagram.participant.ContextUtil;\r
69 import org.simantics.diagram.participant.PointerInteractor2;\r
70 import org.simantics.diagram.participant.SGFocusParticipant;\r
71 import org.simantics.diagram.query.DiagramRequests;\r
72 import org.simantics.diagram.runtime.RuntimeDiagramManager;\r
73 import org.simantics.diagram.stubs.DiagramResource;\r
74 import org.simantics.diagram.symbolcontribution.SymbolProviderFactory;\r
75 import org.simantics.diagram.synchronization.CopyAdvisor;\r
76 import org.simantics.diagram.synchronization.IModifiableSynchronizationContext;\r
77 import org.simantics.diagram.synchronization.SynchronizationHints;\r
78 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
79 import org.simantics.diagram.ui.DiagramModelHints;\r
80 import org.simantics.diagram.ui.SWTPopupMenuParticipant;\r
81 import org.simantics.diagram.ui.SWTPopupMenuParticipantAwt;\r
82 import org.simantics.diagram.ui.WorkbenchSelectionProvider;\r
83 import org.simantics.g2d.canvas.Hints;\r
84 import org.simantics.g2d.canvas.ICanvasContext;\r
85 import org.simantics.g2d.canvas.ICanvasParticipant;\r
86 import org.simantics.g2d.canvas.impl.CanvasContext;\r
87 import org.simantics.g2d.chassis.AWTChassis;\r
88 import org.simantics.g2d.chassis.ICanvasChassis;\r
89 import org.simantics.g2d.chassis.IChassisListener;\r
90 import org.simantics.g2d.chassis.SWTChassis;\r
91 import org.simantics.g2d.connection.IConnectionAdvisor;\r
92 import org.simantics.g2d.diagram.DiagramClass;\r
93 import org.simantics.g2d.diagram.DiagramHints;\r
94 import org.simantics.g2d.diagram.IDiagram;\r
95 import org.simantics.g2d.diagram.handler.PickRequest.PickFilter;\r
96 import org.simantics.g2d.diagram.impl.Diagram;\r
97 import org.simantics.g2d.diagram.participant.DelayedBatchElementPainter;\r
98 import org.simantics.g2d.diagram.participant.DiagramParticipant;\r
99 import org.simantics.g2d.diagram.participant.ElementInteractor;\r
100 import org.simantics.g2d.diagram.participant.ElementPainter;\r
101 import org.simantics.g2d.diagram.participant.Selection;\r
102 import org.simantics.g2d.diagram.participant.TerminalPainter;\r
103 import org.simantics.g2d.diagram.participant.ZOrderHandler;\r
104 import org.simantics.g2d.diagram.participant.pointertool.PointerInteractor;\r
105 import org.simantics.g2d.element.ElementClassProviders;\r
106 import org.simantics.g2d.element.ElementClasses;\r
107 import org.simantics.g2d.element.IElement;\r
108 import org.simantics.g2d.element.IElementClassProvider;\r
109 import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
110 import org.simantics.g2d.elementclass.connection.ConnectionClass;\r
111 import org.simantics.g2d.page.DiagramDesc;\r
112 import org.simantics.g2d.participant.BackgroundPainter;\r
113 import org.simantics.g2d.participant.CanvasBoundsParticipant;\r
114 import org.simantics.g2d.participant.CanvasGrab;\r
115 import org.simantics.g2d.participant.GridPainter;\r
116 import org.simantics.g2d.participant.KeyUtil;\r
117 import org.simantics.g2d.participant.MouseUtil;\r
118 import org.simantics.g2d.participant.Notifications;\r
119 import org.simantics.g2d.participant.PageBorderParticipant;\r
120 import org.simantics.g2d.participant.PanZoomRotateHandler;\r
121 import org.simantics.g2d.participant.PointerPainter;\r
122 import org.simantics.g2d.participant.RenderingQualityInteractor;\r
123 import org.simantics.g2d.participant.RulerPainter;\r
124 import org.simantics.g2d.participant.SymbolUtil;\r
125 import org.simantics.g2d.participant.TimeParticipant;\r
126 import org.simantics.g2d.participant.TransformUtil;\r
127 import org.simantics.g2d.participant.WorkbenchStatusLine;\r
128 import org.simantics.g2d.participant.ZoomToAreaHandler;\r
129 import org.simantics.g2d.tooltip.TerminalTooltipParticipant;\r
130 import org.simantics.g2d.utils.CanvasUtils;\r
131 import org.simantics.layer0.utils.triggers.IActivation;\r
132 import org.simantics.layer0.utils.triggers.IActivationManager;\r
133 import org.simantics.modeling.ModelingResources;\r
134 import org.simantics.modeling.mapping.ComponentCopyAdvisor;\r
135 import org.simantics.modeling.mapping.ElementCopyAdvisor;\r
136 import org.simantics.modeling.mapping.MappedElementCopyAdvisor;\r
137 import org.simantics.modeling.mapping.ModelingSynchronizationHints;\r
138 import org.simantics.modeling.ui.diagramEditor.handlers.LinkBrowsingHandler;\r
139 import org.simantics.modeling.ui.diagramEditor.handlers.StructuralBrowsingHandler;\r
140 import org.simantics.modeling.ui.preferences.DiagramPreferenceUtil;\r
141 import org.simantics.modeling.ui.preferences.DiagramPreferences;\r
142 import org.simantics.project.ontology.ProjectResource;\r
143 import org.simantics.scenegraph.INode;\r
144 import org.simantics.scenegraph.g2d.snap.GridSnapAdvisor;\r
145 import org.simantics.scenegraph.utils.NodeUtil;\r
146 import org.simantics.selectionview.StandardPropertyPage;\r
147 import org.simantics.structural.stubs.StructuralResource2;\r
148 import org.simantics.structural2.modelingRules.IModelingRules;\r
149 import org.simantics.ui.SimanticsUI;\r
150 import org.simantics.ui.jobs.SessionGarbageCollectorJob;\r
151 import org.simantics.ui.workbench.IPropertyPage;\r
152 import org.simantics.ui.workbench.IResourceEditorInput;\r
153 import org.simantics.ui.workbench.IResourceEditorInput2;\r
154 import org.simantics.ui.workbench.TitleRequest;\r
155 import org.simantics.ui.workbench.TitleUpdater;\r
156 import org.simantics.ui.workbench.ToolTipRequest;\r
157 import org.simantics.ui.workbench.editor.input.InputValidationCombinators;\r
158 import org.simantics.utils.DataContainer;\r
159 import org.simantics.utils.datastructures.hints.HintContext;\r
160 import org.simantics.utils.datastructures.hints.HintListenerAdapter;\r
161 import org.simantics.utils.datastructures.hints.IHintContext;\r
162 import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
163 import org.simantics.utils.datastructures.hints.IHintListener;\r
164 import org.simantics.utils.datastructures.hints.IHintObservable;\r
165 import org.simantics.utils.threads.AWTThread;\r
166 import org.simantics.utils.threads.IThreadWorkQueue;\r
167 import org.simantics.utils.threads.SWTThread;\r
168 import org.simantics.utils.threads.ThreadUtils;\r
169 import org.simantics.utils.ui.ErrorLogger;\r
170 import org.simantics.utils.ui.ExceptionUtils;\r
171 \r
172 import com.kitfox.svg.SVGCache;\r
173 \r
174 /**\r
175  * @author Toni Kalajainen\r
176  * @author Tuukka Lehtonen\r
177  */\r
178 public class DiagramViewer \r
179   //extends EditorPart implements IResourceEditorPart2, \r
180     implements ListenerSupport, IAdaptable {\r
181 \r
182     public interface DiagramViewerHost {\r
183         void doSetPartName(String name);\r
184         void doSetTitleToolTip(String name);\r
185     }\r
186 \r
187     public static final String                     DIAGRAMMING_CONTEXT      = "org.simantics.modeling.ui.diagramming";\r
188     private static final String                     PREFERENCE_VIRTUAL_GRAPH = "preferences";\r
189 \r
190     private static final boolean                    PROFILE                  = false;\r
191 \r
192     ParametrizedRead<IResourceEditorInput, Boolean> INPUT_VALIDATOR =\r
193         Combinators.compose(\r
194                 InputValidationCombinators.or(\r
195                         // Normal configuration diagrams of a model\r
196                         Combinators.compose(\r
197                                 InputValidationCombinators.hasURI(),\r
198                                 InputValidationCombinators.partialFunction(ModelingResources.URIs.DiagramToComposite)\r
199                         ),\r
200                         // Configuration diagrams of a component type\r
201                         Combinators.compose(\r
202                                 InputValidationCombinators.hasURI(),\r
203                                 Combinators.compose(\r
204                                         InputValidationCombinators.partialFunction(StructuralResource2.URIs.Defines),\r
205                                         InputValidationCombinators.partialFunction(ModelingResources.URIs.DiagramToComposite)\r
206                                 )\r
207                         )\r
208                 ),\r
209                 InputValidationCombinators.extractInputResource()\r
210         );\r
211 \r
212     protected EditorState                editorState;\r
213 \r
214     protected boolean                    disposed           = false;\r
215     protected IThreadWorkQueue           swt;\r
216     protected IStatusLineManager         statusLineManager;\r
217     protected Display                    display;\r
218     protected LocalResourceManager       resourceManager;\r
219     protected SWTChassis                 c;\r
220     protected IDiagram                   sourceDiagram;\r
221     protected DataContainer<IDiagram>    sourceDiagramContainer;\r
222     protected CanvasContext              canvasContext;\r
223     protected ISessionContextProvider    sessionContextProvider;\r
224     protected ISessionContext            sessionContext;\r
225     protected Resource                   diagramResource;\r
226     protected GraphToDiagramSynchronizer synchronizer;\r
227     protected IActivation                activation;\r
228     protected ContextUtil                contextUtil;\r
229     protected SWTPopupMenuParticipant    popupMenuParticipant;\r
230     \r
231     protected DiagramPreferences         diagramPreferences;\r
232     protected DiagramDesc                diagramDesc;\r
233     protected GridSnapAdvisor            snapAdvisor;\r
234 \r
235     private RuntimeDiagramManager        runtimeDiagramManager;\r
236 \r
237     /**\r
238      * Set externally in\r
239      * {@link #init(DiagramViewerHost, IEditorSite, IEditorInput, DataContainer, WorkbenchSelectionProvider)}\r
240      * .\r
241      */\r
242     protected WorkbenchSelectionProvider selectionProvider;\r
243 \r
244     public Resource getRuntime() {\r
245         RuntimeDiagramManager rtdm = runtimeDiagramManager;\r
246         return (rtdm == null) ? null : rtdm.getRuntimeDiagram();\r
247     }\r
248 \r
249     public ParametrizedRead<IResourceEditorInput, Boolean> getInputValidator() {\r
250         return INPUT_VALIDATOR;\r
251     }\r
252 \r
253     protected void addDropParticipants(ICanvasContext ctx) {\r
254         ctx.getDefaultHintContext().setHint(Hints.KEY_ALLOWED_DRAG_ACTIONS, DnDConstants.ACTION_COPY);\r
255 \r
256         ctx.add(new PopulateElementDropParticipant(synchronizer, getSite()));\r
257         ctx.add(new PopulateElementMonitorDropParticipant(synchronizer, 0.5, 0.5));\r
258     }\r
259 \r
260     protected CopyPasteStrategy getCopyPasteStrategy() {\r
261                 try {\r
262                         CopyPasteStrategy cpStrategy = Simantics.getSession().syncRequest(new PossibleAdapter<CopyPasteStrategy>(getInputResource(), CopyPasteStrategy.class));\r
263                         if(cpStrategy != null) return cpStrategy;\r
264                 } catch (DatabaseException e) {\r
265                 }\r
266                 return getDefaultCopyPasteStrategy();\r
267     }\r
268     \r
269     protected CopyPasteStrategy getDefaultCopyPasteStrategy() {\r
270         return new DefaultCopyPasteStrategy();\r
271     }\r
272 \r
273     protected CopyAdvisor getCopyAdvisor() {\r
274                 try {\r
275                         CopyAdvisor advisor = Simantics.getSession().syncRequest(new PossibleAdapter<CopyAdvisor>(getInputResource(), CopyAdvisor.class));\r
276                         if(advisor != null) return advisor;\r
277                 } catch (DatabaseException e) {\r
278                 }\r
279                 return new MappedElementCopyAdvisor(new ElementCopyAdvisor(), new ComponentCopyAdvisor());\r
280     }\r
281     \r
282     /**\r
283      * @param ctx\r
284      * TODO: change argument from CanvasContext to ICanvasContext\r
285      */\r
286     protected void addKeyBindingParticipants(CanvasContext ctx) {\r
287         //ctx.add( new KeyToCommand( CommandKeyBinding.DEFAULT_BINDINGS ) );\r
288         ctx.add(new DeleteHandler(statusLineManager));\r
289         ctx.add(new CopyPasteHandler(getCopyPasteStrategy(), statusLineManager).setWorkbenchSite(getEditorSite()));\r
290         ctx.add(new ConnectionCommandHandler());\r
291     }\r
292 \r
293     protected void addPopupmenu(ICanvasContext ctx) {\r
294         ctx.add(popupMenuParticipant);\r
295     }\r
296 \r
297     protected void addWorkbenchSelectionProvider(ICanvasContext ctx) {\r
298         if (selectionProvider != null)\r
299             ctx.add(selectionProvider);\r
300     }\r
301 \r
302     protected void addViewManipulationParticipants(CanvasContext ctx) {\r
303         ctx.add(new PanZoomRotateHandler());\r
304         //ctx.add(new MousePanZoomInteractor());\r
305         //ctx.add(new MultitouchPanZoomRotateInteractor());\r
306         // ctx.add( new OrientationRestorer() );\r
307         ctx.add(new ZoomToAreaHandler());\r
308     }\r
309 \r
310     protected void addDiagramParticipants(ICanvasContext ctx) {\r
311         ctx.add(new ZOrderHandler());\r
312         ctx.add(getPointerInteractor());\r
313         ctx.add(new ElementInteractor());\r
314         ctx.add(new Selection());\r
315         ctx.add(new DiagramParticipant());\r
316         ctx.add(new ElementPainter());\r
317         //ctx.add(new ElementHeartbeater());\r
318         //ctx.add(new ZoomTransitionParticipant(TransitionFunction.SIGMOID));\r
319         //ctx.add(new TooltipParticipant());\r
320         ctx.add(new TerminalTooltipParticipant());\r
321     }\r
322 \r
323     protected void addPainterParticipants(ICanvasContext ctx) {\r
324         ctx.add(new RenderingQualityInteractor());\r
325         ctx.add(new TerminalPainter(true, true, false, true));\r
326         ctx.add(new DelayedBatchElementPainter(PickFilter.FILTER_MONITORS, 500, TimeUnit.MILLISECONDS));\r
327     }\r
328 \r
329     protected void addStructureParticipants(ICanvasContext ctx) {\r
330         addWorkbenchSelectionProvider(ctx);\r
331         // Add visual browsing capabilities for structural models\r
332         ctx.add(new StructuralBrowsingHandler(getSite(), sessionContext, getResourceInput2()));\r
333         ctx.add(new LinkBrowsingHandler(getSite(), this, sessionContext));\r
334     }\r
335 \r
336     /**\r
337      * Override to add any diagram/canvas participants to the canvas context\r
338      * initialized for the editor.\r
339      * \r
340      * @param ctx\r
341      */\r
342     protected void addOtherParticipants(CanvasContext ctx) {\r
343     }\r
344 \r
345     public static Set<String> defaultPropertyBrowseContexts = Collections.singleton(ProjectResource.URIs.ProjectBrowseContext);\r
346 \r
347     protected Set<String> getPropertyPageContexts() {\r
348         try {\r
349             return BrowseContext.getBrowseContextClosure(SimanticsUI.getSession(), defaultPropertyBrowseContexts);\r
350         } catch (DatabaseException e) {\r
351             ExceptionUtils.logAndShowError("Failed to load modeled browse contexts for property page, see exception for details.", e);\r
352             return defaultPropertyBrowseContexts;\r
353         }\r
354     }\r
355 \r
356     protected IPropertyPage createPropertyPage(IWorkbenchPartSite site, Set<String> contexts) {\r
357         return new StandardPropertyPage(site, contexts);\r
358     }\r
359 \r
360     protected String getPopupId() {\r
361         return "#ModelingDiagramPopup";\r
362     }\r
363 \r
364     protected void getPreferences() {\r
365         this.diagramPreferences = DiagramPreferenceUtil.getPreferences();\r
366     }\r
367 \r
368     protected void initSession() {\r
369         sessionContextProvider = SimanticsUI.getSessionContextProvider();\r
370         sessionContext = sessionContextProvider.getSessionContext();\r
371     }\r
372 \r
373     protected void readNames() {\r
374         String name = getEditorInput().getName();\r
375         host.doSetPartName(name);\r
376         host.doSetTitleToolTip(name);\r
377     }\r
378 \r
379     class ChassisListener implements IChassisListener {\r
380         @Override\r
381         public void chassisClosed(ICanvasChassis sender) {\r
382             // Prevent deadlock while disposing which using syncExec would result in.\r
383             final ICanvasContext ctx = canvasContext;\r
384             ThreadUtils.asyncExec(ctx.getThreadAccess(), new Runnable() {\r
385                 @Override\r
386                 public void run() {\r
387                     if (ctx != null) {\r
388                         saveEditorState(ctx);\r
389                         ctx.getHintStack().removeKeyHintListener(GridPainter.KEY_GRID_ENABLED, canvasHintListener);\r
390                         ctx.getHintStack().removeKeyHintListener(RulerPainter.KEY_RULER_ENABLED, canvasHintListener);\r
391                         final AWTChassis awtChassis = c.getAWTComponent();\r
392                         if (awtChassis != null)\r
393                             awtChassis.setCanvasContext(null);\r
394                         ctx.dispose();\r
395                     }\r
396 \r
397                     if (sourceDiagramContainer != null) {\r
398                         sourceDiagramContainer.set(null);\r
399                         sourceDiagramContainer = null;\r
400                     }\r
401 \r
402                     if (sourceDiagram != null)\r
403                         sourceDiagram.dispose();\r
404 \r
405                     if(synchronizer != null) {\r
406                         synchronizer.dispose();\r
407                         // Let GC work.\r
408                         synchronizer = null;\r
409                     }\r
410 \r
411                     if (runtimeDiagramManager != null) {\r
412                         runtimeDiagramManager.dispose();\r
413                         runtimeDiagramManager = null;\r
414                     }\r
415                 }\r
416             });\r
417             c.removeChassisListener(ChassisListener.this);\r
418         }\r
419     }\r
420 \r
421     protected void createChassis(Composite parent) {\r
422         resourceManager = new LocalResourceManager(JFaceResources.getResources(), parent);\r
423         c = new SWTChassis(parent, 0);\r
424 \r
425         Object task = BEGIN("DV.precreateParticipants");\r
426         createCustomParticipants();\r
427         END(task);\r
428 \r
429         c.populate(component -> {\r
430             if (!disposed) {\r
431                 c.addChassisListener(new ChassisListener());\r
432                 initializeCanvas();\r
433             }\r
434         });\r
435     }\r
436 \r
437     protected void beforeSetCanvasContext(ICanvasContext canvasContext2) {\r
438     }\r
439 \r
440     /**\r
441      * Invoke this only from the AWT thread.\r
442      * @param context\r
443      */\r
444     protected void setCanvasContext(ICanvasContext context) {\r
445         // Cannot directly invoke SWTChassis.setCanvasContext only because it\r
446         // needs to be invoked in the SWT thread and AWTChassis.setCanvasContext in the\r
447         // AWT thread, but directly invoking SWTChassis.setCanvasContext would call both\r
448         // in the SWT thread which would cause synchronous scheduling of AWT\r
449         // runnables which is always a potential source of deadlocks.\r
450         c.getAWTComponent().setCanvasContext(canvasContext);\r
451         swt.asyncExec(new Runnable() {\r
452             @Override\r
453             public void run() {\r
454                 if (!c.isDisposed())\r
455                     // For AWT, this is a no-operation.\r
456                     c.setCanvasContext(canvasContext);\r
457             }\r
458         });\r
459     }\r
460 \r
461     public void createPartControl(Composite parent) {\r
462         //ProfileObserver.begin = System.nanoTime();\r
463         display = parent.getDisplay(); \r
464         swt = SWTThread.getThreadAccess(display);\r
465         statusLineManager = getEditorSite().getActionBars().getStatusLineManager();\r
466 \r
467         Object task = BEGIN("DV.initSession");\r
468         initSession();\r
469         END(task);\r
470 \r
471         diagramResource = getInputResource();\r
472         readNames();\r
473         getPreferences();\r
474 \r
475         try {\r
476             this.runtimeDiagramManager = RuntimeDiagramManager.track(sessionContext.getSession(), diagramResource, getEditorInput(), this);\r
477 \r
478             // Create the canvas context here before finishing createPartControl\r
479             // to give DiagramViewerActionContributor a chance to work.\r
480             // The context can be created in SWT thread without scheduling\r
481             // to the context thread and having potential deadlocks.\r
482             IThreadWorkQueue thread = AWTThread.getThreadAccess();\r
483             this.canvasContext = new CanvasContext(thread);\r
484             this.canvasContext.setLocked(true);\r
485 \r
486             task = BEGIN("DV.createChassis");\r
487             createChassis(parent);\r
488             END(task);\r
489         } catch (DatabaseException e) {\r
490             ErrorLogger.defaultLogError(e);\r
491         }\r
492     }\r
493 \r
494 \r
495         /**\r
496      * A method invoked before chassis construction for creating such\r
497      * {@link ICanvasParticipant}s that need to be constructed in the SWT\r
498      * thread.\r
499      * \r
500      * Use it for creating any such canvas participants during the viewer \r
501      * construction and add them to the {@link ICanvasContext} later on from\r
502      * the AWT thread.\r
503      */\r
504     protected void createCustomParticipants() {\r
505         if (SimanticsUI.isLinuxGTK()) {\r
506                 popupMenuParticipant = new SWTPopupMenuParticipantAwt(getSite(), c, display, getPopupId());\r
507         } else {\r
508                 popupMenuParticipant = new SWTPopupMenuParticipant(getSite(), c, display, getPopupId());\r
509         }\r
510     }\r
511 \r
512     /**\r
513      * Invoke this only from the AWT thread.\r
514      */\r
515     protected void initializeCanvas() {\r
516         Object canvasInit = BEGIN("DV.canvasInitialization");\r
517 \r
518         Object task = BEGIN("DV.createViewerCanvas");\r
519         initializeCanvasContext(canvasContext);\r
520         END(task);\r
521 \r
522         beforeSetCanvasContext(canvasContext);\r
523         //FullscreenUtils.addFullScreenHandler(canvasContext, s, canvasProvider);\r
524 \r
525         // Without this all diagram participants will crash like there's no tomorrow.\r
526         // Just trying to keep the behavior a bit more sane in case of\r
527         // errors instead of flooding the console with exceptions.\r
528         canvasContext.getDefaultHintContext().setHint(DiagramHints.KEY_DIAGRAM, Diagram.spawnNew(DiagramClass.DEFAULT));\r
529 \r
530         // Changes in ruler/grid activity shall be written as\r
531         // workspace-persistent diagram-specific preferences.\r
532         canvasContext.getHintStack().addKeyHintListener(GridPainter.KEY_GRID_ENABLED, canvasHintListener);\r
533         canvasContext.getHintStack().addKeyHintListener(RulerPainter.KEY_RULER_ENABLED, canvasHintListener);\r
534 \r
535         task = BEGIN("DV.setCanvasContext");\r
536         setCanvasContext(canvasContext);\r
537         END(task);\r
538 \r
539         // Finish loading in a worker thread because it may be a time consuming\r
540         // process to load a large diagram and we don't want unnecessary AWT\r
541         // thread contention.\r
542         Job loadJob = new DiagramViewerLoadJob(this);\r
543         loadJob.schedule();\r
544 \r
545         END(canvasInit);\r
546     }\r
547 \r
548     protected void activateUiContexts(ContextUtil util) {\r
549         util.activate(DIAGRAMMING_CONTEXT);\r
550     }\r
551 \r
552     /**\r
553      * @param monitor the progress monitor to use for reporting progress to the\r
554      *        user. It is the caller's responsibility to call done() on the\r
555      *        given monitor. Accepts <code>null</code>, indicating that no\r
556      *        progress should be reported and that the operation cannot be\r
557      *        cancelled.\r
558      */\r
559     protected void performActivation(IProgressMonitor monitor) {\r
560         SubMonitor progress = SubMonitor.convert(monitor, "Activate Mapping", 100);\r
561         IActivationManager activationManager = sessionContext.getSession().peekService(IActivationManager.class);\r
562         if (activationManager != null) {\r
563             activation = activationManager.activate(diagramResource);\r
564         }\r
565         progress.worked(100);\r
566     }\r
567 \r
568     protected void onCreated() {\r
569     }\r
570 \r
571     /**\r
572      * @param diagram\r
573      */\r
574     protected void scheduleZoomToFit(IDiagram diagram) {\r
575         if (diagram == null)\r
576             throw new IllegalStateException("diagram is null");\r
577 \r
578         CanvasUtils.scheduleZoomToFit(swt, () -> disposed, canvasContext, diagram);\r
579     }\r
580 \r
581     /**\r
582      * Subclasses may override but should always invoke super.\r
583      * \r
584      * @param diagram\r
585      * @param initialHints\r
586      * @throws DatabaseException\r
587      */\r
588     protected void fillInitialDiagramHints(Resource diagram, IHintContext initialHints) throws DatabaseException {\r
589         IModelingRules modelingRules = sessionContext.getSession().syncRequest(\r
590                 DiagramRequests.getModelingRules(diagram, null));\r
591         if (modelingRules != null) {\r
592             initialHints.setHint(DiagramModelHints.KEY_MODELING_RULES, modelingRules);\r
593             initialHints.setHint(DiagramHints.CONNECTION_ADVISOR,\r
594                     getConnectionAdvisor(modelingRules, sessionContext.getSession()));\r
595         }\r
596 \r
597         initialHints.setHint(SynchronizationHints.COPY_ADVISOR, getCopyAdvisor());\r
598         initialHints.setHint(DiagramHints.KEY_USE_CONNECTION_FLAGS, Boolean.TRUE);\r
599         initialHints.setHint(DiagramHints.KEY_ALLOW_CONNECTION_BRANCHING, Boolean.TRUE);\r
600         initialHints.setHint(DiagramHints.KEY_ALLOW_ROUTE_POINTS, Boolean.TRUE);\r
601     }\r
602 \r
603     /**\r
604      * @param monitor the progress monitor to use for reporting progress to the\r
605      *        user. It is the caller's responsibility to call done() on the\r
606      *        given monitor. Accepts <code>null</code>, indicating that no\r
607      *        progress should be reported and that the operation cannot be\r
608      *        cancelled.\r
609      * @param r\r
610      * @return\r
611      * @throws DatabaseException\r
612      */\r
613     protected IDiagram loadDiagram(IProgressMonitor monitor, final Resource r) throws DatabaseException {\r
614         // Pre-load modeling rules and possibly other hints too since they are\r
615         // needed already while loading the diagram contents.\r
616         IHintContext initialHints = new HintContext();\r
617         fillInitialDiagramHints(r, initialHints);\r
618         IDiagram d = loadDiagram(monitor, r, initialHints);\r
619         return d;\r
620     }\r
621 \r
622     /**\r
623      * @param monitor the progress monitor to use for reporting progress to the\r
624      *        user. It is the caller's responsibility to call done() on the\r
625      *        given monitor. Accepts <code>null</code>, indicating that no\r
626      *        progress should be reported and that the operation cannot be\r
627      *        cancelled.\r
628      * @param diagram\r
629      * @param initialHints\r
630      * @return\r
631      * @throws DatabaseException\r
632      */\r
633     protected IDiagram loadDiagram(IProgressMonitor monitor, Resource diagram, IHintContext initialHints) throws DatabaseException {\r
634         RuntimeDiagramManager rtdm = runtimeDiagramManager;\r
635         Resource runtimeDiagram = rtdm != null ? rtdm.getRuntimeDiagram() : null;\r
636         IDiagramLoader loader = synchronizer;\r
637         if (rtdm == null || runtimeDiagram == null || loader == null)\r
638                 return null;\r
639         IDiagram d = sessionContext.getSession().syncRequest(\r
640                 DiagramRequests.loadDiagram(monitor, getResourceInput2().getModel(null), diagram,\r
641                         runtimeDiagram, null, loader, initialHints));\r
642         return d;\r
643     }\r
644 \r
645     protected void beforeSetDiagram(IDiagram diagram) {\r
646     }\r
647 \r
648     protected PointerInteractor getPointerInteractor() {\r
649         return new PointerInteractor2(true, true, true, false, true, false, synchronizer.getElementClassProvider());\r
650     }\r
651 \r
652     protected IConnectionAdvisor getConnectionAdvisor(IModelingRules modelingRules, Session session) {\r
653         return new ModelledConnectionAdvisor(modelingRules, sessionContext.getSession());\r
654     }\r
655 \r
656     protected GraphToDiagramSynchronizer createSynchronizer(final ICanvasContext ctx, final ISessionContext sessionContext) {\r
657         try {\r
658             return sessionContext.getSession().syncRequest(new Read<GraphToDiagramSynchronizer>() {\r
659                 @Override\r
660                 public GraphToDiagramSynchronizer perform(ReadGraph graph) throws DatabaseException {\r
661                     GraphToDiagramSynchronizer sync = new GraphToDiagramSynchronizer(graph, ctx, createElementClassProvider(graph));\r
662                     initializeSynchronizationContext(graph, sync);\r
663                     return sync;\r
664                 }\r
665             });\r
666         } catch (DatabaseException e) {\r
667             throw new UnsupportedOperationException("Failed to initialize data model synchronizer", e);\r
668         }\r
669     }\r
670 \r
671     protected void initializeSynchronizationContext(ReadGraph graph, IModifiableSynchronizationContext context) {\r
672         context.set(ModelingSynchronizationHints.MODELING_RESOURCE, ModelingResources.getInstance(graph));\r
673     }\r
674 \r
675     protected IElementClassProvider createElementClassProvider(ReadGraph graph) {\r
676         DiagramResource dr = DiagramResource.getInstance(graph);\r
677         return ElementClassProviders.mappedProvider(\r
678                 ElementClasses.CONNECTION, ConnectionClass.CLASS.newClassWith(new StaticObjectAdapter(dr.RouteGraphConnection)),\r
679                 ElementClasses.FLAG, FlagClassFactory.createFlagClass(dr.Flag, dr.Flag_Terminal)\r
680         );\r
681     }\r
682     \r
683     protected SimpleElementTransformHandler getTransformHandler() {\r
684         return new SimpleElementTransformHandler(true, true, true);\r
685     }\r
686 \r
687     public void initializeCanvasContext(CanvasContext ctx) {\r
688         IHintContext h = ctx.getDefaultHintContext();\r
689 \r
690         // The canvas context should not be painted until it is ready to avoid\r
691         // unnecessary visual glitches.\r
692         h.setHint(Hints.KEY_DISABLE_PAINTING, Boolean.TRUE);\r
693 \r
694         Object task = BEGIN("createSynchronizer");\r
695         this.synchronizer = createSynchronizer(ctx, sessionContext);\r
696         END(task);\r
697 \r
698         IContextService contextService = (IContextService) getSite().getService(IContextService.class);\r
699         contextUtil = new ContextUtil(contextService, swt);\r
700 \r
701         // Support & Util Participants\r
702         ctx.add(new TransformUtil());\r
703         ctx.add(new MouseUtil());\r
704         ctx.add(new KeyUtil());\r
705         ctx.add(contextUtil);\r
706         ctx.add(new WorkbenchStatusLine(statusLineManager));\r
707         ctx.add(new CanvasGrab());\r
708         ctx.add(new SymbolUtil());\r
709         ctx.add(new TimeParticipant());\r
710         ctx.add(new CanvasBoundsParticipant());\r
711         ctx.add(new Notifications());\r
712 \r
713         ctx.add(new SGFocusParticipant(c, DIAGRAMMING_CONTEXT));\r
714 \r
715         // Debug participant(s)\r
716         // ctx.add( new PointerPainter() );\r
717         // ctx.add( new HandPainter() );\r
718         h.setHint(PointerPainter.KEY_PAINT_POINTER, true);\r
719 \r
720         // Pan & Zoom & Rotate\r
721         addViewManipulationParticipants(ctx);\r
722 \r
723         ctx.add(getTransformHandler());\r
724         ctx.add(new ExpandSelectionHandler(getEditorSite().getActionBars().getStatusLineManager()));\r
725 \r
726         // Key bindings\r
727         addKeyBindingParticipants(ctx);\r
728 \r
729         // Grid & Ruler & Background\r
730         ctx.add(new GridPainter());\r
731         ctx.add(new RulerPainter());\r
732         ctx.add(new BackgroundPainter());\r
733 \r
734         h.setHint(Hints.KEY_DISPLAY_PAGE, diagramPreferences.get(DiagramPreferences.P_DISPLAY_PAGE_SIZE));\r
735         h.setHint(Hints.KEY_DISPLAY_MARGINS, diagramPreferences.get(DiagramPreferences.P_DISPLAY_MARGINS));\r
736         ctx.add(new PageBorderParticipant());\r
737 \r
738         // h.setHint(Hints.KEY_GRID_COLOR, new Color(0.9f, 0.9f, 0.9f));\r
739         // h.setHint(Hints.KEY_BACKGROUND_COLOR, Color.LIGHT_GRAY);\r
740         h.setHint(Hints.KEY_GRID_COLOR, new Color(0.9f, 0.9f, 0.9f));\r
741         h.setHint(Hints.KEY_BACKGROUND_COLOR, Color.WHITE);\r
742         h.setHint(RulerPainter.KEY_RULER_BACKGROUND_COLOR, new Color(0.9f, 0.9f, 0.9f, 0.75f));\r
743         h.setHint(RulerPainter.KEY_RULER_TEXT_COLOR, Color.BLACK);\r
744 \r
745         ////// Diagram Participants //////\r
746         addDiagramParticipants(ctx);\r
747         addPainterParticipants(ctx);\r
748 \r
749         /////// D'n'D ///////\r
750         addDropParticipants(ctx);\r
751 \r
752         h.setHint(ElementPainter.KEY_SELECTION_FRAME_COLOR, Color.MAGENTA);\r
753         h.setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);\r
754 \r
755         h.setHint(PanZoomRotateHandler.KEY_ZOOM_IN_LIMIT, 100000.0);\r
756         h.setHint(PanZoomRotateHandler.KEY_ZOOM_OUT_LIMIT, 10.0);\r
757 \r
758         Double snapResolution = diagramPreferences.get(DiagramPreferences.P_SNAP_GRID_SIZE);\r
759         this.snapAdvisor = new GridSnapAdvisor(snapResolution);\r
760         h.setHint(DiagramHints.SNAP_ADVISOR, this.snapAdvisor);\r
761         h.setHint(GridPainter.KEY_GRID_SIZE, snapResolution);\r
762         h.setHint(GridPainter.KEY_GRID_ENABLED, Boolean.FALSE);\r
763 \r
764         // Workbench selection provider\r
765         addStructureParticipants(ctx);\r
766 \r
767         // Pop-up menu\r
768         addPopupmenu(ctx);\r
769 \r
770         // Load page frame description settings\r
771         loadPageSettings(ctx);\r
772 \r
773         addOtherParticipants(ctx);\r
774 \r
775         ctx.assertParticipantDependencies();\r
776         ctx.setLocked(false);\r
777     }\r
778 \r
779     protected void loadPageSettings(ICanvasContext ctx) {\r
780         DiagramDesc diagramDesc = null;\r
781 \r
782         // load diagram page configuration\r
783         if (diagramResource != null) {\r
784             try {\r
785                 diagramDesc = sessionContext.getSession().syncRequest(DiagramRequests.getDiagramDesc(diagramResource));\r
786             } catch (DatabaseException e) {\r
787                 ErrorLogger.defaultLogError(e);\r
788             }\r
789         }\r
790 \r
791         if (diagramDesc == null) {\r
792             // Take page description from the preferences if nothing else is available.\r
793             final DiagramDesc desc = diagramDesc = diagramPreferences.getDiagramDesc();\r
794 \r
795             // Write page configuration to graph\r
796             sessionContext.getSession().asyncRequest(new WriteRequest() {\r
797                 @Override\r
798                 public void perform(WriteGraph graph) throws DatabaseException {\r
799                     if (graph.isImmutable(diagramResource))\r
800                         return;\r
801                     CommonDBUtils.selectClusterSet(graph, diagramResource);\r
802                     DiagramGraphUtil.setDiagramDesc(graph, diagramResource, desc);\r
803                 }\r
804             }, parameter -> {\r
805                 if (parameter != null)\r
806                     ErrorLogger.defaultLogError("Failed to write default diagram page description to database, see exception for details", parameter);\r
807             });\r
808         }\r
809 \r
810         setDiagramDesc(ctx, diagramDesc);\r
811 \r
812         // Create a listener to react to page setting changes.\r
813         sessionContext.getSession().asyncRequest(DiagramRequests.getDiagramDesc(diagramResource),\r
814                 new ListenerDelegate<DiagramDesc>(this) {\r
815             @Override\r
816             public void execute(final DiagramDesc result) {\r
817                 if (result != null && canvasContext != null) {\r
818                     ThreadUtils.asyncExec(canvasContext.getThreadAccess(), new Runnable() {\r
819                         @Override\r
820                         public void run() {\r
821                             if (!disposed)\r
822                                 setDiagramDesc(canvasContext, result);\r
823                         }\r
824                     });\r
825                 }\r
826             }\r
827         });\r
828     }\r
829 \r
830     protected void setDiagramDesc(ICanvasContext ctx, DiagramDesc diagramDesc) {\r
831         if (diagramDesc == null)\r
832             throw new NullPointerException("null diagram desc");\r
833 \r
834         if (diagramDesc.equals(this.diagramDesc))\r
835             return;\r
836 \r
837         this.diagramDesc = diagramDesc;\r
838         IHintContext hints = ctx.getDefaultHintContext();\r
839         hints.setHint(Hints.KEY_PAGE_DESC, diagramDesc.getPageDesc());\r
840         hints.setHint(Hints.KEY_DISPLAY_PAGE, diagramDesc.isPageBordersVisible());\r
841         hints.setHint(Hints.KEY_DISPLAY_MARGINS, diagramDesc.isMarginsVisible());\r
842         hints.setHint(GridPainter.KEY_GRID_ENABLED, diagramDesc.isGridVisible());\r
843         hints.setHint(RulerPainter.KEY_RULER_ENABLED, diagramDesc.isRulerVisible());\r
844         snapAdvisor.setResolution(diagramDesc.getGridSize());\r
845         hints.setHint(GridPainter.KEY_GRID_SIZE, diagramDesc.getGridSize());\r
846     }\r
847 \r
848     /**\r
849      * Must be invoked from the AWT thread only.\r
850      * \r
851      * @param state\r
852      * @param ctx\r
853      */\r
854     protected void applyEditorState(final EditorState state, final ICanvasContext ctx) {\r
855         final IDiagram diagram = ctx.getHintStack().getHint(DiagramHints.KEY_DIAGRAM);\r
856 \r
857         if (state.viewTransform != null && state.viewTransform.getDeterminant() != 0) {\r
858             for (PanZoomRotateHandler h : ctx.getItemsByClass(PanZoomRotateHandler.class)) {\r
859                 h.setTransform(state.viewTransform);\r
860             }\r
861         }\r
862 \r
863         if (diagram != null) {\r
864             if (state.viewTransform != null)\r
865                 diagram.removeHint(DiagramHints.KEY_INITIAL_ZOOM_TO_FIT);\r
866 \r
867             if (state.toolMode != null)\r
868                 ctx.getDefaultHintContext().setHint(Hints.KEY_TOOL, state.toToolMode());\r
869             else\r
870                 ctx.getDefaultHintContext().setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);\r
871 \r
872             final Set<IElement> selected = DiagramEditorStates.toElements(state.selection, diagram);\r
873             if (!selected.isEmpty()) {\r
874                 for (Selection s : ctx.getItemsByClass(Selection.class)) {\r
875                     s.setSelection(0, selected);\r
876                 }\r
877             }\r
878         }\r
879     }\r
880 \r
881     protected EditorState getSavedEditorState(ICanvasContext ctx) {\r
882         return DiagramEditorStates.toEditorState(ctx, true, true, true);\r
883     }\r
884 \r
885     protected void saveEditorState(ICanvasContext ctx) {\r
886         DiagramEditorStates.saveEditorState(PREFERENCE_VIRTUAL_GRAPH, diagramResource, getSavedEditorState(ctx) , DiagramViewer.this);\r
887     }\r
888 \r
889     private boolean firstFocus = true;\r
890 \r
891     public void setFocus() {\r
892         \r
893         if(c != null) {\r
894                 c.setFocus();\r
895 \r
896                 if (firstFocus) {\r
897                     // This is a workaround for using the symbol viewer in multi-page\r
898                     // editors which causes the first zoom-to-fit scheduling to happen\r
899                     // already before the controls have been laid out properly.\r
900                     firstFocus = false;\r
901                     firstTimeSetFocus();\r
902                 }\r
903                 \r
904         }\r
905         \r
906     }\r
907 \r
908     protected void firstTimeSetFocus() {\r
909         // [Tuukka@2010-02-11]\r
910         // Removed since this is actually a workaround for multi-page editors.\r
911         //scheduleZoomToFit();\r
912     }\r
913 \r
914     public void dispose() {\r
915         // Deactivate all contexts here because after this the context service\r
916         // in question will not be available.\r
917         if (contextUtil != null) {\r
918             contextUtil.deactivateAll();\r
919         }\r
920 \r
921         disposed = true;\r
922         if (activation != null) {\r
923             activation.deactivate();\r
924             activation = null;\r
925         }\r
926 \r
927         if (resourceManager != null) {\r
928                 resourceManager.dispose();\r
929                 resourceManager = null;\r
930         }\r
931         //super.dispose();\r
932     }\r
933 \r
934     protected Resource getInputResource() {\r
935         return getResourceInput().getResource();\r
936     }\r
937 \r
938     public IResourceEditorInput getResourceInput() {\r
939         return (IResourceEditorInput) getEditorInput();\r
940     }\r
941 \r
942     public IResourceEditorInput2 getResourceInput2() {\r
943         return (IResourceEditorInput2) getEditorInput();\r
944     }\r
945 \r
946     public void init(DiagramViewerHost _host, IEditorSite site, IEditorInput input, DataContainer<IDiagram> diagramContainer, WorkbenchSelectionProvider selectionProvider) {\r
947         if (!(input instanceof IResourceEditorInput))\r
948             throw new RuntimeException("Invalid input: must be IResourceEditorInput");\r
949 \r
950         setHost(_host);\r
951         setSite(site);\r
952         setInput(input);\r
953         this.sourceDiagramContainer = diagramContainer;\r
954         this.selectionProvider = selectionProvider;\r
955 \r
956         // Set initial part name according to the name given by IEditorInput\r
957         host.doSetPartName(getEditorInput().getName());\r
958 \r
959         Session session = SimanticsUI.peekSession();\r
960         if (session != null) {\r
961             Supplier<Boolean> disposedCallback = () -> disposed;\r
962             session.asyncRequest(\r
963                     new TitleRequest(site.getId(), getResourceInput()),\r
964                     new TitleUpdater(site.getShell().getDisplay(), host::doSetPartName, disposedCallback));\r
965             session.asyncRequest(\r
966                     new ToolTipRequest(site.getId(), getResourceInput()),\r
967                     new TitleUpdater(site.getShell().getDisplay(), host::doSetTitleToolTip, disposedCallback));\r
968         }\r
969 \r
970         try {\r
971             // Read previous editor state from the database\r
972             editorState = DiagramEditorStates.readEditorState(getInputResource());\r
973         } catch (DatabaseException e) {\r
974             exception(e);\r
975         }\r
976     }\r
977 \r
978     @SuppressWarnings("unchecked")\r
979     @Override\r
980     public <T> T getAdapter(Class<T> adapter) {\r
981 //        System.out.println("diagramViewer getAdapter " + adapter);\r
982         // Property view support\r
983         if (adapter == IPropertyPage.class)\r
984             return (T) createPropertyPage(getSite(), getPropertyPageContexts());\r
985         // Provide symbols for the editor\r
986         if (adapter == SymbolProviderFactory.class) {\r
987             try {\r
988                 return (T) DiagramTypeUtils.readSymbolProviderFactory(sessionContext.getSession(), diagramResource);\r
989             } catch (DatabaseException e) {\r
990                 ErrorLogger.defaultLogError(getClass() + " failed to adapt to SymbolProviderFactory, see exception for details.", e);\r
991                 return null;\r
992             }\r
993         }\r
994         // Outline view support\r
995         if (adapter == IContentOutlinePage.class)\r
996             return (T) new DiagramOutlinePage(sessionContextProvider, getResourceInput2());\r
997         // Role view support\r
998         if (adapter == ILayersViewPage.class)\r
999             return (T) new DiagramLayersPage(sourceDiagram, canvasContext);\r
1000         // Support external steering of the diagram canvas, zooming etc.\r
1001         if (adapter == ICanvasContext.class)\r
1002             return (T) canvasContext;\r
1003         // Support scene graph debugger view\r
1004         if (adapter == INode.class) {\r
1005             if (canvasContext != null) {\r
1006                 INode node = canvasContext.getCanvasNode();\r
1007                 if (node != null)\r
1008                     return (T) NodeUtil.getRootNode(node);\r
1009             }\r
1010             return null;\r
1011         }\r
1012         // Support retrieval of the current diagram.\r
1013         if (adapter == IDiagram.class)\r
1014             return (T) sourceDiagram;\r
1015         // Why is this here ??\r
1016         if (adapter == Session.class)\r
1017             return (T) sessionContext.getSession();\r
1018         if(adapter == RuntimeDiagramManager.class)\r
1019             return (T) runtimeDiagramManager;\r
1020         if (adapter == Resource.class)\r
1021             return (T) getRuntime();\r
1022         if (adapter == ICanvasChassis.class)\r
1023             return (T) c;\r
1024 \r
1025         return null;\r
1026     }\r
1027 \r
1028     //-------------------------------------------------------------------------\r
1029     // Profiling aid\r
1030 \r
1031     protected static Object BEGIN(String name) {\r
1032         if (PROFILE) {\r
1033             //return ThreadLog.BEGIN(name);\r
1034         }\r
1035         return null;\r
1036     }\r
1037 \r
1038     protected static void END(Object task) {\r
1039         if (PROFILE) {\r
1040             //((Task) task).end();\r
1041         }\r
1042     }\r
1043 \r
1044     //-------------------------------------------------------------------------\r
1045     // implement ListenerSupport\r
1046 \r
1047     @Override\r
1048     public void exception(Throwable t) {\r
1049         ErrorLogger.defaultLogError(t);\r
1050     }\r
1051 \r
1052     @Override\r
1053     public boolean isDisposed() {\r
1054         return disposed;\r
1055     }\r
1056 \r
1057     protected void collectGarbage() {\r
1058         SessionGarbageCollectorJob.getInstance().schedule(0);\r
1059         AWTThread.getThreadAccess().asyncExec(new Runnable() {\r
1060             @Override\r
1061             public void run() {\r
1062                 //System.out.println("BEFORE CLEAR: " + SVGCache.getSVGUniverse().report());\r
1063                 SVGCache.getSVGUniverse().clearUnreferenced();\r
1064                 //System.out.println("AFTER CLEAR: " + SVGCache.getSVGUniverse().report());\r
1065             }\r
1066         });\r
1067     }\r
1068 \r
1069     //-------------------------------------------------------------------------\r
1070     // Listener for certain canvas context hint changes\r
1071 \r
1072     IHintListener canvasHintListener = new HintListenerAdapter() {\r
1073         @Override\r
1074         public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
1075             if (key == GridPainter.KEY_GRID_ENABLED) {\r
1076                 boolean v = Boolean.TRUE.equals(newValue);\r
1077                 if (diagramDesc.isGridVisible() != v)\r
1078                     setGlobalPreference(DiagramResource.URIs.DisplayGrid, v);\r
1079             } else if (key == RulerPainter.KEY_RULER_ENABLED) {\r
1080                 boolean v = Boolean.TRUE.equals(newValue);\r
1081                 if (diagramDesc.isRulerVisible() != v)\r
1082                     setGlobalPreference(DiagramResource.URIs.DisplayRuler, v);\r
1083             }\r
1084         }\r
1085     };\r
1086 \r
1087     private <T> void setGlobalPreference(final String preferenceURI, boolean value) {\r
1088         TagUtil.execute(Simantics.getSession(), PREFERENCE_VIRTUAL_GRAPH, preferenceURI, value, Simantics.getProjectResource());\r
1089     }\r
1090 \r
1091     /*\r
1092      * --------------------------------------------------------------------\r
1093      * Changes related to removal of EditorPart extension from here on down\r
1094      * --------------------------------------------------------------------\r
1095      */\r
1096 \r
1097     private IWorkbenchPartSite partSite;\r
1098     private DiagramViewerHost host;\r
1099     private IEditorInput editorInput = null;\r
1100 \r
1101     /* (non-Javadoc)\r
1102      * Method declared on IWorkbenchPart.\r
1103      */\r
1104     public IWorkbenchPartSite getSite() {\r
1105         return partSite;\r
1106     }\r
1107 \r
1108     public IEditorSite getEditorSite() {\r
1109         return (IEditorSite) getSite();\r
1110     }\r
1111 \r
1112     public IEditorInput getEditorInput() {\r
1113         return editorInput;\r
1114     }\r
1115 \r
1116 //    protected void setPartName(String partName) {\r
1117 ////        if (compatibilityTitleListener != null) {\r
1118 ////            removePropertyListener(compatibilityTitleListener);\r
1119 ////            compatibilityTitleListener = null;\r
1120 ////        }\r
1121 ////\r
1122 ////        super.setPartName(partName);\r
1123 //    }\r
1124  \r
1125 //    protected void setTitleToolTip(String toolTip) {\r
1126 ////        toolTip = Util.safeString(toolTip);\r
1127 ////        //Do not send changes if they are the same\r
1128 ////        if (Util.equals(this.toolTip, toolTip)) {\r
1129 ////                    return;\r
1130 ////            }\r
1131 ////        this.toolTip = toolTip;\r
1132 ////        firePropertyChange(IWorkbenchPart.PROP_TITLE);\r
1133 //    }\r
1134 \r
1135     protected void setHost(DiagramViewerHost host) {\r
1136         this.host = host;\r
1137     }\r
1138 \r
1139     protected void setSite(IWorkbenchPartSite site) {\r
1140         this.partSite = site;\r
1141     }\r
1142 \r
1143     protected void setInput(IEditorInput input) {\r
1144         Assert.isLegal(input != null);\r
1145         editorInput = input;\r
1146     }\r
1147 \r
1148     public Composite getComposite() {\r
1149         return c;\r
1150     }\r
1151 \r
1152 }\r