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 if (coll.size() > 0) {
126 for (vtkProp p : coll) {
127 actorToNode.remove(p);
128 if (p.GetVTKId() != 0) {
129 view.getRenderer().RemoveActor(p);
135 nodeToActor.remove(node);
139 public ParentNode<E> getRootNode() {
140 return (ParentNode<E>)rootNode;
146 public boolean isChangeTracking() {
147 return changeTracking;
151 public void setChangeTracking(boolean enabled) {
152 changeTracking = enabled;
155 private boolean changeTracking = true;
157 protected Object syncMutex = new Object();
160 private List<Pair<E,String>> added = new ArrayList<Pair<E,String>>();
161 private List<Pair<E,String>> removed = new ArrayList<Pair<E,String>>();
162 private MapSet<E, String> updated = new MapSet.Hash<E, String>();
164 private boolean rangeModified = false;
166 public boolean isRangeModified() {
167 return rangeModified;
171 public void onChanged() {
173 UndoContext undoContext = undoRedoSupport.getUndoContext(session);
174 int ucount = undoContext.getAll().size();
175 int rcount = undoContext.getRedoList().size();
176 if (DEBUG) System.out.println("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount);
177 if (ucount < undoOpCount) {
182 if (!runUndo && rcount > 0)
186 undoOpCount = ucount;
187 redoOpCount = rcount;
189 if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo);
190 } catch (DatabaseException e) {
191 // TODO Auto-generated catch block
199 public void updateRenderObjectsFor(E node) {
200 List<vtkProp> toDelete = new ArrayList<vtkProp>();
202 for (vtkProp prop : nodeToActor.getValues(node)) {
203 if (prop.GetVTKId() != 0) {
204 view.getRenderer().RemoveActor(prop);
208 actorToNode.remove(prop);
211 nodeToActor.remove(node);
212 Collection<vtkProp> coll = getActors(node);
214 for (vtkProp prop : coll) {
215 nodeToActor.add(node,prop);
216 actorToNode.put(prop, node);
217 toDelete.remove(prop);
220 for (vtkProp p : toDelete)
224 protected abstract Collection<vtkProp> getActors(E node);
226 @SuppressWarnings("unchecked")
227 private void receiveAdd(E node, String id, boolean db) {
228 if (DEBUG) System.out.println("receiveAdd " + debugString(node) + " " + id + " " + db);
229 synchronized (syncMutex) {
230 for (Pair<E, String> n : added) {
231 if (n.first.equals(node))
234 if (changeTracking) {
235 mapping.rangeModified((E)node.getParent());
236 mapping.rangeModified((E)node);
238 added.add(new Pair<E, String>(node, id));
239 rangeModified = true;
244 @SuppressWarnings("unchecked")
245 private void receiveRemove(E node, String id, boolean db) {
246 if (DEBUG) System.out.println("receiveRemove " + debugString(node) + " " + id + " " + db);
247 synchronized (syncMutex) {
248 for (Pair<E, String> n : removed) {
249 if (n.first.equals(node))
252 if (changeTracking && !db) {
253 mapping.rangeModified((E)node);
254 mapping.rangeModified((E)node.getParent());
256 removed.add(new Pair<E, String>(node, id));
257 rangeModified = true;
262 private void receiveUpdate(E node, String id, boolean db) {
263 if (DEBUG) System.out.println("receiveUpdate " + debugString(node) + " " + id + " " + db);
264 synchronized (syncMutex) {
265 // for (Pair<E, String> n : updated) {
266 // if (n.first.equals(node))
269 if (changeTracking && !db)
270 mapping.rangeModified(node);
271 //updated.add(new Pair<E, String>(node, id));
272 updated.add(node, id);
273 rangeModified = true;
278 private boolean graphUpdates = false;
279 private Set<E> graphModified = new HashSet<E>();
281 private boolean requestCommit = false;
282 private String commitMessage = null;
285 public void commit(String message) {
286 requestCommit = true;
287 commitMessage = message;
290 protected void doCommit() {
291 session.asyncRequest(new WriteRequest() {
294 public void perform(WriteGraph graph) throws DatabaseException {
295 if (DEBUG) System.out.println("Commit " + commitMessage);
296 if (commitMessage != null) {
297 Layer0Utils.addCommentMetadata(graph, commitMessage);
298 graph.markUndoPoint();
299 commitMessage = null;
304 }, new Consumer<DatabaseException>() {
307 public void accept(DatabaseException parameter) {
308 if (parameter != null)
309 ExceptionUtils.logAndShowError("Cannot commit editor changes", parameter);
314 protected void commit(WriteGraph graph) throws DatabaseException {
315 synchronized(syncMutex) {
316 if (DEBUG) System.out.println("Commit");
318 mapping.updateDomain(graph);
319 graphUpdates = false;
321 if (DEBUG) System.out.println("Commit done");
328 public void domainModified() {
331 if (DEBUG)System.out.println("domainModified");
332 session.asyncRequest(new ReadRequest() {
335 public void run(ReadGraph graph) throws DatabaseException {
342 protected void reset(ReadGraph graph) throws MappingException {
343 if (DEBUG) System.out.println("Reset");
345 synchronized (syncMutex) {
347 mapping.getRangeModified().clear();
348 for (DBObject o : mapping.getDomain())
349 mapping.domainModified(o);
350 mapping.updateRange(graph);
351 graphModified.clear();
352 graphUpdates = false;
356 private boolean useFullSyncWithUndo = false;
358 protected void update(ReadGraph graph) throws DatabaseException {
359 if (DEBUG) System.out.println("Graph update start");
360 if (runUndo && useFullSyncWithUndo) {
363 synchronized (syncMutex) {
365 for (DBObject domainObject : mapping.getDomainModified()) {
366 @SuppressWarnings("unchecked")
367 E rangeObject = (E) mapping.get(domainObject);
368 if (rangeObject != null)
369 graphModified.add(rangeObject);
371 mapping.updateRange(graph);
372 graphModified.clear();
375 graphUpdates = false;
379 if (mapping.isRangeModified() && !runUndo && !runRedo)
380 commit((String)null);
381 if (DEBUG) System.out.println("Graph update done");
385 public void rangeModified() {
386 //System.out.println("rangeModified");
391 public void postRender() {
393 // 1. Commit has been requested
394 // 2. There are no pending changes that should be processed in preRender()
395 if (requestCommit && !rangeModified) { // FIXME : not thread safe.
396 requestCommit = false;
401 // Reusable containers for data synchronisation
402 List<Pair<E, String>> rem = new ArrayList<Pair<E,String>>(); // Removed objects
403 List<Pair<E, String>> add = new ArrayList<Pair<E,String>>(); // Added objects
404 MapSet<E, String> mod = new MapSet.Hash<E, String>(); // Modified objects
405 Set<E> propagation = new HashSet<E>(); // Objects with propagated changes
406 Stack<E> stack = new Stack<E>(); // Stack for handling propagation
407 Set<E> delete = Collections.synchronizedSet(new HashSet<E>()); // Objects to be completely deleted
408 Set<E> deleteUC = new HashSet<E>();
411 public synchronized void preRender() {
417 * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache.
418 * This causes problems with Undo and Redo, which cause re-using the removed objects from mapping cache.
420 * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added).
423 @SuppressWarnings("unused")
424 protected void syncDeletes() {
426 for (Pair<E, String> n : removed) {
427 deleteUC.add(n.first);
429 for (Pair<E, String> n : added) {
430 deleteUC.remove(n.first);
432 if (DEBUG && deleteUC.size() > 0) {
433 System.out.println("Delete sync");
435 System.out.println(debugString(n));
438 delete.addAll(deleteUC);
443 * Clears deletable objects from mapping cache.
445 @SuppressWarnings("unused")
446 protected void clearDeletes() {
447 if (DEBUG && delete.size() > 0) System.out.println("Delete");
449 if (DEBUG) System.out.println(debugString(n));
450 mapping.getRange().remove(n);
456 protected String debugString(E n) {
457 return n + "@" + Integer.toHexString(n.hashCode());
460 protected boolean filterChange(List<Pair<E,String>> list,E n) {
461 for (int i = list.size()-1; i >= 0; i--) {
462 if (list.get(i).first == n) {
470 @SuppressWarnings("unchecked")
471 protected void updateCycle() {
478 synchronized (syncMutex) {
479 // Check for overlapping additions and deletions, prevent deleting objects that are also added and vice versa.
480 Deque<E> stack = new ArrayDeque<E>();
481 for (Pair<E, String> n : added) {
484 while (!stack.isEmpty()) {
486 boolean conflict = filterChange(removed, n);
488 if (DEBUG) System.out.println("Prevent removing " + n);
489 //filterChange(added, n)
490 if (filterChange(added, n))
491 if (DEBUG) System.out.println("Prevent adding " + n);
493 if (n instanceof ParentNode) {
494 ParentNode<INode> pn = (ParentNode<INode>)n;
495 for (INode cn : pn.getNodes()) {
503 for (E e : updated.getKeys()) {
504 for (String s : updated.getValues(e)) {
515 for (Pair<E, String> n : rem) {
516 stopListening(n.first);
517 removeActor(n.first);
521 for (Pair<E, String> n : add) {
526 for (E e : mod.getKeys()) {
527 Set<String> ids = mod.getValues(e);
528 if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
529 if (!propagation.contains(e))
534 if (propagation.size() > 0) {
536 stack.addAll(propagation);
538 while (!stack.isEmpty()) {
539 E node = stack.pop();
540 if (propagation.contains(node))
542 propagation.add(node);
543 for (NodeListener l : node.getListeners()) {
545 //changeTracking = false;
546 //l.propertyChanged(node, G3D.URIs.hasPosition);
547 //changeTracking = true;
549 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
552 if (node instanceof ParentNode) {
553 stack.addAll(((ParentNode<E>)node).getNodes());
558 for (E e : mod.getKeys()) {
559 Set<String> ids = mod.getValues(e);
563 for (Pair<E, String> n : rem) {
564 for (NodeListener l : nodeListeners)
565 l.nodeRemoved(null, n.first, n.second);
567 for (Pair<E, String> n : add) {
568 for (NodeListener l : nodeListeners)
569 l.nodeAdded(n.first.getParent(), n.first, n.second);
571 // for (Pair<E, String> n : mod) {
572 // for (NodeListener l : nodeListeners)
573 // l.propertyChanged(n.first, n.second);
575 for (E e : mod.getKeys()) {
576 for (NodeListener l : nodeListeners)
577 for (String s : mod.getValues(e))
578 l.propertyChanged(e, s);
581 synchronized (syncMutex) {
582 if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
583 rangeModified = false;
587 @SuppressWarnings("unchecked")
588 private void listen(INode node) {
589 node.addListener(this);
590 if (node instanceof ParentNode<?>) {
591 ParentNode<INode> parentNode = (ParentNode<INode>)node;
592 for (INode n : parentNode.getNodes())
597 private void stopListening(INode node) {
598 node.removeListener(this);
599 if (node instanceof ParentNode<?>) {
600 @SuppressWarnings("unchecked")
601 ParentNode<INode> parentNode = (ParentNode<INode>)node;
602 for (INode n : parentNode.getNodes())
607 @SuppressWarnings("unchecked")
609 public void propertyChanged(INode node, String id) {
610 //receiveUpdate((E)node, id, graphUpdates);
611 receiveUpdate((E)node, id, graphModified.contains(node));
615 @SuppressWarnings("unchecked")
617 public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
619 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
620 //receiveAdd((E)child, rel ,graphUpdates);
621 receiveAdd((E)child, rel ,graphModified.contains(node));
624 @SuppressWarnings("unchecked")
626 public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
628 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
629 //receiveRemove((E)child, rel, graphUpdates);
630 receiveRemove((E)child, rel, graphModified.contains(node));
632 //FIXME : 1. sometimes removed structural models cause ObjMap to add their children again.
633 // removing the listener here prevents corruption of visual model, but better fix is needed.
634 // 2. detach causes nodeRemoved event, which then causes other critical events to be missed. Took out call:
635 //stopListening(child);
639 public void delete() {
640 if (undoRedoSupport != null)
641 undoRedoSupport.cancel(this);
643 changeTracking = false;
644 view.removeListener(this);
645 mapping.removeMappingListener(this);
647 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
648 nodes.addAll(nodeToActor.getKeys());
649 for (E node : nodes) {
650 node.removeListener(this);
654 for (vtkProp prop : actorToNode.keySet()) {
655 if (prop.GetVTKId() != 0)
664 private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
666 public void addListener(NodeListener listener) {
667 nodeListeners.add(listener);
672 public void removeListener(NodeListener listener) {
673 nodeListeners.remove(listener);
677 public IMapping<DBObject,INode> getMapping() {