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