]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.simulator.toolkit/src/org/simantics/simulator/toolkit/StandardNodeManager.java
402f3884d433270d9161594224d971469f297b3c
[simantics/platform.git] / bundles / org.simantics.simulator.toolkit / src / org / simantics / simulator / toolkit / StandardNodeManager.java
1 /*******************************************************************************
2  * Copyright (c) 2013 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 - initial API and implementation
12  *******************************************************************************/
13 package org.simantics.simulator.toolkit;
14
15 import java.util.ArrayList;
16 import java.util.Collections;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Set;
20 import java.util.concurrent.atomic.AtomicBoolean;
21
22 import org.simantics.databoard.Bindings;
23 import org.simantics.databoard.adapter.AdaptException;
24 import org.simantics.databoard.adapter.Adapter;
25 import org.simantics.databoard.adapter.AdapterConstructionException;
26 import org.simantics.databoard.binding.Binding;
27 import org.simantics.databoard.binding.VariantBinding;
28 import org.simantics.databoard.binding.error.BindingException;
29 import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;
30 import org.simantics.databoard.binding.mutable.Variant;
31 import org.simantics.databoard.type.Datatype;
32 import org.simantics.simulator.variable.NodeManager;
33 import org.simantics.simulator.variable.Realm;
34 import org.simantics.simulator.variable.exceptions.NoSuchNodeException;
35 import org.simantics.simulator.variable.exceptions.NodeManagerException;
36 import org.simantics.simulator.variable.exceptions.NotInRealmException;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import gnu.trove.map.hash.THashMap;
41 import gnu.trove.procedure.TObjectProcedure;
42 import gnu.trove.set.hash.THashSet;
43
44 /**
45  * StandardNodeManager gives default implementations to some methods
46  * of NodeManager.
47  *
48  * @author Antti Villberg
49  */
50 public class StandardNodeManager<Node, Engine extends StandardNodeManagerSupport<Node>> implements NodeManager<Node> {
51
52     private static final Logger LOGGER = LoggerFactory.getLogger(StandardNodeManager.class);
53
54     protected final Node root;
55     protected final StandardRealm<Node,Engine> realm;
56
57     static final Binding NO_BINDING = new VariantBinding() {
58
59         @Override
60         public Object getContent(Object variant, Binding contentBinding) throws BindingException {
61             throw new Error();
62         }
63
64         @Override
65         public Object getContent(Object variant) throws BindingException {
66             throw new Error();
67         }
68
69         @Override
70         public Datatype getContentType(Object variant) throws BindingException {
71             throw new Error();
72         }
73
74         @Override
75         public Binding getContentBinding(Object variant) throws BindingException {
76             throw new Error();
77         }
78
79         @Override
80         public Object create(Binding contentBinding, Object content) throws BindingException {
81             throw new Error();
82         }
83
84         @Override
85         public void setContent(Object variant, Binding contentBinding, Object content) throws BindingException {
86             throw new Error();
87         }
88
89         @Override
90         public boolean isInstance(Object obj) {
91             return true;
92         }
93
94         @Override
95         public void assertInstaceIsValid(Object obj, Set<Object> validInstances) throws BindingException {
96             throw new Error();
97         }
98
99         @Override
100         public int compare(Object o1, Object o2) throws org.simantics.databoard.binding.error.RuntimeBindingException {
101             if(o1 == null) {
102                 if(o2 == null) {
103                     return 0;
104                 } else {
105                     return  - System.identityHashCode(o2);
106                 }
107             } else {
108                 if(o2 == null) {
109                     return  System.identityHashCode(o1);
110                 } else {
111                     if(o1.equals(o2)) return 0;
112                     return System.identityHashCode(o1) - System.identityHashCode(o2);
113                 }
114             }
115         }
116
117     };
118
119     protected THashMap<Node, Variant> valueCache = new THashMap<>();
120     protected THashMap<Node, THashSet<Runnable>> listeners = new THashMap<>();
121
122     AtomicBoolean fireNodeListenersScheduled = new AtomicBoolean(false);
123     Runnable fireNodeListeners = new Runnable() {
124         @Override
125         public void run() {
126             fireNodeListenersScheduled.set(false);
127             TObjectProcedure<Runnable> procedure = r -> {
128                 r.run();
129                 return true;
130             };
131             synchronized(listeners) {
132                 listeners.forEachValue(set -> {
133                     set.forEach(procedure);
134                     return true;
135                 });
136             }
137         }
138     };
139
140     Runnable clearValueCache = () -> valueCache.clear();
141
142     public StandardNodeManager(StandardRealm<Node,Engine> realm, Node root) {
143         assert(realm != null);
144         assert(root != null);
145         this.realm = realm;
146         this.root = root;
147     }
148
149     @Override
150     public List<String> getChildNames(Node node) throws NodeManagerException {
151         List<Node> children = getChildren(node);
152         ArrayList<String> names = new ArrayList<>(children.size());
153         for(Node child : children)
154             names.add(getName(child));
155         return names;
156     }
157
158     @Override
159     public List<String> getPropertyNames(Node node) throws NodeManagerException {
160         List<Node> properties = getProperties(node);
161         ArrayList<String> names = new ArrayList<>(properties.size());
162         for(Node property : properties)
163             names.add(getName(property));
164         return names;
165     }
166
167     @Override
168     public Object getValue(Node node, String propertyName, Binding binding)
169             throws NodeManagerException, BindingException {
170         Node property = getProperty(node, propertyName);
171         if(property == null)
172             throw new NoSuchNodeException("Didn't find a property " + propertyName);
173         return getValue(property, binding);
174     }
175
176     @Override
177     public void setValue(Node node, String propertyName, Object value,
178             Binding binding) throws NodeManagerException, BindingException {
179         Node property = getProperty(node, propertyName);
180         if(property == null)
181             throw new NoSuchNodeException("Didn't find a property " + propertyName);
182         setValue(property, value, binding);
183     }
184
185     @Override
186     public Variant getValue(Node node, String propertyName)
187             throws NodeManagerException {
188         Node property = getProperty(node, propertyName);
189         if(property == null)
190             throw new NoSuchNodeException("Didn't find a property " + propertyName);
191         return getValue(property);
192     }
193
194     @Override
195     public Object getValue(Node node, Binding binding) throws NodeManagerException, BindingException {
196         try {
197             return getValue(node).getValue(binding);
198         } catch (AdaptException e) {
199             throw new BindingException(e);
200         }
201     }
202
203     @Override
204     public String getPropertyURI(Node parent, Node property) {
205         return null;
206     }
207
208     @Override
209     public Realm getRealm() {
210         return realm;
211     }
212
213     public StandardRealm<Node, Engine> getStandardRealm() {
214         return realm;
215     }
216
217     protected String getRealmId() {
218         return realm.getId();
219     }
220
221     public Node getRoot() {
222         return root;
223     }
224
225     protected boolean isRoot(Node node) {
226         return root.equals(node);
227     }
228
229     @Override
230     public void addNodeListener(Node node, Runnable listener) {
231         synchronized(listeners) {
232             THashSet<Runnable> l = listeners.get(node);
233             if(l == null) {
234                 l = new THashSet<>();
235                 listeners.put(node, l);
236             }
237             l.add(listener);
238         }
239         getRealm().asyncExec(listener);
240     }
241
242     @Override
243     public void removeNodeListener(Node node, Runnable listener) {
244         synchronized(listeners) {
245             THashSet<Runnable> l = listeners.get(node);
246             if(l != null) {
247                 l.remove(listener);
248                 if(l.isEmpty())
249                     listeners.remove(node);
250             }
251         }
252     }
253
254     public void fireNodeListeners() {
255         if(!fireNodeListenersScheduled.getAndSet(true))
256             realm.asyncExec(fireNodeListeners);
257     }
258
259     public void fireNodeListenersSync() {
260         try {
261             realm.syncExec(fireNodeListeners);
262         } catch (InterruptedException e) {
263             LOGGER.error("Synchronous node listener firing was interrupted.", e);
264         }
265     }
266
267     public void refreshVariable(Node node) {
268         realm.asyncExec(() -> {
269             valueCache.remove(node);
270             synchronized(listeners) {
271                 THashSet<Runnable> runnables = listeners.get(node);
272                 if (runnables != null) {
273                     for (Runnable r : runnables) {
274                         r.run();
275                     }
276                 }
277             }
278         });
279     }
280
281     public void refreshVariables() {
282         realm.asyncExec(clearValueCache);
283         fireNodeListeners();
284     }
285
286     public void refreshVariablesSync() {
287         try {
288             realm.syncExec(clearValueCache);
289         } catch (InterruptedException e) {
290             LOGGER.error("Synchronous value cache refresh was interrupted.", e);
291         }
292         fireNodeListenersSync();
293     }
294
295     protected Variant getEngineVariantOrCached(Node node) throws NodeManagerException {
296         Variant variant = valueCache.get(node);
297         if(variant == null) {
298             Object value = realm.getEngine().getEngineValue(node);
299             Binding binding = realm.getEngine().getEngineBinding(node);
300             variant = new Variant(binding, value);
301             valueCache.put(node, variant);
302         }
303         return variant;
304     }
305
306     @Override
307     public Variant getValue(Node node) throws NodeManagerException {
308         checkThreadAccess();
309         return getEngineVariantOrCached(node);
310     }
311
312     protected void checkThreadAccess() throws NodeManagerException {
313         if(Thread.currentThread() != realm.getThread())
314             throw new NotInRealmException();
315     }
316
317     protected Datatype getDatatypeForValue(Object value) {
318         Binding binding = Bindings.getBindingUnchecked(value.getClass());
319         if(binding == null) return null;
320         else return binding.type();
321     }
322
323     @Override
324     public void setValue(Node node, Object value, Binding binding)
325             throws NodeManagerException {
326         updateValueInner(node, value, binding);
327         refreshVariable(node);
328     }
329
330     //Update the value of the node and remove from valueCache only the references nodes
331     public void setValueAndFireSelectedListeners(Node node, Object value, Binding binding, Set<Node> references) throws NodeManagerException {
332         if(references.size() > 0) {
333                 for(Node n : references) {
334                         valueCache.remove(n);
335                 }
336         }
337         updateValueInner(node, value, binding);
338         fireNodeListenersSync();
339     }
340     
341     //Update the value of the node helper method
342     private void updateValueInner(Node node, Object value, Binding binding) throws NodeManagerException {
343         checkThreadAccess();
344         Binding targetBinding = realm.getEngine().getEngineBinding(node);
345         if(binding.equals(targetBinding)) {
346             Variant variant = new Variant(binding, value);
347             valueCache.put(node, variant);
348             realm.getEngine().setEngineValue(node, value);
349         } else {
350             try {
351                 Adapter adapter = Bindings.getAdapter(binding, targetBinding);
352                 Object targetValue = adapter.adapt(value);
353                 Variant variant = new Variant(targetBinding, targetValue);
354                 valueCache.put(node, variant);
355                 realm.getEngine().setEngineValue(node, targetValue);
356             } catch (AdapterConstructionException e) {
357                 throw new NodeManagerException(e);
358             } catch (AdaptException e) {
359                 throw new NodeManagerException(e);
360             }
361         }
362     }
363
364     @Override
365     public String getName(Node node) {
366         if(isRoot(node)) {
367             String id = getRealmId();
368             int lastSlash = id.lastIndexOf("/");
369             if(lastSlash == -1) throw new IllegalStateException("Invalid realm id " + id);
370             String name = id.substring(lastSlash+1);
371             return name;
372         } else {
373             return realm.getEngine().getName(node);
374         }
375     }
376
377     @Override
378     public Node getNode(String path) throws NodeManagerException {
379         checkThreadAccess();
380         throw new UnsupportedOperationException();
381     }
382
383     @Override
384     public Node getChild(Node node, String name) throws NodeManagerException {
385         checkThreadAccess();
386         Map<String,Node> map = realm.getEngine().getChildren(node);
387         return map.get(name);
388     }
389
390     @Override
391     public Node getProperty(Node node, String name) throws NodeManagerException {
392         checkThreadAccess();
393         Map<String,Node> map = realm.getEngine().getProperties(node);
394         return map.get(name);
395     }
396
397     @Override
398     public List<Node> getChildren(Node node) throws NodeManagerException {
399         checkThreadAccess();
400         return new ArrayList<Node>(realm.getEngine().getChildren(node).values());
401     }
402
403     @Override
404     public List<Node> getProperties(Node node) throws NodeManagerException {
405         checkThreadAccess();
406         return new ArrayList<Node>(realm.getEngine().getProperties(node).values());
407     }
408
409     @Override
410     public Datatype getDatatype(Node node) throws NodeManagerException {
411         checkThreadAccess();
412         try {
413             Variant v = getEngineVariantOrCached(node);
414             Binding b = v.getBinding();
415             if(b == null) return null;
416             return b.type();
417         } catch (RuntimeBindingConstructionException e) {
418             // There is no datatype for all values
419         }
420         return null;
421     }
422
423     public void clear() {
424         valueCache.clear();
425         listeners.clear();
426     }
427
428     @Override
429     public Set<String> getClassifications(Node node) throws NodeManagerException {
430         return Collections.emptySet();
431     }
432
433 }