1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management in
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.diagram.profile;
14 import java.util.Arrays;
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;
46 * For most style implementations it should be enough to override the following
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>
55 * See each method for a specification of what they are intended for.
57 * Optionally you can also override
58 * {@link #styleResultChanged(Observer, Resource, Object)} for optimization
59 * purposes but this is usually not necessary.
61 * @author Tuukka Lehtonen
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)}
67 public abstract class StyleBase<Result> implements Style {
69 private Object identity;
71 public StyleBase(Object identity) {
72 this.identity = identity;
76 this.identity = getClass();
79 protected <T> T getIdentity() {
84 public int hashCode() {
87 result = prime * result + ((identity == null) ? 0 : identity.hashCode());
92 public boolean equals(Object obj) {
97 if (getClass() != obj.getClass())
99 StyleBase other = (StyleBase) obj;
100 if (identity == null) {
101 if (other.identity != null)
103 } else if (!identity.equals(other.identity))
108 protected Resource getResource() {
109 return getIdentity();
113 * For caching this simple base request that is done in every
114 * {@link StyleBase#calculateStyle(ReadGraph, Resource, Resource, Resource)}.
116 static class RuntimeDiagramVariableRequest extends UnaryRead<Resource, Variable> {
117 public RuntimeDiagramVariableRequest(Resource runtimeDiagram) {
118 super(runtimeDiagram);
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)
127 Variable activeVariable = org.simantics.db.layer0.variable.Variables.getPossibleVariable(graph, variableURI);
128 return activeVariable;
133 * Calculates a typed result to be used for applying the style to a diagram
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.
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)}
147 * database read access
148 * @param runtimeDiagram
149 * resource describing the runtime data of the styled diagram
151 * profile entry resource, don't care if now aware
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)}
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)
163 //System.out.println("URI1: " + configuration.getURI(graph));
164 //System.out.println("URI2: " + activeVariable.getURI(graph));
165 return calculateStyle(graph, runtimeDiagram, entry, groupItem, activeVariable);
169 * Calculates a typed result to be used for applying the style to a diagram
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.
175 * @param graph database read access
176 * @param runtimeDiagram resource describing the runtime data of the styled
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
185 * @return the calculated style result object
186 * @throws DatabaseException
187 * @see {@link StyleBase#calculateStyle(ReadGraph, Resource, Resource, Resource, Variable)}
189 public Result calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource groupItem, Variable activeComposite) throws DatabaseException {
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
198 * {@link #applyStyleForElement(Observer, IDiagram, Object, IElement, Object)}.
204 public void styleResultChanged(Observer observer, Resource runtimeDiagram, Resource object, Result result) {
206 StyleBaseData.getInstance().removeValue(new Tuple3(this, runtimeDiagram, object));
208 StyleBaseData.getInstance().putValue(new Tuple3(this, runtimeDiagram, object), result);
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).
218 * <code>StyleBase</code> ensures that this method is invoked in the AWT
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)}
227 public void applyStyleForNode(EvaluationContext evaluationContext, INode node, Result result) {
230 public void applyStyleForItem(EvaluationContext evaluationContext, DataNodeMap map, Object item, Result value) {
232 final INode node = map.getNode(item);
234 evaluationContext.update();
235 // TODO: continue or return?
239 if (DebugPolicy.DEBUG_PROFILE_STYLE_APPLICATION)
240 System.out.println(StyleBase.this + ": applying style for item " + item + " and element " + node + " with result " + value);
242 applyStyleForNode(evaluationContext, node, value);
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.
252 * @param node a previously tracked and styled scene graph node
254 protected void cleanupStyleForNode(INode node) {
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
265 protected void cleanupStyleForNode(EvaluationContext evaluationContext, INode node) {
266 cleanupStyleForNode(node);
269 protected void cleanupStyleForItem(EvaluationContext evaluationContext, DataNodeMap map, Object item) {
271 final INode node = map.getNode(item);
273 if (DebugPolicy.DEBUG_PROFILE_STYLE_ACTIVATION)
274 System.out.println(this + ".cleanupStyleForItem(" + item + " = " + node + ")");
275 cleanupStyleForNode(evaluationContext, node);
281 static class GroupListener<T> extends ObserverGroupListener {
283 private StyleBase<T> style;
284 private Session session;
285 private Resource runtimeDiagram;
286 private Resource entry;
288 GroupListener(Session session, Resource runtimeDiagram, Resource entry, StyleBase<T> style, Group group, Observer observer) {
289 super(style, group, observer);
291 this.session = session;
292 this.runtimeDiagram = runtimeDiagram;
297 public void add(final Resource item) {
299 if (DebugPolicy.DEBUG_PROFILE_STYLE_GROUP_TRACKING)
300 System.out.println(style + ": added to group " + group + ": " + item);
302 session.asyncRequest(
303 style.getStyleCalculationRequest(runtimeDiagram, entry, item),
304 style.getStyleResultListener(this, item, group, observer, runtimeDiagram)
310 public void remove(Resource item) {
311 if (DebugPolicy.DEBUG_PROFILE_STYLE_GROUP_TRACKING)
312 System.out.println(style + ": removed from group " + group + ": " + item);
314 StyleBaseData.getInstance().removeItem(style, item);
316 // TODO: do something here to dispose of ObserverGroupValueListeners?
324 * @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)
327 public final void activate(RequestProcessor backend, final Resource runtimeDiagram, final Resource entry, final Group group, final EvaluationContext observer) throws DatabaseException {
329 ObserverGroupListener listener = getListener(runtimeDiagram, group);
331 if (listener == null || listener.isDisposed()) {
333 if (DebugPolicy.DEBUG_PROFILE_STYLE_ACTIVATION)
334 System.out.println("activate(" + runtimeDiagram + ", " + group + ", " + observer);
336 listener = new GroupListener<Result>(backend.getSession(), runtimeDiagram, entry, this, group, observer);
338 StyleBaseData.getInstance().putListener(new Tuple3(this, runtimeDiagram, group), listener);
340 group.trackItems(backend, runtimeDiagram, listener);
344 // Register this entry in the listener
345 listener.addEntry(entry);
349 * Used to customize the identity given to graph requests made for this
350 * style. Default identity is getClass().
352 * @return identity object used in graph requests made by this style
354 protected Object getIdentity(Resource entry) {
355 return new Pair<Class<?>, Resource>(getClass(), entry);
359 * @param configuration
360 * @param runtimeDiagram
364 protected Read<Result> getStyleCalculationRequest(Resource runtimeDiagram, final Resource entry, Resource item) {
365 return new TernaryRead<Object, Resource, Resource, Result>(getIdentity(entry), runtimeDiagram, item) {
367 public Result perform(ReadGraph graph) throws DatabaseException {
368 boolean oldSynchronous = graph.getSynchronous();
370 graph.setSynchronous(false);
371 Result result = calculateStyle(graph, parameter2, entry, parameter3);
372 if (DebugPolicy.DEBUG_PROFILE_STYLE_GROUP_TRACKING)
373 System.out.println(StyleBase.this + ": calculated style result for " + NameUtils.getSafeName(graph, parameter3, true) + ": " + result);
376 graph.setSynchronous(oldSynchronous);
383 * @param groupListener
387 * @param runtimeDiagram
390 protected Listener<Result> getStyleResultListener(ObserverGroupListener groupListener, final Resource item,
391 Group group, Observer observer, final Resource runtimeDiagram) {
392 return new ObserverGroupValueListener<Result>(groupListener, observer, group, item) {
394 public void execute(Result result) {
395 if (DebugPolicy.DEBUG_PROFILE_STYLE_GROUP_TRACKING)
396 System.out.println(StyleBase.this + ": style result changed for " + item + ": " + result);
397 styleResultChanged(observer, runtimeDiagram, item, result);
403 * @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)
406 public final void deactivate(Resource runtimeDiagram, Resource entry, Group group,
407 EvaluationContext observer) {
409 ObserverGroupListener listener = getListener(runtimeDiagram, group);
410 if (listener != null) {
412 if (DebugPolicy.DEBUG_PROFILE_STYLE_ACTIVATION)
413 System.out.println("deactivate(" + runtimeDiagram + ", " + group + ", " + observer);
415 IDiagram diagram = observer.getConstant(ProfileKeys.DIAGRAM);
417 listener.removeEntry(entry);
418 if (!listener.hasEntries()) {
420 StyleBaseData.getInstance().removeListener(new Tuple3(this, runtimeDiagram, group));
423 // This was too eager when multiple groups were tracked!
425 if (diagram != null) {
426 cleanupItems(observer, diagram, listener.getItems().toArray());
435 * @see org.simantics.diagram.profile.Style#apply(org.simantics.g2d.diagram.IDiagram, org.simantics.diagram.profile.Group, org.simantics.diagram.profile.Observer)
438 public final void apply(Resource entry, Group group, final EvaluationContext evaluationContext) {
440 ICanvasContext context = evaluationContext.getConstant(ProfileKeys.CANVAS);
442 assert context.getThreadAccess().currentThreadAccess();
444 ObserverGroupListener listener = getListener(evaluationContext.getResource(), group);
445 if (listener == null) {
446 System.out.println(this + "(" + getClass().getSimpleName() + ") had no listener for " + evaluationContext.getResource() + " " + group);
450 final DataNodeMap map = evaluationContext.getConstant(ProfileKeys.NODE_MAP);
452 if (DebugPolicy.DEBUG_PROFILE_STYLE_APPLICATION)
453 System.out.println(StyleBase.this + ": applying style for items: " + listener.getItems());
456 StyleBaseData data = StyleBaseData.getInstance();
458 data.applyRemovals(evaluationContext, this);
460 for (Object item : listener.getItems()) {
461 Result value = data.getValue(new Tuple3(this, evaluationContext.getResource(), item));
462 applyStyleForItem(evaluationContext, map, item, value);
468 * This is ran when this profile entry gets deactivated after being first
469 * active. It allows cleaning up scene graph left-overs for the listened set
470 * of items before deactivation. It will invoke
471 * {@link #cleanupStyleForElement(IDiagram, IElement)} for each diagram element observed
472 * before deactivation in the AWT thread. If the profile observer is
473 * disposed in between scheduling to AWT thread, the method will do nothing.
475 * @param observer the diagram profile observer
476 * @param diagram the diagram this profile system is working with
477 * @param items the diagram data items that need to be cleaned up
479 protected final void cleanupItems(final EvaluationContext evaluationContext, final IDiagram diagram, final Object[] items) {
481 ICanvasContext context = evaluationContext.getConstant(ProfileKeys.CANVAS);
483 context.getThreadAccess().asyncExec(new Runnable() {
488 if (evaluationContext.isDisposed())
491 final DataNodeMap map = evaluationContext.getConstant(ProfileKeys.NODE_MAP);
493 if (DebugPolicy.DEBUG_PROFILE_STYLE_ACTIVATION)
494 System.out.println(this + ".cleanupItems(" + evaluationContext + ", " + diagram + ", " + Arrays.toString(items));
496 for (Object item : items) {
497 cleanupStyleForItem(evaluationContext, map, item);
503 private ObserverGroupListener getListener(Resource runtime, Group group) {
504 return StyleBaseData.getInstance().getListener(new Tuple3(this, runtime, group));