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