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.util.ArrayDeque;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.Deque;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
24 import java.util.Stack;
26 import org.simantics.db.ReadGraph;
27 import org.simantics.db.Session;
28 import org.simantics.db.UndoContext;
29 import org.simantics.db.WriteGraph;
30 import org.simantics.db.common.request.ReadRequest;
31 import org.simantics.db.common.request.WriteRequest;
32 import org.simantics.db.exception.DatabaseException;
33 import org.simantics.db.layer0.util.Layer0Utils;
34 import org.simantics.db.service.UndoRedoSupport;
35 import org.simantics.g3d.ontology.G3D;
36 import org.simantics.g3d.scenegraph.RenderListener;
37 import org.simantics.g3d.scenegraph.base.INode;
38 import org.simantics.g3d.scenegraph.base.NodeListener;
39 import org.simantics.g3d.scenegraph.base.ParentNode;
40 import org.simantics.objmap.exceptions.MappingException;
41 import org.simantics.objmap.graph.IMapping;
42 import org.simantics.objmap.graph.IMappingListener;
43 import org.simantics.utils.datastructures.Callback;
44 import org.simantics.utils.datastructures.MapList;
45 import org.simantics.utils.datastructures.MapSet;
46 import org.simantics.utils.datastructures.Pair;
47 import org.simantics.utils.ui.ExceptionUtils;
51 public abstract class AbstractVTKNodeMap<DBObject,E extends INode> implements VTKNodeMap<DBObject,E>, IMappingListener, RenderListener, NodeListener, UndoRedoSupport.ChangeListener{
53 private static final boolean DEBUG = false;
55 protected Session session;
56 protected IMapping<DBObject,E> mapping;
57 protected VtkView view;
59 private MapList<E, vtkProp> nodeToActor = new MapList<E, vtkProp>();
60 private Map<vtkProp,E> actorToNode = new HashMap<vtkProp, E>();
62 protected ParentNode<E> rootNode;
64 protected UndoRedoSupport undoRedoSupport;
65 protected int undoOpCount = 0;
66 protected int redoOpCount = 0;
67 protected boolean runUndo = false;
68 protected boolean runRedo = false;
69 public AbstractVTKNodeMap(Session session, IMapping<DBObject,E> mapping, VtkView view, ParentNode<E> rootNode) {
70 this.session = session;
71 this.mapping = mapping;
73 this.rootNode = rootNode;
74 view.addListener(this);
75 mapping.addMappingListener(this);
76 rootNode.addListener(this);
78 undoRedoSupport = session.getService(UndoRedoSupport.class);
79 undoRedoSupport.subscribe(this);
81 UndoContext undoContext = undoRedoSupport.getUndoContext(session);
82 undoOpCount = undoContext.getAll().size();
83 redoOpCount = undoContext.getRedoList().size();
84 } catch(DatabaseException e) {
89 protected abstract void addActor(E node);
90 protected abstract void removeActor(E node);
91 protected abstract void updateActor(E node,Set<String> ids);
93 public void repaint() {
97 public void populate() {
98 for (E node : rootNode.getNodes()) {
99 receiveAdd(node, node.getParentRel(),true);
105 public E getNode(vtkProp prop) {
106 return actorToNode.get(prop);
109 @SuppressWarnings("unchecked")
111 public Collection<vtkProp> getRenderObjects(INode node) {
112 return nodeToActor.getValues((E)node);
115 protected <T extends vtkProp> void map(E node, Collection<T> props) {
116 for (vtkProp p : props) {
117 nodeToActor.add(node, p);
118 actorToNode.put(p, node);
122 protected void removeMap(E node) {
123 Collection<vtkProp> coll = nodeToActor.getValuesUnsafe(node);
124 for (vtkProp p : coll) {
125 actorToNode.remove(p);
127 nodeToActor.remove(node);
130 @SuppressWarnings("unchecked")
132 public ParentNode<E> getRootNode() {
133 return (ParentNode<E>)rootNode;
139 public boolean isChangeTracking() {
140 return changeTracking;
144 public void setChangeTracking(boolean enabled) {
145 changeTracking = enabled;
148 private boolean changeTracking = true;
150 protected Object syncMutex = new Object();
153 private List<Pair<E,String>> added = new ArrayList<Pair<E,String>>();
154 private List<Pair<E,String>> removed = new ArrayList<Pair<E,String>>();
155 private MapSet<E, String> updated = new MapSet.Hash<E, String>();
157 private boolean rangeModified = false;
159 public boolean isRangeModified() {
160 return rangeModified;
164 public void onChanged() {
166 UndoContext undoContext = undoRedoSupport.getUndoContext(session);
167 int ucount = undoContext.getAll().size();
168 int rcount = undoContext.getRedoList().size();
169 if (DEBUG) System.out.println("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount);
170 if (ucount < undoOpCount) {
175 if (!runUndo && rcount > 0)
179 undoOpCount = ucount;
180 redoOpCount = rcount;
182 if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo);
183 } catch (DatabaseException e) {
184 // TODO Auto-generated catch block
191 @SuppressWarnings("unchecked")
193 public void updateRenderObjectsFor(E node) {
194 List<vtkProp> toDelete = new ArrayList<vtkProp>();
196 for (vtkProp prop : nodeToActor.getValues((E)node)) {
197 if (prop.GetVTKId() != 0) {
198 view.getRenderer().RemoveActor(prop);
202 actorToNode.remove(prop);
205 nodeToActor.remove((E)node);
206 Collection<vtkProp> coll = getActors((E)node);
208 for (vtkProp prop : coll) {
209 nodeToActor.add((E)node,prop);
210 actorToNode.put(prop, (E)node);
211 toDelete.remove(prop);
214 for (vtkProp p : toDelete)
218 protected abstract Collection<vtkProp> getActors(E node);
220 @SuppressWarnings("unchecked")
221 private void receiveAdd(E node, String id, boolean db) {
222 if (DEBUG) System.out.println("receiveAdd " + debugString(node) + " " + id + " " + db);
223 synchronized (syncMutex) {
224 for (Pair<E, String> n : added) {
225 if (n.first.equals(node))
228 if (changeTracking) {
229 mapping.rangeModified((E)node.getParent());
231 added.add(new Pair<E, String>(node, id));
232 rangeModified = true;
237 @SuppressWarnings("unchecked")
238 private void receiveRemove(E node, String id, boolean db) {
239 if (DEBUG) System.out.println("receiveRemove " + debugString(node) + " " + id + " " + db);
240 synchronized (syncMutex) {
241 for (Pair<E, String> n : removed) {
242 if (n.first.equals(node))
245 if (changeTracking && !db)
246 mapping.rangeModified((E)node.getParent());
247 removed.add(new Pair<E, String>(node, id));
248 rangeModified = true;
253 @SuppressWarnings("unchecked")
254 private void receiveUpdate(E node, String id, boolean db) {
255 if (DEBUG) System.out.println("receiveUpdate " + debugString(node) + " " + id + " " + db);
256 synchronized (syncMutex) {
257 // for (Pair<E, String> n : updated) {
258 // if (n.first.equals(node))
261 if (changeTracking && !db)
262 mapping.rangeModified(node);
263 //updated.add(new Pair<E, String>(node, id));
264 updated.add(node, id);
265 rangeModified = true;
270 private boolean graphUpdates = false;
271 private Set<E> graphModified = new HashSet<E>();
273 private boolean requestCommit = false;
274 private String commitMessage = null;
277 public void commit(String message) {
278 requestCommit = true;
279 commitMessage = message;
282 protected void doCommit() {
283 session.asyncRequest(new WriteRequest() {
286 public void perform(WriteGraph graph) throws DatabaseException {
287 if (DEBUG) System.out.println("Commit " + commitMessage);
288 if (commitMessage != null) {
289 Layer0Utils.addCommentMetadata(graph, commitMessage);
290 graph.markUndoPoint();
291 commitMessage = null;
296 }, new Callback<DatabaseException>() {
299 public void run(DatabaseException parameter) {
300 if (parameter != null)
301 ExceptionUtils.logAndShowError("Cannot commit editor changes", parameter);
306 protected void commit(WriteGraph graph) throws DatabaseException {
307 synchronized(syncMutex) {
308 if (DEBUG) System.out.println("Commit");
310 mapping.updateDomain(graph);
311 graphUpdates = false;
313 if (DEBUG) System.out.println("Commit done");
320 public void domainModified() {
323 if (DEBUG)System.out.println("domainModified");
324 session.asyncRequest(new ReadRequest() {
326 @SuppressWarnings("unchecked")
328 public void run(ReadGraph graph) throws DatabaseException {
335 protected void reset(ReadGraph graph) throws MappingException {
336 if (DEBUG) System.out.println("Reset");
338 synchronized (syncMutex) {
340 mapping.getRangeModified().clear();
341 for (DBObject o : mapping.getDomain())
342 mapping.domainModified(o);
343 mapping.updateRange(graph);
344 graphModified.clear();
345 graphUpdates = false;
349 private boolean useFullSyncWithUndo = false;
351 protected void update(ReadGraph graph) throws DatabaseException {
352 if (DEBUG) System.out.println("Graph update start");
353 if (runUndo && useFullSyncWithUndo) {
356 synchronized (syncMutex) {
358 for (DBObject domainObject : mapping.getDomainModified()) {
359 E rangeObject = mapping.get(domainObject);
360 if (rangeObject != null)
361 graphModified.add(rangeObject);
363 mapping.updateRange(graph);
364 graphModified.clear();
367 graphUpdates = false;
371 if (mapping.isRangeModified() && !runUndo && !runRedo)
372 commit((String)null);
373 if (DEBUG) System.out.println("Graph update done");
377 public void rangeModified() {
378 //System.out.println("rangeModified");
383 public void postRender() {
385 // 1. Commit has been requested
386 // 2. There are no pending changes that should be processed in preRender()
387 if (requestCommit && !rangeModified) { // FIXME : not thread safe.
388 requestCommit = false;
393 // Reusable containers for data synchronisation
394 List<Pair<E, String>> rem = new ArrayList<Pair<E,String>>(); // Removed objects
395 List<Pair<E, String>> add = new ArrayList<Pair<E,String>>(); // Added objects
396 MapSet<E, String> mod = new MapSet.Hash<E, String>(); // Modified objects
397 Set<E> propagation = new HashSet<E>(); // Objects with propagated changes
398 Stack<E> stack = new Stack<E>(); // Stack for handling propagation
399 Set<E> delete = Collections.synchronizedSet(new HashSet<E>()); // Objects to be completely deleted
400 Set<E> deleteUC = new HashSet<E>();
403 public synchronized void preRender() {
409 * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache.
410 * This causes problems with Undo and Redo, which cause re-using the removed objects from mapping cache.
412 * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added).
415 protected void syncDeletes() {
417 for (Pair<E, String> n : removed) {
418 deleteUC.add(n.first);
420 for (Pair<E, String> n : added) {
421 deleteUC.remove(n.first);
423 if (DEBUG && deleteUC.size() > 0) {
424 System.out.println("Delete sync");
426 System.out.println(debugString(n));
429 delete.addAll(deleteUC);
434 * Clears deletable objects from mapping cache.
436 protected void clearDeletes() {
437 if (DEBUG && delete.size() > 0) System.out.println("Delete");
439 if (DEBUG) System.out.println(debugString(n));
440 mapping.getRange().remove(n);
445 protected String debugString(E n) {
446 return n + "@" + Integer.toHexString(n.hashCode());
449 protected boolean filterChange(List<Pair<E,String>> list,E n) {
450 for (int i = list.size()-1; i >= 0; i--) {
451 if (list.get(i).first == n) {
459 @SuppressWarnings("unchecked")
460 protected void updateCycle() {
467 synchronized (syncMutex) {
468 // Check for overlapping additions and deletions, prevent deleting objects that are also added and vice versa.
469 Deque<E> stack = new ArrayDeque<E>();
470 for (Pair<E, String> n : added) {
473 while (!stack.isEmpty()) {
475 boolean conflict = filterChange(removed, n);
477 System.out.println("Prevent removing " + n);
478 //filterChange(added, n)
479 if (filterChange(added, n))
480 System.out.println("Prevent adding " + n);
482 if (n instanceof ParentNode) {
483 ParentNode<INode> pn = (ParentNode<INode>)n;
484 for (INode cn : pn.getNodes()) {
492 for (E e : updated.getKeys()) {
493 for (String s : updated.getValues(e)) {
505 for (Pair<E, String> n : rem) {
506 stopListening(n.first);
507 removeActor(n.first);
510 for (Pair<E, String> n : add) {
515 for (E e : mod.getKeys()) {
516 Set<String> ids = mod.getValues(e);
517 if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
518 if (!propagation.contains(e))
523 if (propagation.size() > 0) {
525 stack.addAll(propagation);
527 while (!stack.isEmpty()) {
528 E node = stack.pop();
529 if (propagation.contains(node))
531 propagation.add(node);
532 for (NodeListener l : node.getListeners()) {
534 //changeTracking = false;
535 //l.propertyChanged(node, G3D.URIs.hasPosition);
536 //changeTracking = true;
538 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
541 if (node instanceof ParentNode) {
542 stack.addAll(((ParentNode<E>)node).getNodes());
547 // synchronized (syncMutex) {
548 // rem.addAll(removed);
549 // add.addAll(added);
550 // //mod.addAll(updated);
551 // for (E e : updated.getKeys()) {
552 // for (String s : updated.getValues(e))
561 for (E e : mod.getKeys()) {
562 Set<String> ids = mod.getValues(e);
567 for (Pair<E, String> n : rem) {
568 for (NodeListener l : nodeListeners)
569 l.nodeRemoved(null, n.first, n.second);
571 for (Pair<E, String> n : add) {
572 for (NodeListener l : nodeListeners)
573 l.nodeAdded(n.first.getParent(), n.first, n.second);
575 // for (Pair<E, String> n : mod) {
576 // for (NodeListener l : nodeListeners)
577 // l.propertyChanged(n.first, n.second);
579 for (E e : mod.getKeys()) {
580 for (NodeListener l : nodeListeners)
581 for (String s : mod.getValues(e))
582 l.propertyChanged(e, s);
585 synchronized (syncMutex) {
586 if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
587 rangeModified = false;
591 @SuppressWarnings("unchecked")
592 private void listen(INode node) {
593 node.addListener(this);
594 if (node instanceof ParentNode<?>) {
595 ParentNode<INode> parentNode = (ParentNode<INode>)node;
596 for (INode n : parentNode.getNodes())
601 private void stopListening(INode node) {
602 node.removeListener(this);
603 if (node instanceof ParentNode<?>) {
604 @SuppressWarnings("unchecked")
605 ParentNode<INode> parentNode = (ParentNode<INode>)node;
606 for (INode n : parentNode.getNodes())
611 @SuppressWarnings("unchecked")
613 public void propertyChanged(INode node, String id) {
614 //receiveUpdate((E)node, id, graphUpdates);
615 receiveUpdate((E)node, id, graphModified.contains(node));
619 @SuppressWarnings("unchecked")
621 public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
623 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
624 //receiveAdd((E)child, rel ,graphUpdates);
625 receiveAdd((E)child, rel ,graphModified.contains(node));
629 @SuppressWarnings("unchecked")
631 public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
633 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
634 //receiveRemove((E)child, rel, graphUpdates);
635 receiveRemove((E)child, rel, graphModified.contains(node));
637 //FIXME : sometimes removed structural models cause ObjMap to add their children again.
638 // removing the listener here prevents corruption of visual model, but better fix is needed.
639 stopListening(child);
643 public void delete() {
644 if (undoRedoSupport != null)
645 undoRedoSupport.cancel(this);
647 changeTracking = false;
648 view.removeListener(this);
649 mapping.removeMappingListener(this);
651 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
652 nodes.addAll(nodeToActor.getKeys());
653 for (E node : nodes) {
654 node.removeListener(this);
658 for (vtkProp prop : actorToNode.keySet()) {
659 if (prop.GetVTKId() != 0)
668 private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
670 public void addListener(NodeListener listener) {
671 nodeListeners.add(listener);
676 public void removeListener(NodeListener listener) {
677 nodeListeners.remove(listener);
681 public IMapping<DBObject,E> getMapping() {