]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/diagramEditor/DiagramViewer.java
Rid TypicalPropertyTester of database read transactions
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / diagramEditor / DiagramViewer.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2019 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
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;
14
15 import java.awt.Color;
16 import java.awt.dnd.DnDConstants;
17 import java.util.Collections;
18 import java.util.Set;
19 import java.util.concurrent.TimeUnit;
20 import java.util.function.Supplier;
21
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;
174
175 import com.kitfox.svg.SVGCache;
176
177 /**
178  * @author Toni Kalajainen
179  * @author Tuukka Lehtonen
180  */
181 public class DiagramViewer 
182   //extends EditorPart implements IResourceEditorPart2, 
183     implements ListenerSupport, IAdaptable {
184
185     public interface DiagramViewerHost {
186         void doSetPartName(String name);
187         void doSetTitleToolTip(String name);
188     }
189
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$
192
193     private static final boolean                    PROFILE                  = false;
194
195     ParametrizedRead<IResourceEditorInput, Boolean> INPUT_VALIDATOR =
196         Combinators.compose(
197                 InputValidationCombinators.or(
198                         // Normal configuration diagrams of a model
199                         Combinators.compose(
200                                 InputValidationCombinators.hasURI(),
201                                 InputValidationCombinators.partialFunction(ModelingResources.URIs.DiagramToComposite)
202                         ),
203                         // Configuration diagrams of a component type
204                         Combinators.compose(
205                                 InputValidationCombinators.hasURI(),
206                                 Combinators.compose(
207                                         InputValidationCombinators.partialFunction(StructuralResource2.URIs.Defines),
208                                         InputValidationCombinators.partialFunction(ModelingResources.URIs.DiagramToComposite)
209                                 )
210                         )
211                 ),
212                 InputValidationCombinators.extractInputResource()
213         );
214
215     protected EditorState                editorState;
216
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;
233     
234     protected DiagramPreferences         diagramPreferences;
235     protected DiagramDesc                diagramDesc;
236     protected GridSnapAdvisor            snapAdvisor;
237
238     private RuntimeDiagramManager        runtimeDiagramManager;
239     private HasDiagramSourceListener     hasDiagramSourceListener;
240
241     /**
242      * Set externally in
243      * {@link #init(DiagramViewerHost, IEditorSite, IEditorInput, DataContainer, WorkbenchSelectionProvider)}
244      * .
245      */
246     protected WorkbenchSelectionProvider selectionProvider;
247
248     public Resource getRuntime() {
249         RuntimeDiagramManager rtdm = runtimeDiagramManager;
250         return (rtdm == null) ? null : rtdm.getRuntimeDiagram();
251     }
252
253     public ParametrizedRead<IResourceEditorInput, Boolean> getInputValidator() {
254         return INPUT_VALIDATOR;
255     }
256
257     protected void addDropParticipants(ICanvasContext ctx) {
258         ctx.getDefaultHintContext().setHint(Hints.KEY_ALLOWED_DRAG_ACTIONS, DnDConstants.ACTION_COPY);
259
260         ctx.add(new PopulateElementDropParticipant(synchronizer, getSite()));
261         ctx.add(new PopulateElementMonitorDropParticipant(synchronizer, 0.5, 0.5));
262     }
263
264     protected CopyPasteStrategy getCopyPasteStrategy() {
265                 try {
266                         CopyPasteStrategy cpStrategy = Simantics.getSession().syncRequest(new PossibleAdapter<CopyPasteStrategy>(getInputResource(), CopyPasteStrategy.class));
267                         if(cpStrategy != null) return cpStrategy;
268                 } catch (DatabaseException e) {
269                 }
270                 return getDefaultCopyPasteStrategy();
271     }
272     
273     protected CopyPasteStrategy getDefaultCopyPasteStrategy() {
274         return new DefaultCopyPasteStrategy();
275     }
276
277     protected CopyAdvisor getCopyAdvisor() {
278                 try {
279                         CopyAdvisor advisor = Simantics.getSession().syncRequest(new PossibleAdapter<CopyAdvisor>(getInputResource(), CopyAdvisor.class));
280                         if(advisor != null) return advisor;
281                 } catch (DatabaseException e) {
282                 }
283                 return new MappedElementCopyAdvisor(new ElementCopyAdvisor(), new ComponentCopyAdvisor());
284     }
285     
286     /**
287      * @param ctx
288      * TODO: change argument from CanvasContext to ICanvasContext
289      */
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());
295     }
296
297     protected void addPopupmenu(ICanvasContext ctx) {
298         ctx.add(popupMenuParticipant);
299     }
300
301     protected void addWorkbenchSelectionProvider(ICanvasContext ctx) {
302         if (selectionProvider != null)
303             ctx.add(selectionProvider);
304     }
305
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());
312     }
313
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());
325     }
326
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));
331     }
332
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));
338     }
339
340     /**
341      * Override to add any diagram/canvas participants to the canvas context
342      * initialized for the editor.
343      * 
344      * @param ctx
345      */
346     protected void addOtherParticipants(CanvasContext ctx) {
347     }
348
349     public static Set<String> defaultPropertyBrowseContexts = Collections.singleton(ProjectResource.URIs.ProjectBrowseContext);
350
351     protected Set<String> getPropertyPageContexts() {
352         try {
353             return BrowseContext.getBrowseContextClosure(Simantics.getSession(), defaultPropertyBrowseContexts);
354         } catch (DatabaseException e) {
355             ExceptionUtils.logAndShowError(Messages.DiagramViewer_FailedtoLoadModeled, e);
356             return defaultPropertyBrowseContexts;
357         }
358     }
359
360     protected IPropertyPage createPropertyPage(IWorkbenchPartSite site, Set<String> contexts) {
361         return new StandardPropertyPage(site, contexts);
362     }
363
364     protected String getPopupId() {
365         return "#ModelingDiagramPopup"; //$NON-NLS-1$
366     }
367
368     protected void getPreferences() {
369         this.diagramPreferences = DiagramPreferenceUtil.getPreferences();
370     }
371
372     protected void initSession() {
373         sessionContextProvider = Simantics.getSessionContextProvider();
374         sessionContext = sessionContextProvider.getSessionContext();
375     }
376
377     protected void readNames() {
378         String name = getEditorInput().getName();
379         host.doSetPartName(name);
380         host.doSetTitleToolTip(name);
381     }
382
383     class ChassisListener implements IChassisListener {
384         @Override
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() {
389                 @Override
390                 public void run() {
391                     if (ctx != null) {
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);
398                         ctx.dispose();
399                     }
400
401                     if (sourceDiagramContainer != null) {
402                         sourceDiagramContainer.set(null);
403                         sourceDiagramContainer = null;
404                     }
405
406                     if (sourceDiagram != null)
407                         sourceDiagram.dispose();
408
409                     if(synchronizer != null) {
410                         synchronizer.dispose();
411                         // Let GC work.
412                         synchronizer = null;
413                     }
414
415                     if (runtimeDiagramManager != null) {
416                         runtimeDiagramManager.dispose();
417                         runtimeDiagramManager = null;
418                     }
419                 }
420             });
421             c.removeChassisListener(ChassisListener.this);
422         }
423     }
424
425     protected void createChassis(Composite parent) {
426         resourceManager = new LocalResourceManager(JFaceResources.getResources(), parent);
427         c = new SWTChassis(parent, 0);
428
429         Object task = BEGIN("DV.precreateParticipants"); //$NON-NLS-1$
430         createCustomParticipants();
431         END(task);
432
433         c.populate(component -> {
434             if (!disposed) {
435                 c.addChassisListener(new ChassisListener());
436                 initializeCanvas();
437             }
438         });
439     }
440
441     protected void beforeSetCanvasContext(ICanvasContext canvasContext2) {
442     }
443
444     /**
445      * Invoke this only from the AWT thread.
446      * @param context
447      */
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() {
456             @Override
457             public void run() {
458                 if (!c.isDisposed())
459                     // For AWT, this is a no-operation.
460                     c.setCanvasContext(canvasContext);
461             }
462         });
463     }
464
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();
470
471         Object task = BEGIN("DV.initSession"); //$NON-NLS-1$
472         initSession();
473         END(task);
474
475         diagramResource = getInputResource();
476         readNames();
477         getPreferences();
478
479         try {
480             this.runtimeDiagramManager = RuntimeDiagramManager.track(sessionContext.getSession(), diagramResource, getEditorInput(), this);
481
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);
489
490             task = BEGIN("DV.createChassis"); //$NON-NLS-1$
491             createChassis(parent);
492             END(task);
493         } catch (DatabaseException e) {
494             ErrorLogger.defaultLogError(e);
495         }
496     }
497
498
499         /**
500      * A method invoked before chassis construction for creating such
501      * {@link ICanvasParticipant}s that need to be constructed in the SWT
502      * thread.
503      * 
504      * Use it for creating any such canvas participants during the viewer 
505      * construction and add them to the {@link ICanvasContext} later on from
506      * the AWT thread.
507      */
508     protected void createCustomParticipants() {
509         if (SimanticsUI.isLinuxGTK()) {
510                 popupMenuParticipant = new SWTPopupMenuParticipantAwt(getSite(), c, display, getPopupId());
511         } else {
512                 popupMenuParticipant = new SWTPopupMenuParticipant(getSite(), c, display, getPopupId());
513         }
514     }
515
516     /**
517      * Invoke this only from the AWT thread.
518      */
519     protected void initializeCanvas() {
520         Object canvasInit = BEGIN("DV.canvasInitialization"); //$NON-NLS-1$
521
522         Object task = BEGIN("DV.createViewerCanvas"); //$NON-NLS-1$
523         initializeCanvasContext(canvasContext);
524         END(task);
525
526         beforeSetCanvasContext(canvasContext);
527         //FullscreenUtils.addFullScreenHandler(canvasContext, s, canvasProvider);
528
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));
533
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);
538
539         task = BEGIN("DV.setCanvasContext"); //$NON-NLS-1$
540         setCanvasContext(canvasContext);
541         END(task);
542
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);
547         loadJob.schedule();
548
549         END(canvasInit);
550     }
551
552     protected void activateUiContexts(ContextUtil util) {
553         util.activate(DIAGRAMMING_CONTEXT);
554     }
555
556     /**
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
561      *        cancelled.
562      */
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);
568         }
569         progress.worked(100);
570     }
571
572     protected void onCreated() {
573     }
574
575     /**
576      * @param diagram
577      */
578     protected void scheduleZoomToFit(IDiagram diagram) {
579         if (diagram == null)
580             throw new IllegalStateException("diagram is null"); //$NON-NLS-1$
581
582         CanvasUtils.scheduleZoomToFit(swt, () -> disposed, canvasContext, diagram);
583     }
584
585     /**
586      * Subclasses may override but should always invoke super.
587      * 
588      * @param diagram
589      * @param initialHints
590      * @throws DatabaseException
591      */
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()));
599         }
600
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);
605     }
606
607     /**
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
612      *        cancelled.
613      * @param r
614      * @return
615      * @throws DatabaseException
616      */
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);
623         return d;
624     }
625
626     /**
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
631      *        cancelled.
632      * @param diagram
633      * @param initialHints
634      * @return
635      * @throws DatabaseException
636      */
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)
642             return 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);
646
647             // #399: Enable certain PropertyTester implementation without database transactions
648             ModelingResources MOD = ModelingResources.getInstance(graph);
649             Resource composite = graph.getPossibleObject(diagram, MOD.DiagramToComposite);
650             result.setHint(
651                     DiagramModelHints.KEY_DIAGRAM_RESOURCE_TYPE_URIS,
652                     graph.syncRequest(new TypeURIs(diagram)));
653             result.setHint(
654                     DiagramModelHints.KEY_MAPPED_COMPOSITE_RESOURCE_TYPE_URIS,
655                     composite != null ? graph.syncRequest(new TypeURIs(composite)) : Collections.emptySet());
656
657             Resource diagramSource = graph.syncRequest(
658                     new PossibleObject(diagram, MOD.HasDiagramSource),
659                     hasDiagramSourceListener = new HasDiagramSourceListener(sourceDiagramContainer));
660             ElementUtils.setOrRemoveHint(
661                     result, 
662                     DiagramModelHints.KEY_HAS_DIAGRAM_SOURCE,
663                     diagramSource);
664
665             return result;
666         });
667         return d;
668     }
669
670     protected void beforeSetDiagram(IDiagram diagram) {
671     }
672
673     protected PointerInteractor getPointerInteractor() {
674         return new PointerInteractor2(true, true, true, false, true, false, synchronizer.getElementClassProvider());
675     }
676
677     protected IConnectionAdvisor getConnectionAdvisor(IModelingRules modelingRules, Session session) {
678         return new ModelledConnectionAdvisor(modelingRules, sessionContext.getSession());
679     }
680
681     protected GraphToDiagramSynchronizer createSynchronizer(final ICanvasContext ctx, final ISessionContext sessionContext) {
682         try {
683             return sessionContext.getSession().syncRequest(new Read<GraphToDiagramSynchronizer>() {
684                 @Override
685                 public GraphToDiagramSynchronizer perform(ReadGraph graph) throws DatabaseException {
686                     GraphToDiagramSynchronizer sync = new GraphToDiagramSynchronizer(graph, ctx, createElementClassProvider(graph));
687                     initializeSynchronizationContext(graph, sync);
688                     return sync;
689                 }
690             });
691         } catch (DatabaseException e) {
692             throw new UnsupportedOperationException("Failed to initialize data model synchronizer", e); //$NON-NLS-1$
693         }
694     }
695
696     protected void initializeSynchronizationContext(ReadGraph graph, IModifiableSynchronizationContext context) {
697         context.set(ModelingSynchronizationHints.MODELING_RESOURCE, ModelingResources.getInstance(graph));
698     }
699
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)
705         );
706     }
707     
708     protected SimpleElementTransformHandler getTransformHandler() {
709         return new SimpleElementTransformHandler(true, true, true);
710     }
711
712     public void initializeCanvasContext(CanvasContext ctx) {
713         IHintContext h = ctx.getDefaultHintContext();
714
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);
718
719         Object task = BEGIN("createSynchronizer"); //$NON-NLS-1$
720         this.synchronizer = createSynchronizer(ctx, sessionContext);
721         END(task);
722
723         IContextService contextService = (IContextService) getSite().getService(IContextService.class);
724         contextUtil = new ContextUtil(contextService, swt);
725
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());
737
738         ctx.add(new SGFocusParticipant(c, DIAGRAMMING_CONTEXT));
739
740         // Debug participant(s)
741         // ctx.add( new PointerPainter() );
742         // ctx.add( new HandPainter() );
743         h.setHint(PointerPainter.KEY_PAINT_POINTER, true);
744
745         // Pan & Zoom & Rotate
746         addViewManipulationParticipants(ctx);
747
748         ctx.add(getTransformHandler());
749         ctx.add(new ExpandSelectionHandler(getEditorSite().getActionBars().getStatusLineManager()));
750
751         // Key bindings
752         addKeyBindingParticipants(ctx);
753
754         // Grid & Ruler & Background
755         addGridRulerBackgroundParticipants(ctx);
756
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());
760
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);
767
768         ////// Diagram Participants //////
769         addDiagramParticipants(ctx);
770         addPainterParticipants(ctx);
771
772         /////// D'n'D ///////
773         addDropParticipants(ctx);
774
775         h.setHint(ElementPainter.KEY_SELECTION_FRAME_COLOR, Color.MAGENTA);
776         h.setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
777
778         h.setHint(PanZoomRotateHandler.KEY_ZOOM_IN_LIMIT, 100000.0);
779         h.setHint(PanZoomRotateHandler.KEY_ZOOM_OUT_LIMIT, 10.0);
780
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);
786
787         // Workbench selection provider
788         addStructureParticipants(ctx);
789
790         // Pop-up menu
791         addPopupmenu(ctx);
792
793         // Load page frame description settings
794         loadPageSettings(ctx);
795
796         addOtherParticipants(ctx);
797
798         ctx.assertParticipantDependencies();
799         ctx.setLocked(false);
800     }
801
802     protected void addGridRulerBackgroundParticipants(CanvasContext ctx) {
803         ctx.add(new GridPainter());
804         ctx.add(new RulerPainter());
805         ctx.add(new BackgroundPainter());
806     }
807
808     protected void loadPageSettings(ICanvasContext ctx) {
809         DiagramDesc diagramDesc = null;
810
811         // load diagram page configuration
812         if (diagramResource != null) {
813             try {
814                 diagramDesc = sessionContext.getSession().syncRequest(DiagramRequests.getDiagramDesc(diagramResource));
815             } catch (DatabaseException e) {
816                 ErrorLogger.defaultLogError(e);
817             }
818         }
819
820         if (diagramDesc == null) {
821             // Take page description from the preferences if nothing else is available.
822             final DiagramDesc desc = diagramDesc = diagramPreferences.getDiagramDesc();
823
824             // Write page configuration to graph
825             sessionContext.getSession().asyncRequest(new WriteRequest() {
826                 @Override
827                 public void perform(WriteGraph graph) throws DatabaseException {
828                     if (graph.isImmutable(diagramResource))
829                         return;
830                     CommonDBUtils.selectClusterSet(graph, diagramResource);
831                     DiagramGraphUtil.setDiagramDesc(graph, diagramResource, desc);
832                 }
833             }, parameter -> {
834                 if (parameter != null)
835                     ErrorLogger.defaultLogError("Failed to write default diagram page description to database, see exception for details", parameter); //$NON-NLS-1$
836             });
837         }
838
839         setDiagramDesc(ctx, diagramDesc);
840
841         // Create a listener to react to page setting changes.
842         sessionContext.getSession().asyncRequest(DiagramRequests.getDiagramDesc(diagramResource),
843                 new ListenerDelegate<DiagramDesc>(this) {
844             @Override
845             public void execute(final DiagramDesc result) {
846                 if (result != null && canvasContext != null) {
847                     ThreadUtils.asyncExec(canvasContext.getThreadAccess(), new Runnable() {
848                         @Override
849                         public void run() {
850                             if (!disposed)
851                                 setDiagramDesc(canvasContext, result);
852                         }
853                     });
854                 }
855             }
856         });
857     }
858
859     protected void setDiagramDesc(ICanvasContext ctx, DiagramDesc diagramDesc) {
860         if (diagramDesc == null)
861             throw new NullPointerException("null diagram desc"); //$NON-NLS-1$
862
863         if (diagramDesc.equals(this.diagramDesc))
864             return;
865
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());
875     }
876
877     /**
878      * Must be invoked from the AWT thread only.
879      * 
880      * @param state
881      * @param ctx
882      */
883     protected void applyEditorState(final EditorState state, final ICanvasContext ctx) {
884         final IDiagram diagram = ctx.getHintStack().getHint(DiagramHints.KEY_DIAGRAM);
885
886         if (state.viewTransform != null && state.viewTransform.getDeterminant() != 0) {
887             for (PanZoomRotateHandler h : ctx.getItemsByClass(PanZoomRotateHandler.class)) {
888                 h.setTransform(state.viewTransform);
889             }
890         }
891
892         if (diagram != null) {
893             if (state.viewTransform != null)
894                 diagram.removeHint(DiagramHints.KEY_INITIAL_ZOOM_TO_FIT);
895
896             if (state.toolMode != null)
897                 ctx.getDefaultHintContext().setHint(Hints.KEY_TOOL, state.toToolMode());
898             else
899                 ctx.getDefaultHintContext().setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
900
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);
905                 }
906             }
907         }
908     }
909
910     protected EditorState getSavedEditorState(ICanvasContext ctx) {
911         return DiagramEditorStates.toEditorState(ctx, true, true, true);
912     }
913
914     protected void saveEditorState(ICanvasContext ctx) {
915         DiagramEditorStates.saveEditorState(PREFERENCE_VIRTUAL_GRAPH, diagramResource, getSavedEditorState(ctx) , DiagramViewer.this);
916     }
917
918     private boolean firstFocus = true;
919
920     public void setFocus() {
921         
922         if(c != null) {
923                 c.setFocus();
924
925                 if (firstFocus) {
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.
929                     firstFocus = false;
930                     firstTimeSetFocus();
931                 }
932                 
933         }
934         
935     }
936
937     protected void firstTimeSetFocus() {
938         // [Tuukka@2010-02-11]
939         // Removed since this is actually a workaround for multi-page editors.
940         //scheduleZoomToFit();
941     }
942
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();
948         }
949
950         disposed = true;
951
952         if (hasDiagramSourceListener != null) {
953             hasDiagramSourceListener.dispose();
954             hasDiagramSourceListener = null;
955         }
956
957         if (activation != null) {
958             activation.deactivate();
959             activation = null;
960         }
961
962         if (resourceManager != null) {
963                 resourceManager.dispose();
964                 resourceManager = null;
965         }
966         //super.dispose();
967     }
968
969     protected Resource getInputResource() {
970         return getResourceInput().getResource();
971     }
972
973     public IResourceEditorInput getResourceInput() {
974         return (IResourceEditorInput) getEditorInput();
975     }
976
977     public IResourceEditorInput2 getResourceInput2() {
978         return (IResourceEditorInput2) getEditorInput();
979     }
980
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$
984
985         setHost(_host);
986         setSite(site);
987         setInput(input);
988         this.sourceDiagramContainer = diagramContainer;
989         this.selectionProvider = selectionProvider;
990
991         // Set initial part name according to the name given by IEditorInput
992         host.doSetPartName(getEditorInput().getName());
993
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));
1003         }
1004
1005         try {
1006             // Read previous editor state from the database
1007             editorState = DiagramEditorStates.readEditorState(getInputResource());
1008         } catch (DatabaseException e) {
1009             exception(e);
1010         }
1011     }
1012
1013     @SuppressWarnings("unchecked")
1014     @Override
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) {
1022             try {
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$
1026                 return null;
1027             }
1028         }
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();
1042                 if (node != null)
1043                     return (T) NodeUtil.getRootNode(node);
1044             }
1045             return null;
1046         }
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)
1058             return (T) c;
1059
1060         return null;
1061     }
1062
1063     //-------------------------------------------------------------------------
1064     // Profiling aid
1065
1066     protected static Object BEGIN(String name) {
1067         if (PROFILE) {
1068             //return ThreadLog.BEGIN(name);
1069         }
1070         return null;
1071     }
1072
1073     protected static void END(Object task) {
1074         if (PROFILE) {
1075             //((Task) task).end();
1076         }
1077     }
1078
1079     //-------------------------------------------------------------------------
1080     // implement ListenerSupport
1081
1082     @Override
1083     public void exception(Throwable t) {
1084         ErrorLogger.defaultLogError(t);
1085     }
1086
1087     @Override
1088     public boolean isDisposed() {
1089         return disposed;
1090     }
1091
1092     protected void collectGarbage() {
1093         SessionGarbageCollectorJob.getInstance().schedule(0);
1094         AWTThread.getThreadAccess().asyncExec(new Runnable() {
1095             @Override
1096             public void run() {
1097                 //System.out.println("BEFORE CLEAR: " + SVGCache.getSVGUniverse().report());
1098                 SVGCache.getSVGUniverse().clearUnreferenced();
1099                 //System.out.println("AFTER CLEAR: " + SVGCache.getSVGUniverse().report());
1100             }
1101         });
1102     }
1103
1104     //-------------------------------------------------------------------------
1105     // Listener for certain canvas context hint changes
1106
1107     IHintListener canvasHintListener = new HintListenerAdapter() {
1108         @Override
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);
1118             }
1119         }
1120     };
1121
1122     private <T> void setGlobalPreference(final String preferenceURI, boolean value) {
1123         TagUtil.execute(Simantics.getSession(), PREFERENCE_VIRTUAL_GRAPH, preferenceURI, value, Simantics.getProjectResource());
1124     }
1125
1126     /*
1127      * --------------------------------------------------------------------
1128      * Changes related to removal of EditorPart extension from here on down
1129      * --------------------------------------------------------------------
1130      */
1131
1132     private IWorkbenchPartSite partSite;
1133     private DiagramViewerHost host;
1134     private IEditorInput editorInput = null;
1135
1136     /* (non-Javadoc)
1137      * Method declared on IWorkbenchPart.
1138      */
1139     public IWorkbenchPartSite getSite() {
1140         return partSite;
1141     }
1142
1143     public IEditorSite getEditorSite() {
1144         return (IEditorSite) getSite();
1145     }
1146
1147     public IEditorInput getEditorInput() {
1148         return editorInput;
1149     }
1150
1151 //    protected void setPartName(String partName) {
1152 ////        if (compatibilityTitleListener != null) {
1153 ////            removePropertyListener(compatibilityTitleListener);
1154 ////            compatibilityTitleListener = null;
1155 ////        }
1156 ////
1157 ////        super.setPartName(partName);
1158 //    }
1159  
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)) {
1164 ////                    return;
1165 ////            }
1166 ////        this.toolTip = toolTip;
1167 ////        firePropertyChange(IWorkbenchPart.PROP_TITLE);
1168 //    }
1169
1170     protected void setHost(DiagramViewerHost host) {
1171         this.host = host;
1172     }
1173
1174     protected void setSite(IWorkbenchPartSite site) {
1175         this.partSite = site;
1176     }
1177
1178     protected void setInput(IEditorInput input) {
1179         Assert.isLegal(input != null);
1180         editorInput = input;
1181     }
1182
1183     public Composite getComposite() {
1184         return c;
1185     }
1186
1187 }