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