]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/common/AbstractVTKNodeMap.java
Handle PipeRun removals with detaching Components.
[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                 
501                         rem.addAll(removed);
502                         add.addAll(added);
503                         for (E e : updated.getKeys()) {
504                                 for (String s : updated.getValues(e)) {
505                                         mod.add(e, s);
506                                 }
507                         }
508                         syncDeletes();
509                         removed.clear();
510                         added.clear();
511                         updated.clear();
512                 }
513                 
514                 
515                 for (Pair<E, String> n : rem) {
516                         stopListening(n.first);
517                         removeActor(n.first);
518                         n.first.remove();
519                 }
520                 
521             for (Pair<E, String> n : add) {
522                 addActor(n.first);
523                 listen(n.first);
524             }
525                 
526                 for (E e : mod.getKeys()) {
527                         Set<String> ids = mod.getValues(e);
528                         if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
529                                 if (!propagation.contains(e))
530                                         propagation.add(e);
531                         }
532                 }
533
534                 if (propagation.size() > 0) {
535                         stack.clear();
536                         stack.addAll(propagation);
537                         propagation.clear();
538                         while (!stack.isEmpty()) {
539                                 E node = stack.pop();
540                                 if (propagation.contains(node))
541                                         continue;
542                                 propagation.add(node);
543                                 for (NodeListener l : node.getListeners()) {
544                                         if (l == this) {
545                                                 //changeTracking = false;
546                                                 //l.propertyChanged(node, G3D.URIs.hasPosition);
547                                                 //changeTracking = true;
548                                         } else {
549                                                 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
550                                         }
551                                 }
552                                 if (node instanceof ParentNode) {
553                                         stack.addAll(((ParentNode<E>)node).getNodes());
554                                 }
555                         }
556                 }
557                 
558                 for (E e : mod.getKeys()) {
559                         Set<String> ids = mod.getValues(e);
560                         updateActor(e,ids);
561                 }
562
563                 for (Pair<E, String> n : rem) {
564                         for (NodeListener l : nodeListeners)
565                                 l.nodeRemoved(null, n.first, n.second);
566                 }
567                 for (Pair<E, String> n : add) {
568                         for (NodeListener l : nodeListeners)
569                                 l.nodeAdded(n.first.getParent(), n.first, n.second);
570                 }
571 //      for (Pair<E, String> n : mod) {
572 //          for (NodeListener l : nodeListeners)
573 //              l.propertyChanged(n.first, n.second);
574 //      }
575                 for (E e : mod.getKeys()) {
576                         for (NodeListener l : nodeListeners)
577                                 for (String s : mod.getValues(e))
578                                         l.propertyChanged(e, s);
579                 }
580                 
581                 synchronized (syncMutex) {
582                         if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
583                                 rangeModified = false;
584                 }
585         }
586         
587         @SuppressWarnings("unchecked")
588         private void listen(INode node) {
589                 node.addListener(this);
590                 if (node instanceof ParentNode<?>) {
591                         ParentNode<INode> parentNode = (ParentNode<INode>)node;
592                         for (INode n : parentNode.getNodes())
593                                 listen(n);
594                 }
595         }
596         
597         private void stopListening(INode node) {
598                 node.removeListener(this);
599                 if (node instanceof ParentNode<?>) {
600                         @SuppressWarnings("unchecked")
601                         ParentNode<INode> parentNode = (ParentNode<INode>)node;
602                         for (INode n : parentNode.getNodes())
603                                 stopListening(n);
604                 }
605         }
606         
607         @SuppressWarnings("unchecked")
608         @Override
609         public void propertyChanged(INode node, String id) {
610                 //receiveUpdate((E)node, id, graphUpdates);
611                 receiveUpdate((E)node, id, graphModified.contains(node));
612                 
613         }
614         
615         @SuppressWarnings("unchecked")
616         @Override
617         public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
618                         String rel) {
619                 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
620                 //receiveAdd((E)child, rel ,graphUpdates);
621                 receiveAdd((E)child, rel ,graphModified.contains(node));
622         }
623         
624         @SuppressWarnings("unchecked")
625         @Override
626         public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
627                         String rel) {
628                 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
629                 //receiveRemove((E)child, rel, graphUpdates);
630                 receiveRemove((E)child, rel, graphModified.contains(node));
631                 
632                 //FIXME : 1. sometimes removed structural models cause ObjMap to add their children again.
633                 //           removing the listener here prevents corruption of visual model, but better fix is needed.
634                 //        2. detach causes nodeRemoved event, which then causes other critical events to be missed. Took out call: 
635                 //stopListening(child);
636         }
637         
638         @Override
639         public void delete() {
640                 if (undoRedoSupport != null)
641                         undoRedoSupport.cancel(this);
642                 
643                 changeTracking = false;
644                 view.removeListener(this);
645                 mapping.removeMappingListener(this);
646
647                 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
648                 nodes.addAll(nodeToActor.getKeys());
649                 for (E node : nodes) {
650                         node.removeListener(this);
651                         removeActor(node);
652                         node.cleanup();
653                 }
654                 for (vtkProp prop : actorToNode.keySet()) {
655                         if (prop.GetVTKId() != 0) 
656                                 prop.Delete();
657                 }
658                 actorToNode.clear();
659                 nodeToActor.clear();
660                 
661         }
662         
663         
664         private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
665         @Override
666         public void addListener(NodeListener listener) {
667                 nodeListeners.add(listener);
668                 
669         }
670         
671         @Override
672         public void removeListener(NodeListener listener) {
673                 nodeListeners.remove(listener);
674                 
675         }
676         
677         public IMapping<DBObject,INode> getMapping() {
678                 return mapping;
679         }
680         
681         
682 }