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.lang.reflect.InvocationTargetException;
15 import java.util.ArrayDeque;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Deque;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
25 import java.util.Stack;
27 import org.eclipse.ui.PlatformUI;
28 import org.eclipse.ui.progress.IProgressService;
29 import org.simantics.db.ReadGraph;
30 import org.simantics.db.Session;
31 import org.simantics.db.UndoContext;
32 import org.simantics.db.WriteGraph;
33 import org.simantics.db.common.request.UniqueRead;
34 import org.simantics.db.common.request.WriteRequest;
35 import org.simantics.db.exception.DatabaseException;
36 import org.simantics.db.layer0.util.Layer0Utils;
37 import org.simantics.db.procedure.SyncProcedure;
38 import org.simantics.db.service.UndoRedoSupport;
39 import org.simantics.g3d.ontology.G3D;
40 import org.simantics.g3d.scenegraph.RenderListener;
41 import org.simantics.g3d.scenegraph.base.INode;
42 import org.simantics.g3d.scenegraph.base.NodeListener;
43 import org.simantics.g3d.scenegraph.base.ParentNode;
44 import org.simantics.objmap.exceptions.MappingException;
45 import org.simantics.objmap.graph.IMapping;
46 import org.simantics.objmap.graph.IMappingListener;
47 import org.simantics.utils.datastructures.MapList;
48 import org.simantics.utils.datastructures.MapSet;
49 import org.simantics.utils.datastructures.Pair;
50 import org.simantics.utils.ui.ExceptionUtils;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
56 public abstract class AbstractVTKNodeMap<DBObject,E extends INode> implements VTKNodeMap<DBObject,E>, IMappingListener, RenderListener, NodeListener, UndoRedoSupport.ChangeListener{
58 private static final boolean DEBUG = true;
60 private static final Logger LOGGER = LoggerFactory.getLogger(AbstractVTKNodeMap.class);
62 protected Session session;
63 protected IMapping<DBObject, INode> mapping;
64 protected VtkView view;
66 private MapList<E, vtkProp> nodeToActor = new MapList<E, vtkProp>();
67 private Map<vtkProp,E> actorToNode = new HashMap<vtkProp, E>();
69 protected ParentNode<E> rootNode;
71 protected UndoRedoSupport undoRedoSupport;
72 protected int undoOpCount = 0;
73 protected int redoOpCount = 0;
74 protected boolean runUndo = false;
75 protected boolean runRedo = false;
76 public AbstractVTKNodeMap(Session session, IMapping<DBObject,INode> mapping, VtkView view, ParentNode<E> rootNode) {
77 this.session = session;
78 this.mapping = mapping;
80 this.rootNode = rootNode;
81 view.addListener(this);
82 mapping.addMappingListener(this);
83 rootNode.addListener(this);
85 undoRedoSupport = session.getService(UndoRedoSupport.class);
86 undoRedoSupport.subscribe(this);
88 UndoContext undoContext = undoRedoSupport.getUndoContext(session);
89 undoOpCount = undoContext.getAll().size();
90 redoOpCount = undoContext.getRedoList().size();
91 } catch(DatabaseException e) {
96 protected abstract void addActor(E node);
97 protected abstract void removeActor(E node);
98 protected abstract void updateActor(E node,Set<String> ids);
100 public void repaint() {
104 public void populate() {
105 for (E node : rootNode.getNodes()) {
106 receiveAdd(node, node.getParentRel(),true);
112 public E getNode(vtkProp prop) {
113 return actorToNode.get(prop);
116 @SuppressWarnings("unchecked")
118 public Collection<vtkProp> getRenderObjects(INode node) {
119 return nodeToActor.getValues((E) node);
122 protected <T extends vtkProp> void map(E node, Collection<T> props) {
123 for (vtkProp p : props) {
124 nodeToActor.add(node, p);
125 actorToNode.put(p, node);
129 protected void removeMap(E node) {
130 Collection<vtkProp> coll = nodeToActor.getValuesUnsafe(node);
131 if (coll.size() > 0) {
133 for (vtkProp p : coll) {
134 actorToNode.remove(p);
135 if (p.GetVTKId() != 0) {
136 view.getRenderer().RemoveActor(p);
142 nodeToActor.remove(node);
146 public ParentNode<E> getRootNode() {
147 return (ParentNode<E>)rootNode;
153 public boolean isChangeTracking() {
154 return changeTracking;
158 public void setChangeTracking(boolean enabled) {
159 changeTracking = enabled;
162 private boolean changeTracking = true;
164 protected Object syncMutex = new Object();
167 private List<Pair<E,String>> added = new ArrayList<Pair<E,String>>();
168 private List<Pair<E,String>> removed = new ArrayList<Pair<E,String>>();
169 private MapSet<E, String> updated = new MapSet.Hash<E, String>();
171 private boolean rangeModified = false;
173 public boolean isRangeModified() {
174 return rangeModified;
178 public void onChanged() {
180 UndoContext undoContext = undoRedoSupport.getUndoContext(session);
181 int ucount = undoContext.getAll().size();
182 int rcount = undoContext.getRedoList().size();
183 if (DEBUG) System.out.println("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount);
184 if (ucount < undoOpCount) {
189 if (!runUndo && rcount > 0)
193 undoOpCount = ucount;
194 redoOpCount = rcount;
196 if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo);
197 } catch (DatabaseException e) {
198 // TODO Auto-generated catch block
206 public void updateRenderObjectsFor(E node) {
207 List<vtkProp> toDelete = new ArrayList<vtkProp>();
209 for (vtkProp prop : nodeToActor.getValues(node)) {
210 if (prop.GetVTKId() != 0) {
211 view.getRenderer().RemoveActor(prop);
215 actorToNode.remove(prop);
218 nodeToActor.remove(node);
219 Collection<vtkProp> coll = getActors(node);
221 for (vtkProp prop : coll) {
222 nodeToActor.add(node,prop);
223 actorToNode.put(prop, node);
224 toDelete.remove(prop);
227 for (vtkProp p : toDelete)
231 protected abstract Collection<vtkProp> getActors(E node);
233 @SuppressWarnings("unchecked")
234 private void receiveAdd(E node, String id, boolean db) {
235 if (DEBUG) System.out.println("receiveAdd " + debugString(node) + " " + id + " " + db);
236 synchronized (syncMutex) {
237 for (Pair<E, String> n : added) {
238 if (n.first.equals(node))
241 if (changeTracking) {
242 mapping.rangeModified((E)node.getParent());
243 mapping.rangeModified((E)node);
245 added.add(new Pair<E, String>(node, id));
246 rangeModified = true;
251 @SuppressWarnings("unchecked")
252 private void receiveRemove(E node, String id, boolean db) {
253 if (DEBUG) System.out.println("receiveRemove " + debugString(node) + " " + id + " " + db);
254 synchronized (syncMutex) {
255 for (Pair<E, String> n : removed) {
256 if (n.first.equals(node))
259 if (changeTracking && !db) {
260 mapping.rangeModified((E)node);
261 mapping.rangeModified((E)node.getParent());
263 removed.add(new Pair<E, String>(node, id));
264 rangeModified = true;
269 private void receiveUpdate(E node, String id, boolean db) {
270 if (DEBUG) System.out.println("receiveUpdate " + debugString(node) + " " + id + " " + db);
271 synchronized (syncMutex) {
272 // for (Pair<E, String> n : updated) {
273 // if (n.first.equals(node))
276 if (changeTracking && !db)
277 mapping.rangeModified(node);
278 //updated.add(new Pair<E, String>(node, id));
279 updated.add(node, id);
280 rangeModified = true;
285 private boolean graphUpdates = false;
286 private Set<E> graphModified = new HashSet<E>();
288 private boolean requestCommit = false;
289 private String commitMessage = null;
292 public void commit(String message) {
293 requestCommit = true;
294 commitMessage = message;
297 protected void doCommit() {
298 IProgressService service = PlatformUI.getWorkbench().getProgressService();
300 service.busyCursorWhile(monitor -> {
302 session.syncRequest(new WriteRequest() {
304 public void perform(WriteGraph graph) throws DatabaseException {
305 if (DEBUG) System.out.println("Commit " + commitMessage);
306 if (commitMessage != null) {
307 Layer0Utils.addCommentMetadata(graph, commitMessage);
308 graph.markUndoPoint();
309 commitMessage = null;
314 } catch (DatabaseException e) {
315 ExceptionUtils.logAndShowError("Cannot commit editor changes", e);
318 } catch (InvocationTargetException | InterruptedException e) {
319 LOGGER.error("Unexpected exception", e);
323 protected void commit(WriteGraph graph) throws DatabaseException {
324 synchronized(syncMutex) {
325 if (DEBUG) System.out.println("Commit");
327 mapping.updateDomain(graph);
328 graphUpdates = false;
330 if (DEBUG) System.out.println("Commit done");
337 public void domainModified() {
340 if (DEBUG)System.out.println("domainModified");
341 session.asyncRequest(new UniqueRead<Object>() {
343 public Object perform(ReadGraph graph) throws DatabaseException {
346 }, new SyncProcedure<Object>() {
348 public void execute(ReadGraph graph, Object result) throws DatabaseException {
349 // Perform all updates to the model in a single query thread
354 public void exception(ReadGraph graph, Throwable throwable) throws DatabaseException {
355 LOGGER.error("Failed to update pipeline changes" + throwable);
360 protected void reset(ReadGraph graph) throws MappingException {
361 if (DEBUG) System.out.println("Reset");
364 mapping.getRangeModified().clear();
365 for (DBObject o : mapping.getDomain())
366 mapping.domainModified(o);
367 mapping.updateRange(graph);
368 graphModified.clear();
369 graphUpdates = false;
372 private boolean useFullSyncWithUndo = false;
374 protected void update(ReadGraph graph) throws DatabaseException {
375 synchronized (syncMutex) {
376 if (DEBUG) System.out.println("Graph update start");
378 if (runUndo && useFullSyncWithUndo) {
382 for (DBObject domainObject : mapping.getDomainModified()) {
383 @SuppressWarnings("unchecked")
384 E rangeObject = (E) mapping.get(domainObject);
385 if (rangeObject != null)
386 graphModified.add(rangeObject);
388 mapping.updateRange(graph);
389 graphModified.clear();
392 graphUpdates = false;
395 if (mapping.isRangeModified() && !runUndo && !runRedo)
396 commit((String)null);
398 if (DEBUG) System.out.println("Graph update done");
403 public void rangeModified() {
404 //System.out.println("rangeModified");
409 public void postRender() {
411 // 1. Commit has been requested
412 // 2. There are no pending changes that should be processed in preRender()
413 if (requestCommit && !rangeModified) { // FIXME : not thread safe.
414 requestCommit = false;
419 // Reusable containers for data synchronisation
420 List<Pair<E, String>> rem = new ArrayList<Pair<E,String>>(); // Removed objects
421 List<Pair<E, String>> add = new ArrayList<Pair<E,String>>(); // Added objects
422 MapSet<E, String> mod = new MapSet.Hash<E, String>(); // Modified objects
423 Set<E> propagation = new HashSet<E>(); // Objects with propagated changes
424 Stack<E> stack = new Stack<E>(); // Stack for handling propagation
425 Set<E> delete = Collections.synchronizedSet(new HashSet<E>()); // Objects to be completely deleted
426 Set<E> deleteUC = new HashSet<E>();
429 public synchronized void preRender() {
435 * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache.
436 * This causes problems with Undo and Redo, which cause re-using the removed objects from mapping cache.
438 * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added).
441 @SuppressWarnings("unused")
442 protected void syncDeletes() {
444 for (Pair<E, String> n : removed) {
445 deleteUC.add(n.first);
447 for (Pair<E, String> n : added) {
448 deleteUC.remove(n.first);
450 if (DEBUG && deleteUC.size() > 0) {
451 System.out.println("Delete sync");
453 System.out.println(debugString(n));
456 delete.addAll(deleteUC);
461 * Clears deletable objects from mapping cache.
463 @SuppressWarnings("unused")
464 protected void clearDeletes() {
465 if (DEBUG && delete.size() > 0) System.out.println("Delete");
467 if (DEBUG) System.out.println(debugString(n));
468 mapping.getRange().remove(n);
474 protected String debugString(E n) {
475 return n + "@" + Integer.toHexString(n.hashCode());
478 protected boolean filterChange(List<Pair<E,String>> list,E n) {
479 for (int i = list.size()-1; i >= 0; i--) {
480 if (list.get(i).first == n) {
488 @SuppressWarnings("unchecked")
489 protected void updateCycle() {
496 synchronized (syncMutex) {
497 // Check for overlapping additions and deletions, prevent deleting objects that are also added and vice versa.
498 Deque<E> stack = new ArrayDeque<E>();
499 for (Pair<E, String> n : added) {
502 while (!stack.isEmpty()) {
504 boolean conflict = filterChange(removed, n);
506 if (DEBUG) System.out.println("Prevent removing " + n);
507 //filterChange(added, n)
508 if (filterChange(added, n))
509 if (DEBUG) System.out.println("Prevent adding " + n);
511 if (n instanceof ParentNode) {
512 ParentNode<INode> pn = (ParentNode<INode>)n;
513 for (INode cn : pn.getNodes()) {
518 // Do not process updates for removed nodes.
519 for (Pair<E, String> r : removed) {
520 updated.removeValues(r.first);
524 for (E e : updated.getKeys()) {
525 for (String s : updated.getValues(e)) {
536 for (Pair<E, String> n : rem) {
537 stopListening(n.first);
538 removeActor(n.first);
542 for (Pair<E, String> n : add) {
547 for (E e : mod.getKeys()) {
548 Set<String> ids = mod.getValues(e);
549 if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
550 if (!propagation.contains(e))
555 if (propagation.size() > 0) {
557 stack.addAll(propagation);
559 while (!stack.isEmpty()) {
560 E node = stack.pop();
561 if (propagation.contains(node))
563 propagation.add(node);
564 for (NodeListener l : node.getListeners()) {
566 //changeTracking = false;
567 //l.propertyChanged(node, G3D.URIs.hasPosition);
568 //changeTracking = true;
570 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
573 if (node instanceof ParentNode) {
574 stack.addAll(((ParentNode<E>)node).getNodes());
579 for (E e : mod.getKeys()) {
580 Set<String> ids = mod.getValues(e);
584 for (Pair<E, String> n : rem) {
585 for (NodeListener l : nodeListeners)
586 l.nodeRemoved(null, n.first, n.second);
588 for (Pair<E, String> n : add) {
589 for (NodeListener l : nodeListeners)
590 l.nodeAdded(n.first.getParent(), n.first, n.second);
592 // for (Pair<E, String> n : mod) {
593 // for (NodeListener l : nodeListeners)
594 // l.propertyChanged(n.first, n.second);
596 for (E e : mod.getKeys()) {
597 for (NodeListener l : nodeListeners)
598 for (String s : mod.getValues(e))
599 l.propertyChanged(e, s);
602 synchronized (syncMutex) {
603 if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
604 rangeModified = false;
608 @SuppressWarnings("unchecked")
609 private void listen(INode node) {
610 node.addListener(this);
611 if (node instanceof ParentNode<?>) {
612 ParentNode<INode> parentNode = (ParentNode<INode>)node;
613 for (INode n : parentNode.getNodes())
618 private void stopListening(INode node) {
619 node.removeListener(this);
620 if (node instanceof ParentNode<?>) {
621 @SuppressWarnings("unchecked")
622 ParentNode<INode> parentNode = (ParentNode<INode>)node;
623 for (INode n : parentNode.getNodes())
628 @SuppressWarnings("unchecked")
630 public void propertyChanged(INode node, String id) {
631 //receiveUpdate((E)node, id, graphUpdates);
632 receiveUpdate((E)node, id, graphModified.contains(node));
636 @SuppressWarnings("unchecked")
638 public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
640 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
641 //receiveAdd((E)child, rel ,graphUpdates);
642 receiveAdd((E)child, rel ,graphModified.contains(node));
645 @SuppressWarnings("unchecked")
647 public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
649 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
650 //receiveRemove((E)child, rel, graphUpdates);
651 receiveRemove((E)child, rel, graphModified.contains(node));
653 //FIXME : 1. sometimes removed structural models cause ObjMap to add their children again.
654 // removing the listener here prevents corruption of visual model, but better fix is needed.
655 // 2. detach causes nodeRemoved event, which then causes other critical events to be missed. Took out call:
656 //stopListening(child);
660 public void delete() {
661 if (undoRedoSupport != null)
662 undoRedoSupport.cancel(this);
664 changeTracking = false;
665 view.removeListener(this);
666 mapping.removeMappingListener(this);
668 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
669 nodes.addAll(nodeToActor.getKeys());
670 for (E node : nodes) {
671 node.removeListener(this);
675 for (vtkProp prop : actorToNode.keySet()) {
676 if (prop.GetVTKId() != 0)
685 private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
687 public void addListener(NodeListener listener) {
688 nodeListeners.add(listener);
693 public void removeListener(NodeListener listener) {
694 nodeListeners.remove(listener);
698 public IMapping<DBObject,INode> getMapping() {