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