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