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 protected MapList<E, vtkProp> nodeToActor = new MapList<E, vtkProp>();
60 protected 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) {
91 protected abstract void addActor(E node);
92 protected abstract void removeActor(E node);
93 protected abstract void updateActor(E node,Set<String> ids);
95 public void repaint() {
99 public void populate() {
100 for (E node : rootNode.getNodes()) {
101 receiveAdd(node, node.getParentRel(),true);
107 public E getNode(vtkProp prop) {
108 return actorToNode.get(prop);
111 @SuppressWarnings("unchecked")
113 public Collection<vtkProp> getRenderObjects(INode node) {
114 return nodeToActor.getValues((E)node);
117 @SuppressWarnings("unchecked")
119 public ParentNode<E> getRootNode() {
120 return (ParentNode<E>)rootNode;
126 public boolean isChangeTracking() {
127 return changeTracking;
131 public void setChangeTracking(boolean enabled) {
132 changeTracking = enabled;
135 private boolean changeTracking = true;
137 protected Object syncMutex = new Object();
140 private List<Pair<E,String>> added = new ArrayList<Pair<E,String>>();
141 private List<Pair<E,String>> removed = new ArrayList<Pair<E,String>>();
142 private MapSet<E, String> updated = new MapSet.Hash<E, String>();
144 private boolean rangeModified = false;
146 public boolean isRangeModified() {
147 return rangeModified;
151 public void onChanged() {
153 UndoContext undoContext = undoRedoSupport.getUndoContext(session);
154 int ucount = undoContext.getAll().size();
155 int rcount = undoContext.getRedoList().size();
156 if (DEBUG) System.out.println("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount);
157 if (ucount < undoOpCount) {
162 if (!runUndo && rcount > 0)
166 undoOpCount = ucount;
167 redoOpCount = rcount;
169 if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo);
170 } catch (DatabaseException e) {
171 // TODO Auto-generated catch block
178 @SuppressWarnings("unchecked")
180 public void updateRenderObjectsFor(E node) {
181 List<vtkProp> toDelete = new ArrayList<vtkProp>();
183 for (vtkProp prop : nodeToActor.getValues((E)node)) {
184 if (prop.GetVTKId() != 0) {
185 view.getRenderer().RemoveActor(prop);
189 actorToNode.remove(prop);
192 nodeToActor.remove((E)node);
193 Collection<vtkProp> coll = getActors((E)node);
195 for (vtkProp prop : coll) {
196 nodeToActor.add((E)node,prop);
197 actorToNode.put(prop, (E)node);
198 toDelete.remove(prop);
201 for (vtkProp p : toDelete)
205 protected abstract Collection<vtkProp> getActors(E node);
207 @SuppressWarnings("unchecked")
208 private void receiveAdd(E node, String id, boolean db) {
209 if (DEBUG) System.out.println("receiveAdd " + debugString(node) + " " + id + " " + db);
210 synchronized (syncMutex) {
211 for (Pair<E, String> n : added) {
212 if (n.first.equals(node))
215 if (changeTracking) {
216 mapping.rangeModified((E)node.getParent());
218 added.add(new Pair<E, String>(node, id));
219 rangeModified = true;
224 @SuppressWarnings("unchecked")
225 private void receiveRemove(E node, String id, boolean db) {
226 if (DEBUG) System.out.println("receiveRemove " + debugString(node) + " " + id + " " + db);
227 synchronized (syncMutex) {
228 for (Pair<E, String> n : removed) {
229 if (n.first.equals(node))
232 if (changeTracking && !db)
233 mapping.rangeModified((E)node.getParent());
234 removed.add(new Pair<E, String>(node, id));
235 rangeModified = true;
240 @SuppressWarnings("unchecked")
241 private void receiveUpdate(E node, String id, boolean db) {
242 if (DEBUG) System.out.println("receiveUpdate " + debugString(node) + " " + id + " " + db);
243 synchronized (syncMutex) {
244 // for (Pair<E, String> n : updated) {
245 // if (n.first.equals(node))
248 if (changeTracking && !db)
249 mapping.rangeModified(node);
250 //updated.add(new Pair<E, String>(node, id));
251 updated.add(node, id);
252 rangeModified = true;
257 private boolean graphUpdates = false;
258 private Set<E> graphModified = new HashSet<E>();
260 private boolean requestCommit = false;
261 private String commitMessage = null;
264 public void commit(String message) {
265 requestCommit = true;
266 commitMessage = message;
269 protected void doCommit() {
270 session.asyncRequest(new WriteRequest() {
273 public void perform(WriteGraph graph) throws DatabaseException {
274 if (DEBUG) System.out.println("Commit " + commitMessage);
275 if (commitMessage != null) {
276 Layer0Utils.addCommentMetadata(graph, commitMessage);
277 graph.markUndoPoint();
278 commitMessage = null;
283 }, new Callback<DatabaseException>() {
286 public void run(DatabaseException parameter) {
287 if (parameter != null)
288 ExceptionUtils.logAndShowError("Cannot commit editor changes", parameter);
293 protected void commit(WriteGraph graph) throws DatabaseException {
294 synchronized(syncMutex) {
295 if (DEBUG) System.out.println("Commit");
297 mapping.updateDomain(graph);
298 graphUpdates = false;
300 if (DEBUG) System.out.println("Commit done");
307 public void domainModified() {
310 if (DEBUG)System.out.println("domainModified");
311 session.asyncRequest(new ReadRequest() {
313 @SuppressWarnings("unchecked")
315 public void run(ReadGraph graph) throws DatabaseException {
322 protected void reset(ReadGraph graph) throws MappingException {
323 if (DEBUG) System.out.println("Reset");
325 synchronized (syncMutex) {
327 mapping.getRangeModified().clear();
328 for (DBObject o : mapping.getDomain())
329 mapping.domainModified(o);
330 mapping.updateRange(graph);
331 graphModified.clear();
332 graphUpdates = false;
336 private boolean useFullSyncWithUndo = false;
338 protected void update(ReadGraph graph) throws DatabaseException {
339 if (DEBUG) System.out.println("Graph update start");
340 if (runUndo && useFullSyncWithUndo) {
343 synchronized (syncMutex) {
345 for (DBObject domainObject : mapping.getDomainModified()) {
346 E rangeObject = mapping.get(domainObject);
347 if (rangeObject != null)
348 graphModified.add(rangeObject);
350 mapping.updateRange(graph);
351 graphModified.clear();
354 graphUpdates = false;
358 if (mapping.isRangeModified() && !runUndo && !runRedo)
359 commit((String)null);
360 if (DEBUG) System.out.println("Graph update done");
364 public void rangeModified() {
365 //System.out.println("rangeModified");
370 public void postRender() {
372 // 1. Commit has been requested
373 // 2. There are no pending changes that should be processed in preRender()
374 if (requestCommit && !rangeModified) { // FIXME : not thread safe.
375 requestCommit = false;
380 // Reusable containers for data synchronisation
381 List<Pair<E, String>> rem = new ArrayList<Pair<E,String>>(); // Removed objects
382 List<Pair<E, String>> add = new ArrayList<Pair<E,String>>(); // Added objects
383 MapSet<E, String> mod = new MapSet.Hash<E, String>(); // Modified objects
384 Set<E> propagation = new HashSet<E>(); // Objects with propagated changes
385 Stack<E> stack = new Stack<E>(); // Stack for handling propagation
386 Set<E> delete = Collections.synchronizedSet(new HashSet<E>()); // Objects to be completely deleted
387 Set<E> deleteUC = new HashSet<E>();
390 public synchronized void preRender() {
396 * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache.
397 * This causes problems with Undo and Redo, whcih the end up re-using the removed objects from mapping cache.
399 * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added).
402 protected void syncDeletes() {
404 for (Pair<E, String> n : removed) {
405 deleteUC.add(n.first);
407 for (Pair<E, String> n : added) {
408 deleteUC.remove(n.first);
410 if (DEBUG && deleteUC.size() > 0) {
411 System.out.println("Delete sync");
413 System.out.println(debugString(n));
416 delete.addAll(deleteUC);
421 * Clears deletable objects from mapping cache.
423 protected void clearDeletes() {
424 if (DEBUG && delete.size() > 0) System.out.println("Delete");
426 if (DEBUG) System.out.println(debugString(n));
427 mapping.getRange().remove(n);
432 protected String debugString(E n) {
433 return n + "@" + Integer.toHexString(n.hashCode());
436 protected boolean filterChange(List<Pair<E,String>> list,E n) {
437 for (int i = list.size()-1; i >= 0; i--) {
438 if (list.get(i).first == n) {
446 @SuppressWarnings("unchecked")
447 protected void updateCycle() {
454 synchronized (syncMutex) {
455 // Check for overlapping additions and deletions, prevent deleting objects that are also added and vice versa.
456 Deque<E> stack = new ArrayDeque<E>();
457 for (Pair<E, String> n : added) {
460 while (!stack.isEmpty()) {
462 boolean conflict = filterChange(removed, n);
464 System.out.println("Prevent removing " + n);
465 //filterChange(added, n)
466 if (filterChange(added, n))
467 System.out.println("Prevent adding " + n);
469 if (n instanceof ParentNode) {
470 ParentNode<INode> pn = (ParentNode<INode>)n;
471 for (INode cn : pn.getNodes()) {
479 for (E e : updated.getKeys()) {
480 for (String s : updated.getValues(e)) {
492 for (Pair<E, String> n : rem) {
493 stopListening(n.first);
494 removeActor(n.first);
497 for (Pair<E, String> n : add) {
502 for (E e : mod.getKeys()) {
503 Set<String> ids = mod.getValues(e);
504 if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
505 if (!propagation.contains(e))
510 if (propagation.size() > 0) {
512 stack.addAll(propagation);
514 while (!stack.isEmpty()) {
515 E node = stack.pop();
516 if (propagation.contains(node))
518 propagation.add(node);
519 for (NodeListener l : node.getListeners()) {
521 //changeTracking = false;
522 //l.propertyChanged(node, G3D.URIs.hasPosition);
523 //changeTracking = true;
525 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
528 if (node instanceof ParentNode) {
529 stack.addAll(((ParentNode<E>)node).getNodes());
534 // synchronized (syncMutex) {
535 // rem.addAll(removed);
536 // add.addAll(added);
537 // //mod.addAll(updated);
538 // for (E e : updated.getKeys()) {
539 // for (String s : updated.getValues(e))
548 for (E e : mod.getKeys()) {
549 Set<String> ids = mod.getValues(e);
554 for (Pair<E, String> n : rem) {
555 for (NodeListener l : nodeListeners)
556 l.nodeRemoved(null, n.first, n.second);
558 for (Pair<E, String> n : add) {
559 for (NodeListener l : nodeListeners)
560 l.nodeAdded(n.first.getParent(), n.first, n.second);
562 // for (Pair<E, String> n : mod) {
563 // for (NodeListener l : nodeListeners)
564 // l.propertyChanged(n.first, n.second);
566 for (E e : mod.getKeys()) {
567 for (NodeListener l : nodeListeners)
568 for (String s : mod.getValues(e))
569 l.propertyChanged(e, s);
572 synchronized (syncMutex) {
573 if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
574 rangeModified = false;
578 @SuppressWarnings("unchecked")
579 private void listen(INode node) {
580 node.addListener(this);
581 if (node instanceof ParentNode<?>) {
582 ParentNode<INode> parentNode = (ParentNode<INode>)node;
583 for (INode n : parentNode.getNodes())
588 private void stopListening(INode node) {
589 node.removeListener(this);
590 if (node instanceof ParentNode<?>) {
591 @SuppressWarnings("unchecked")
592 ParentNode<INode> parentNode = (ParentNode<INode>)node;
593 for (INode n : parentNode.getNodes())
598 @SuppressWarnings("unchecked")
600 public void propertyChanged(INode node, String id) {
601 //receiveUpdate((E)node, id, graphUpdates);
602 receiveUpdate((E)node, id, graphModified.contains(node));
606 @SuppressWarnings("unchecked")
608 public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
610 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
611 //receiveAdd((E)child, rel ,graphUpdates);
612 receiveAdd((E)child, rel ,graphModified.contains(node));
616 @SuppressWarnings("unchecked")
618 public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
620 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
621 //receiveRemove((E)child, rel, graphUpdates);
622 receiveRemove((E)child, rel, graphModified.contains(node));
624 //FIXME : sometimes removed structural models cause ObjMap to add their children again.
625 // removing the listener here prevents corruption of visual model, but better fix is needed.
626 stopListening(child);
630 public void delete() {
631 if (undoRedoSupport != null)
632 undoRedoSupport.cancel(this);
634 changeTracking = false;
635 view.removeListener(this);
636 mapping.removeMappingListener(this);
638 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
639 nodes.addAll(nodeToActor.getKeys());
640 for (E node : nodes) {
641 node.removeListener(this);
645 for (vtkProp prop : actorToNode.keySet()) {
646 if (prop.GetVTKId() != 0)
655 private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
657 public void addListener(NodeListener listener) {
658 nodeListeners.add(listener);
663 public void removeListener(NodeListener listener) {
664 nodeListeners.remove(listener);
668 public IMapping<DBObject,E> getMapping() {