]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network.ui/src/org/simantics/district/network/ui/function/Functions.java
016a1420dba6a4a8b5588c4e8e4a7735633f2ae2
[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.layout.GridData;
13 import org.eclipse.swt.layout.GridLayout;
14 import org.eclipse.swt.widgets.Combo;
15 import org.eclipse.swt.widgets.Composite;
16 import org.eclipse.swt.widgets.Control;
17 import org.eclipse.swt.widgets.Group;
18 import org.eclipse.swt.widgets.Label;
19 import org.eclipse.swt.widgets.Shell;
20 import org.eclipse.ui.PlatformUI;
21 import org.eclipse.ui.dialogs.SelectionStatusDialog;
22 import org.simantics.NameLabelUtil;
23 import org.simantics.Simantics;
24 import org.simantics.browsing.ui.common.modifiers.EnumeratedValue;
25 import org.simantics.browsing.ui.common.modifiers.Enumeration;
26 import org.simantics.browsing.ui.graph.impl.GraphEnumerationModifier;
27 import org.simantics.databoard.Bindings;
28 import org.simantics.db.ReadGraph;
29 import org.simantics.db.Resource;
30 import org.simantics.db.Session;
31 import org.simantics.db.WriteGraph;
32 import org.simantics.db.common.request.IndexRoot;
33 import org.simantics.db.common.request.ReadRequest;
34 import org.simantics.db.common.request.WriteRequest;
35 import org.simantics.db.exception.DatabaseException;
36 import org.simantics.db.exception.RuntimeDatabaseException;
37 import org.simantics.db.layer0.variable.Variable;
38 import org.simantics.db.layer0.variable.Variables.Role;
39 import org.simantics.db.procedure.Procedure;
40 import org.simantics.diagram.stubs.DiagramResource;
41 import org.simantics.district.network.ontology.DistrictNetworkResource;
42 import org.simantics.layer0.Layer0;
43 import org.simantics.modeling.ModelingResources;
44 import org.simantics.modeling.ModelingUtils;
45 import org.simantics.modeling.adapters.NewCompositeActionFactory;
46 import org.simantics.modeling.typicals.TypicalUtil;
47 import org.simantics.scl.reflection.annotations.SCLValue;
48 import org.simantics.structural.stubs.StructuralResource2;
49 import org.simantics.ui.workbench.action.DefaultActions;
50 import org.simantics.utils.ui.SWTUtils;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 public class Functions {
55
56     private static final Logger LOGGER = LoggerFactory.getLogger(Functions.class);
57     
58     private Functions() {
59     }
60
61     private static class HasMappingEnumerationModifier extends GraphEnumerationModifier {
62
63         public HasMappingEnumerationModifier(Session session, Resource subject, Resource relation, Enumeration<Resource> enumeration, Resource value) {
64             super(session, subject, relation, enumeration, value);
65         }
66
67     }
68
69     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
70     public static Object defaultEdgeMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
71         Resource diagram = resolveElement(graph, context);
72         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
73         return baseMappingModifier(graph, diagram, DN.EdgeDefaultMapping, DN.Mapping_EdgeMapping, context);
74     }
75     
76     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
77     public static Object defaultVertexMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
78         System.out.println(graph.getURI(resource));
79         System.out.println(context.getURI(graph));
80         
81         Resource diagram = resolveElement(graph, context);
82         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
83         return baseMappingModifier(graph, diagram, DN.VertexDefaultMapping, DN.Mapping_VertexMapping, context);
84     }
85     
86     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
87     public static Object mappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
88         
89         Resource element = resolveElement(graph, context);
90         Resource mappingType = resolveMappingType(graph, element);
91         return baseMappingModifier(graph, element, DistrictNetworkResource.getInstance(graph).HasMapping, mappingType, context);
92     }
93
94     public static Map<String, Resource> getVertexMappings(ReadGraph graph, Resource resource) throws DatabaseException {
95         return getNetworkMappingsByType(graph, resource , DistrictNetworkResource.getInstance(graph).Mapping_VertexMapping);
96     }
97
98     public static Map<String, Resource> getEdgeMappings(ReadGraph graph, Resource resource) throws DatabaseException {
99         return getNetworkMappingsByType(graph, resource , DistrictNetworkResource.getInstance(graph).Mapping_EdgeMapping);
100     }
101
102     public static Map<String, Resource> getNetworkMappingsByType(ReadGraph graph, Resource element, Resource mappingType) throws DatabaseException {
103         Resource indexRoot = graph.sync(new IndexRoot(element));
104         List<Resource> mappings = ModelingUtils.searchByType(graph, indexRoot, mappingType);
105         Map<String, Resource> result = new HashMap<>(mappings.size());
106         Layer0 L0 = Layer0.getInstance(graph);
107         mappings.forEach(mapping -> {
108             try {
109                 String name = graph.getRelatedValue2(mapping, L0.HasName);
110                 result.put(name, mapping);
111             } catch (DatabaseException e) {
112                 e.printStackTrace();
113             }
114         });
115         return result;
116     }
117     
118     private static Object baseMappingModifier(ReadGraph graph, Resource element, Resource property, Resource mappingType, Variable context) throws DatabaseException {
119         Resource indexRoot = graph.sync(new IndexRoot(element));
120         List<Resource> mappings = ModelingUtils.searchByType(graph, indexRoot, mappingType);
121         Enumeration<Resource> enums = Enumeration
122                 .make(mappings.stream().map(m -> createEnumeratedValue(graph, m)).collect(Collectors.toList()));
123         
124         Resource currentMapping = graph.getSingleObject(element, property);
125         
126         return new HasMappingEnumerationModifier(Simantics.getSession(), element, property, enums, currentMapping);
127     }
128     
129     private static Resource resolveMappingType(ReadGraph graph, Resource element) throws DatabaseException {
130         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
131         if (graph.isInstanceOf(element, DN.Edge))
132             return DN.Mapping_EdgeMapping;
133         else if (graph.isInstanceOf(element, DN.Vertex))
134             return DN.Mapping_VertexMapping;
135         throw new IllegalStateException("No mapping type found for element " + element + " : " + graph.getPossibleURI(element));
136     }
137
138     private static Resource resolveElement(ReadGraph graph, Variable variable) throws DatabaseException {
139         Role role = variable.getPossibleRole(graph);
140         if (role.equals(Role.PROPERTY))
141             return resolveElement(graph, variable.getParent(graph));
142         else
143             return variable.getRepresents(graph);
144     }
145
146     private static EnumeratedValue<Resource> createEnumeratedValue(ReadGraph graph, Resource resource) {
147         try {
148             String label = NameLabelUtil.modalName(graph, resource);
149             return new EnumeratedValue<Resource>(label, resource);
150         } catch (DatabaseException e) {
151             throw new RuntimeDatabaseException(e);
152         }
153     }
154     
155     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
156     public static Object enumerationValues(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
157         Variable var = (Variable) context;
158         System.out.println(graph.getURI(resource));
159         System.out.println(var.getURI(graph));
160         return Collections.emptyList();
161     }
162     
163     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
164     public static Object convertToValue(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
165         return graph.getRelatedValue2(resource, Layer0.getInstance(graph).HasName, Bindings.STRING);
166 //        return null;
167     }
168     
169     
170     @SCLValue(type = "Resource -> String -> Resource -> Resource")
171     public static Resource compositeInstantiator(final Resource compositeType, final String defaultName, final Resource target) throws DatabaseException {
172         
173         return TypicalUtil.syncExec(procedure -> {
174             if (!SWTUtils.asyncExec(PlatformUI.getWorkbench().getDisplay(), () -> {
175                 try {
176                     queryInitialValuesAndCreateComposite(compositeType, target, defaultName, procedure);
177                 } catch (Throwable t) {
178                     procedure.exception(t);
179                 }
180             })) {
181                 procedure.execute(null);
182             }
183         });
184     }
185
186     private static class DefaultMappingsDialog extends SelectionStatusDialog {
187
188         private Combo vertexMappingCombo;
189         private Combo edgeMappingCombo;
190         private Combo crsCombo;
191         private Composite composite;
192         
193         private Resource configuration;
194         private Map<String, Resource> vertexMappings = new HashMap<>();
195         private Map<String, Resource> edgeMappings = new HashMap<>();
196         
197         private Resource defaultVertexMapping;
198         private Resource defaultEdgeMapping;
199
200         protected DefaultMappingsDialog(Shell parentShell, Resource configuration) {
201             super(parentShell);
202             this.configuration = configuration;
203             setTitle("Select mappings for new DN diagram");
204         }
205
206         public Resource getDefaultVertexMapping() {
207             return defaultVertexMapping;
208         }
209
210         public Resource getDefaultEdgeMapping() {
211             return defaultEdgeMapping;
212         }
213
214         @Override
215         protected Control createDialogArea(Composite parent) {
216             composite = (Composite) super.createDialogArea(parent);
217             
218             createMappingsGroup(composite);
219             createCRSSettingsGroup(composite);
220             
221             // compute default values
222             Simantics.getSession().asyncRequest(new ReadRequest() {
223
224                 @Override
225                 public void run(ReadGraph graph) throws DatabaseException {
226                     
227                     vertexMappings = getVertexMappings(graph, configuration);
228                     edgeMappings = getEdgeMappings(graph, configuration);
229                     
230                     composite.getDisplay().asyncExec(() -> {
231                         
232                         vertexMappingCombo.setItems(vertexMappings.keySet().toArray(new String[vertexMappings.size()]));
233                         edgeMappingCombo.setItems(edgeMappings.keySet().toArray(new String[edgeMappings.size()]));
234                         vertexMappingCombo.select(0);
235                         edgeMappingCombo.select(0);
236                     }); 
237                     
238                 }
239             });
240             return composite;
241         }
242         
243         private void createMappingsGroup(Composite parent) {
244             Group group= new Group(parent, SWT.NONE);
245             group.setFont(parent.getFont());
246             group.setText("Default mappings");
247             GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
248             group.setLayout(new GridLayout(1, false));
249             
250             Composite cmposite = new Composite(group, SWT.NONE);
251             cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
252             cmposite.setLayout(new GridLayout(2, false));
253             
254             Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
255             vertexMappingLabel.setText("Default vertex mapping");
256
257             vertexMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
258             GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
259             
260             Label edgeMappingLabel = new Label(cmposite, SWT.NONE);
261             edgeMappingLabel.setText("Default edge mapping");
262
263             edgeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
264             GridDataFactory.fillDefaults().grab(true, false).applyTo(edgeMappingCombo);
265         }
266         
267         private void createCRSSettingsGroup(Composite parent) {
268             Group group= new Group(parent, SWT.NONE);
269             group.setFont(parent.getFont());
270             group.setText("CRS settings");
271             GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
272             group.setLayout(new GridLayout(1, false));
273             
274             Composite cmposite = new Composite(group, SWT.NONE);
275             cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
276             cmposite.setLayout(new GridLayout(2, false));
277             
278             Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
279             vertexMappingLabel.setText("Default CRS");
280
281             crsCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
282             GridData textData = new GridData(SWT.FILL, SWT.CENTER, true, false);
283             crsCombo.setLayoutData(textData);
284         }
285         
286
287         @Override
288         protected void computeResult() {
289             defaultVertexMapping = vertexMappings.get(vertexMappingCombo.getItem(vertexMappingCombo.getSelectionIndex()));
290             defaultEdgeMapping = edgeMappings.get(edgeMappingCombo.getItem(edgeMappingCombo.getSelectionIndex()));
291         }
292         
293     }
294     
295     private static void queryInitialValuesAndCreateComposite(final Resource compositeType, final Resource target,
296             String defaultName, final Procedure<Resource> procedure) {
297         DefaultMappingsDialog dialog = new DefaultMappingsDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), target);
298
299         if (dialog.open() != Dialog.OK) {
300             procedure.execute(null);
301             return;
302         }
303         Simantics.getSession().asyncRequest(
304                 NewCompositeActionFactory.createCompositeRequest(target, defaultName, compositeType),
305                 new Procedure<Resource>() {
306                     @Override
307                     public void execute(Resource composite) {
308                         Simantics.getSession().asyncRequest(new WriteRequest() {
309                             
310                             @Override
311                             public void perform(WriteGraph graph) throws DatabaseException {
312                                 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
313                                 Resource diagram = graph.getSingleObject(composite, ModelingResources.getInstance(graph).CompositeToDiagram);
314                                 graph.claim(diagram, DN.EdgeDefaultMapping, dialog.getDefaultEdgeMapping());
315                                 graph.claim(diagram, DN.VertexDefaultMapping, dialog.getDefaultVertexMapping());
316                             }
317                         });
318                         DefaultActions.asyncPerformDefaultAction(Simantics.getSession(), composite, false, false, true);
319                         procedure.execute(composite);
320                     }
321
322                     @Override
323                     public void exception(Throwable t) {
324                         LOGGER.error("Failed to create composite, see exception for details.", t);
325                         procedure.exception(t);
326                     }
327                 });
328     }
329 }