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.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.List;
22 import java.util.Stack;
24 import org.simantics.db.ReadGraph;
25 import org.simantics.db.Session;
26 import org.simantics.db.UndoContext;
27 import org.simantics.db.WriteGraph;
28 import org.simantics.db.common.request.ReadRequest;
29 import org.simantics.db.common.request.WriteRequest;
30 import org.simantics.db.exception.DatabaseException;
31 import org.simantics.db.layer0.util.Layer0Utils;
32 import org.simantics.db.service.UndoRedoSupport;
33 import org.simantics.g3d.ontology.G3D;
34 import org.simantics.g3d.scenegraph.RenderListener;
35 import org.simantics.g3d.scenegraph.base.INode;
36 import org.simantics.g3d.scenegraph.base.NodeListener;
37 import org.simantics.g3d.scenegraph.base.ParentNode;
38 import org.simantics.objmap.exceptions.MappingException;
39 import org.simantics.objmap.graph.IMapping;
40 import org.simantics.objmap.graph.IMappingListener;
41 import org.simantics.utils.datastructures.Callback;
42 import org.simantics.utils.datastructures.MapList;
43 import org.simantics.utils.datastructures.MapSet;
44 import org.simantics.utils.datastructures.Pair;
45 import org.simantics.utils.ui.ExceptionUtils;
49 public abstract class AbstractVTKNodeMap<E extends INode> implements VTKNodeMap<E>, IMappingListener, RenderListener, NodeListener, UndoRedoSupport.ChangeListener{
51 private static final boolean DEBUG = false;
53 protected Session session;
54 protected IMapping<Object,E> mapping;
55 protected VtkView view;
57 protected MapList<E, vtkProp> nodeToActor = new MapList<E, vtkProp>();
58 protected Map<vtkProp,E> actorToNode = new HashMap<vtkProp, E>();
60 protected ParentNode<E> rootNode;
62 protected UndoRedoSupport undoRedoSupport;
63 protected int undoOpCount = 0;
64 protected int redoOpCount = 0;
65 protected boolean runUndo = false;
66 protected boolean runRedo = false;
67 public AbstractVTKNodeMap(Session session, IMapping<Object,E> mapping, VtkView view, ParentNode<E> rootNode) {
68 this.session = session;
69 this.mapping = mapping;
71 this.rootNode = rootNode;
72 view.addListener(this);
73 mapping.addMappingListener(this);
74 rootNode.addListener(this);
76 undoRedoSupport = session.getService(UndoRedoSupport.class);
77 undoRedoSupport.subscribe(this);
79 UndoContext undoContext = undoRedoSupport.getUndoContext(session);
80 undoOpCount = undoContext.getAll().size();
81 redoOpCount = undoContext.getRedoList().size();
82 } 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 @SuppressWarnings("unchecked")
117 public ParentNode<E> getRootNode() {
118 return (ParentNode<E>)rootNode;
124 public boolean isChangeTracking() {
125 return changeTracking;
129 public void setChangeTracking(boolean enabled) {
130 changeTracking = enabled;
133 private boolean changeTracking = true;
135 protected Object syncMutex = new Object();
138 private List<Pair<E,String>> added = new ArrayList<Pair<E,String>>();
139 private List<Pair<E,String>> removed = new ArrayList<Pair<E,String>>();
140 private MapSet<E, String> updated = new MapSet.Hash<E, String>();
142 private boolean rangeModified = false;
145 public void onChanged() {
147 UndoContext undoContext = undoRedoSupport.getUndoContext(session);
148 int ucount = undoContext.getAll().size();
149 int rcount = undoContext.getRedoList().size();
150 if (DEBUG) System.out.println("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount);
151 if (ucount < undoOpCount) {
156 if (!runUndo && rcount > 0)
160 undoOpCount = ucount;
161 redoOpCount = rcount;
163 if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo);
164 } catch (DatabaseException e) {
165 // TODO Auto-generated catch block
172 @SuppressWarnings("unchecked")
174 public void updateRenderObjectsFor(E node) {
175 List<vtkProp> toDelete = new ArrayList<vtkProp>();
177 for (vtkProp prop : nodeToActor.getValues((E)node)) {
178 if (prop.GetVTKId() != 0) {
179 view.getRenderer().RemoveActor(prop);
183 actorToNode.remove(prop);
186 nodeToActor.remove((E)node);
187 Collection<vtkProp> coll = getActors((E)node);
189 for (vtkProp prop : coll) {
190 nodeToActor.add((E)node,prop);
191 actorToNode.put(prop, (E)node);
192 toDelete.remove(prop);
195 for (vtkProp p : toDelete)
199 protected abstract Collection<vtkProp> getActors(E node);
201 @SuppressWarnings("unchecked")
202 private void receiveAdd(E node, String id, boolean db) {
203 if (DEBUG) System.out.println("receiveAdd " + debugString(node) + " " + id + " " + db);
204 synchronized (syncMutex) {
205 for (Pair<E, String> n : added) {
206 if (n.first.equals(node))
209 if (changeTracking) {
210 mapping.rangeModified((E)node.getParent());
212 added.add(new Pair<E, String>(node, id));
213 rangeModified = true;
218 @SuppressWarnings("unchecked")
219 private void receiveRemove(E node, String id, boolean db) {
220 if (DEBUG) System.out.println("receiveRemove " + debugString(node) + " " + id + " " + db);
221 synchronized (syncMutex) {
222 for (Pair<E, String> n : removed) {
223 if (n.first.equals(node))
226 if (changeTracking && !db)
227 mapping.rangeModified((E)node.getParent());
228 removed.add(new Pair<E, String>(node, id));
229 rangeModified = true;
234 @SuppressWarnings("unchecked")
235 private void receiveUpdate(E node, String id, boolean db) {
236 if (DEBUG) System.out.println("receiveUpdate " + debugString(node) + " " + id + " " + db);
237 synchronized (syncMutex) {
238 // for (Pair<E, String> n : updated) {
239 // if (n.first.equals(node))
242 if (changeTracking && !db)
243 mapping.rangeModified(node);
244 //updated.add(new Pair<E, String>(node, id));
245 updated.add(node, id);
246 rangeModified = true;
251 private boolean graphUpdates = false;
252 private Set<E> graphModified = new HashSet<E>();
254 private boolean requestCommit = false;
255 private String commitMessage = null;
258 public void commit(String message) {
259 requestCommit = true;
260 commitMessage = message;
263 protected void doCommit() {
264 session.asyncRequest(new WriteRequest() {
267 public void perform(WriteGraph graph) throws DatabaseException {
268 if (DEBUG) System.out.println("Commit " + commitMessage);
269 if (commitMessage != null) {
270 Layer0Utils.addCommentMetadata(graph, commitMessage);
271 graph.markUndoPoint();
272 commitMessage = null;
277 }, new Callback<DatabaseException>() {
280 public void run(DatabaseException parameter) {
281 if (parameter != null)
282 ExceptionUtils.logAndShowError("Cannot commit editor changes", parameter);
287 protected void commit(WriteGraph graph) throws DatabaseException {
288 synchronized(syncMutex) {
289 if (DEBUG) System.out.println("Commit");
291 mapping.updateDomain(graph);
292 graphUpdates = false;
294 if (DEBUG) System.out.println("Commit done");
301 public void domainModified() {
304 if (DEBUG)System.out.println("domainModified");
305 session.asyncRequest(new ReadRequest() {
307 @SuppressWarnings("unchecked")
309 public void run(ReadGraph graph) throws DatabaseException {
316 protected void reset(ReadGraph graph) throws MappingException {
317 if (DEBUG) System.out.println("Reset");
318 synchronized (syncMutex) {
320 mapping.getRangeModified().clear();
321 for (Object o : mapping.getDomain())
322 mapping.domainModified(o);
323 mapping.updateRange(graph);
324 graphModified.clear();
325 graphUpdates = false;
329 private boolean useFullSyncWithUndo = false;
331 protected void update(ReadGraph graph) throws DatabaseException {
332 if (DEBUG) System.out.println("Graph update start");
333 if (runUndo && useFullSyncWithUndo) {
336 synchronized (syncMutex) {
338 for (Object domainObject : mapping.getDomainModified()) {
339 E rangeObject = mapping.get(domainObject);
340 if (rangeObject != null)
341 graphModified.add(rangeObject);
343 mapping.updateRange(graph);
344 graphModified.clear();
347 graphUpdates = false;
351 if (mapping.isRangeModified() && !runUndo && !runRedo)
352 commit((String)null);
353 if (DEBUG) System.out.println("Graph update done");
357 public void rangeModified() {
358 //System.out.println("rangeModified");
363 public void postRender() {
365 // 1. Commit has been requested
366 // 2. There are no pending changes that should be processed in preRender()
367 if (requestCommit && !rangeModified) { // FIXME : not thread safe.
368 requestCommit = false;
373 // Reusable containers for data synchronisation
374 List<Pair<E, String>> rem = new ArrayList<Pair<E,String>>(); // Removed objects
375 List<Pair<E, String>> add = new ArrayList<Pair<E,String>>(); // Added objects
376 MapSet<E, String> mod = new MapSet.Hash<E, String>(); // Modified objects
377 Set<E> propagation = new HashSet<E>(); // Objects with propagated changes
378 Stack<E> stack = new Stack<E>(); // Stack for handling propagation
379 Set<E> delete = Collections.synchronizedSet(new HashSet<E>()); // Objects to be completely deleted
380 Set<E> deleteUC = new HashSet<E>();
383 public synchronized void preRender() {
389 * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache.
390 * This causes problems with Undo and Redo, whcih the end up re-using the removed objects from mapping cache.
392 * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added).
395 protected void syncDeletes() {
397 for (Pair<E, String> n : removed) {
398 deleteUC.add(n.first);
400 for (Pair<E, String> n : added) {
401 deleteUC.remove(n.first);
403 if (DEBUG && deleteUC.size() > 0) {
404 System.out.println("Delete sync");
406 System.out.println(debugString(n));
409 delete.addAll(deleteUC);
414 * Clears deletable objects from mapping cache.
416 protected void clearDeletes() {
417 if (DEBUG && delete.size() > 0) System.out.println("Delete");
419 if (DEBUG) System.out.println(debugString(n));
420 mapping.getRange().remove(n);
425 protected String debugString(E n) {
426 return n + "@" + Integer.toHexString(n.hashCode());
429 @SuppressWarnings("unchecked")
430 protected void updateCycle() {
437 synchronized (syncMutex) {
440 for (E e : updated.getKeys()) {
441 for (String s : updated.getValues(e)) {
451 for (Pair<E, String> n : rem) {
452 stopListening(n.first);
453 removeActor(n.first);
456 for (Pair<E, String> n : add) {
461 for (E e : mod.getKeys()) {
462 Set<String> ids = mod.getValues(e);
463 if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
464 if (!propagation.contains(e))
469 if (propagation.size() > 0) {
471 stack.addAll(propagation);
473 while (!stack.isEmpty()) {
474 E node = stack.pop();
475 if (propagation.contains(node))
477 propagation.add(node);
478 for (NodeListener l : node.getListeners()) {
480 //changeTracking = false;
481 //l.propertyChanged(node, G3D.URIs.hasPosition);
482 //changeTracking = true;
484 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
487 if (node instanceof ParentNode) {
488 stack.addAll(((ParentNode<E>)node).getNodes());
493 // synchronized (syncMutex) {
494 // rem.addAll(removed);
495 // add.addAll(added);
496 // //mod.addAll(updated);
497 // for (E e : updated.getKeys()) {
498 // for (String s : updated.getValues(e))
507 for (E e : mod.getKeys()) {
508 Set<String> ids = mod.getValues(e);
513 for (Pair<E, String> n : rem) {
514 for (NodeListener l : nodeListeners)
515 l.nodeRemoved(null, n.first, n.second);
517 for (Pair<E, String> n : add) {
518 for (NodeListener l : nodeListeners)
519 l.nodeAdded(n.first.getParent(), n.first, n.second);
521 // for (Pair<E, String> n : mod) {
522 // for (NodeListener l : nodeListeners)
523 // l.propertyChanged(n.first, n.second);
525 for (E e : mod.getKeys()) {
526 for (NodeListener l : nodeListeners)
527 for (String s : mod.getValues(e))
528 l.propertyChanged(e, s);
531 synchronized (syncMutex) {
532 if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
533 rangeModified = false;
537 @SuppressWarnings("unchecked")
538 private void listen(INode node) {
539 node.addListener(this);
540 if (node instanceof ParentNode<?>) {
541 ParentNode<INode> parentNode = (ParentNode<INode>)node;
542 for (INode n : parentNode.getNodes())
547 private void stopListening(INode node) {
548 node.removeListener(this);
549 if (node instanceof ParentNode<?>) {
550 @SuppressWarnings("unchecked")
551 ParentNode<INode> parentNode = (ParentNode<INode>)node;
552 for (INode n : parentNode.getNodes())
557 @SuppressWarnings("unchecked")
559 public void propertyChanged(INode node, String id) {
560 //receiveUpdate((E)node, id, graphUpdates);
561 receiveUpdate((E)node, id, graphModified.contains(node));
565 @SuppressWarnings("unchecked")
567 public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
569 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
570 //receiveAdd((E)child, rel ,graphUpdates);
571 receiveAdd((E)child, rel ,graphModified.contains(node));
575 @SuppressWarnings("unchecked")
577 public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
579 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
580 //receiveRemove((E)child, rel, graphUpdates);
581 receiveRemove((E)child, rel, graphModified.contains(node));
583 //FIXME : sometimes removed structural models cause ObjMap to add their children again.
584 // removing the listener here prevents corruption of visual model, but better fix is needed.
585 stopListening(child);
589 public void delete() {
590 if (undoRedoSupport != null)
591 undoRedoSupport.cancel(this);
593 changeTracking = false;
594 view.removeListener(this);
595 mapping.removeMappingListener(this);
597 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
598 nodes.addAll(nodeToActor.getKeys());
599 for (E node : nodes) {
600 node.removeListener(this);
604 for (vtkProp prop : actorToNode.keySet()) {
605 if (prop.GetVTKId() != 0)
614 private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
616 public void addListener(NodeListener listener) {
617 nodeListeners.add(listener);
622 public void removeListener(NodeListener listener) {
623 nodeListeners.remove(listener);
627 public IMapping<Object,E> getMapping() {