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());
230 mapping.rangeModified((E)node);
232 added.add(new Pair<E, String>(node, id));
233 rangeModified = true;
238 @SuppressWarnings("unchecked")
239 private void receiveRemove(E node, String id, boolean db) {
240 if (DEBUG) System.out.println("receiveRemove " + debugString(node) + " " + id + " " + db);
241 synchronized (syncMutex) {
242 for (Pair<E, String> n : removed) {
243 if (n.first.equals(node))
246 if (changeTracking && !db) {
247 mapping.rangeModified((E)node);
248 mapping.rangeModified((E)node.getParent());
250 removed.add(new Pair<E, String>(node, id));
251 rangeModified = true;
256 @SuppressWarnings("unchecked")
257 private void receiveUpdate(E node, String id, boolean db) {
258 if (DEBUG) System.out.println("receiveUpdate " + debugString(node) + " " + id + " " + db);
259 synchronized (syncMutex) {
260 // for (Pair<E, String> n : updated) {
261 // if (n.first.equals(node))
264 if (changeTracking && !db)
265 mapping.rangeModified(node);
266 //updated.add(new Pair<E, String>(node, id));
267 updated.add(node, id);
268 rangeModified = true;
273 private boolean graphUpdates = false;
274 private Set<E> graphModified = new HashSet<E>();
276 private boolean requestCommit = false;
277 private String commitMessage = null;
280 public void commit(String message) {
281 requestCommit = true;
282 commitMessage = message;
285 protected void doCommit() {
286 session.asyncRequest(new WriteRequest() {
289 public void perform(WriteGraph graph) throws DatabaseException {
290 if (DEBUG) System.out.println("Commit " + commitMessage);
291 if (commitMessage != null) {
292 Layer0Utils.addCommentMetadata(graph, commitMessage);
293 graph.markUndoPoint();
294 commitMessage = null;
299 }, new Callback<DatabaseException>() {
302 public void run(DatabaseException parameter) {
303 if (parameter != null)
304 ExceptionUtils.logAndShowError("Cannot commit editor changes", parameter);
309 protected void commit(WriteGraph graph) throws DatabaseException {
310 synchronized(syncMutex) {
311 if (DEBUG) System.out.println("Commit");
313 mapping.updateDomain(graph);
314 graphUpdates = false;
316 if (DEBUG) System.out.println("Commit done");
323 public void domainModified() {
326 if (DEBUG)System.out.println("domainModified");
327 session.asyncRequest(new ReadRequest() {
329 @SuppressWarnings("unchecked")
331 public void run(ReadGraph graph) throws DatabaseException {
338 protected void reset(ReadGraph graph) throws MappingException {
339 if (DEBUG) System.out.println("Reset");
341 synchronized (syncMutex) {
343 mapping.getRangeModified().clear();
344 for (DBObject o : mapping.getDomain())
345 mapping.domainModified(o);
346 mapping.updateRange(graph);
347 graphModified.clear();
348 graphUpdates = false;
352 private boolean useFullSyncWithUndo = false;
354 protected void update(ReadGraph graph) throws DatabaseException {
355 if (DEBUG) System.out.println("Graph update start");
356 if (runUndo && useFullSyncWithUndo) {
359 synchronized (syncMutex) {
361 for (DBObject domainObject : mapping.getDomainModified()) {
362 E rangeObject = mapping.get(domainObject);
363 if (rangeObject != null)
364 graphModified.add(rangeObject);
366 mapping.updateRange(graph);
367 graphModified.clear();
370 graphUpdates = false;
374 if (mapping.isRangeModified() && !runUndo && !runRedo)
375 commit((String)null);
376 if (DEBUG) System.out.println("Graph update done");
380 public void rangeModified() {
381 //System.out.println("rangeModified");
386 public void postRender() {
388 // 1. Commit has been requested
389 // 2. There are no pending changes that should be processed in preRender()
390 if (requestCommit && !rangeModified) { // FIXME : not thread safe.
391 requestCommit = false;
396 // Reusable containers for data synchronisation
397 List<Pair<E, String>> rem = new ArrayList<Pair<E,String>>(); // Removed objects
398 List<Pair<E, String>> add = new ArrayList<Pair<E,String>>(); // Added objects
399 MapSet<E, String> mod = new MapSet.Hash<E, String>(); // Modified objects
400 Set<E> propagation = new HashSet<E>(); // Objects with propagated changes
401 Stack<E> stack = new Stack<E>(); // Stack for handling propagation
402 Set<E> delete = Collections.synchronizedSet(new HashSet<E>()); // Objects to be completely deleted
403 Set<E> deleteUC = new HashSet<E>();
406 public synchronized void preRender() {
412 * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache.
413 * This causes problems with Undo and Redo, which cause re-using the removed objects from mapping cache.
415 * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added).
418 protected void syncDeletes() {
420 for (Pair<E, String> n : removed) {
421 deleteUC.add(n.first);
423 for (Pair<E, String> n : added) {
424 deleteUC.remove(n.first);
426 if (DEBUG && deleteUC.size() > 0) {
427 System.out.println("Delete sync");
429 System.out.println(debugString(n));
432 delete.addAll(deleteUC);
437 * Clears deletable objects from mapping cache.
439 protected void clearDeletes() {
440 if (DEBUG && delete.size() > 0) System.out.println("Delete");
442 if (DEBUG) System.out.println(debugString(n));
443 mapping.getRange().remove(n);
449 protected String debugString(E n) {
450 return n + "@" + Integer.toHexString(n.hashCode());
453 protected boolean filterChange(List<Pair<E,String>> list,E n) {
454 for (int i = list.size()-1; i >= 0; i--) {
455 if (list.get(i).first == n) {
463 @SuppressWarnings("unchecked")
464 protected void updateCycle() {
471 synchronized (syncMutex) {
472 // Check for overlapping additions and deletions, prevent deleting objects that are also added and vice versa.
473 Deque<E> stack = new ArrayDeque<E>();
474 for (Pair<E, String> n : added) {
477 while (!stack.isEmpty()) {
479 boolean conflict = filterChange(removed, n);
481 System.out.println("Prevent removing " + n);
482 //filterChange(added, n)
483 if (filterChange(added, n))
484 System.out.println("Prevent adding " + n);
486 if (n instanceof ParentNode) {
487 ParentNode<INode> pn = (ParentNode<INode>)n;
488 for (INode cn : pn.getNodes()) {
496 for (E e : updated.getKeys()) {
497 for (String s : updated.getValues(e)) {
509 for (Pair<E, String> n : rem) {
510 stopListening(n.first);
511 removeActor(n.first);
514 for (Pair<E, String> n : add) {
519 for (E e : mod.getKeys()) {
520 Set<String> ids = mod.getValues(e);
521 if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
522 if (!propagation.contains(e))
527 if (propagation.size() > 0) {
529 stack.addAll(propagation);
531 while (!stack.isEmpty()) {
532 E node = stack.pop();
533 if (propagation.contains(node))
535 propagation.add(node);
536 for (NodeListener l : node.getListeners()) {
538 //changeTracking = false;
539 //l.propertyChanged(node, G3D.URIs.hasPosition);
540 //changeTracking = true;
542 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
545 if (node instanceof ParentNode) {
546 stack.addAll(((ParentNode<E>)node).getNodes());
551 // synchronized (syncMutex) {
552 // rem.addAll(removed);
553 // add.addAll(added);
554 // //mod.addAll(updated);
555 // for (E e : updated.getKeys()) {
556 // for (String s : updated.getValues(e))
565 for (E e : mod.getKeys()) {
566 Set<String> ids = mod.getValues(e);
571 for (Pair<E, String> n : rem) {
572 for (NodeListener l : nodeListeners)
573 l.nodeRemoved(null, n.first, n.second);
575 for (Pair<E, String> n : add) {
576 for (NodeListener l : nodeListeners)
577 l.nodeAdded(n.first.getParent(), n.first, n.second);
579 // for (Pair<E, String> n : mod) {
580 // for (NodeListener l : nodeListeners)
581 // l.propertyChanged(n.first, n.second);
583 for (E e : mod.getKeys()) {
584 for (NodeListener l : nodeListeners)
585 for (String s : mod.getValues(e))
586 l.propertyChanged(e, s);
589 synchronized (syncMutex) {
590 if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
591 rangeModified = false;
595 @SuppressWarnings("unchecked")
596 private void listen(INode node) {
597 node.addListener(this);
598 if (node instanceof ParentNode<?>) {
599 ParentNode<INode> parentNode = (ParentNode<INode>)node;
600 for (INode n : parentNode.getNodes())
605 private void stopListening(INode node) {
606 node.removeListener(this);
607 if (node instanceof ParentNode<?>) {
608 @SuppressWarnings("unchecked")
609 ParentNode<INode> parentNode = (ParentNode<INode>)node;
610 for (INode n : parentNode.getNodes())
615 @SuppressWarnings("unchecked")
617 public void propertyChanged(INode node, String id) {
618 //receiveUpdate((E)node, id, graphUpdates);
619 receiveUpdate((E)node, id, graphModified.contains(node));
623 @SuppressWarnings("unchecked")
625 public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
627 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
628 //receiveAdd((E)child, rel ,graphUpdates);
629 receiveAdd((E)child, rel ,graphModified.contains(node));
632 @SuppressWarnings("unchecked")
634 public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
636 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
637 //receiveRemove((E)child, rel, graphUpdates);
638 receiveRemove((E)child, rel, graphModified.contains(node));
640 //FIXME : 1. sometimes removed structural models cause ObjMap to add their children again.
641 // removing the listener here prevents corruption of visual model, but better fix is needed.
642 // 2. detach causes nodeRemoved event, which then causes other critical events to be missed. Took out th
643 //stopListening(child);
647 public void delete() {
648 if (undoRedoSupport != null)
649 undoRedoSupport.cancel(this);
651 changeTracking = false;
652 view.removeListener(this);
653 mapping.removeMappingListener(this);
655 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
656 nodes.addAll(nodeToActor.getKeys());
657 for (E node : nodes) {
658 node.removeListener(this);
662 for (vtkProp prop : actorToNode.keySet()) {
663 if (prop.GetVTKId() != 0)
672 private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
674 public void addListener(NodeListener listener) {
675 nodeListeners.add(listener);
680 public void removeListener(NodeListener listener) {
681 nodeListeners.remove(listener);
685 public IMapping<DBObject,E> getMapping() {