]> gerrit.simantics Code Review - simantics/interop.git/blob - org.simantics.interop.update/src/org/simantics/interop/update/model/ModelUpdate.java
aabe29d58c59d5e09ec2cdf8f017dc6df46a1113
[simantics/interop.git] / org.simantics.interop.update / src / org / simantics / interop / update / model / ModelUpdate.java
1 package org.simantics.interop.update.model;
2
3 import java.util.ArrayDeque;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.Deque;
7 import java.util.List;
8 import java.util.Map.Entry;
9
10 import org.simantics.Simantics;
11 import org.simantics.db.ReadGraph;
12 import org.simantics.db.Resource;
13 import org.simantics.db.Session;
14 import org.simantics.db.Statement;
15 import org.simantics.db.WriteGraph;
16 import org.simantics.db.common.request.ReadRequest;
17 import org.simantics.db.exception.DatabaseException;
18 import org.simantics.db.layer0.util.Layer0Utils;
19 import org.simantics.db.request.Read;
20 import org.simantics.interop.test.GraphChanges;
21 import org.simantics.interop.test.GraphChanges.Modification;
22 import org.simantics.interop.test.GraphComparator;
23 import org.simantics.utils.datastructures.Pair;
24
25 public abstract class ModelUpdate {
26         
27         private Resource oldModel;      // old model that is going to be updated (User modified model)
28         private Resource newModel;      // new model that contains the updates   (New design model)
29         private Resource originalModel; // original model (optional) that is used for detecting and retaining user made changes (Old design model)
30         
31         private GraphChanges changes;   // changes between old /new
32         private UpdateTree updateTree;
33         private UpdateList updateList;
34         
35         private GraphChanges changes2;  // changes between original / old
36         private UpdateTree updateTree2;
37         private UpdateList updateList2;
38         
39         private GraphChanges changes3;  // changes between original / new
40         private UpdateTree updateTree3;
41         private UpdateList updateList3;
42         
43         private UpdateNode3 updateNode3;
44         
45         private List<ChangeFilter> filters = new ArrayList<ChangeFilter>();
46         private List<ChangeFilter2> userFilters = new ArrayList<ChangeFilter2>();
47         
48         boolean init = false;
49         
50         public void setInput(Resource oldModel, Resource newModel) throws DatabaseException {
51                 setInput(oldModel, newModel, null, false);
52         }
53         
54         /**
55          * Initialises the ModelUpdate with given input
56          * @param oldModel the model that is going to be updated (User modified model)
57          * @param newModel the model containing updates (New design model)
58          * @param originalModel the model that is used for detecting and retaining user made changes (Old design model). Parameter can be null.
59          * @param newDistinct when originalModel is given, additions to the old and the new model (when compared to the original model) are forced to be distinct. 
60          * @throws DatabaseException
61          */
62         public void setInput(Resource oldModel, Resource newModel, Resource originalModel, boolean newDistinct) throws DatabaseException{
63                 this.oldModel = oldModel;
64                 this.newModel = newModel;
65                 this.originalModel = originalModel;
66 //              addFilters(filters);
67                 if (originalModel != null) {
68                         // tree way comparison
69                         // compare the original and the old model
70                         Pair<GraphComparator,String> result2 = getChanges(originalModel, oldModel);
71                         GraphComparator comparator2  = result2.first;
72                         if (result2.second != null)
73                                 showWarning(result2.second);
74                         comparator2.test(getSession());
75                         changes2 = comparator2.getChanges();
76                         changes2 = getSession().syncRequest(createFilterRead(changes2, filters));
77                         Pair<UpdateTree, UpdateList> chg2 = createChangeObjects(changes2);
78                         updateTree2 = chg2.first;
79                         updateList2 = chg2.second;
80                         
81                         // compare the original and the new model
82                         Pair<GraphComparator,String> result3 = getChanges(originalModel,newModel);
83                         GraphComparator comparator3  = result3.first;
84                         if (result3.second != null)
85                                 showWarning(result3.second);
86                         comparator3.test(getSession());
87                         changes3 = comparator3.getChanges();
88                         changes3 = getSession().syncRequest(createFilterRead(changes3, filters));
89                 }
90                 
91                 Pair<GraphComparator,String> result = getChanges(oldModel,newModel);
92                 GraphComparator comparator  = result.first;
93                 if (result.second != null)
94                         showWarning(result.second);
95                 if (originalModel != null) {
96                         // three-way comparison: use change information to configure
97                         // the comparison between the old and the new model.
98                         
99                         // 1. map comparable resources
100                         for (Entry<Resource, Resource> origToOld : changes2.getComparable().getEntries()) {
101                                 Resource oldR = origToOld.getValue();
102                                 Resource newR = changes3.getComparable().getRight(origToOld.getKey());
103                                 if (newR != null) {
104                                         comparator.addComparableResources(oldR, newR);
105                                 }
106                         }
107                         // 2. mark removed resources as distinct, so that comparison does not pair them
108                         for (Statement s : changes2.getDeletions()) {
109                                 if (changes3.getComparable().containsLeft(s.getObject()))
110                                         comparator.addNonMatchedRight(changes3.getComparable().getRight(s.getObject()));
111                         }
112                         
113                         for (Statement s : changes3.getDeletions()) {
114                                 if (changes2.getComparable().containsLeft(s.getObject()))
115                                         comparator.addNonMatchedLeft(changes2.getComparable().getRight(s.getObject()));
116                         }
117                         if (newDistinct) {
118                                 // 3. mark added resources as distinct, so that comparison does not pair them
119                                 for (Statement s : changes2.getAdditions()) {
120                                         comparator.addNonMatchedLeft(s.getObject());
121                                 }
122                                 
123                                 for (Statement s : changes3.getAdditions()) {
124                                         comparator.addNonMatchedRight(s.getObject());
125                                 }
126                         }
127                 }
128                 comparator.test(getSession());
129                 changes = comparator.getChanges();
130                 changes = getSession().syncRequest(createFilterRead(changes, filters));
131                 Pair<UpdateTree, UpdateList> chg = createChangeObjects(changes);
132         updateTree = chg.first;
133         updateList = chg.second;
134                 if (userFilters.size() != 0) {
135                         refreshUserFilters();
136                 }
137                 
138                 
139                 if (originalModel != null) {
140                         defaultSelections();
141                 }
142                 
143                 init = true;
144         }
145         
146         public void addFilter(ChangeFilter filter) {
147                 if (init)
148                         throw new IllegalStateException("ModelUpdate has been initialized, adjusting filters is no longer possible.");
149                 filters.add(filter);
150                 
151         }
152         
153         public List<ChangeFilter> getFilters() {
154                 return Collections.unmodifiableList(filters);
155         }
156         
157         /**
158          * Adds an user filter. Use refreshUserFilters() to apply the changes.
159          * @param filter
160          */
161         public void addUserFilter(ChangeFilter2 filter) {
162                 userFilters.add(filter);
163         }
164         
165         /**
166          * Removes an user filter. Use refreshUserFilters() to apply the changes.
167          * @param filter
168          */
169         public void removeUserFilter(ChangeFilter2 filter) {
170                 userFilters.remove(filter);
171         }
172         
173         /**
174          * Clears user filters.  Use refreshUserFilters() to apply the changes.
175          */
176         public void clearUserFilters() {
177                 userFilters.clear();
178         }
179         
180         public List<ChangeFilter2> getUserFilters() {
181                 return userFilters;
182         }
183         
184         public void refreshUserFilters() throws DatabaseException{
185                 // use user filters to set visible flags of changes.
186                 // First, set all changes visible.
187                 Deque<UpdateNode> stack = new ArrayDeque<>();
188                 stack.push(updateTree.getRootNode());
189                 while (!stack.isEmpty()) {
190                         UpdateNode n = stack.pop();
191                         n.setVisible(true);
192                         stack.addAll(n.getChildren());
193                 }
194                 for (PropertyChange pc : updateList.getChanges()) {
195                         pc.setVisible(true);
196                 }
197                 if (userFilters.size() > 0) {
198                     if (changes2 != null && changes3 != null) {
199                         getUpdateTree3();
200                     }
201                     getSession().syncRequest(new ReadRequest() {
202                 
203                 @Override
204                 public void run(ReadGraph graph) throws DatabaseException {
205                     for (PropertyChange change : updateList.getChanges()) {
206                         boolean visible = true;
207                         for (ChangeFilter2 filter : userFilters) {
208                             if (!filter.accept(graph, change)) {
209                                 visible = false;
210                                 break;
211                             }
212                         }
213                         change.setVisible(visible);
214                     }
215                     if (updateTree3 != null) {
216                         Deque<UpdateNode3> stack = new ArrayDeque<>();
217                         stack.add(getUpdateNode3());
218                         while (!stack.isEmpty()) {
219                             UpdateNode3 n = stack.pop();
220                             boolean visible = true;
221                             for (ChangeFilter2 filter : userFilters) {
222                                 if (!filter.accept(graph, n)) {
223                                     visible = false;
224                                     break;
225                                 }
226                             }
227                             n.setVisible(visible);
228                             for (UpdateNode3 c : n.getChildren())
229                                 stack.push(c);
230                         }
231                     } else {
232                     
233                         Deque<UpdateNode> stack = new ArrayDeque<>();
234                         stack.add(updateTree.getRootNode());
235                         while (!stack.isEmpty()) {
236                             UpdateNode n = stack.pop();
237                             boolean visible = true;
238                             for (ChangeFilter2 filter : userFilters) {
239                                 if (!filter.accept(graph, n)) {
240                                     visible = false;
241                                     break;
242                                 }
243                             }
244                             n.setVisible(visible);
245                             for (UpdateNode c : n.getChildren())
246                                 stack.push(c);
247                         }
248                     }
249                 }
250             });
251                 }
252         }
253         
254         protected abstract Pair<GraphComparator,String> getChanges(Resource r1, Resource r2)  throws DatabaseException;
255         
256         protected Pair<UpdateTree, UpdateList> createChangeObjects(GraphChanges changes) throws DatabaseException{
257             UpdateTree updateTree = getUpdateTree(changes);
258         UpdateList updateList = getUpdateList(changes);
259         postProcess(updateTree, updateList);
260         return new Pair<UpdateTree, UpdateList>(updateTree, updateList);
261         }
262         
263         protected abstract UpdateTree getUpdateTree(GraphChanges changes) throws DatabaseException;
264         protected UpdateList getUpdateList(GraphChanges changes) throws DatabaseException {
265                 return new UpdateList(changes, changes.getModifications());
266         }
267         
268
269         protected void postProcess(UpdateTree updateTree, UpdateList updateList) throws DatabaseException{
270             
271         }
272         
273         public Resource getOldModel() {
274                 return oldModel;
275         }
276         
277         public Resource getNewModel() {
278                 return newModel;
279         }
280         
281         public Resource getOriginalModel() {
282                 return originalModel;
283         }
284         
285         public boolean isInit() {
286                 return init;
287         }
288         
289         public GraphChanges getChanges() {
290                 return changes;
291         }
292         public UpdateTree getUpdateTree() {
293                 return updateTree;
294         }
295         public UpdateList getUpdateList() {
296                 return updateList;
297         }
298         public GraphChanges getChanges2() {
299                 return changes2;
300         }
301         
302         public UpdateTree getUpdateTree2() {
303                 return updateTree2;
304         }
305         public UpdateList getUpdateList2() {
306                 return updateList2;
307         }
308         
309         public GraphChanges getChanges3() {
310                 return changes3;
311         }
312         
313         public UpdateTree getUpdateTree3() throws DatabaseException{
314                 if (updateTree3 == null && changes3 != null) {
315                     Pair<UpdateTree, UpdateList> chg3 = createChangeObjects(changes3);
316             updateTree3 = chg3.first;
317             updateList3 = chg3.second;
318                 }
319                 return updateTree3;
320         }
321         public UpdateList getUpdateList3() throws DatabaseException {
322                 if (updateList3 == null && changes3 != null) {
323                     Pair<UpdateTree, UpdateList> chg3 = createChangeObjects(changes3);
324             updateTree3 = chg3.first;
325             updateList3 = chg3.second;
326                 }
327                 return updateList3;
328         }
329         
330         public UpdateNode3 getUpdateNode3() throws DatabaseException {
331             if (updateNode3 == null && changes2 != null && changes3 != null) {
332                 updateNode3 = UpdateNode3.getCombinedTree(this);
333             }
334             return updateNode3;
335         }
336
337         
338         public void applyAll(WriteGraph graph) throws DatabaseException {
339                 Layer0Utils.addCommentMetadata(graph, "Apply all model updates");
340                 graph.markUndoPoint();
341                 for (PropertyChange mod : updateList.getChanges()) {
342                         mod.apply(graph);
343                 }
344                 
345                 updateTree.getUpdateOps().applyAll(graph);
346         }
347         
348         public void applySelected(WriteGraph graph) throws DatabaseException {
349                 Layer0Utils.addCommentMetadata(graph, "Apply selected model updates");
350                 graph.markUndoPoint();
351                 
352                 updateTree.getUpdateOps().applySelected(graph);
353                 
354                 for (PropertyChange mod : updateList.getChanges()) {
355                         if (mod.selected())
356                                 mod.apply(graph);
357                 }
358         }
359         
360         
361         
362         
363         protected Session getSession() {
364                 return Simantics.getSession();
365         }
366         
367         public Read<GraphChanges> createFilterRead(GraphChanges changes, List<ChangeFilter> filters) {
368                 return new FilterChangesRead(changes, filters);
369         }
370         
371         
372         
373         public static class FilterChangesRead implements Read<GraphChanges> {
374                 private GraphChanges changes;
375                 private List<ChangeFilter> filters;
376                 
377                 public FilterChangesRead(GraphChanges changes, List<ChangeFilter> filters) {
378                         this.changes = changes;
379                         this.filters = filters;
380                 }
381                 
382                 @Override
383                 public GraphChanges perform(ReadGraph graph) throws DatabaseException {
384                         return filterChanges(graph, changes);
385                 }
386                 
387                 /**
388                  * Filters changes:
389                  * 1. Changes that are not essential for model update (changes that can be found when the models are exactly the same)
390                  * 2. Runs custom filters for value changes. 
391                  * 
392                  * @param g
393                  * @param changes
394                  * @return
395                  * @throws DatabaseException
396                  */
397                 protected GraphChanges filterChanges(ReadGraph g, GraphChanges changes) throws DatabaseException 
398             {
399                         
400                         List<Modification> modifications = new ArrayList<Modification>();
401                         
402                 for (Modification mod : changes.getModifications()) {
403                         
404                         boolean accept = true;
405                         for (ChangeFilter filter : filters) {
406                                 if (!filter.accept(g, mod)) {
407                                         accept = false;
408                                         break;
409                                 }       
410                         }
411                         if (accept)
412                                 modifications.add(mod);
413                 }
414                 List<Statement> deletions = new ArrayList<Statement>();
415                 for (Statement del : changes.getDeletions()) {
416                 
417                 boolean accept = true;
418                 for (ChangeFilter filter : filters) {
419                     if (!filter.acceptDeletion(g, del)) {
420                         accept = false;
421                         break;
422                     }   
423                 }
424                 if (accept)
425                     deletions.add(del);
426             }
427                 List<Statement> additions = new ArrayList<Statement>();
428             for (Statement del : changes.getAdditions()) {
429                 
430                 boolean accept = true;
431                 for (ChangeFilter filter : filters) {
432                     if (!filter.acceptAddition(g, del)) {
433                         accept = false;
434                         break;
435                     }   
436                 }
437                 if (accept)
438                     additions.add(del);
439             }
440
441                 GraphChanges newChanges =  new GraphChanges(changes.getResource1(),changes.getResource2(),deletions, additions, modifications, changes.getComparable());
442                 return newChanges;
443             }
444         }
445
446         /**
447          * Interface for built-in filters that are used for processing raw change data before forming UpdateTree + UpdateList
448          * @author luukkainen
449          *
450          */
451         public interface ChangeFilter {
452                 public boolean accept(ReadGraph g, Modification change) throws DatabaseException;
453                 public boolean acceptAddition(ReadGraph g, Statement addition) throws DatabaseException;
454                 public boolean acceptDeletion(ReadGraph g, Statement deletion) throws DatabaseException;
455         }
456         
457         /**
458          * Interface for user defined filters. 
459          * 
460          * This filter only affects visible flags.
461          *  
462          * @author luukkainen
463          *
464          */
465         public interface ChangeFilter2 {
466             public boolean accept(ReadGraph g, PropertyChange change) throws DatabaseException;
467             public boolean accept(ReadGraph g, UpdateNode change) throws DatabaseException;
468             public boolean accept(ReadGraph g, UpdateNode3 change) throws DatabaseException;
469         }
470
471         
472         /**
473          * 
474          * Filters floating point value changes (default filter is set filter when the change is less than 1%)  
475          *
476          */
477         protected class FPValueFilter implements ChangeFilter  {
478                 
479                 private double percentage = 0.01;
480                 
481                 public FPValueFilter() {
482                         
483                 }
484                 
485                 public FPValueFilter(double percentage) {
486                         if (percentage < 0.0 || percentage > 1.0)
487                                 throw new IllegalArgumentException("Percentage must be between 0.0 and 1.0.");
488                         this.percentage = percentage;
489                 }
490                 
491                 @Override
492                 public boolean accept(ReadGraph g, Modification change) throws DatabaseException {
493                         //filter floating point values that have less than 1% difference.
494                         if (change.getLeftStm() == null || change.getRightStm() == null)
495                                 return true;
496                         if (!g.hasValue(change.getLeftStm().getObject()) || !g.hasValue(change.getRightStm().getObject()))
497                                 return true;
498                 Object v1 = g.getValue(change.getLeftStm().getObject());
499                 Object v2 = g.getValue(change.getRightStm().getObject());
500                 
501                 if (v1 instanceof Double && v2 instanceof Double) {
502                         double d1 = (Double)v1;
503                         double d2 = (Double)v2;
504                         if (Math.abs(d1-d2) / Math.max(Math.abs(d1), Math.abs(d2)) < percentage)
505                                 return false;
506                 } else if (v1 instanceof Float && v2 instanceof Float) {
507                         float d1 = (Float)v1;
508                         float d2 = (Float)v2;
509                         if (Math.abs(d1-d2) / Math.max(Math.abs(d1), Math.abs(d2)) < percentage)
510                                 return false;
511                 }
512
513                 return true;
514                 }
515                 
516                 @Override
517                 public boolean acceptAddition(ReadGraph g, Statement addition) throws DatabaseException {
518                     return true;
519                 }
520                 
521                 @Override
522                 public boolean acceptDeletion(ReadGraph g, Statement deletion) throws DatabaseException {
523                     return true;
524                 }
525         }
526         
527         public void defaultSelections() {
528                 if (changes3 == null) {
529                         return;
530                 }
531                 // select all changes
532                 for (Entry<Resource, UpdateOp> op : updateTree.getUpdateOps().getResourceMap().entrySet()) {
533                         op.getValue().select(true);
534                 }
535                 
536                 
537                 for (PropertyChange pair : updateList.getChanges()) {
538                         pair.select(true);
539                 }
540                 
541                 // preserve user-made changes (by removing selections)
542                 for (Entry<Resource, UpdateOp> op : updateTree.getUpdateOps().getResourceMap().entrySet()) {
543                         UpdateOp op2 = updateTree2.getUpdateOps().getUpdateOp(op.getKey());
544                         if (op2 == null) {
545                                 if (changes3.getComparable().containsRight(op.getKey())){
546                                         op2 = updateTree2.getUpdateOps().getUpdateOp(changes3.getComparable().getLeft(op.getKey()));
547                                 }
548                         }
549                         if (op2 != null && op.getValue().getClass() == op2.getClass()) {
550                                 op.getValue().select(false);
551                         }
552                 }
553                 
554                 for (PropertyChange pair : updateList.getChanges()) {
555                         if (pair.getFirst() != null) {
556                                 boolean found = false;
557                                 for (PropertyChange pair2 : updateList2.getChanges()) {
558                                         if (pair.getFirst() != null && pair.getFirst().equals(pair2.getSecond())) {
559                                                 found = true;
560                                                 break;
561                                         }
562                                 }
563                                 if (found) {
564                                         pair.select(false);
565                                 }
566                         }
567                 }
568                 
569         }
570         
571         private void showWarning(String string) {
572                 for (WarningListener l : warningListeners)
573                         l.showWarning(this, string);
574         }
575         
576         private List<WarningListener> warningListeners = new ArrayList<>();
577         
578         public static interface WarningListener {
579                 void showWarning(ModelUpdate update, String warning);
580         }
581         
582         public void addListener(WarningListener listener) {
583                 warningListeners.add(listener);
584         }
585         
586         public void removeListener(WarningListener listener) {
587                 warningListeners.remove(listener);
588         }
589 }