]> gerrit.simantics Code Review - simantics/platform.git/blob
5c3d7fbe3a26318d0761461b8765ce042c87a9b2
[simantics/platform.git] /
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 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  *******************************************************************************/
12 package org.simantics.modeling.ui.diagram.monitor;
13
14 import java.awt.geom.AffineTransform;
15 import java.awt.geom.Rectangle2D;
16 import java.util.HashMap;
17 import java.util.Map;
18 import java.util.concurrent.atomic.AtomicReference;
19
20 import org.simantics.browsing.ui.common.ErrorLogger;
21 import org.simantics.common.color.Color;
22 import org.simantics.databoard.Bindings;
23 import org.simantics.db.AsyncReadGraph;
24 import org.simantics.db.ReadGraph;
25 import org.simantics.db.Resource;
26 import org.simantics.db.Session;
27 import org.simantics.db.exception.DatabaseException;
28 import org.simantics.db.layer0.util.EvaluatingListener;
29 import org.simantics.db.layer0.util.EvaluatingListener.Evaluation;
30 import org.simantics.db.layer0.variable.RVI;
31 import org.simantics.db.layer0.variable.Variables;
32 import org.simantics.db.procedure.AsyncProcedure;
33 import org.simantics.diagram.adapter.SyncElementFactory;
34 import org.simantics.diagram.content.ConnectionUtil;
35 import org.simantics.diagram.elements.MonitorClass;
36 import org.simantics.diagram.stubs.DiagramResource;
37 import org.simantics.diagram.stubs.G2DResource;
38 import org.simantics.diagram.synchronization.CompositeHintSynchronizer;
39 import org.simantics.diagram.synchronization.IHintSynchronizer;
40 import org.simantics.diagram.synchronization.SynchronizationHints;
41 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
42 import org.simantics.diagram.synchronization.graph.ElementLoader;
43 import org.simantics.diagram.synchronization.graph.MonitorSynchronizer;
44 import org.simantics.diagram.synchronization.graph.TransformSynchronizer;
45 import org.simantics.diagram.ui.DiagramModelHints;
46 import org.simantics.g2d.canvas.ICanvasContext;
47 import org.simantics.g2d.diagram.IDiagram;
48 import org.simantics.g2d.diagram.handler.DataElementMap;
49 import org.simantics.g2d.diagram.handler.Relationship;
50 import org.simantics.g2d.diagram.handler.RelationshipHandler;
51 import org.simantics.g2d.element.ElementClass;
52 import org.simantics.g2d.element.ElementHints;
53 import org.simantics.g2d.element.ElementUtils;
54 import org.simantics.g2d.element.IElement;
55 import org.simantics.g2d.element.handler.TextEditor;
56 import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;
57 import org.simantics.layer0.Layer0;
58 import org.simantics.modeling.ModelingResources;
59 import org.simantics.scl.runtime.function.Function1;
60 import org.simantics.ui.colors.Colors;
61 import org.simantics.ui.fonts.FontDescriptor;
62 import org.simantics.ui.fonts.Fonts;
63 import org.simantics.utils.datastructures.Callback;
64 import org.simantics.utils.datastructures.hints.IHintContext.Key;
65 import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;
66
67 /**
68  * TODO: recognize experiment disposal and reset monitor contents at that point
69  * FIXME: monitor does not handle editing properly, and tries to include physical unit as part of numeric value
70  */
71 public class MonitorClassFactory2 extends SyncElementFactory {
72
73     private static final Key               KEY_VARIABLE_LISTENER = new KeyOf(MonitorListener.class,
74                                                                          "MONITOR_VARIABLE_LISTENER");
75
76     private static final String            CLASS_ID          = "Monitor";
77
78     private static final IHintSynchronizer HINT_SYNCHRONIZER = new CompositeHintSynchronizer(
79             MonitorSynchronizer.INSTANCE,
80             TransformSynchronizer.INSTANCE);
81
82     public static ElementClass createMonitorClass(Resource elementType) {
83         // set "default scale" to no scaling, 1.0, 1.0
84         return MonitorClass.create(1.0, 1.0, new StaticObjectAdapter(elementType)).setId(CLASS_ID);
85     }
86
87     // staticScale{X,Y} define the scale of the static monitor image
88     public static ElementClass createMonitorClass(Resource elementType, IElement parentElement, HashMap<String, String> substitutions, Object component, String suffix, double staticScaleX, double staticScaleY) {
89         return MonitorClass.create(parentElement, substitutions, component, suffix, staticScaleX, staticScaleY, new StaticObjectAdapter(elementType)).setId(CLASS_ID);
90     }
91
92     @Override
93     public void create(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementType,
94             AsyncProcedure<ElementClass> procedure) {
95         procedure.execute(graph, createMonitorClass(elementType));
96     }
97
98     @Override
99     public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource element, final IElement e) throws DatabaseException {
100         if (!graph.hasStatement(element))
101             return;
102
103         final Layer0 L0 = Layer0.getInstance(graph);
104         final G2DResource G2D = G2DResource.getInstance(graph);
105         final DiagramResource DIA = DiagramResource.getInstance(graph);
106
107         // Must be done here to allow for the relationship manager to work properly.
108         e.setHint(ElementHints.KEY_OBJECT, element);
109         e.setHint(SynchronizationHints.HINT_SYNCHRONIZER, HINT_SYNCHRONIZER);
110
111         AffineTransform at = DiagramGraphUtil.getAffineTransform(graph, element);
112         ElementUtils.setTransform(e, at);
113
114         // Load alignments
115         Resource hAlign = graph.getPossibleObject(element, G2D.HasHorizontalAlignment);
116         Resource vAlign = graph.getPossibleObject(element, G2D.HasVerticalAlignment);
117
118         final Double borderWidth = graph.getPossibleRelatedValue(element, G2D.HasStrokeWidth);
119         Double direction = graph.getPossibleRelatedValue(element, DIA.HasDirection);
120         double bounds[] = DiagramGraphUtil.getPossibleRelatedDoubleArray(graph, element, G2D.HasBounds);
121         if (bounds != null) {
122             e.setHint(ElementHints.KEY_BOUNDS, new Rectangle2D.Double(bounds[0], bounds[1], bounds[2], bounds[3]));
123         }
124
125         if (hAlign != null)
126             e.setHint(ElementHints.KEY_HORIZONTAL_ALIGN, DiagramGraphUtil.toAlignment(hAlign, G2D, MonitorClass.DEFAULT_HORIZONTAL_ALIGN));
127         if (vAlign != null)
128             e.setHint(ElementHints.KEY_VERTICAL_ALIGN, DiagramGraphUtil.toVerticalAlignment(vAlign, G2D, MonitorClass.DEFAULT_VERTICAL_ALIGN));
129         if (direction != null)
130             e.setHint(MonitorClass.KEY_DIRECTION, direction);
131         if (borderWidth != null)
132             e.setHint(MonitorClass.KEY_BORDER_WIDTH, borderWidth);
133
134         String suffix = graph.getPossibleRelatedValue(element, DIA.HasMonitorSuffix, Bindings.STRING);
135         if (suffix != null) e.setHint(MonitorClass.KEY_MONITOR_SUFFIX, suffix);
136
137         String label = graph.getPossibleRelatedValue(element, L0.HasLabel);
138         ElementUtils.setText(e, label);
139
140         FontDescriptor fd = graph.getPossibleRelatedAdapter(element, DIA.HasFont, FontDescriptor.class);
141         if(fd != null) ElementUtils.setTextFont(e, Fonts.awt(fd));
142         Color color = graph.getPossibleRelatedAdapter(element, DIA.HasColor, Color.class);
143         if(color != null) ElementUtils.setTextColor(e, Colors.awt(color));
144
145         loadParentRelationships(graph, element, e);
146
147         final Map<String, String> substitutions = new HashMap<String, String>();
148         substitutions.put("#v1", "");
149
150         final Resource diagramRuntime = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RUNTIME_RESOURCE);
151         if (diagramRuntime != null) {
152             final Session session = graph.getSession();
153
154             // Resolve validator for monitor input if possible.
155             final AtomicReference<Function1<String, String>> validator = new AtomicReference<Function1<String, String>>();
156             MonitorVariable monitorVariable = graph.syncRequest(new ResolveMonitorVariable(diagramRuntime, element));
157             boolean readOnly = true;
158             if (monitorVariable != null) {
159                 Function1<String, String> func = monitorVariable.getVariable().getPossiblePropertyValue(graph, Variables.INPUT_VALIDATOR); 
160                 validator.set( func );
161                 if (func != null)
162                     e.setHint(MonitorClass.KEY_INPUT_VALIDATOR, func);
163                 RVI rvi = monitorVariable.getRVI();
164                 if (rvi != null)
165                     e.setHint(MonitorClass.KEY_RVI, rvi);
166                 readOnly = Boolean.TRUE.equals(
167                         monitorVariable.getVariable().getPossiblePropertyValue(graph, Variables.READONLY, Bindings.BOOLEAN));
168             }
169
170             TextEditor ed = null;
171             if (!readOnly &&
172                     (ed = e.getElementClass().getAtMostOneItemOfClass(TextEditor.class)) != null) {
173                 ed.setModifier(e, new TextEditor.Modifier() {
174                     @Override
175                     public String getValue(IElement e) {
176                         return MonitorClass.editText(e);
177                     }
178
179                     @Override
180                     public String isValid(IElement e, String text) {
181                         if (validator.get() != null)
182                             return validator.get().apply(text);
183                         return null;
184                     }
185
186                     @Override
187                     public void modify(final IElement e, final String text) {
188                         session.asyncRequest(new ResolveMonitorVariable(diagramRuntime, element),
189                                 new EvaluatingListener<MonitorVariable>(
190                                         new EvaluatingListener.Criterion<MonitorVariable>() {
191                             @Override
192                             public Evaluation evaluate(MonitorVariable result) {
193                                 return result != null ? Evaluation.ACCEPT : Evaluation.IGNORE;
194                             }
195                         }) {
196                             @Override
197                             public void accepted(MonitorVariable var) {
198                                 session.asyncRequest(new MonitorVariableWrite(var.getVariable(), text), new Callback<DatabaseException>() {
199                                     @Override
200                                     public void run(DatabaseException e) {
201                                         if (e != null)
202                                             ErrorLogger.defaultLogError(e);
203                                     }
204                                 });
205                             }
206                             @Override
207                             public void exception(Throwable t) {
208                                 ErrorLogger.defaultLogError(t);
209                             }
210                         });
211                     }
212
213                 });
214             }
215
216             IElement mappedElement = diagram.getDiagramClass().getSingleItem(DataElementMap.class).getElement(diagram, element);
217             MonitorListener monitorListener = new MonitorListener(element, canvas, diagram, substitutions);
218             if (mappedElement != null) {
219                 MonitorListener oldListener = mappedElement.getHint(KEY_VARIABLE_LISTENER);
220                 if (oldListener != null)
221                     oldListener.dispose();
222                 mappedElement.setHint(KEY_VARIABLE_LISTENER, monitorListener);
223             }
224
225             if(monitorVariable != null)
226                 graph.asyncRequest(new MonitorVariableValueRequest(diagramRuntime, element), monitorListener);
227             
228         }
229     }
230
231     private void loadParentRelationships(ReadGraph graph, Resource element, IElement e) throws DatabaseException {
232         DiagramResource DIA = DiagramResource.getInstance(graph);
233         ModelingResources MOD = ModelingResources.getInstance(graph);
234
235         Resource monitorComponent = graph.getPossibleObject(element, DIA.HasMonitorComponent);
236         Resource parentDiagramElement = null;
237         if (monitorComponent != null)
238             parentDiagramElement = graph.getPossibleObject(monitorComponent, MOD.ComponentToElement);
239
240         // Load parent relationship after all elements have been loaded.
241         if (parentDiagramElement != null) {
242             final Resource pde = parentDiagramElement;
243             e.setHint(DiagramModelHints.KEY_ELEMENT_LOADER, new ElementLoader() {
244                 @Override
245                 public void load(ReadGraph g, IDiagram diagram, IElement element) throws DatabaseException {
246                     loadParentRelationship(g, diagram, element, pde);
247                 }
248             });
249         }
250     }
251
252     boolean loadParentRelationship(ReadGraph g, IDiagram diagram, IElement element, Resource parentElementResource)
253             throws DatabaseException {
254         // If no relationship handler is available, stop loading.
255         RelationshipHandler rh = diagram.getDiagramClass().getAtMostOneItemOfClass(RelationshipHandler.class);
256         if (rh == null)
257             return true;
258
259         DiagramResource DIA = DiagramResource.getInstance(g);
260         DataElementMap map = diagram.getDiagramClass().getSingleItem(DataElementMap.class);
261         IElement parentElement = map.getElement(diagram, parentElementResource);
262
263         if (parentElement != null) {
264             element.setHint(ElementHints.KEY_PARENT_ELEMENT, parentElement);
265             rh.claim(diagram, element, Relationship.CHILD_OF, parentElement);
266
267             Resource tailNode = null;
268             if (g.isInstanceOf(parentElementResource, DIA.Connection)) {
269                 tailNode = ConnectionUtil.getConnectionTailNode(g, parentElementResource);
270             }
271
272             if (tailNode != null) {
273                 IElement tailNodeElement = map.getElement(diagram, tailNode);
274                 if (parentElement != null) {
275                     element.setHint(ElementHints.KEY_PARENT_ELEMENT, tailNodeElement);
276                     rh.claim(diagram, element, Relationship.CHILD_OF, tailNodeElement);
277                 }
278             }
279
280             return true;
281         }
282
283         return false;
284     }
285
286 }