]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.diagram/src/org/simantics/diagram/profile/StyleBase.java
e1d8b1fbf7e67e043c8af93202f03d95747d9216
[simantics/platform.git] / bundles / org.simantics.diagram / src / org / simantics / diagram / profile / StyleBase.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management in
3  * 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  *******************************************************************************/
12 package org.simantics.diagram.profile;
13
14 import java.util.Arrays;
15
16 import org.simantics.databoard.Bindings;
17 import org.simantics.db.ReadGraph;
18 import org.simantics.db.RequestProcessor;
19 import org.simantics.db.Resource;
20 import org.simantics.db.Session;
21 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
22 import org.simantics.db.common.request.TernaryRead;
23 import org.simantics.db.common.request.UnaryRead;
24 import org.simantics.db.common.utils.NameUtils;
25 import org.simantics.db.exception.DatabaseException;
26 import org.simantics.db.layer0.variable.Variable;
27 import org.simantics.db.procedure.Listener;
28 import org.simantics.db.request.Read;
29 import org.simantics.diagram.stubs.DiagramResource;
30 import org.simantics.g2d.canvas.ICanvasContext;
31 import org.simantics.g2d.diagram.IDiagram;
32 import org.simantics.g2d.element.IElement;
33 import org.simantics.scenegraph.INode;
34 import org.simantics.scenegraph.profile.DataNodeMap;
35 import org.simantics.scenegraph.profile.EvaluationContext;
36 import org.simantics.scenegraph.profile.Group;
37 import org.simantics.scenegraph.profile.Observer;
38 import org.simantics.scenegraph.profile.Style;
39 import org.simantics.scenegraph.profile.common.ObserverGroupListener;
40 import org.simantics.scenegraph.profile.common.ObserverGroupValueListener;
41 import org.simantics.scenegraph.profile.impl.DebugPolicy;
42 import org.simantics.scl.runtime.tuple.Tuple3;
43 import org.simantics.utils.datastructures.Pair;
44
45 /**
46  * For most style implementations it should be enough to override the following
47  * methods:
48  * <ul>
49  * <li>{@link #calculateStyle(ReadGraph, Resource, Resource, Variable)}</li>
50  * <li>{@link #applyStyleForElement(Observer, Object, IElement, Object)}</li>
51  * <li>{@link #cleanupStyleForElement(IDiagram, IElement)}</li>
52  * </ul>
53  * 
54  * <p>
55  * See each method for a specification of what they are intended for.
56  * 
57  * Optionally you can also override
58  * {@link #styleResultChanged(Observer, Resource, Object)} for optimization
59  * purposes but this is usually not necessary.
60  * 
61  * @author Tuukka Lehtonen
62  * f
63  * @param <Result> type of result objects for styled group items tracked by this
64  *        style implementation, see
65  *        {@link #calculateStyle(ReadGraph, Resource, Resource, Variable)}
66  */
67 public abstract class StyleBase<Result> implements Style {
68
69     private Object identity;
70
71     public StyleBase(Object identity) {
72         this.identity = identity;
73     }
74
75     public StyleBase() {
76         this.identity = getClass();
77     }
78
79     protected <T> T getIdentity() {
80         return (T)identity;
81     }
82
83     @Override
84     public int hashCode() {
85         final int prime = 31;
86         int result = 1;
87         result = prime * result + ((identity == null) ? 0 : identity.hashCode());
88         return result;
89     }
90
91     @Override
92     public boolean equals(Object obj) {
93         if (this == obj)
94             return true;
95         if (obj == null)
96             return false;
97         if (getClass() != obj.getClass())
98             return false;
99         StyleBase other = (StyleBase) obj;
100         if (identity == null) {
101             if (other.identity != null)
102                 return false;
103         } else if (!identity.equals(other.identity))
104             return false;
105         return true;
106     }
107
108     protected Resource getResource() {
109         return getIdentity();
110     }
111
112     /**
113      * For caching this simple base request that is done in every
114      * {@link StyleBase#calculateStyle(ReadGraph, Resource, Resource, Resource)}.
115      */
116     static class RuntimeDiagramVariableRequest extends UnaryRead<Resource, Variable> {
117         public RuntimeDiagramVariableRequest(Resource runtimeDiagram) {
118             super(runtimeDiagram);
119         }
120
121         @Override
122         public Variable perform(ReadGraph graph) throws DatabaseException {
123             DiagramResource DIA = DiagramResource.getInstance(graph);
124             String variableURI = graph.getPossibleRelatedValue(parameter, DIA.RuntimeDiagram_HasVariable, Bindings.STRING);
125             if (variableURI == null)
126                 return null;
127             Variable activeVariable = org.simantics.db.layer0.variable.Variables.getPossibleVariable(graph, variableURI);
128             return activeVariable;
129         }
130     }
131
132     /**
133      * Calculates a typed result to be used for applying the style to a diagram
134      * in
135      * {@link #applyStyleForElement(Observer, IDiagram, Object, IElement, Object)}
136      * . The graph request system will take care of only notifying other systems
137      * when the style result actually changes.
138      * 
139      * <p>
140      * This implementation uses {@link RuntimeDiagramVariableRequest} to
141      * discover the active composite variable related to the specified
142      * runtimeDiagram and invokes
143      * {@link StyleBase#calculateStyle(ReadGraph, Resource, Resource, Resource, Variable)}
144      * with it.
145      * 
146      * @param graph
147      *            database read access
148      * @param runtimeDiagram
149      *            resource describing the runtime data of the styled diagram
150      * @param entry
151      *            profile entry resource, don't care if now aware
152      * @param groupItem
153      *            an item belonging to the observed group
154      * @return the calculated style result object
155      * @throws DatabaseException
156      * @see {@link StyleBase#calculateStyle(ReadGraph, Resource, Resource, Resource, Variable)}
157      */
158     public Result calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource groupItem) throws DatabaseException {
159         Variable activeVariable = graph.syncRequest(new RuntimeDiagramVariableRequest(runtimeDiagram), TransientCacheListener.<Variable>instance());
160         if (activeVariable == null)
161             return null;
162
163         //System.out.println("URI1: " + configuration.getURI(graph));
164         //System.out.println("URI2: " + activeVariable.getURI(graph));
165         return calculateStyle(graph, runtimeDiagram, entry, groupItem, activeVariable);
166     }
167
168     /**
169      * Calculates a typed result to be used for applying the style to a diagram
170      * in
171      * {@link #applyStyleForElement(Observer, IDiagram, Object, IElement, Object)}
172      * . The graph request system will take care of only notifying other systems
173      * when the style result actually changes.
174      * 
175      * @param graph database read access
176      * @param runtimeDiagram resource describing the runtime data of the styled
177      *        diagram
178      * @param entry profile entry resource, don't care if now aware
179      * @param groupItem an item belonging to the observed group
180      * @param activeComposite variable for accessing the active realization of the
181      *        diagram's corresponding composite. This may change when
182      *        experiments are activate and deactivated. When there is no
183      *        experiment active, this is the base realization, i.e. the
184      *        configuration.
185      * @return the calculated style result object
186      * @throws DatabaseException
187      * @see {@link StyleBase#calculateStyle(ReadGraph, Resource, Resource, Resource, Variable)}
188      */
189     public Result calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource groupItem, Variable activeComposite) throws DatabaseException {
190         return null;
191     }
192
193     /**
194      * Invoked when the result calculated by
195      * {@link #calculateStyle(ReadGraph, Resource, Resource, Variable)} changes.
196      * Used for keeping track of the latest calculated style values that are
197      * applied in
198      * {@link #applyStyleForElement(Observer, IDiagram, Object, IElement, Object)}.
199      * 
200      * @param observer
201      * @param object
202      * @param result
203      */
204     public void styleResultChanged(Observer observer, Resource runtimeDiagram, Resource object, Result result) {
205         if (result == null)
206             StyleBaseData.getInstance().removeValue(new Tuple3(this, runtimeDiagram, object));
207         else
208             StyleBaseData.getInstance().putValue(new Tuple3(this, runtimeDiagram, object), result);
209         observer.update();
210     }
211
212     /**
213      * Apply the latest style result calculated by
214      * {@link #calculateStyle(ReadGraph, Resource, Resource, Variable)} to the
215      * scene graph of the specified diagram item (i.e. element).
216      * 
217      * <p>
218      * <code>StyleBase</code> ensures that this method is invoked in the AWT
219      * thread only.
220      * 
221      * @param observer profile system observer
222      * @param item the styled diagram item data
223      * @param element the styled diagram element representing the data item
224      * @param result the latest result calculated by
225      *        {@link #calculateStyle(ReadGraph, Resource, Resource, Variable)}
226      */
227     public void applyStyleForNode(EvaluationContext evaluationContext, INode node, Result result) {
228     }
229     
230     public void applyStyleForItem(EvaluationContext evaluationContext, DataNodeMap map, Object item, Result value) {
231         
232         final INode node = map.getNode(item);
233         if (node == null) {
234             evaluationContext.update();
235             // TODO: continue or return?
236             return;
237         }
238
239         if (DebugPolicy.DEBUG_PROFILE_STYLE_APPLICATION)
240             System.out.println(StyleBase.this + ": applying style for item " + item + " and element " + node + " with result " + value);
241
242         applyStyleForNode(evaluationContext, node, value);
243         
244     }
245
246     /**
247      * This method is invoked by
248      * {@link #cleanupStyleForNode(EvaluationContext, INode)} when the style is
249      * deactivated. It is invoked for each diagram element tracked by the style
250      * before deactivation.
251      * 
252      * @param node a previously tracked and styled scene graph node
253      */
254     protected void cleanupStyleForNode(INode node) {
255     }
256
257     /**
258      * This method is invoked by
259      * {@link #cleanupStyleForItem(EvaluationContext, DataNodeMap, Object)} when the style is
260      * deactivated. It is invoked for each diagram element tracked by the style
261      * before deactivation.
262      * @param evaluationContext the context of this style evaluation
263      * @param node a previously tracked and styled scene graph node
264      */
265     protected void cleanupStyleForNode(EvaluationContext evaluationContext, INode node) {
266         cleanupStyleForNode(node);
267     }
268
269     protected void cleanupStyleForItem(EvaluationContext evaluationContext, DataNodeMap map, Object item) {
270
271         final INode node = map.getNode(item);
272         if (node != null) {
273             if (DebugPolicy.DEBUG_PROFILE_STYLE_ACTIVATION)
274                 System.out.println(this + ".cleanupStyleForItem(" + item + " = " + node + ")");
275             cleanupStyleForNode(evaluationContext, node);
276         }
277
278     }
279     
280     
281     static class GroupListener<T> extends ObserverGroupListener {
282         
283         private StyleBase<T> style;
284         private Session session;
285         private Resource runtimeDiagram;
286         private Resource entry;
287         
288         GroupListener(Session session, Resource runtimeDiagram, Resource entry, StyleBase<T> style, Group group, Observer observer) {
289                 super(style, group, observer);
290                 this.style = style;
291                 this.session = session;
292                 this.runtimeDiagram = runtimeDiagram;
293                 this.entry = entry;
294         }
295         
296           @Override
297           public void add(final Resource item) {
298
299                   if (DebugPolicy.DEBUG_PROFILE_STYLE_GROUP_TRACKING)
300                   System.out.println(style + ": added to group " + group + ": " + item);
301
302               session.asyncRequest(
303                       style.getStyleCalculationRequest(runtimeDiagram, entry, item),
304                       style.getStyleResultListener(this, item, group, observer, runtimeDiagram)
305               );
306
307               super.add(item);
308           }
309           @Override
310           public void remove(Resource item) {
311               if (DebugPolicy.DEBUG_PROFILE_STYLE_GROUP_TRACKING)
312                   System.out.println(style + ": removed from group " + group + ": " + item);
313
314               StyleBaseData.getInstance().removeItem(style, item);
315
316               // TODO: do something here to dispose of ObserverGroupValueListeners?
317               super.remove(item);
318           }  
319           
320     }
321     
322     /* (non-Javadoc)
323      * @see org.simantics.diagram.profile.Style#activate(org.simantics.db.RequestProcessor, org.simantics.db.Resource, org.simantics.db.layer0.variable.Variable, org.simantics.diagram.profile.Group, org.simantics.diagram.profile.Observer)
324      */
325     @Override
326     public final void activate(RequestProcessor backend, final Resource runtimeDiagram, final Resource entry, final Group group, final EvaluationContext observer) throws DatabaseException {
327
328         ObserverGroupListener listener = getListener(runtimeDiagram, group);
329
330         if (listener == null || listener.isDisposed()) {
331
332             if (DebugPolicy.DEBUG_PROFILE_STYLE_ACTIVATION)
333                 System.out.println("activate(" + runtimeDiagram + ", " + group + ", " + observer);
334
335             listener = new GroupListener<Result>(backend.getSession(), runtimeDiagram, entry, this, group, observer);
336
337             StyleBaseData.getInstance().putListener(new Tuple3(this, runtimeDiagram, group), listener);
338
339             group.trackItems(backend, runtimeDiagram, listener);
340
341         }
342
343         // Register this entry in the listener
344         listener.addEntry(entry);
345     }
346
347     /**
348      * Used to customize the identity given to graph requests made for this
349      * style. Default identity is getClass().
350      * 
351      * @return identity object used in graph requests made by this style
352      */
353     protected Object getIdentity(Resource entry) {
354         return new Pair<Class<?>, Resource>(getClass(), entry);
355     }
356
357     /**
358      * @param configuration
359      * @param runtimeDiagram
360      * @param item
361      * @return
362      */
363     protected Read<Result> getStyleCalculationRequest(Resource runtimeDiagram, final Resource entry, Resource item) {
364         return new TernaryRead<Object, Resource, Resource, Result>(getIdentity(entry), runtimeDiagram, item) {
365             @Override
366             public Result perform(ReadGraph graph) throws DatabaseException {
367                 boolean oldSynchronous = graph.getSynchronous();
368                 try {
369                     graph.setSynchronous(false);
370                     Result result = calculateStyle(graph, parameter2, entry, parameter3);
371                     if (DebugPolicy.DEBUG_PROFILE_STYLE_GROUP_TRACKING)
372                         System.out.println(StyleBase.this + ": calculated style result for " + NameUtils.getSafeName(graph, parameter3, true) + ": " + result);
373                     return result;
374                 } finally {
375                     graph.setSynchronous(oldSynchronous);
376                 }
377             }
378         };
379     }
380
381     /**
382      * @param groupListener
383      * @param item
384      * @param group
385      * @param observer
386      * @param runtimeDiagram 
387      * @return
388      */
389     protected Listener<Result> getStyleResultListener(ObserverGroupListener groupListener, final Resource item,
390             Group group, Observer observer, final Resource runtimeDiagram) {
391         return new ObserverGroupValueListener<Result>(groupListener, observer, group, item) {
392             @Override
393             public void execute(Result result) {
394                 if (DebugPolicy.DEBUG_PROFILE_STYLE_GROUP_TRACKING)
395                     System.out.println(StyleBase.this + ": style result changed for " + item + ": " + result);
396                 styleResultChanged(observer, runtimeDiagram, item, result);
397             }
398         };
399     }
400
401     /* (non-Javadoc)
402      * @see org.simantics.diagram.profile.Style#deactivate(org.simantics.db.RequestProcessor, org.simantics.db.Resource, org.simantics.db.layer0.variable.Variable, org.simantics.diagram.profile.Group, org.simantics.diagram.profile.Observer)
403      */
404     @Override
405     public final void deactivate(Resource runtimeDiagram, Resource entry, Group group,
406             EvaluationContext observer) {
407
408         ObserverGroupListener listener = getListener(runtimeDiagram, group);
409         if (listener != null) {
410
411             if (DebugPolicy.DEBUG_PROFILE_STYLE_ACTIVATION)
412                 System.out.println("deactivate(" + runtimeDiagram + ", " + group + ", " + observer);
413
414             IDiagram diagram = observer.getConstant(ProfileKeys.DIAGRAM);
415
416             listener.removeEntry(entry);
417             if (!listener.hasEntries()) {
418                 listener.dispose();
419                 StyleBaseData.getInstance().removeListener(new Tuple3(this, runtimeDiagram, group));
420             }
421
422             // This was too eager when multiple groups were tracked!
423             //values.clear();
424             if (diagram != null) {
425                 cleanupItems(observer, diagram, listener.getItems().toArray());
426                 diagram = null;
427             }
428             observer.update();
429         }
430
431     }
432
433     /* (non-Javadoc)
434      * @see org.simantics.diagram.profile.Style#apply(org.simantics.g2d.diagram.IDiagram, org.simantics.diagram.profile.Group, org.simantics.diagram.profile.Observer)
435      */
436     @Override
437     public final void apply(Resource entry, Group group, final EvaluationContext evaluationContext) {
438
439         ICanvasContext context = evaluationContext.getConstant(ProfileKeys.CANVAS);
440         
441         assert context.getThreadAccess().currentThreadAccess();
442
443         ObserverGroupListener listener = getListener(evaluationContext.getResource(), group);
444         if (listener == null) {
445             System.out.println(this + "(" + getClass().getSimpleName() + ") had no listener for " + evaluationContext.getResource() + " " + group);
446             return;
447         }
448         
449         final DataNodeMap map = evaluationContext.getConstant(ProfileKeys.NODE_MAP);
450
451         if (DebugPolicy.DEBUG_PROFILE_STYLE_APPLICATION)
452             System.out.println(StyleBase.this + ": applying style for items: " + listener.getItems());
453
454         
455         StyleBaseData data = StyleBaseData.getInstance();
456         
457         data.applyRemovals(evaluationContext, this);
458         
459         for (Object item : listener.getItems()) {
460             Result value = data.getValue(new Tuple3(this, evaluationContext.getResource(), item));
461             applyStyleForItem(evaluationContext, map, item, value);
462         }
463         
464     }
465
466     /**
467      * This is ran when this profile entry gets deactivated after being first
468      * active. It allows cleaning up scene graph left-overs for the listened set
469      * of items before deactivation. It will invoke
470      * {@link #cleanupStyleForElement(IDiagram, IElement)} for each diagram element observed
471      * before deactivation in the AWT thread. If the profile observer is
472      * disposed in between scheduling to AWT thread, the method will do nothing.
473      * 
474      * @param observer the diagram profile observer
475      * @param diagram the diagram this profile system is working with
476      * @param items the diagram data items that need to be cleaned up
477      */
478     protected final void cleanupItems(final EvaluationContext evaluationContext, final IDiagram diagram, final Object[] items) {
479
480         ICanvasContext context = evaluationContext.getConstant(ProfileKeys.CANVAS);
481
482         context.getThreadAccess().asyncExec(new Runnable() {
483                 
484             @Override
485             public void run() {
486                 
487                 if (evaluationContext.isDisposed())
488                     return;
489
490                 final DataNodeMap map = evaluationContext.getConstant(ProfileKeys.NODE_MAP);
491                 
492                 if (DebugPolicy.DEBUG_PROFILE_STYLE_ACTIVATION)
493                     System.out.println(this + ".cleanupItems(" + evaluationContext + ", " + diagram + ", " + Arrays.toString(items));
494
495                 for (Object item : items) {
496                     cleanupStyleForItem(evaluationContext, map, item);
497                 }
498             }
499         });
500     }
501     
502     private ObserverGroupListener getListener(Resource runtime, Group group) {
503         return StyleBaseData.getInstance().getListener(new Tuple3(this, runtime, group));
504     }
505
506 }