1 /*******************************************************************************
2 * Copyright (c) 2012, 2013 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.g3d.vtk.common;
14 import java.lang.reflect.InvocationTargetException;
15 import java.util.ArrayDeque;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Deque;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
25 import java.util.Stack;
27 import org.eclipse.ui.PlatformUI;
28 import org.eclipse.ui.progress.IProgressService;
29 import org.simantics.db.ReadGraph;
30 import org.simantics.db.Session;
31 import org.simantics.db.UndoContext;
32 import org.simantics.db.WriteGraph;
33 import org.simantics.db.common.request.UniqueRead;
34 import org.simantics.db.common.request.WriteRequest;
35 import org.simantics.db.exception.DatabaseException;
36 import org.simantics.db.layer0.util.Layer0Utils;
37 import org.simantics.db.procedure.SyncProcedure;
38 import org.simantics.db.service.UndoRedoSupport;
39 import org.simantics.g3d.ontology.G3D;
40 import org.simantics.g3d.scenegraph.RenderListener;
41 import org.simantics.g3d.scenegraph.base.INode;
42 import org.simantics.g3d.scenegraph.base.NodeListener;
43 import org.simantics.g3d.scenegraph.base.ParentNode;
44 import org.simantics.objmap.exceptions.MappingException;
45 import org.simantics.objmap.graph.IMapping;
46 import org.simantics.objmap.graph.IMappingListener;
47 import org.simantics.utils.datastructures.MapList;
48 import org.simantics.utils.datastructures.MapSet;
49 import org.simantics.utils.datastructures.Pair;
50 import org.simantics.utils.ui.ExceptionUtils;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
56 public abstract class AbstractVTKNodeMap<DBObject,E extends INode> implements VTKNodeMap<DBObject,E>, IMappingListener, RenderListener, NodeListener, UndoRedoSupport.ChangeListener{
58 private static final Logger LOGGER = LoggerFactory.getLogger(AbstractVTKNodeMap.class);
60 protected Session session;
61 protected IMapping<DBObject, INode> mapping;
62 protected VtkView view;
64 private MapList<E, vtkProp> nodeToActor = new MapList<E, vtkProp>();
65 private Map<vtkProp,E> actorToNode = new HashMap<vtkProp, E>();
67 protected ParentNode<E> rootNode;
69 protected UndoRedoSupport undoRedoSupport;
70 protected int undoOpCount = 0;
71 protected int redoOpCount = 0;
72 protected boolean runUndo = false;
73 protected boolean runRedo = false;
74 public AbstractVTKNodeMap(Session session, IMapping<DBObject,INode> mapping, VtkView view, ParentNode<E> rootNode) {
75 this.session = session;
76 this.mapping = mapping;
78 this.rootNode = rootNode;
79 view.addListener(this);
80 mapping.addMappingListener(this);
81 rootNode.addListener(this);
83 undoRedoSupport = session.getService(UndoRedoSupport.class);
84 undoRedoSupport.subscribe(this);
86 UndoContext undoContext = undoRedoSupport.getUndoContext(session);
87 undoOpCount = undoContext.getAll().size();
88 redoOpCount = undoContext.getRedoList().size();
89 } catch(DatabaseException e) {
90 LOGGER.error("Error reading from undo context", e);
94 protected abstract void addActor(E node);
95 protected abstract void removeActor(E node);
96 protected abstract void updateActor(E node,Set<String> ids);
98 public void repaint() {
102 public void populate() {
103 for (E node : rootNode.getNodes()) {
104 receiveAdd(node, node.getParentRel(),true);
110 public E getNode(vtkProp prop) {
111 return actorToNode.get(prop);
114 @SuppressWarnings("unchecked")
116 public Collection<vtkProp> getRenderObjects(INode node) {
117 return nodeToActor.getValues((E) node);
120 protected <T extends vtkProp> void map(E node, Collection<T> props) {
121 for (vtkProp p : props) {
122 nodeToActor.add(node, p);
123 actorToNode.put(p, node);
127 protected void removeMap(E node) {
128 Collection<vtkProp> coll = nodeToActor.getValuesUnsafe(node);
129 if (coll.size() > 0) {
131 for (vtkProp p : coll) {
132 actorToNode.remove(p);
133 if (p.GetVTKId() != 0) {
134 view.getRenderer().RemoveActor(p);
140 nodeToActor.remove(node);
144 public ParentNode<E> getRootNode() {
145 return (ParentNode<E>)rootNode;
151 public boolean isChangeTracking() {
152 return changeTracking;
156 public void setChangeTracking(boolean enabled) {
157 changeTracking = enabled;
160 private boolean changeTracking = true;
162 protected Object syncMutex = new Object();
165 private List<Pair<E,String>> added = new ArrayList<Pair<E,String>>();
166 private List<Pair<E,String>> removed = new ArrayList<Pair<E,String>>();
167 private MapSet<E, String> updated = new MapSet.Hash<E, String>();
169 private boolean rangeModified = false;
171 public boolean isRangeModified() {
172 return rangeModified;
176 public void onChanged() {
178 UndoContext undoContext = undoRedoSupport.getUndoContext(session);
179 int ucount = undoContext.getAll().size();
180 int rcount = undoContext.getRedoList().size();
182 if (LOGGER.isTraceEnabled()) LOGGER.trace("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount);
183 if (ucount < undoOpCount) {
188 if (!runUndo && rcount > 0)
192 undoOpCount = ucount;
193 redoOpCount = rcount;
195 if (LOGGER.isTraceEnabled()) LOGGER.trace("Undo " + runUndo + " Redo " + runRedo);
196 } catch (DatabaseException e) {
197 // TODO Auto-generated catch block
205 public void updateRenderObjectsFor(E node) {
206 List<vtkProp> toDelete = new ArrayList<vtkProp>();
208 for (vtkProp prop : nodeToActor.getValues(node)) {
209 if (prop.GetVTKId() != 0) {
210 view.getRenderer().RemoveActor(prop);
214 actorToNode.remove(prop);
217 nodeToActor.remove(node);
218 Collection<vtkProp> coll = getActors(node);
220 for (vtkProp prop : coll) {
221 nodeToActor.add(node,prop);
222 actorToNode.put(prop, node);
223 toDelete.remove(prop);
226 for (vtkProp p : toDelete)
230 protected abstract Collection<vtkProp> getActors(E node);
232 @SuppressWarnings("unchecked")
233 private void receiveAdd(E node, String id, boolean db) {
234 if (LOGGER.isTraceEnabled()) LOGGER.trace("receiveAdd " + debugString(node) + " " + id + " " + db);
235 synchronized (syncMutex) {
236 for (Pair<E, String> n : added) {
237 if (n.first.equals(node))
240 if (changeTracking) {
241 mapping.rangeModified((E)node.getParent());
242 mapping.rangeModified((E)node);
244 added.add(new Pair<E, String>(node, id));
245 rangeModified = true;
250 @SuppressWarnings("unchecked")
251 private void receiveRemove(E node, String id, boolean db) {
252 if (LOGGER.isTraceEnabled()) LOGGER.trace("receiveRemove " + debugString(node) + " " + id + " " + db);
253 synchronized (syncMutex) {
254 for (Pair<E, String> n : removed) {
255 if (n.first.equals(node))
258 if (changeTracking && !db) {
259 mapping.rangeModified((E)node);
260 mapping.rangeModified((E)node.getParent());
262 removed.add(new Pair<E, String>(node, id));
263 rangeModified = true;
268 private void receiveUpdate(E node, String id, boolean db) {
269 if (LOGGER.isTraceEnabled()) LOGGER.trace("receiveUpdate " + debugString(node) + " " + id + " " + db);
270 synchronized (syncMutex) {
271 // for (Pair<E, String> n : updated) {
272 // if (n.first.equals(node))
275 if (changeTracking && !db)
276 mapping.rangeModified(node);
277 //updated.add(new Pair<E, String>(node, id));
278 updated.add(node, id);
279 rangeModified = true;
284 private boolean graphUpdates = false;
285 private Set<E> graphModified = new HashSet<E>();
287 private boolean requestCommit = false;
288 private String commitMessage = null;
291 public void commit(String message) {
292 requestCommit = true;
293 commitMessage = message;
296 protected void doCommit() {
297 IProgressService service = PlatformUI.getWorkbench().getProgressService();
299 service.busyCursorWhile(monitor -> {
301 session.syncRequest(new WriteRequest() {
303 public void perform(WriteGraph graph) throws DatabaseException {
304 if (LOGGER.isTraceEnabled()) LOGGER.trace("Commit " + commitMessage);
305 if (commitMessage != null) {
306 Layer0Utils.addCommentMetadata(graph, commitMessage);
307 graph.markUndoPoint();
308 commitMessage = null;
313 } catch (DatabaseException e) {
314 ExceptionUtils.logAndShowError("Cannot commit editor changes", e);
318 } catch (InvocationTargetException | InterruptedException e) {
319 LOGGER.error("Unexpected exception", e);
323 protected void postCommit() {}
325 protected void commit(WriteGraph graph) throws DatabaseException {
326 synchronized(syncMutex) {
327 if (LOGGER.isTraceEnabled()) LOGGER.trace("Commit");
329 mapping.updateDomain(graph);
330 graphUpdates = false;
332 if (LOGGER.isTraceEnabled()) LOGGER.trace("Commit done");
339 public void domainModified() {
342 if (LOGGER.isTraceEnabled()) LOGGER.trace("domainModified");
343 session.asyncRequest(new UniqueRead<Object>() {
345 public Object perform(ReadGraph graph) throws DatabaseException {
348 }, new SyncProcedure<Object>() {
350 public void execute(ReadGraph graph, Object result) throws DatabaseException {
351 // Perform all updates to the model in a single query thread
356 public void exception(ReadGraph graph, Throwable throwable) throws DatabaseException {
357 LOGGER.error("Failed to update pipeline changes" + throwable);
362 protected void reset(ReadGraph graph) throws MappingException {
363 if (LOGGER.isTraceEnabled()) LOGGER.trace("Reset");
366 mapping.getRangeModified().clear();
367 for (DBObject o : mapping.getDomain())
368 mapping.domainModified(o);
369 mapping.updateRange(graph);
370 graphModified.clear();
371 graphUpdates = false;
374 private boolean useFullSyncWithUndo = false;
376 protected void update(ReadGraph graph) throws DatabaseException {
377 if (LOGGER.isTraceEnabled()) LOGGER.trace("Graph update start");
379 if (runUndo && useFullSyncWithUndo) {
380 synchronized (syncMutex) {
384 synchronized (syncMutex) {
386 for (DBObject domainObject : mapping.getDomainModified()) {
387 @SuppressWarnings("unchecked")
388 E rangeObject = (E) mapping.get(domainObject);
389 if (rangeObject != null)
390 graphModified.add(rangeObject);
395 mapping.updateRange(graph);
397 synchronized (syncMutex) {
398 graphModified.clear();
403 graphUpdates = false;
406 if (mapping.isRangeModified() && !runUndo && !runRedo)
407 commit((String)null);
409 if (LOGGER.isTraceEnabled()) LOGGER.trace("Graph update done");
413 public void rangeModified() {
414 //LOGGER.trace("rangeModified");
419 public void postRender() {
421 // 1. Commit has been requested
422 // 2. There are no pending changes that should be processed in preRender()
423 if (requestCommit && !rangeModified) { // FIXME : not thread safe.
424 requestCommit = false;
429 // Reusable containers for data synchronisation
430 List<Pair<E, String>> rem = new ArrayList<Pair<E,String>>(); // Removed objects
431 List<Pair<E, String>> add = new ArrayList<Pair<E,String>>(); // Added objects
432 MapSet<E, String> mod = new MapSet.Hash<E, String>(); // Modified objects
433 Set<E> propagation = new HashSet<E>(); // Objects with propagated changes
434 Stack<E> stack = new Stack<E>(); // Stack for handling propagation
435 Set<E> delete = Collections.synchronizedSet(new HashSet<E>()); // Objects to be completely deleted
436 Set<E> deleteUC = new HashSet<E>();
439 public synchronized void preRender() {
445 * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache.
446 * This causes problems with Undo and Redo, which cause re-using the removed objects from mapping cache.
448 * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added).
451 protected void syncDeletes() {
453 for (Pair<E, String> n : removed) {
454 deleteUC.add(n.first);
456 for (Pair<E, String> n : added) {
457 deleteUC.remove(n.first);
459 if (LOGGER.isTraceEnabled() && deleteUC.size() > 0) {
460 LOGGER.trace("Delete sync");
462 LOGGER.trace(debugString(n));
465 delete.addAll(deleteUC);
470 * Clears deletable objects from mapping cache.
472 protected void clearDeletes() {
473 if (LOGGER.isTraceEnabled() && delete.size() > 0) LOGGER.trace("Delete");
475 if (LOGGER.isTraceEnabled()) LOGGER.trace(debugString(n));
476 mapping.getRange().remove(n);
482 protected String debugString(E n) {
483 return n + "@" + Integer.toHexString(n.hashCode());
486 protected boolean filterChange(List<Pair<E,String>> list,E n) {
487 for (int i = list.size()-1; i >= 0; i--) {
488 if (list.get(i).first == n) {
496 @SuppressWarnings("unchecked")
497 protected void updateCycle() {
504 synchronized (syncMutex) {
505 // Check for overlapping additions and deletions, prevent deleting objects that are also added and vice versa.
506 Deque<E> stack = new ArrayDeque<E>();
507 for (Pair<E, String> n : added) {
510 while (!stack.isEmpty()) {
512 boolean conflict = filterChange(removed, n);
514 if (LOGGER.isTraceEnabled()) LOGGER.trace("Prevent removing " + n);
515 //filterChange(added, n)
516 if (filterChange(added, n))
517 if (LOGGER.isTraceEnabled()) LOGGER.trace("Prevent adding " + n);
519 if (n instanceof ParentNode) {
520 ParentNode<INode> pn = (ParentNode<INode>)n;
521 for (INode cn : pn.getNodes()) {
526 // Do not process updates for removed nodes.
527 for (Pair<E, String> r : removed) {
528 updated.removeValues(r.first);
532 for (E e : updated.getKeys()) {
533 for (String s : updated.getValues(e)) {
544 for (Pair<E, String> n : rem) {
545 stopListening(n.first);
546 removeActor(n.first);
550 for (Pair<E, String> n : add) {
555 for (E e : mod.getKeys()) {
556 Set<String> ids = mod.getValues(e);
557 if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
558 if (!propagation.contains(e))
563 if (propagation.size() > 0) {
565 stack.addAll(propagation);
567 while (!stack.isEmpty()) {
568 E node = stack.pop();
569 if (propagation.contains(node))
571 propagation.add(node);
572 for (NodeListener l : node.getListeners()) {
574 //changeTracking = false;
575 //l.propertyChanged(node, G3D.URIs.hasPosition);
576 //changeTracking = true;
578 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
581 if (node instanceof ParentNode) {
582 stack.addAll(((ParentNode<E>)node).getNodes());
587 for (E e : mod.getKeys()) {
588 Set<String> ids = mod.getValues(e);
592 for (Pair<E, String> n : rem) {
593 for (NodeListener l : nodeListeners)
594 l.nodeRemoved(null, n.first, n.second);
596 for (Pair<E, String> n : add) {
597 for (NodeListener l : nodeListeners)
598 l.nodeAdded(n.first.getParent(), n.first, n.second);
600 // for (Pair<E, String> n : mod) {
601 // for (NodeListener l : nodeListeners)
602 // l.propertyChanged(n.first, n.second);
604 for (E e : mod.getKeys()) {
605 for (NodeListener l : nodeListeners)
606 for (String s : mod.getValues(e))
607 l.propertyChanged(e, s);
610 synchronized (syncMutex) {
611 if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
612 rangeModified = false;
616 @SuppressWarnings("unchecked")
617 private void listen(INode node) {
618 node.addListener(this);
619 if (node instanceof ParentNode<?>) {
620 ParentNode<INode> parentNode = (ParentNode<INode>)node;
621 for (INode n : parentNode.getNodes())
626 private void stopListening(INode node) {
627 node.removeListener(this);
628 if (node instanceof ParentNode<?>) {
629 @SuppressWarnings("unchecked")
630 ParentNode<INode> parentNode = (ParentNode<INode>)node;
631 for (INode n : parentNode.getNodes())
636 @SuppressWarnings("unchecked")
638 public void propertyChanged(INode node, String id) {
639 //receiveUpdate((E)node, id, graphUpdates);
640 receiveUpdate((E)node, id, graphModified.contains(node));
644 @SuppressWarnings("unchecked")
646 public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
648 if (LOGGER.isTraceEnabled()) LOGGER.trace("Node added " + child + " parent " + node);
649 //receiveAdd((E)child, rel ,graphUpdates);
650 receiveAdd((E)child, rel ,graphModified.contains(node));
653 @SuppressWarnings("unchecked")
655 public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
657 if (LOGGER.isTraceEnabled()) LOGGER.trace("Node removed " + child + " parent " + node);
658 //receiveRemove((E)child, rel, graphUpdates);
659 receiveRemove((E)child, rel, graphModified.contains(node));
661 //FIXME : 1. sometimes removed structural models cause ObjMap to add their children again.
662 // removing the listener here prevents corruption of visual model, but better fix is needed.
663 // 2. detach causes nodeRemoved event, which then causes other critical events to be missed. Took out call:
664 //stopListening(child);
668 public void delete() {
669 if (undoRedoSupport != null)
670 undoRedoSupport.cancel(this);
672 changeTracking = false;
673 view.removeListener(this);
674 mapping.removeMappingListener(this);
676 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
677 nodes.addAll(nodeToActor.getKeys());
678 for (E node : nodes) {
679 node.removeListener(this);
683 for (vtkProp prop : actorToNode.keySet()) {
684 if (prop.GetVTKId() != 0)
693 private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
695 public void addListener(NodeListener listener) {
696 nodeListeners.add(listener);
701 public void removeListener(NodeListener listener) {
702 nodeListeners.remove(listener);
706 public IMapping<DBObject,INode> getMapping() {