]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/common/AbstractVTKNodeMap.java
Node listeners were removed too soon.
[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
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;
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,E> 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,E> 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             for (vtkProp p : coll) {
125                 actorToNode.remove(p);
126             }
127             nodeToActor.remove(node);
128         }
129         
130         @SuppressWarnings("unchecked")
131         @Override
132         public ParentNode<E> getRootNode() {
133                 return (ParentNode<E>)rootNode;
134         }
135         
136         
137         
138         @Override
139         public boolean isChangeTracking() {
140                 return changeTracking;
141         }
142         
143         @Override
144         public void setChangeTracking(boolean enabled) {
145                 changeTracking = enabled;
146         }
147         
148         private boolean changeTracking = true;
149         
150         protected Object syncMutex = new Object(); 
151         
152
153         private List<Pair<E,String>> added = new ArrayList<Pair<E,String>>();
154         private List<Pair<E,String>> removed = new ArrayList<Pair<E,String>>();
155         private MapSet<E, String> updated = new MapSet.Hash<E, String>();
156
157         private boolean rangeModified = false;
158         
159         public boolean isRangeModified() {
160         return rangeModified;
161     }
162         
163         @Override
164         public void onChanged() {
165                 try {
166                         UndoContext undoContext = undoRedoSupport.getUndoContext(session);
167                         int ucount = undoContext.getAll().size();
168                         int rcount = undoContext.getRedoList().size();
169                         if (DEBUG) System.out.println("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount);
170                         if (ucount < undoOpCount) {
171                                 runUndo = true;
172                         } else {
173                                 runUndo = false;
174                         }
175                         if (!runUndo && rcount > 0)
176                                 runRedo = true;
177                         else
178                                 runRedo = false;
179                         undoOpCount = ucount;
180                         redoOpCount = rcount;
181                         
182                         if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo);
183                 } catch (DatabaseException e) {
184                         // TODO Auto-generated catch block
185                         e.printStackTrace();
186                 }
187                 
188                 
189         }
190         
191         @SuppressWarnings("unchecked")
192         @Override
193         public void updateRenderObjectsFor(E node) {
194                 List<vtkProp> toDelete = new ArrayList<vtkProp>();
195                 view.lock();
196                 for (vtkProp prop : nodeToActor.getValues((E)node)) {
197                         if (prop.GetVTKId() != 0) {
198                                 view.getRenderer().RemoveActor(prop);
199                                 //prop.Delete();
200                                 toDelete.add(prop);
201                         }
202                         actorToNode.remove(prop);
203                 }
204                 view.unlock();
205                 nodeToActor.remove((E)node);
206                 Collection<vtkProp> coll = getActors((E)node);
207                 if (coll != null) {
208                         for (vtkProp prop : coll) {
209                                 nodeToActor.add((E)node,prop);
210                                 actorToNode.put(prop, (E)node);
211                                 toDelete.remove(prop);
212                         }
213                 }
214                 for (vtkProp p : toDelete)
215                         p.Delete();
216         }
217         
218         protected abstract  Collection<vtkProp> getActors(E node);
219         
220         @SuppressWarnings("unchecked")
221         private void receiveAdd(E node, String id, boolean db) {
222                 if (DEBUG) System.out.println("receiveAdd " + debugString(node)  + " " + id + " " + db);
223                 synchronized (syncMutex) {
224                         for (Pair<E, String> n : added) {
225                                 if (n.first.equals(node))
226                                         return;
227                         }
228                         if (changeTracking) {
229                                 mapping.rangeModified((E)node.getParent());
230                                 mapping.rangeModified((E)node);
231                         }
232                         added.add(new Pair<E, String>(node, id));
233                         rangeModified = true;
234                 }
235                 repaint();
236         }
237         
238         @SuppressWarnings("unchecked")
239         private void receiveRemove(E node, String id, boolean db) {
240                 if (DEBUG) System.out.println("receiveRemove " + debugString(node)  + " " + id + " " + db);
241                 synchronized (syncMutex) {
242                         for (Pair<E, String> n : removed) {
243                                 if (n.first.equals(node))
244                                         return;
245                         }
246                         if (changeTracking && !db) {
247                             mapping.rangeModified((E)node);
248                                 mapping.rangeModified((E)node.getParent());
249                         }
250                         removed.add(new Pair<E, String>(node, id));
251                         rangeModified = true;
252                 }
253                 repaint();
254         }
255         
256         @SuppressWarnings("unchecked")
257         private void receiveUpdate(E node, String id, boolean db) {
258                 if (DEBUG) System.out.println("receiveUpdate " + debugString(node)  + " " + id + " " + db);
259                 synchronized (syncMutex) {
260 //          for (Pair<E, String> n : updated) {
261 //              if (n.first.equals(node))
262 //                  return;
263 //          }
264                         if (changeTracking && !db)
265                                 mapping.rangeModified(node);
266                         //updated.add(new Pair<E, String>(node, id));
267                         updated.add(node, id);
268                         rangeModified = true;
269                 }
270                 repaint();
271         }
272         
273         private boolean graphUpdates = false;
274         private Set<E> graphModified = new HashSet<E>();
275         
276         private boolean requestCommit = false;
277         private String commitMessage = null;
278         
279         @Override
280         public void commit(String message) {
281                 requestCommit = true;
282                 commitMessage = message;
283         }
284         
285         protected void doCommit() {
286                 session.asyncRequest(new WriteRequest() {
287                         
288                         @Override
289                         public void perform(WriteGraph graph) throws DatabaseException {
290                                 if (DEBUG) System.out.println("Commit " + commitMessage);
291                                 if (commitMessage != null) {
292                                         Layer0Utils.addCommentMetadata(graph, commitMessage);
293                                         graph.markUndoPoint();
294                                         commitMessage = null;
295                                 }
296                                 commit(graph);
297                         }
298                         
299                 }, new Callback<DatabaseException>() {
300                         
301                         @Override
302                         public void run(DatabaseException parameter) {
303                                 if (parameter != null)
304                                         ExceptionUtils.logAndShowError("Cannot commit editor changes", parameter);
305                         }
306                 });
307         }
308         
309         protected void commit(WriteGraph graph) throws DatabaseException {
310                 synchronized(syncMutex) {
311                         if (DEBUG) System.out.println("Commit");
312                         graphUpdates = true;
313                         mapping.updateDomain(graph);
314                         graphUpdates = false;
315                         clearDeletes();
316                         if (DEBUG) System.out.println("Commit done");
317                 }
318         }
319         
320         
321         
322         @Override
323         public void domainModified() {
324                 if (graphUpdates)
325                         return;
326                 if (DEBUG)System.out.println("domainModified");
327                 session.asyncRequest(new ReadRequest() {
328                         
329                         @SuppressWarnings("unchecked")
330                         @Override
331                         public void run(ReadGraph graph) throws DatabaseException {
332                                 update(graph);
333                         }
334                 });
335                 
336         }
337         
338         protected void reset(ReadGraph graph) throws MappingException {
339                 if (DEBUG) System.out.println("Reset");
340                 
341                 synchronized (syncMutex) {
342                         graphUpdates = true;
343                         mapping.getRangeModified().clear();
344                         for (DBObject o : mapping.getDomain())
345                                 mapping.domainModified(o);
346                         mapping.updateRange(graph);
347                         graphModified.clear();
348                         graphUpdates = false;
349                 }
350         }
351         
352         private boolean useFullSyncWithUndo = false;
353         
354         protected void update(ReadGraph graph) throws DatabaseException {
355                 if (DEBUG) System.out.println("Graph update start");
356                 if (runUndo && useFullSyncWithUndo) {
357                         reset(graph);
358                 } else {
359                         synchronized (syncMutex) {
360                                 graphUpdates = true;
361                                 for (DBObject domainObject : mapping.getDomainModified()) {
362                                         E rangeObject = mapping.get(domainObject);
363                                         if (rangeObject != null)
364                                                 graphModified.add(rangeObject);
365                                 }
366                                 mapping.updateRange(graph);
367                                 graphModified.clear();
368                                 syncDeletes();
369                                 clearDeletes();
370                                 graphUpdates = false;
371                         }
372                 }
373                 
374                 if (mapping.isRangeModified() && !runUndo && !runRedo)
375                         commit((String)null);
376                 if (DEBUG) System.out.println("Graph update done");
377         }
378         
379         @Override
380         public void rangeModified() {
381                 //System.out.println("rangeModified");
382
383         }
384         
385         @Override
386         public void postRender() {
387                 // Commit changes if
388                 // 1. Commit has been requested
389                 // 2. There are no pending changes that should be processed in preRender() 
390                 if (requestCommit && !rangeModified) { // FIXME : not thread safe.
391                         requestCommit = false;
392                         doCommit();
393                 }
394         }
395         
396         // Reusable containers for data synchronisation
397         List<Pair<E, String>> rem = new ArrayList<Pair<E,String>>();  // Removed objects
398         List<Pair<E, String>> add = new ArrayList<Pair<E,String>>();  // Added objects
399         MapSet<E, String> mod = new MapSet.Hash<E, String>();         // Modified objects
400         Set<E> propagation = new HashSet<E>();                        // Objects with propagated changes 
401         Stack<E> stack = new Stack<E>();                              // Stack for handling propagation
402         Set<E> delete = Collections.synchronizedSet(new HashSet<E>()); // Objects to be completely deleted
403         Set<E> deleteUC = new HashSet<E>();
404         
405         @Override
406         public synchronized void preRender() {
407                 updateCycle();
408         }
409         
410         
411         /**
412          * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache.
413          * This causes problems with Undo and Redo, which cause re-using the removed objects from mapping cache.
414          * 
415          * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added).  
416          * 
417          */
418         protected void syncDeletes() {
419                 deleteUC.clear();
420                 for (Pair<E, String> n : removed) {
421                         deleteUC.add(n.first);   
422                 }
423                 for (Pair<E, String> n : added) {
424                         deleteUC.remove(n.first);   
425                 } 
426                 if (DEBUG && deleteUC.size() > 0) {
427                         System.out.println("Delete sync");
428                         for (E n : delete) {
429                                 System.out.println(debugString(n));
430                         }
431                 }
432                 delete.addAll(deleteUC);
433                 deleteUC.clear();
434         }
435
436         /**
437          * Clears deletable objects from mapping cache.
438          */
439         protected void clearDeletes() {
440                 if (DEBUG && delete.size() > 0) System.out.println("Delete");
441                 for (E n : delete) {
442                         if (DEBUG) System.out.println(debugString(n));
443                         mapping.getRange().remove(n);
444                         stopListening(n);
445                 }
446                 delete.clear();
447         }
448         
449         protected String debugString(E n) {
450                 return n + "@" + Integer.toHexString(n.hashCode());
451         }
452         
453         protected boolean filterChange(List<Pair<E,String>> list,E n) {
454             for (int i = list.size()-1; i >= 0; i--) {
455             if (list.get(i).first == n) {
456                 list.remove(i);
457                 return true;
458             }
459         }
460             return false;
461         }
462         
463         @SuppressWarnings("unchecked")
464         protected void updateCycle() {
465                 rem.clear();
466                 add.clear();
467                 mod.clear();
468                 propagation.clear();
469                 
470                 
471                 synchronized (syncMutex) {
472                     // Check for overlapping additions and deletions, prevent deleting objects that are also added and vice versa.
473                     Deque<E> stack = new ArrayDeque<E>();
474                 for (Pair<E, String> n : added) {
475                     stack.add(n.first);
476                 }
477                 while (!stack.isEmpty()) {
478                     E n = stack.pop();
479                     boolean conflict = filterChange(removed, n);
480                     if (conflict) {
481                         System.out.println("Prevent removing " + n);
482                         //filterChange(added, n)
483                         if (filterChange(added, n))
484                             System.out.println("Prevent adding " + n);
485                     }
486                     if (n instanceof ParentNode) {
487                         ParentNode<INode> pn = (ParentNode<INode>)n;
488                         for (INode cn : pn.getNodes()) {
489                             stack.push((E)cn);
490                         }
491                     }
492                 }
493                 
494                         rem.addAll(removed);
495                         add.addAll(added);
496                         for (E e : updated.getKeys()) {
497                                 for (String s : updated.getValues(e)) {
498                                         mod.add(e, s);
499                                 }
500                         }
501                         syncDeletes();
502                         removed.clear();
503                         added.clear();
504                         updated.clear();
505                 }
506                 
507                 
508                 
509                 for (Pair<E, String> n : rem) {
510                         stopListening(n.first);
511                         removeActor(n.first);
512                 }
513                 
514                 for (Pair<E, String> n : add) {
515                         addActor(n.first);
516                         listen(n.first);
517                 }
518                 
519                 for (E e : mod.getKeys()) {
520                         Set<String> ids = mod.getValues(e);
521                         if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
522                                 if (!propagation.contains(e))
523                                         propagation.add(e);
524                         }
525                 }
526
527                 if (propagation.size() > 0) {
528                         stack.clear();
529                         stack.addAll(propagation);
530                         propagation.clear();
531                         while (!stack.isEmpty()) {
532                                 E node = stack.pop();
533                                 if (propagation.contains(node))
534                                         continue;
535                                 propagation.add(node);
536                                 for (NodeListener l : node.getListeners()) {
537                                         if (l == this) {
538                                                 //changeTracking = false;
539                                                 //l.propertyChanged(node, G3D.URIs.hasPosition);
540                                                 //changeTracking = true;
541                                         } else {
542                                                 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
543                                         }
544                                 }
545                                 if (node instanceof ParentNode) {
546                                         stack.addAll(((ParentNode<E>)node).getNodes());
547                                 }
548                         }
549                 }
550                 
551 //      synchronized (syncMutex) {
552 //          rem.addAll(removed);
553 //          add.addAll(added);
554 //          //mod.addAll(updated);
555 //          for (E e : updated.getKeys()) {
556 //              for (String s : updated.getValues(e))
557 //                  mod.add(e, s);
558 //          }
559 //          
560 //          removed.clear();
561 //          added.clear();
562 //          updated.clear();
563 //      }
564                 
565                 for (E e : mod.getKeys()) {
566                         Set<String> ids = mod.getValues(e);
567                         updateActor(e,ids);
568                 }
569                 
570                 
571                 for (Pair<E, String> n : rem) {
572                         for (NodeListener l : nodeListeners)
573                                 l.nodeRemoved(null, n.first, n.second);
574                 }
575                 for (Pair<E, String> n : add) {
576                         for (NodeListener l : nodeListeners)
577                                 l.nodeAdded(n.first.getParent(), n.first, n.second);
578                 }
579 //      for (Pair<E, String> n : mod) {
580 //          for (NodeListener l : nodeListeners)
581 //              l.propertyChanged(n.first, n.second);
582 //      }
583                 for (E e : mod.getKeys()) {
584                         for (NodeListener l : nodeListeners)
585                                 for (String s : mod.getValues(e))
586                                         l.propertyChanged(e, s);
587                 }
588                 
589                 synchronized (syncMutex) {
590                         if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
591                                 rangeModified = false;
592                 }
593         }
594         
595         @SuppressWarnings("unchecked")
596         private void listen(INode node) {
597                 node.addListener(this);
598                 if (node instanceof ParentNode<?>) {
599                         ParentNode<INode> parentNode = (ParentNode<INode>)node;
600                         for (INode n : parentNode.getNodes())
601                                 listen(n);
602                 }
603         }
604         
605         private void stopListening(INode node) {
606                 node.removeListener(this);
607                 if (node instanceof ParentNode<?>) {
608                         @SuppressWarnings("unchecked")
609                         ParentNode<INode> parentNode = (ParentNode<INode>)node;
610                         for (INode n : parentNode.getNodes())
611                                 stopListening(n);
612                 }
613         }
614         
615         @SuppressWarnings("unchecked")
616         @Override
617         public void propertyChanged(INode node, String id) {
618                 //receiveUpdate((E)node, id, graphUpdates);
619                 receiveUpdate((E)node, id, graphModified.contains(node));
620                 
621         }
622         
623         @SuppressWarnings("unchecked")
624         @Override
625         public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
626                         String rel) {
627                 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
628                 //receiveAdd((E)child, rel ,graphUpdates);
629                 receiveAdd((E)child, rel ,graphModified.contains(node));
630         }
631         
632         @SuppressWarnings("unchecked")
633         @Override
634         public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
635                         String rel) {
636                 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
637                 //receiveRemove((E)child, rel, graphUpdates);
638                 receiveRemove((E)child, rel, graphModified.contains(node));
639                 
640                 //FIXME : 1. sometimes removed structural models cause ObjMap to add their children again.
641                 //           removing the listener here prevents corruption of visual model, but better fix is needed.
642                 //        2. detach causes nodeRemoved event, which then causes other critical events to be missed. Took out th 
643                 //stopListening(child);
644         }
645         
646         @Override
647         public void delete() {
648                 if (undoRedoSupport != null)
649                         undoRedoSupport.cancel(this);
650                 
651                 changeTracking = false;
652                 view.removeListener(this);
653                 mapping.removeMappingListener(this);
654
655                 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
656                 nodes.addAll(nodeToActor.getKeys());
657                 for (E node : nodes) {
658                         node.removeListener(this);
659                         removeActor(node);
660                         node.cleanup();
661                 }
662                 for (vtkProp prop : actorToNode.keySet()) {
663                         if (prop.GetVTKId() != 0) 
664                                 prop.Delete();
665                 }
666                 actorToNode.clear();
667                 nodeToActor.clear();
668                 
669         }
670         
671         
672         private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
673         @Override
674         public void addListener(NodeListener listener) {
675                 nodeListeners.add(listener);
676                 
677         }
678         
679         @Override
680         public void removeListener(NodeListener listener) {
681                 nodeListeners.remove(listener);
682                 
683         }
684         
685         public IMapping<DBObject,E> getMapping() {
686                 return mapping;
687         }
688         
689         
690 }