Don't recompile all expressions if only one is modified
[simantics/platform.git] / bundles / org.simantics.modeling / src / org / simantics / modeling / scl / issue / SCLExpressionIssueProvider.java
1 package org.simantics.modeling.scl.issue;
2
3 import java.util.ArrayList;
4 import java.util.HashSet;
5 import java.util.List;
6 import java.util.Objects;
7 import java.util.Set;
8 import java.util.TreeSet;
9 import java.util.concurrent.ConcurrentHashMap;
10
11 import org.eclipse.jface.viewers.StructuredSelection;
12 import org.eclipse.swt.widgets.Display;
13 import org.eclipse.swt.widgets.Shell;
14 import org.simantics.Simantics;
15 import org.simantics.db.Disposable;
16 import org.simantics.db.ReadGraph;
17 import org.simantics.db.Resource;
18 import org.simantics.db.common.procedure.adapter.DisposableListener;
19 import org.simantics.db.common.procedure.adapter.DisposableSyncListener;
20 import org.simantics.db.common.procedure.adapter.SyncListenerAdapter;
21 import org.simantics.db.common.request.TernaryRead;
22 import org.simantics.db.common.request.UnaryRead;
23 import org.simantics.db.common.request.UniqueRead;
24 import org.simantics.db.exception.DatabaseException;
25 import org.simantics.db.layer0.util.Layer0Utils;
26 import org.simantics.db.layer0.variable.Variable;
27 import org.simantics.db.layer0.variable.Variables;
28 import org.simantics.layer0.Layer0;
29 import org.simantics.modeling.ModelingUtils;
30 import org.simantics.scl.compiler.errors.CompilationError;
31 import org.simantics.scl.compiler.errors.Locations;
32 import org.simantics.scl.osgi.issues.SCLIssueProviderFactory;
33 import org.simantics.scl.osgi.issues.SCLIssueProviderFactory.SCLIssueProvider;
34 import org.simantics.scl.osgi.issues.SCLIssuesTableEntry;
35 import org.simantics.scl.runtime.SCLContext;
36 import org.simantics.scl.runtime.function.Function1;
37 import org.simantics.structural.stubs.StructuralResource2;
38 import org.simantics.ui.workbench.action.DefaultActions;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public class SCLExpressionIssueProvider implements SCLIssueProvider {
43
44     public static class SCLExpressionIssueProviderFactory implements SCLIssueProviderFactory {
45
46         @Override
47         public SCLIssueProvider getSCLIssueProvider() {
48             return new SCLExpressionIssueProvider();
49         }
50
51     }
52
53     private static final Logger LOGGER = LoggerFactory.getLogger(SCLExpressionIssueProvider.class);
54     private boolean disposed = false;
55     private ComponentSyncListenerAdapter listener;
56
57     SCLExpressionIssueProvider() {
58     }
59
60     @Override
61     public void listenIssues(Runnable callback) {
62         listener = new ComponentSyncListenerAdapter(callback);
63         Simantics.getSession().asyncRequest(new ComponentRequest(), listener);
64     }
65
66     @Override
67     public List<SCLIssuesTableEntry> getIssues() {
68         return listener.getIssues();
69     }
70
71     @Override
72     public void dispose() {
73         listener.dispose();
74         disposed = true;
75     }
76
77     private static void openResource(Shell shell, Resource resource) {
78         DefaultActions.performDefaultAction(shell, new StructuredSelection(resource));
79     }
80
81     private static class ComponentRequest extends UniqueRead<Set<Resource>> {
82
83         @Override
84         public Set<Resource> perform(ReadGraph graph) throws DatabaseException {
85             Layer0 L0 = Layer0.getInstance(graph);
86             Set<Resource> indexRoots = new TreeSet<Resource>();
87             for(Resource ontology : Layer0Utils.listOntologies(graph)) {
88                 if (graph.isInstanceOf(ontology, L0.SharedOntology)) {
89                     indexRoots.add(ontology);
90                 }
91             }
92
93             for(Resource child : graph.getObjects(Simantics.getProjectResource(), L0.ConsistsOf)) {
94                 if (graph.isInstanceOf(child, L0.IndexRoot)) {
95                     indexRoots.add(child);
96                 }
97             }
98
99             StructuralResource2 STR = StructuralResource2.getInstance(graph);
100
101             Set<Resource> allComponents = new HashSet<>();
102             for (Resource ontology : indexRoots) {
103                 List<Resource> components = ModelingUtils.searchByTypeShallow(graph, ontology, STR.Component);
104                 allComponents.addAll(components);
105             }
106             return allComponents;
107         }
108     }
109     
110     private static class SCLValueRequest extends UnaryRead<Resource, Set<ResourceHolder>> {
111
112         public SCLValueRequest(Resource parameter) {
113             super(parameter);
114         }
115
116         @Override
117         public Set<ResourceHolder> perform(ReadGraph graph) throws DatabaseException {
118             Layer0 L0 = Layer0.getInstance(graph);
119             Set<ResourceHolder> results = new HashSet<>();
120             for (Resource predicate : graph.getPredicates(parameter)) {
121                 if (graph.isSubrelationOf(predicate, L0.HasProperty)) {
122                     for (Resource object : graph.getObjects(parameter, predicate)) {
123                         if (graph.isInstanceOf(object, L0.SCLValue)) {
124                             results.add(new ResourceHolder(parameter, predicate, object));
125                         }
126                     }
127                 }
128             }
129             return results;
130         }
131     }
132     
133     private static class SCLExpressionValidationRequest extends TernaryRead<Resource, Resource, Resource, SCLIssuesTableEntry> {
134
135         public SCLExpressionValidationRequest(Resource component, Resource predicate, Resource object) {
136             super(component, predicate, object);
137         }
138
139         @Override
140         public SCLIssuesTableEntry perform(ReadGraph graph) throws DatabaseException {
141             Resource type = graph.getPossibleType(parameter3, Layer0.getInstance(graph).SCLValue);
142             if (type == null) {
143                 return null;
144             }
145             if (!graph.hasStatement(parameter))
146                 return null;
147             
148             Variable componentVariable = Variables.getVariable(graph, parameter);
149             Variable propertyVariable = componentVariable.getProperty(graph, parameter2);
150             
151             Variable typeVariable = Variables.getVariable(graph, type);
152
153             Function1<Variable, String> func = typeVariable.getPossiblePropertyValue(graph, "validator");
154             if (func == null) {
155                 // No validator available
156                 if (LOGGER.isTraceEnabled())
157                     LOGGER.trace("No validator available for " + typeVariable.getURI(graph));
158                 return null;
159             }
160
161             SCLContext sclContext = SCLContext.getCurrent();
162             Object oldGraph = sclContext.get("graph");
163             try {
164                 sclContext.put("graph", graph);
165                 String validatorValue = func.apply(propertyVariable);
166                 if (validatorValue != null && !validatorValue.isEmpty()) {
167                     return new SCLIssuesTableEntry(propertyVariable.getURI(graph), new CompilationError(Locations.NO_LOCATION, validatorValue.replace("\n", " "))) {
168                         @Override
169                         public void openLocation() {
170                             openResource(Display.getCurrent().getActiveShell(), parameter);
171                         }
172                     };
173                 }
174             } catch (Throwable t) {
175                 LOGGER.error("Failed to invoke type validator function " + func, t);
176             } finally {
177                 sclContext.put("graph", oldGraph);
178             }
179             return null;
180         }
181     }
182     
183     private static class ComponentSyncListenerAdapter extends SyncListenerAdapter<Set<Resource>> implements Disposable {
184
185         private ConcurrentHashMap<Resource, SCLValueDisposableSyncListener> currentlyListening = new ConcurrentHashMap<>();
186         private boolean disposed;
187         private Runnable callback;
188         
189         public ComponentSyncListenerAdapter(Runnable callback) {
190             this.callback = callback;
191         }
192         
193         @Override
194         public void execute(ReadGraph graph, Set<Resource> newComponents) {
195             if (currentlyListening.isEmpty() && newComponents.isEmpty()) {
196                 // we can stop here as nothing will change
197                 return;
198             }
199             
200             Set<Resource> removedComponents = new HashSet<>(currentlyListening.keySet());
201             removedComponents.removeAll(newComponents);
202             
203             Set<Resource> addedComponents = new HashSet<>(newComponents);
204             addedComponents.removeAll(currentlyListening.keySet());
205             
206             for (Resource removedComponent : removedComponents) {
207                 // stop listening
208                 DisposableSyncListener<?> listener = currentlyListening.remove(removedComponent);
209                 listener.dispose();
210             }
211             
212             for (Resource addedComponent : addedComponents) {
213                 SCLValueDisposableSyncListener listener = new SCLValueDisposableSyncListener(callback);
214                 currentlyListening.put(addedComponent, listener);
215                 graph.asyncRequest(new SCLValueRequest(addedComponent), listener);
216             }
217         }
218         
219         public List<SCLIssuesTableEntry> getIssues() {
220             List<SCLIssuesTableEntry> issues = new ArrayList<>();
221             for (SCLValueDisposableSyncListener listener : currentlyListening.values()) {
222                 List<SCLIssuesTableEntry> listenerIssues = listener.getIssues();
223                 if (listenerIssues != null && !listenerIssues.isEmpty())
224                     issues.addAll(listenerIssues);
225             }
226             return issues;
227         }
228         
229         @Override
230         public void dispose() {
231             currentlyListening.values().forEach(l -> l.dispose());
232             currentlyListening.clear();
233             this.disposed = true;
234         }
235         
236         @Override
237         public boolean isDisposed() {
238             return disposed;
239         }
240     }
241     
242     private static class SCLValueDisposableSyncListener extends DisposableSyncListener<Set<ResourceHolder>> {
243
244         private Runnable callback;
245         private ConcurrentHashMap<ResourceHolder, SCLIssuesTableEntryDisposableListener> currentlyListeningSCLValues = new ConcurrentHashMap<>();
246         
247         public SCLValueDisposableSyncListener(Runnable callback) {
248             this.callback = callback;
249         }
250         
251         @Override
252         public void execute(ReadGraph graph, Set<ResourceHolder> newComponents) throws DatabaseException {
253             if (currentlyListeningSCLValues.isEmpty() && newComponents.isEmpty()) {
254                 // we can stop here as nothing will change
255                 return;
256             }
257             
258             
259             Set<ResourceHolder> removedComponents = new HashSet<>(currentlyListeningSCLValues.keySet());
260             removedComponents.removeAll(newComponents);
261             
262             Set<ResourceHolder> addedComponents = new HashSet<>(newComponents);
263             addedComponents.removeAll(currentlyListeningSCLValues.keySet());
264             
265             for (ResourceHolder removedComponent : removedComponents) {
266                 // stop listening
267                 DisposableListener<?> listener = currentlyListeningSCLValues.remove(removedComponent);
268                 listener.dispose();
269             }
270             
271             for (ResourceHolder sclValue : addedComponents) {
272                 SCLIssuesTableEntryDisposableListener listener = new SCLIssuesTableEntryDisposableListener(callback);
273                 currentlyListeningSCLValues.put(sclValue, listener);
274                 graph.syncRequest(new SCLExpressionValidationRequest(sclValue.component, sclValue.predicate, sclValue.object), listener);
275             }
276             if (callback != null) {
277                 callback.run();
278             }
279         }
280
281         public List<SCLIssuesTableEntry> getIssues() {
282             if (currentlyListeningSCLValues.isEmpty())
283                 return null;
284             List<SCLIssuesTableEntry> issues = new ArrayList<>();
285             for (SCLIssuesTableEntryDisposableListener listener : currentlyListeningSCLValues.values()) {
286                 if (listener.getResult() != null)
287                     issues.add(listener.getResult());
288             }
289             return issues;
290         }
291
292         @Override
293         public void exception(ReadGraph graph, Throwable throwable) throws DatabaseException {
294             LOGGER.error("Could not listen", throwable);
295         }
296         
297         @Override
298         public void dispose() {
299             currentlyListeningSCLValues.values().forEach(l -> l.dispose());
300             currentlyListeningSCLValues.clear();
301             super.dispose();
302         }
303         
304     }
305     
306     private static class SCLIssuesTableEntryDisposableListener extends DisposableListener<SCLIssuesTableEntry> {
307
308         private SCLIssuesTableEntry result;
309         private Runnable callback;
310         
311         public SCLIssuesTableEntryDisposableListener(Runnable callback) {
312             this.callback = callback;
313         }
314         
315         @Override
316         public void execute(SCLIssuesTableEntry result) {
317             if (!Objects.equals(this.result, result)) {
318                 this.result = result;
319                 if (callback != null) {
320                     callback.run();
321                 }
322             }
323         }
324
325         @Override
326         public void exception(Throwable t) {
327             LOGGER.error("", t);
328         }
329         
330         public SCLIssuesTableEntry getResult() {
331             return result;
332         }
333     }
334     
335     private static class ResourceHolder {
336
337         Resource component;
338         Resource predicate;
339         Resource object;
340         
341         public ResourceHolder(Resource component, Resource predicate, Resource object) {
342             this.component = Objects.requireNonNull(component);
343             this.predicate = Objects.requireNonNull(predicate);
344             this.object = Objects.requireNonNull(object);
345         }
346
347         @Override
348         public int hashCode() {
349             final int prime = 31;
350             int result = 1;
351             result = prime * result + component.hashCode();
352             result = prime * result + object.hashCode();
353             result = prime * result + predicate.hashCode();
354             return result;
355         }
356
357         @Override
358         public boolean equals(Object obj) {
359             if (this == obj)
360                 return true;
361             if (obj == null)
362                 return false;
363             if (getClass() != obj.getClass())
364                 return false;
365             ResourceHolder other = (ResourceHolder) obj;
366             if (!component.equals(other.component))
367                 return false;
368             if (!object.equals(other.object))
369                 return false;
370             if (!predicate.equals(other.predicate))
371                 return false;
372             return true;
373         }
374
375     }
376 }