]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network.ui/src/org/simantics/district/network/ui/function/Functions.java
Lots of changes to district stuff
[simantics/district.git] / org.simantics.district.network.ui / src / org / simantics / district / network / ui / function / Functions.java
1 package org.simantics.district.network.ui.function;
2
3 import java.util.Collections;
4 import java.util.HashMap;
5 import java.util.List;
6 import java.util.Map;
7 import java.util.stream.Collectors;
8
9 import org.eclipse.jface.dialogs.Dialog;
10 import org.eclipse.jface.layout.GridDataFactory;
11 import org.eclipse.swt.SWT;
12 import org.eclipse.swt.events.SelectionAdapter;
13 import org.eclipse.swt.events.SelectionEvent;
14 import org.eclipse.swt.layout.GridData;
15 import org.eclipse.swt.layout.GridLayout;
16 import org.eclipse.swt.widgets.Combo;
17 import org.eclipse.swt.widgets.Composite;
18 import org.eclipse.swt.widgets.Control;
19 import org.eclipse.swt.widgets.Group;
20 import org.eclipse.swt.widgets.Label;
21 import org.eclipse.swt.widgets.Shell;
22 import org.eclipse.ui.PlatformUI;
23 import org.eclipse.ui.dialogs.SelectionStatusDialog;
24 import org.simantics.NameLabelUtil;
25 import org.simantics.Simantics;
26 import org.simantics.browsing.ui.common.modifiers.EnumeratedValue;
27 import org.simantics.browsing.ui.common.modifiers.Enumeration;
28 import org.simantics.browsing.ui.graph.impl.GraphEnumerationModifier;
29 import org.simantics.databoard.Bindings;
30 import org.simantics.db.ReadGraph;
31 import org.simantics.db.Resource;
32 import org.simantics.db.Session;
33 import org.simantics.db.WriteGraph;
34 import org.simantics.db.common.request.IndexRoot;
35 import org.simantics.db.common.request.ReadRequest;
36 import org.simantics.db.common.request.WriteRequest;
37 import org.simantics.db.exception.DatabaseException;
38 import org.simantics.db.exception.RuntimeDatabaseException;
39 import org.simantics.db.exception.ServiceException;
40 import org.simantics.db.layer0.variable.Variable;
41 import org.simantics.db.layer0.variable.Variables.Role;
42 import org.simantics.db.procedure.Procedure;
43 import org.simantics.district.network.ontology.DistrictNetworkResource;
44 import org.simantics.layer0.Layer0;
45 import org.simantics.modeling.ModelingResources;
46 import org.simantics.modeling.ModelingUtils;
47 import org.simantics.modeling.adapters.NewCompositeActionFactory;
48 import org.simantics.modeling.typicals.TypicalUtil;
49 import org.simantics.scl.reflection.annotations.SCLValue;
50 import org.simantics.structural.stubs.StructuralResource2;
51 import org.simantics.ui.workbench.action.DefaultActions;
52 import org.simantics.utils.ui.SWTUtils;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 public class Functions {
57
58     private static final Logger LOGGER = LoggerFactory.getLogger(Functions.class);
59     
60     private Functions() {
61     }
62
63     private static class HasMappingEnumerationModifier extends GraphEnumerationModifier {
64
65         public HasMappingEnumerationModifier(Session session, Resource subject, Resource relation, Enumeration<Resource> enumeration, Resource value) {
66             super(session, subject, relation, enumeration, value);
67         }
68
69     }
70
71     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
72     public static Object defaultEdgeMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
73         Resource diagram = resolveElement(graph, context);
74         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
75         return baseMappingModifier(graph, diagram, DN.EdgeDefaultMapping, DN.Mapping_EdgeMapping, context);
76     }
77     
78     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
79     public static Object defaultVertexMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
80         System.out.println(graph.getURI(resource));
81         System.out.println(context.getURI(graph));
82         
83         Resource diagram = resolveElement(graph, context);
84         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
85         return baseMappingModifier(graph, diagram, DN.VertexDefaultMapping, DN.Mapping_VertexMapping, context);
86     }
87     
88     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
89     public static Object mappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
90         
91         Resource element = resolveElement(graph, context);
92         Resource mappingType = resolveMappingType(graph, element);
93         return baseMappingModifier(graph, element, DistrictNetworkResource.getInstance(graph).HasMapping, mappingType, context);
94     }
95
96     public static Map<String, Resource> getVertexMappings(ReadGraph graph, Resource resource) throws DatabaseException {
97         Map<String, Resource> second = getNetworkMappingsByType(graph, resource , DistrictNetworkResource.getInstance(graph).Mapping_VertexMapping);
98         return second;
99     }
100
101     public static Map<String, Resource> getEdgeMappings(ReadGraph graph, Resource resource) throws DatabaseException {
102         Map<String, Resource> second = getNetworkMappingsByType(graph, resource , DistrictNetworkResource.getInstance(graph).Mapping_EdgeMapping);
103         return second;
104     }
105     
106     public static Map<String, Resource> getCRSs(ReadGraph graph, Resource resource) throws DatabaseException {
107         Map<String, Resource> result = getNetworkMappingsByType(graph, resource, DistrictNetworkResource.getInstance(graph).SpatialRefSystem);
108         return result;
109         
110     }
111
112     public static Map<String, Resource> getNetworkMappingsByType(ReadGraph graph, Resource element, Resource mappingType) throws DatabaseException {
113         Resource indexRoot = graph.sync(new IndexRoot(element));
114         List<Resource> mappings = ModelingUtils.searchByType(graph, indexRoot, mappingType);
115         Map<String, Resource> result = new HashMap<>(mappings.size());
116         Layer0 L0 = Layer0.getInstance(graph);
117         mappings.forEach(mapping -> {
118             try {
119                 String name = graph.getRelatedValue2(mapping, L0.HasName);
120                 result.put(name, mapping);
121             } catch (DatabaseException e) {
122                 e.printStackTrace();
123             }
124         });
125         return result;
126     }
127     
128     private static Object baseMappingModifier(ReadGraph graph, Resource element, Resource property, Resource mappingType, Variable context) throws DatabaseException {
129         Resource indexRoot = graph.sync(new IndexRoot(element));
130         List<Resource> mappings = ModelingUtils.searchByType(graph, indexRoot, mappingType);
131         Enumeration<Resource> enums = Enumeration
132                 .make(mappings.stream().map(m -> createEnumeratedValue(graph, m)).collect(Collectors.toList()));
133         
134         Resource currentMapping = graph.getSingleObject(element, property);
135         
136         return new HasMappingEnumerationModifier(Simantics.getSession(), element, property, enums, currentMapping);
137     }
138     
139     private static Resource resolveMappingType(ReadGraph graph, Resource element) throws DatabaseException {
140         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
141         if (graph.isInstanceOf(element, DN.Edge))
142             return DN.Mapping_EdgeMapping;
143         else if (graph.isInstanceOf(element, DN.Vertex))
144             return DN.Mapping_VertexMapping;
145         throw new IllegalStateException("No mapping type found for element " + element + " : " + graph.getPossibleURI(element));
146     }
147
148     private static Resource resolveElement(ReadGraph graph, Variable variable) throws DatabaseException {
149         Role role = variable.getPossibleRole(graph);
150         if (role.equals(Role.PROPERTY))
151             return resolveElement(graph, variable.getParent(graph));
152         else
153             return variable.getRepresents(graph);
154     }
155
156     private static EnumeratedValue<Resource> createEnumeratedValue(ReadGraph graph, Resource resource) {
157         try {
158             String label = NameLabelUtil.modalName(graph, resource);
159             return new EnumeratedValue<Resource>(label, resource);
160         } catch (DatabaseException e) {
161             throw new RuntimeDatabaseException(e);
162         }
163     }
164     
165     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
166     public static Object enumerationValues(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
167         Variable var = (Variable) context;
168         System.out.println(graph.getURI(resource));
169         System.out.println(var.getURI(graph));
170         return Collections.emptyList();
171     }
172     
173     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
174     public static Object convertToValue(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
175         return graph.getRelatedValue2(resource, Layer0.getInstance(graph).HasName, Bindings.STRING);
176 //        return null;
177     }
178     
179     
180     @SCLValue(type = "Resource -> String -> Resource -> Resource")
181     public static Resource compositeInstantiator(final Resource compositeType, final String defaultName, final Resource target) throws DatabaseException {
182         
183         return TypicalUtil.syncExec(procedure -> {
184             if (!SWTUtils.asyncExec(PlatformUI.getWorkbench().getDisplay(), () -> {
185                 try {
186                     queryInitialValuesAndCreateComposite(compositeType, target, defaultName, procedure);
187                 } catch (Throwable t) {
188                     procedure.exception(t);
189                 }
190             })) {
191                 procedure.execute(null);
192             }
193         });
194     }
195
196     private static class DefaultMappingsDialog extends SelectionStatusDialog {
197
198         private Combo vertexMappingCombo;
199         private Combo edgeMappingCombo;
200         private Combo crsCombo;
201         private Composite composite;
202         
203         private Resource configuration;
204         private Map<String, Resource> vertexMappings = new HashMap<>();
205         private Map<String, Resource> edgeMappings = new HashMap<>();
206         private Map<String, Resource> composites = new HashMap<>();
207         private Map<String, Resource> crss = new HashMap<>();
208         private Map<String, Map<String, Resource>> components = new HashMap<>();
209         
210         private Resource defaultVertexMapping;
211         private Resource defaultEdgeMapping;
212         private Resource defaultCRS;
213         
214         private Combo compositeMappingCombo;
215         private Combo componentMappingCombo;
216
217         protected DefaultMappingsDialog(Shell parentShell, Resource configuration) {
218             super(parentShell);
219             this.configuration = configuration;
220             setTitle("Select mappings for new DN diagram");
221         }
222
223         public Resource getDefaultVertexMapping() {
224             return defaultVertexMapping;
225         }
226
227         public Resource getDefaultEdgeMapping() {
228             return defaultEdgeMapping;
229         }
230
231         @Override
232         protected Control createDialogArea(Composite parent) {
233             composite = (Composite) super.createDialogArea(parent);
234             
235             createMappingsGroup(composite);
236             createExistingCompositeGroup(composite);
237             createCRSSettingsGroup(composite);
238             
239             // compute default values
240             Simantics.getSession().asyncRequest(new ReadRequest() {
241
242                 @Override
243                 public void run(ReadGraph graph) throws DatabaseException {
244                     
245                     vertexMappings = getVertexMappings(graph, configuration);
246                     edgeMappings = getEdgeMappings(graph, configuration);
247                     
248                     composites = getComposites(graph, configuration);
249                     if (composites.size() > 0) {
250                         components = getComponents(graph, composites.get(0));
251                     }
252                     
253                     crss = getCRSs(graph, configuration);
254                     
255                     composite.getDisplay().asyncExec(() -> {
256                         
257                         vertexMappingCombo.setItems(vertexMappings.keySet().toArray(new String[vertexMappings.size()]));
258                         edgeMappingCombo.setItems(edgeMappings.keySet().toArray(new String[edgeMappings.size()]));
259                         
260                         crsCombo.setItems(crss.keySet().toArray(new String[crss.size()]));
261                         
262                         compositeMappingCombo.setItems(composites.keySet().toArray(new String[composites.size()]));
263                         vertexMappingCombo.select(0);
264                         edgeMappingCombo.select(0);
265                         
266                         crsCombo.select(0);
267                         
268                         if (!composites.isEmpty())
269                             compositeMappingCombo.select(0);
270                     }); 
271                     
272                 }
273             });
274             return composite;
275         }
276         
277         protected Map<String, Map<String, Resource>> getComponents(ReadGraph graph, Resource resource) {
278             // TODO Auto-generated method stub
279             return null;
280         }
281
282         protected Map<String, Resource> getComposites(ReadGraph graph, Resource element) throws DatabaseException {
283             Resource indexRoot = graph.sync(new IndexRoot(element));
284             List<Resource> composites = ModelingUtils.searchByType(graph, indexRoot, StructuralResource2.getInstance(graph).Composite);
285             List<Resource> nonDistrictComposites = composites.stream().filter(comp -> {
286                 try {
287                     return !graph.isInstanceOf(comp, DistrictNetworkResource.getInstance(graph).Composite);
288                 } catch (ServiceException e1) {
289                     LOGGER.error("Could not check if composite " + comp + " is instanceOf DistrictNetwork.composite");
290                     return false;
291                 }
292             }).collect(Collectors.toList());
293             Map<String, Resource> result = new HashMap<>(nonDistrictComposites.size());
294             Layer0 L0 = Layer0.getInstance(graph);
295             nonDistrictComposites.forEach(mapping -> {
296                 try {
297                     String name = graph.getRelatedValue2(mapping, L0.HasName);
298                     result.put(name, mapping);
299                 } catch (DatabaseException e) {
300                     e.printStackTrace();
301                 }
302             });
303             return result;
304         }
305
306         private void createMappingsGroup(Composite parent) {
307             Group group= new Group(parent, SWT.NONE);
308             group.setFont(parent.getFont());
309             group.setText("Default mappings");
310             GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
311             group.setLayout(new GridLayout(1, false));
312             
313             Composite cmposite = new Composite(group, SWT.NONE);
314             cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
315             cmposite.setLayout(new GridLayout(2, false));
316             
317             Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
318             vertexMappingLabel.setText("Default vertex mapping");
319
320             vertexMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
321             GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
322             
323             Label edgeMappingLabel = new Label(cmposite, SWT.NONE);
324             edgeMappingLabel.setText("Default edge mapping");
325
326             edgeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
327             GridDataFactory.fillDefaults().grab(true, false).applyTo(edgeMappingCombo);
328         }
329         
330         private void createExistingCompositeGroup(Composite parent) {
331             Group group= new Group(parent, SWT.NONE);
332             group.setFont(parent.getFont());
333             group.setText("Mapped composite");
334             GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
335             group.setLayout(new GridLayout(1, false));
336             
337             Composite cmposite = new Composite(group, SWT.NONE);
338             cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
339             cmposite.setLayout(new GridLayout(2, false));
340             
341             Label compositeMappingLabel = new Label(cmposite, SWT.NONE);
342             compositeMappingLabel.setText("Select composite");
343
344             compositeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
345             GridDataFactory.fillDefaults().grab(true, false).applyTo(compositeMappingCombo);
346             compositeMappingCombo.addSelectionListener(new SelectionAdapter() {
347                 
348                 @Override
349                 public void widgetSelected(SelectionEvent e) {
350                     super.widgetSelected(e);
351                     recalculateMappapleComponents();
352                 }
353             });
354             
355             Label compojnentMappingLabel = new Label(cmposite, SWT.NONE);
356             compojnentMappingLabel.setText("Select component");
357             
358             componentMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
359             GridDataFactory.fillDefaults().grab(true, false).applyTo(componentMappingCombo);
360         }
361         
362         protected void recalculateMappapleComponents() {
363             Simantics.getSession().asyncRequest(new ReadRequest() {
364                 
365                 @Override
366                 public void run(ReadGraph graph) throws DatabaseException {
367                     
368                     
369                     composite.getDisplay().asyncExec(() -> {
370                         
371                     }); 
372                 }
373             });
374         }
375
376         private void createCRSSettingsGroup(Composite parent) {
377             Group group= new Group(parent, SWT.NONE);
378             group.setFont(parent.getFont());
379             group.setText("CRS settings");
380             GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
381             group.setLayout(new GridLayout(1, false));
382             
383             Composite cmposite = new Composite(group, SWT.NONE);
384             cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
385             cmposite.setLayout(new GridLayout(2, false));
386             
387             Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
388             vertexMappingLabel.setText("Default CRS");
389
390             crsCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
391             GridData textData = new GridData(SWT.FILL, SWT.CENTER, true, false);
392             crsCombo.setLayoutData(textData);
393         }
394         
395
396         @Override
397         protected void computeResult() {
398             defaultVertexMapping = vertexMappings.get(vertexMappingCombo.getItem(vertexMappingCombo.getSelectionIndex()));
399             defaultEdgeMapping = edgeMappings.get(edgeMappingCombo.getItem(edgeMappingCombo.getSelectionIndex()));
400             defaultCRS = crss.get(crsCombo.getItem(crsCombo.getSelectionIndex()));
401         }
402
403         public Resource getCRS() {
404             return defaultCRS;
405         }
406         
407     }
408     
409     private static void queryInitialValuesAndCreateComposite(final Resource compositeType, final Resource target,
410             String defaultName, final Procedure<Resource> procedure) {
411         DefaultMappingsDialog dialog = new DefaultMappingsDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), target);
412
413         if (dialog.open() != Dialog.OK) {
414             procedure.execute(null);
415             return;
416         }
417         Simantics.getSession().asyncRequest(
418                 NewCompositeActionFactory.createCompositeRequest(target, defaultName, compositeType),
419                 new Procedure<Resource>() {
420                     @Override
421                     public void execute(Resource composite) {
422                         Simantics.getSession().asyncRequest(new WriteRequest() {
423                             
424                             @Override
425                             public void perform(WriteGraph graph) throws DatabaseException {
426                                 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
427                                 Resource diagram = graph.getSingleObject(composite, ModelingResources.getInstance(graph).CompositeToDiagram);
428                                 graph.claim(diagram, DN.EdgeDefaultMapping, dialog.getDefaultEdgeMapping());
429                                 graph.claim(diagram, DN.VertexDefaultMapping, dialog.getDefaultVertexMapping());
430                                 graph.claim(diagram, DN.HasSpatialRefSystem, dialog.getCRS());
431                             }
432                         });
433                         DefaultActions.asyncPerformDefaultAction(Simantics.getSession(), composite, false, false, true);
434                         procedure.execute(composite);
435                     }
436
437                     @Override
438                     public void exception(Throwable t) {
439                         LOGGER.error("Failed to create composite, see exception for details.", t);
440                         procedure.exception(t);
441                     }
442                 });
443     }
444 }