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;
25 import java.util.function.Consumer;
27 import org.simantics.db.ReadGraph;
28 import org.simantics.db.Session;
29 import org.simantics.db.UndoContext;
30 import org.simantics.db.WriteGraph;
31 import org.simantics.db.common.request.ReadRequest;
32 import org.simantics.db.common.request.WriteRequest;
33 import org.simantics.db.exception.DatabaseException;
34 import org.simantics.db.layer0.util.Layer0Utils;
35 import org.simantics.db.service.UndoRedoSupport;
36 import org.simantics.g3d.ontology.G3D;
37 import org.simantics.g3d.scenegraph.RenderListener;
38 import org.simantics.g3d.scenegraph.base.INode;
39 import org.simantics.g3d.scenegraph.base.NodeListener;
40 import org.simantics.g3d.scenegraph.base.ParentNode;
41 import org.simantics.objmap.exceptions.MappingException;
42 import org.simantics.objmap.graph.IMapping;
43 import org.simantics.objmap.graph.IMappingListener;
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, INode> 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,INode> 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);
131 public ParentNode<E> getRootNode() {
132 return (ParentNode<E>)rootNode;
138 public boolean isChangeTracking() {
139 return changeTracking;
143 public void setChangeTracking(boolean enabled) {
144 changeTracking = enabled;
147 private boolean changeTracking = true;
149 protected Object syncMutex = new Object();
152 private List<Pair<E,String>> added = new ArrayList<Pair<E,String>>();
153 private List<Pair<E,String>> removed = new ArrayList<Pair<E,String>>();
154 private MapSet<E, String> updated = new MapSet.Hash<E, String>();
156 private boolean rangeModified = false;
158 public boolean isRangeModified() {
159 return rangeModified;
163 public void onChanged() {
165 UndoContext undoContext = undoRedoSupport.getUndoContext(session);
166 int ucount = undoContext.getAll().size();
167 int rcount = undoContext.getRedoList().size();
168 if (DEBUG) System.out.println("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount);
169 if (ucount < undoOpCount) {
174 if (!runUndo && rcount > 0)
178 undoOpCount = ucount;
179 redoOpCount = rcount;
181 if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo);
182 } catch (DatabaseException e) {
183 // TODO Auto-generated catch block
191 public void updateRenderObjectsFor(E node) {
192 List<vtkProp> toDelete = new ArrayList<vtkProp>();
194 for (vtkProp prop : nodeToActor.getValues(node)) {
195 if (prop.GetVTKId() != 0) {
196 view.getRenderer().RemoveActor(prop);
200 actorToNode.remove(prop);
203 nodeToActor.remove(node);
204 Collection<vtkProp> coll = getActors(node);
206 for (vtkProp prop : coll) {
207 nodeToActor.add(node,prop);
208 actorToNode.put(prop, node);
209 toDelete.remove(prop);
212 for (vtkProp p : toDelete)
216 protected abstract Collection<vtkProp> getActors(E node);
218 @SuppressWarnings("unchecked")
219 private void receiveAdd(E node, String id, boolean db) {
220 if (DEBUG) System.out.println("receiveAdd " + debugString(node) + " " + id + " " + db);
221 synchronized (syncMutex) {
222 for (Pair<E, String> n : added) {
223 if (n.first.equals(node))
226 if (changeTracking) {
227 mapping.rangeModified((E)node.getParent());
228 mapping.rangeModified((E)node);
230 added.add(new Pair<E, String>(node, id));
231 rangeModified = true;
236 @SuppressWarnings("unchecked")
237 private void receiveRemove(E node, String id, boolean db) {
238 if (DEBUG) System.out.println("receiveRemove " + debugString(node) + " " + id + " " + db);
239 synchronized (syncMutex) {
240 for (Pair<E, String> n : removed) {
241 if (n.first.equals(node))
244 if (changeTracking && !db) {
245 mapping.rangeModified((E)node);
246 mapping.rangeModified((E)node.getParent());
248 removed.add(new Pair<E, String>(node, id));
249 rangeModified = true;
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 Consumer<DatabaseException>() {
299 public void accept(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() {
327 public void run(ReadGraph graph) throws DatabaseException {
334 protected void reset(ReadGraph graph) throws MappingException {
335 if (DEBUG) System.out.println("Reset");
337 synchronized (syncMutex) {
339 mapping.getRangeModified().clear();
340 for (DBObject o : mapping.getDomain())
341 mapping.domainModified(o);
342 mapping.updateRange(graph);
343 graphModified.clear();
344 graphUpdates = false;
348 private boolean useFullSyncWithUndo = false;
350 protected void update(ReadGraph graph) throws DatabaseException {
351 if (DEBUG) System.out.println("Graph update start");
352 if (runUndo && useFullSyncWithUndo) {
355 synchronized (syncMutex) {
357 for (DBObject domainObject : mapping.getDomainModified()) {
358 @SuppressWarnings("unchecked")
359 E rangeObject = (E) 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 @SuppressWarnings("unused")
416 protected void syncDeletes() {
418 for (Pair<E, String> n : removed) {
419 deleteUC.add(n.first);
421 for (Pair<E, String> n : added) {
422 deleteUC.remove(n.first);
424 if (DEBUG && deleteUC.size() > 0) {
425 System.out.println("Delete sync");
427 System.out.println(debugString(n));
430 delete.addAll(deleteUC);
435 * Clears deletable objects from mapping cache.
437 @SuppressWarnings("unused")
438 protected void clearDeletes() {
439 if (DEBUG && delete.size() > 0) System.out.println("Delete");
441 if (DEBUG) System.out.println(debugString(n));
442 mapping.getRange().remove(n);
448 protected String debugString(E n) {
449 return n + "@" + Integer.toHexString(n.hashCode());
452 protected boolean filterChange(List<Pair<E,String>> list,E n) {
453 for (int i = list.size()-1; i >= 0; i--) {
454 if (list.get(i).first == n) {
462 @SuppressWarnings("unchecked")
463 protected void updateCycle() {
470 synchronized (syncMutex) {
471 // Check for overlapping additions and deletions, prevent deleting objects that are also added and vice versa.
472 Deque<E> stack = new ArrayDeque<E>();
473 for (Pair<E, String> n : added) {
476 while (!stack.isEmpty()) {
478 boolean conflict = filterChange(removed, n);
480 System.out.println("Prevent removing " + n);
481 //filterChange(added, n)
482 if (filterChange(added, n))
483 System.out.println("Prevent adding " + n);
485 if (n instanceof ParentNode) {
486 ParentNode<INode> pn = (ParentNode<INode>)n;
487 for (INode cn : pn.getNodes()) {
495 for (E e : updated.getKeys()) {
496 for (String s : updated.getValues(e)) {
508 for (Pair<E, String> n : rem) {
509 stopListening(n.first);
510 removeActor(n.first);
513 for (Pair<E, String> n : add) {
518 for (E e : mod.getKeys()) {
519 Set<String> ids = mod.getValues(e);
520 if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
521 if (!propagation.contains(e))
526 if (propagation.size() > 0) {
528 stack.addAll(propagation);
530 while (!stack.isEmpty()) {
531 E node = stack.pop();
532 if (propagation.contains(node))
534 propagation.add(node);
535 for (NodeListener l : node.getListeners()) {
537 //changeTracking = false;
538 //l.propertyChanged(node, G3D.URIs.hasPosition);
539 //changeTracking = true;
541 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
544 if (node instanceof ParentNode) {
545 stack.addAll(((ParentNode<E>)node).getNodes());
550 // synchronized (syncMutex) {
551 // rem.addAll(removed);
552 // add.addAll(added);
553 // //mod.addAll(updated);
554 // for (E e : updated.getKeys()) {
555 // for (String s : updated.getValues(e))
564 for (E e : mod.getKeys()) {
565 Set<String> ids = mod.getValues(e);
570 for (Pair<E, String> n : rem) {
571 for (NodeListener l : nodeListeners)
572 l.nodeRemoved(null, n.first, n.second);
574 for (Pair<E, String> n : add) {
575 for (NodeListener l : nodeListeners)
576 l.nodeAdded(n.first.getParent(), n.first, n.second);
578 // for (Pair<E, String> n : mod) {
579 // for (NodeListener l : nodeListeners)
580 // l.propertyChanged(n.first, n.second);
582 for (E e : mod.getKeys()) {
583 for (NodeListener l : nodeListeners)
584 for (String s : mod.getValues(e))
585 l.propertyChanged(e, s);
588 synchronized (syncMutex) {
589 if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
590 rangeModified = false;
594 @SuppressWarnings("unchecked")
595 private void listen(INode node) {
596 node.addListener(this);
597 if (node instanceof ParentNode<?>) {
598 ParentNode<INode> parentNode = (ParentNode<INode>)node;
599 for (INode n : parentNode.getNodes())
604 private void stopListening(INode node) {
605 node.removeListener(this);
606 if (node instanceof ParentNode<?>) {
607 @SuppressWarnings("unchecked")
608 ParentNode<INode> parentNode = (ParentNode<INode>)node;
609 for (INode n : parentNode.getNodes())
614 @SuppressWarnings("unchecked")
616 public void propertyChanged(INode node, String id) {
617 //receiveUpdate((E)node, id, graphUpdates);
618 receiveUpdate((E)node, id, graphModified.contains(node));
622 @SuppressWarnings("unchecked")
624 public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
626 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
627 //receiveAdd((E)child, rel ,graphUpdates);
628 receiveAdd((E)child, rel ,graphModified.contains(node));
631 @SuppressWarnings("unchecked")
633 public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
635 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
636 //receiveRemove((E)child, rel, graphUpdates);
637 receiveRemove((E)child, rel, graphModified.contains(node));
639 //FIXME : 1. sometimes removed structural models cause ObjMap to add their children again.
640 // removing the listener here prevents corruption of visual model, but better fix is needed.
641 // 2. detach causes nodeRemoved event, which then causes other critical events to be missed. Took out th
642 //stopListening(child);
646 public void delete() {
647 if (undoRedoSupport != null)
648 undoRedoSupport.cancel(this);
650 changeTracking = false;
651 view.removeListener(this);
652 mapping.removeMappingListener(this);
654 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
655 nodes.addAll(nodeToActor.getKeys());
656 for (E node : nodes) {
657 node.removeListener(this);
661 for (vtkProp prop : actorToNode.keySet()) {
662 if (prop.GetVTKId() != 0)
671 private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
673 public void addListener(NodeListener listener) {
674 nodeListeners.add(listener);
679 public void removeListener(NodeListener listener) {
680 nodeListeners.remove(listener);
684 public IMapping<DBObject,INode> getMapping() {