Guard graph SCL module compilation
[simantics/platform.git] / bundles / org.simantics.modeling / src / org / simantics / modeling / scl / GraphModuleSourceRepository.java
1 package org.simantics.modeling.scl;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5
6 import org.simantics.Simantics;
7 import org.simantics.db.ReadGraph;
8 import org.simantics.db.Resource;
9 import org.simantics.db.WriteGraph;
10 import org.simantics.db.common.request.UnaryRead;
11 import org.simantics.db.common.request.WriteRequest;
12 import org.simantics.db.exception.DatabaseException;
13 import org.simantics.db.procedure.SyncListener;
14 import org.simantics.db.request.Read;
15 import org.simantics.db.request.ReadExt;
16 import org.simantics.db.request.RequestFlags;
17 import org.simantics.layer0.Layer0;
18 import org.simantics.modeling.ModelingUtils;
19 import org.simantics.modeling.internal.Activator;
20 import org.simantics.modeling.scl.ontologymodule.OntologyModuleSourceRepository;
21 import org.simantics.scl.compiler.internal.codegen.types.JavaReferenceValidatorFactory;
22 import org.simantics.scl.compiler.module.repository.UpdateListener;
23 import org.simantics.scl.compiler.module.repository.UpdateListener.Observable;
24 import org.simantics.scl.compiler.source.ModuleSource;
25 import org.simantics.scl.compiler.source.StringModuleSource;
26 import org.simantics.scl.compiler.source.repository.ModuleSourceRepository;
27 import org.simantics.scl.osgi.internal.OsgiJavaReferenceValidatorFactory;
28 import org.simantics.scl.runtime.SCLContext;
29 import org.simantics.scl.runtime.tuple.Tuple0;
30 import org.simantics.structural2.utils.StructuralUtils;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import gnu.trove.procedure.TObjectProcedure;
35 import gnu.trove.set.hash.THashSet;
36
37 public enum GraphModuleSourceRepository implements ModuleSourceRepository {
38     INSTANCE; 
39     
40     private static final Logger LOGGER = LoggerFactory.getLogger(OntologyModuleSourceRepository.class);
41
42     private static final OsgiJavaReferenceValidatorFactory REFERENCE_VALIDATOR_FACTORY = new OsgiJavaReferenceValidatorFactory(Activator.getContext().getBundle());
43
44     @Override
45     public ModuleSource getModuleSource(final String moduleName, UpdateListener listener) {
46         if(!moduleName.startsWith("http://"))
47             return null; // Don't do a graph request if this cannot be a resource
48
49         Read<ModuleSource> request = new ReadModuleSource(moduleName);
50
51         try {
52             if(listener != null)
53                 return Simantics.getAvailableRequestProcessor().syncRequest(request, new ModuleListener(listener, moduleName));
54             else
55                 return Simantics.getAvailableRequestProcessor().syncRequest(request);
56         } catch (DatabaseException e) {
57             LOGGER.error("Failed to read graph module {}.",  moduleName, e);
58             return null;
59         }
60     }
61
62     static class ModuleListener implements SyncListener<ModuleSource>, Observable {
63         UpdateListener listener;
64         boolean alreadyExecutedOnce;
65         final String moduleName;
66         public ModuleListener(UpdateListener listener, String moduleName) {
67             this.listener = listener;
68             this.listener.addObservable(this);
69             this.moduleName = moduleName;
70         }
71         @Override
72         public void removeListener(UpdateListener listener) {
73             this.listener = null;
74         }
75         @Override
76         public boolean isDisposed() {
77             return listener == null;
78         }
79         private void fireUpdate(ReadGraph graph) {
80             if(listener != null) {
81                 SCLContext context = SCLContext.getCurrent();
82                 Object oldGraph = context.put("graph", graph);
83                 try {
84                     listener.notifyAboutUpdate();
85                 } finally {
86                     listener = null;
87                     context.put("graph", oldGraph);
88                 }
89             }
90         }
91         @Override
92         public void execute(ReadGraph graph, ModuleSource result)
93                 throws DatabaseException {
94             if(alreadyExecutedOnce)
95                 fireUpdate(graph);
96             else
97                 alreadyExecutedOnce = true;
98         }
99         @Override
100         public void exception(ReadGraph graph, Throwable t)
101                 throws DatabaseException {
102             LOGGER.error("Could not listen {}", this, t);
103             if(alreadyExecutedOnce && listener != null)
104                 fireUpdate(graph);
105         }
106
107         @Override
108         public String toString() {
109             return moduleName + " " + listener + " (" + alreadyExecutedOnce + ") [" + getClass().toString() + "]";
110         }
111     };
112     
113     public static class GraphModuleSource extends StringModuleSource {
114
115         private final boolean immutable;
116
117         public GraphModuleSource(String moduleName, ClassLoader classLoader, String moduleText, boolean immutable) {
118             super(moduleName, classLoader, moduleText);
119             this.immutable = immutable;
120         }
121         
122         @Override
123         public boolean isUpdateable() {
124             return !immutable;
125         }
126         
127         @Override
128         public void update(String newSourceText) {
129             try {
130                 Simantics.getSession().syncRequest(new WriteModuleSource(getModuleName(), newSourceText));
131             } catch (DatabaseException e) {
132                 LOGGER.error("Could not update {} with newSourceText {}", this, newSourceText);
133             }
134         }
135         
136         @Override
137         public JavaReferenceValidatorFactory getJavaReferenceValidatorFactory() {
138             return REFERENCE_VALIDATOR_FACTORY;
139         }
140     }
141
142     static class PossibleResourceIU extends UnaryRead<String,Resource> implements ReadExt {
143
144         public PossibleResourceIU(String parameter) {
145             super(parameter);
146         }
147
148         @Override
149         public Resource perform(ReadGraph graph) throws DatabaseException {
150             return graph.getPossibleResource(parameter);
151         }
152
153         @Override
154         public boolean isImmutable(ReadGraph graph) throws DatabaseException {
155             return false;
156         }
157
158         @Override
159         public int getType() {
160             return RequestFlags.IMMEDIATE_UPDATE;
161         }
162         
163     }
164     
165     static class ReadModuleSource extends UnaryRead<String, ModuleSource> {
166         public ReadModuleSource(String moduleName) {
167             super(moduleName);
168         }
169
170         @Override
171         public ModuleSource perform(ReadGraph graph) throws DatabaseException {
172             Resource moduleResource = graph.syncRequest(new PossibleResourceIU(parameter));
173             if(moduleResource == null)
174                 return null;
175             Layer0 L0 = Layer0.getInstance(graph);
176             if(!graph.isInstanceOf(moduleResource, L0.SCLModule))
177                 return null;
178             String text = graph.getRelatedValue(moduleResource, L0.SCLModule_definition);
179             boolean immutable = StructuralUtils.isImmutable(graph, moduleResource);
180             return new GraphModuleSource(parameter, getClass().getClassLoader(), text, immutable);
181         }
182     }
183     
184     static class WriteModuleSource extends WriteRequest {
185         private final String moduleURI;
186         private final String sourceText;
187         
188         public WriteModuleSource(String moduleURI, String sourceText) {
189             this.moduleURI = moduleURI;
190             this.sourceText = sourceText;
191         }
192
193         @Override
194         public void perform(WriteGraph graph) throws DatabaseException {
195             Resource moduleResource = graph.getPossibleResource(moduleURI);
196             if(moduleResource == null)
197                 return;
198             Layer0 L0 = Layer0.getInstance(graph);
199             if(!graph.isInstanceOf(moduleResource, L0.SCLModule))
200                 return;
201             graph.claimLiteral(moduleResource, L0.SCLModule_definition, sourceText);
202         }
203     }
204
205     private THashSet<String> getAllModules(ReadGraph graph) throws DatabaseException {
206         THashSet<String> result = new THashSet<String>(); 
207         Resource projectResource = Simantics.getProjectResource();
208         Layer0 L0 = Layer0.getInstance(graph);
209         for(Resource model : graph.getObjects(projectResource, L0.ConsistsOf)) {
210             if(graph.isInstanceOf(model, L0.IndexRoot)) {
211                 for(Resource module : ModelingUtils.searchByType(graph, model, L0.SCLModule))
212                     result.add(graph.getURI(module));
213             }
214         }
215         
216         Collection<Resource> ontologies = Simantics.applySCL("Simantics/SharedOntologies", "getSharedOntologies", graph, Tuple0.INSTANCE);
217         for (Resource ontology : ontologies) {
218             for(Resource module : ModelingUtils.searchByType(graph, ontology, L0.SCLModule))
219                 try {
220                     result.add(graph.getURI(module));
221                 } catch(DatabaseException e) {
222                     LOGGER.error("Failed to find uri for " + module + ".");
223                 }
224         }
225         
226         return result;
227     }
228     
229     @Override
230     public void forAllModules(TObjectProcedure<String> procedure) {
231         THashSet<String> moduleURIs = null;
232         try {
233             moduleURIs = Simantics.getAvailableRequestProcessor().syncRequest(new Read<THashSet<String>>() {
234                 @Override
235                 public THashSet<String> perform(ReadGraph graph)
236                         throws DatabaseException {
237                     return getAllModules(graph);
238                 }
239             });
240             moduleURIs.forEach(procedure);
241         } catch (DatabaseException e) {
242             LOGGER.error("Could not execute procedure {} for all modules {}", procedure, String.valueOf(moduleURIs), e);
243         }
244     }
245     
246     @Override
247     public Collection<String> getModuleNames() {
248         ArrayList<String> result = new ArrayList<>();
249         forAllModules((String name) -> {
250             result.add(name);
251             return true;
252         });
253         return result;
254     }
255 }