]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/common/AbstractVTKNodeMap.java
Fix removed nodes leaving visible graphical elements.
[simantics/3d.git] / org.simantics.g3d.vtk / src / org / simantics / g3d / vtk / common / AbstractVTKNodeMap.java
1 /*******************************************************************************
2  * Copyright (c) 2012, 2013 Association for Decentralized Information Management in
3  * Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.g3d.vtk.common;
13
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;
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.Stack;
25 import java.util.function.Consumer;
26
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;
48
49 import vtk.vtkProp;
50
51 public abstract class AbstractVTKNodeMap<DBObject,E extends INode> implements VTKNodeMap<DBObject,E>, IMappingListener, RenderListener, NodeListener, UndoRedoSupport.ChangeListener{
52
53         private static final boolean DEBUG = false;
54         
55         protected Session session;
56         protected IMapping<DBObject, INode> mapping;
57         protected VtkView view;
58         
59         private MapList<E, vtkProp> nodeToActor = new MapList<E, vtkProp>();
60         private Map<vtkProp,E> actorToNode = new HashMap<vtkProp, E>();
61
62         protected ParentNode<E> rootNode;
63         
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;
72                 this.view = view;
73                 this.rootNode = rootNode;
74                 view.addListener(this);
75                 mapping.addMappingListener(this);
76                 rootNode.addListener(this);
77                 
78                 undoRedoSupport = session.getService(UndoRedoSupport.class);
79                 undoRedoSupport.subscribe(this);
80                 try {
81                         UndoContext undoContext = undoRedoSupport.getUndoContext(session); 
82                         undoOpCount = undoContext.getAll().size();
83                         redoOpCount = undoContext.getRedoList().size();
84                 } catch(DatabaseException e) {
85                         e.printStackTrace();
86                 }
87         }
88
89         protected abstract void addActor(E node);
90         protected abstract void removeActor(E node);
91         protected abstract void updateActor(E node,Set<String> ids);
92         
93         public void repaint() {
94                 view.refresh();
95         }
96         
97         public void populate() {
98                 for (E node : rootNode.getNodes()) {
99                         receiveAdd(node, node.getParentRel(),true);
100                 }
101                 repaint();
102         }
103         
104         @Override
105         public E getNode(vtkProp prop) {
106                 return actorToNode.get(prop);
107         }
108         
109         @SuppressWarnings("unchecked")
110         @Override
111         public Collection<vtkProp> getRenderObjects(INode node) {
112                 return nodeToActor.getValues((E) node);
113         }
114         
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);
119             }
120         }
121         
122         protected void removeMap(E node) {
123             Collection<vtkProp> coll = nodeToActor.getValuesUnsafe(node);
124             if (coll.size() > 0) {
125                 view.lock();
126             for (vtkProp p : coll) {
127                 actorToNode.remove(p);
128                 if (p.GetVTKId() != 0) {
129                     view.getRenderer().RemoveActor(p);
130                     p.Delete();
131                 }
132             }
133             view.unlock();
134             }
135             nodeToActor.remove(node);
136         }
137         
138         @Override
139         public ParentNode<E> getRootNode() {
140                 return (ParentNode<E>)rootNode;
141         }
142         
143         
144         
145         @Override
146         public boolean isChangeTracking() {
147                 return changeTracking;
148         }
149         
150         @Override
151         public void setChangeTracking(boolean enabled) {
152                 changeTracking = enabled;
153         }
154         
155         private boolean changeTracking = true;
156         
157         protected Object syncMutex = new Object(); 
158         
159
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>();
163
164         private boolean rangeModified = false;
165         
166         public boolean isRangeModified() {
167         return rangeModified;
168     }
169         
170         @Override
171         public void onChanged() {
172                 try {
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) {
178                                 runUndo = true;
179                         } else {
180                                 runUndo = false;
181                         }
182                         if (!runUndo && rcount > 0)
183                                 runRedo = true;
184                         else
185                                 runRedo = false;
186                         undoOpCount = ucount;
187                         redoOpCount = rcount;
188                         
189                         if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo);
190                 } catch (DatabaseException e) {
191                         // TODO Auto-generated catch block
192                         e.printStackTrace();
193                 }
194                 
195                 
196         }
197         
198         @Override
199         public void updateRenderObjectsFor(E node) {
200                 List<vtkProp> toDelete = new ArrayList<vtkProp>();
201                 view.lock();
202                 for (vtkProp prop : nodeToActor.getValues(node)) {
203                         if (prop.GetVTKId() != 0) {
204                                 view.getRenderer().RemoveActor(prop);
205                                 //prop.Delete();
206                                 toDelete.add(prop);
207                         }
208                         actorToNode.remove(prop);
209                 }
210                 view.unlock();
211                 nodeToActor.remove(node);
212                 Collection<vtkProp> coll = getActors(node);
213                 if (coll != null) {
214                         for (vtkProp prop : coll) {
215                                 nodeToActor.add(node,prop);
216                                 actorToNode.put(prop, node);
217                                 toDelete.remove(prop);
218                         }
219                 }
220                 for (vtkProp p : toDelete)
221                         p.Delete();
222         }
223         
224         protected abstract  Collection<vtkProp> getActors(E node);
225         
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))
232                                         return;
233                         }
234                         if (changeTracking) {
235                                 mapping.rangeModified((E)node.getParent());
236                                 mapping.rangeModified((E)node);
237                         }
238                         added.add(new Pair<E, String>(node, id));
239                         rangeModified = true;
240                 }
241                 repaint();
242         }
243         
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))
250                                         return;
251                         }
252                         if (changeTracking && !db) {
253                             mapping.rangeModified((E)node);
254                                 mapping.rangeModified((E)node.getParent());
255                         }
256                         removed.add(new Pair<E, String>(node, id));
257                         rangeModified = true;
258                 }
259                 repaint();
260         }
261         
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))
267 //                  return;
268 //          }
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;
274                 }
275                 repaint();
276         }
277         
278         private boolean graphUpdates = false;
279         private Set<E> graphModified = new HashSet<E>();
280         
281         private boolean requestCommit = false;
282         private String commitMessage = null;
283         
284         @Override
285         public void commit(String message) {
286                 requestCommit = true;
287                 commitMessage = message;
288         }
289         
290         protected void doCommit() {
291                 session.asyncRequest(new WriteRequest() {
292                         
293                         @Override
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;
300                                 }
301                                 commit(graph);
302                         }
303                         
304                 }, new Consumer<DatabaseException>() {
305                         
306                         @Override
307                         public void accept(DatabaseException parameter) {
308                                 if (parameter != null)
309                                         ExceptionUtils.logAndShowError("Cannot commit editor changes", parameter);
310                         }
311                 });
312         }
313         
314         protected void commit(WriteGraph graph) throws DatabaseException {
315                 synchronized(syncMutex) {
316                         if (DEBUG) System.out.println("Commit");
317                         graphUpdates = true;
318                         mapping.updateDomain(graph);
319                         graphUpdates = false;
320                         clearDeletes();
321                         if (DEBUG) System.out.println("Commit done");
322                 }
323         }
324         
325         
326         
327         @Override
328         public void domainModified() {
329                 if (graphUpdates)
330                         return;
331                 if (DEBUG)System.out.println("domainModified");
332                 session.asyncRequest(new ReadRequest() {
333                         
334                         @Override
335                         public void run(ReadGraph graph) throws DatabaseException {
336                                 update(graph);
337                         }
338                 });
339                 
340         }
341         
342         protected void reset(ReadGraph graph) throws MappingException {
343                 if (DEBUG) System.out.println("Reset");
344                 
345                 synchronized (syncMutex) {
346                         graphUpdates = true;
347                         mapping.getRangeModified().clear();
348                         for (DBObject o : mapping.getDomain())
349                                 mapping.domainModified(o);
350                         mapping.updateRange(graph);
351                         graphModified.clear();
352                         graphUpdates = false;
353                 }
354         }
355         
356         private boolean useFullSyncWithUndo = false;
357         
358         protected void update(ReadGraph graph) throws DatabaseException {
359                 if (DEBUG) System.out.println("Graph update start");
360                 if (runUndo && useFullSyncWithUndo) {
361                         reset(graph);
362                 } else {
363                     synchronized (syncMutex) {
364                                 graphUpdates = true;
365                                 for (DBObject domainObject : mapping.getDomainModified()) {
366                                         @SuppressWarnings("unchecked")
367                                         E rangeObject = (E) mapping.get(domainObject);
368                                         if (rangeObject != null)
369                                                 graphModified.add(rangeObject);
370                                 }
371                                 mapping.updateRange(graph);
372                                 graphModified.clear();
373                                 syncDeletes();
374                                 clearDeletes();
375                                 graphUpdates = false;
376                 }
377                 }
378                 
379                 if (mapping.isRangeModified() && !runUndo && !runRedo)
380                         commit((String)null);
381                 if (DEBUG) System.out.println("Graph update done");
382         }
383         
384         @Override
385         public void rangeModified() {
386                 //System.out.println("rangeModified");
387
388         }
389         
390         @Override
391         public void postRender() {
392                 // Commit changes if
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;
397                         doCommit();
398                 }
399         }
400         
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>();
409         
410         @Override
411         public synchronized void preRender() {
412                 updateCycle();
413         }
414         
415         
416         /**
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.
419          * 
420          * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added).  
421          * 
422          */
423         @SuppressWarnings("unused")
424         protected void syncDeletes() {
425                 deleteUC.clear();
426                 for (Pair<E, String> n : removed) {
427                         deleteUC.add(n.first);   
428                 }
429                 for (Pair<E, String> n : added) {
430                         deleteUC.remove(n.first);   
431                 } 
432                 if (DEBUG && deleteUC.size() > 0) {
433                         System.out.println("Delete sync");
434                         for (E n : delete) {
435                                 System.out.println(debugString(n));
436                         }
437                 }
438                 delete.addAll(deleteUC);
439                 deleteUC.clear();
440         }
441
442         /**
443          * Clears deletable objects from mapping cache.
444          */
445         @SuppressWarnings("unused")
446         protected void clearDeletes() {
447                 if (DEBUG && delete.size() > 0) System.out.println("Delete");
448                 for (E n : delete) {
449                         if (DEBUG) System.out.println(debugString(n));
450                         mapping.getRange().remove(n);
451                         stopListening(n);
452                 }
453                 delete.clear();
454         }
455         
456         protected String debugString(E n) {
457                 return n + "@" + Integer.toHexString(n.hashCode());
458         }
459         
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) {
463                 list.remove(i);
464                 return true;
465             }
466         }
467             return false;
468         }
469         
470         @SuppressWarnings("unchecked")
471         protected void updateCycle() {
472                 rem.clear();
473                 add.clear();
474                 mod.clear();
475                 propagation.clear();
476                 
477                 
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) {
482                     stack.add(n.first);
483                 }
484                 while (!stack.isEmpty()) {
485                     E n = stack.pop();
486                     boolean conflict = filterChange(removed, n);
487                     if (conflict) {
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);
492                     }
493                     if (n instanceof ParentNode) {
494                         ParentNode<INode> pn = (ParentNode<INode>)n;
495                         for (INode cn : pn.getNodes()) {
496                             stack.push((E)cn);
497                         }
498                     }
499                 }
500                 // Do not process updates for removed nodes.
501                 for (Pair<E, String> r : removed) {
502                     updated.removeValues(r.first);
503                 }
504                         rem.addAll(removed);
505                         add.addAll(added);
506                         for (E e : updated.getKeys()) {
507                                 for (String s : updated.getValues(e)) {
508                                         mod.add(e, s);
509                                 }
510                         }
511                         syncDeletes();
512                         removed.clear();
513                         added.clear();
514                         updated.clear();
515                 }
516                 
517                 
518                 for (Pair<E, String> n : rem) {
519                         stopListening(n.first);
520                         removeActor(n.first);
521                         n.first.remove();
522                 }
523                 
524             for (Pair<E, String> n : add) {
525                 addActor(n.first);
526                 listen(n.first);
527             }
528                 
529                 for (E e : mod.getKeys()) {
530                         Set<String> ids = mod.getValues(e);
531                         if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
532                                 if (!propagation.contains(e))
533                                         propagation.add(e);
534                         }
535                 }
536
537                 if (propagation.size() > 0) {
538                         stack.clear();
539                         stack.addAll(propagation);
540                         propagation.clear();
541                         while (!stack.isEmpty()) {
542                                 E node = stack.pop();
543                                 if (propagation.contains(node))
544                                         continue;
545                                 propagation.add(node);
546                                 for (NodeListener l : node.getListeners()) {
547                                         if (l == this) {
548                                                 //changeTracking = false;
549                                                 //l.propertyChanged(node, G3D.URIs.hasPosition);
550                                                 //changeTracking = true;
551                                         } else {
552                                                 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
553                                         }
554                                 }
555                                 if (node instanceof ParentNode) {
556                                         stack.addAll(((ParentNode<E>)node).getNodes());
557                                 }
558                         }
559                 }
560                 
561                 for (E e : mod.getKeys()) {
562                         Set<String> ids = mod.getValues(e);
563                         updateActor(e,ids);
564                 }
565
566                 for (Pair<E, String> n : rem) {
567                         for (NodeListener l : nodeListeners)
568                                 l.nodeRemoved(null, n.first, n.second);
569                 }
570                 for (Pair<E, String> n : add) {
571                         for (NodeListener l : nodeListeners)
572                                 l.nodeAdded(n.first.getParent(), n.first, n.second);
573                 }
574 //      for (Pair<E, String> n : mod) {
575 //          for (NodeListener l : nodeListeners)
576 //              l.propertyChanged(n.first, n.second);
577 //      }
578                 for (E e : mod.getKeys()) {
579                         for (NodeListener l : nodeListeners)
580                                 for (String s : mod.getValues(e))
581                                         l.propertyChanged(e, s);
582                 }
583                 
584                 synchronized (syncMutex) {
585                         if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
586                                 rangeModified = false;
587                 }
588         }
589         
590         @SuppressWarnings("unchecked")
591         private void listen(INode node) {
592                 node.addListener(this);
593                 if (node instanceof ParentNode<?>) {
594                         ParentNode<INode> parentNode = (ParentNode<INode>)node;
595                         for (INode n : parentNode.getNodes())
596                                 listen(n);
597                 }
598         }
599         
600         private void stopListening(INode node) {
601                 node.removeListener(this);
602                 if (node instanceof ParentNode<?>) {
603                         @SuppressWarnings("unchecked")
604                         ParentNode<INode> parentNode = (ParentNode<INode>)node;
605                         for (INode n : parentNode.getNodes())
606                                 stopListening(n);
607                 }
608         }
609         
610         @SuppressWarnings("unchecked")
611         @Override
612         public void propertyChanged(INode node, String id) {
613                 //receiveUpdate((E)node, id, graphUpdates);
614                 receiveUpdate((E)node, id, graphModified.contains(node));
615                 
616         }
617         
618         @SuppressWarnings("unchecked")
619         @Override
620         public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
621                         String rel) {
622                 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
623                 //receiveAdd((E)child, rel ,graphUpdates);
624                 receiveAdd((E)child, rel ,graphModified.contains(node));
625         }
626         
627         @SuppressWarnings("unchecked")
628         @Override
629         public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
630                         String rel) {
631                 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
632                 //receiveRemove((E)child, rel, graphUpdates);
633                 receiveRemove((E)child, rel, graphModified.contains(node));
634                 
635                 //FIXME : 1. sometimes removed structural models cause ObjMap to add their children again.
636                 //           removing the listener here prevents corruption of visual model, but better fix is needed.
637                 //        2. detach causes nodeRemoved event, which then causes other critical events to be missed. Took out call: 
638                 //stopListening(child);
639         }
640         
641         @Override
642         public void delete() {
643                 if (undoRedoSupport != null)
644                         undoRedoSupport.cancel(this);
645                 
646                 changeTracking = false;
647                 view.removeListener(this);
648                 mapping.removeMappingListener(this);
649
650                 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
651                 nodes.addAll(nodeToActor.getKeys());
652                 for (E node : nodes) {
653                         node.removeListener(this);
654                         removeActor(node);
655                         node.cleanup();
656                 }
657                 for (vtkProp prop : actorToNode.keySet()) {
658                         if (prop.GetVTKId() != 0) 
659                                 prop.Delete();
660                 }
661                 actorToNode.clear();
662                 nodeToActor.clear();
663                 
664         }
665         
666         
667         private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
668         @Override
669         public void addListener(NodeListener listener) {
670                 nodeListeners.add(listener);
671                 
672         }
673         
674         @Override
675         public void removeListener(NodeListener listener) {
676                 nodeListeners.remove(listener);
677                 
678         }
679         
680         public IMapping<DBObject,INode> getMapping() {
681                 return mapping;
682         }
683         
684         
685 }