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