1 package org.simantics.district.network.ui.function;
3 import java.util.Collections;
4 import java.util.HashMap;
7 import java.util.stream.Collectors;
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;
56 public class Functions {
58 private static final Logger LOGGER = LoggerFactory.getLogger(Functions.class);
63 private static class HasMappingEnumerationModifier extends GraphEnumerationModifier {
65 public HasMappingEnumerationModifier(Session session, Resource subject, Resource relation, Enumeration<Resource> enumeration, Resource value) {
66 super(session, subject, relation, enumeration, value);
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);
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));
83 Resource diagram = resolveElement(graph, context);
84 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
85 return baseMappingModifier(graph, diagram, DN.VertexDefaultMapping, DN.Mapping_VertexMapping, context);
88 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
89 public static Object mappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
91 Resource element = resolveElement(graph, context);
92 Resource mappingType = resolveMappingType(graph, element);
93 return baseMappingModifier(graph, element, DistrictNetworkResource.getInstance(graph).HasMapping, mappingType, context);
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);
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);
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);
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 -> {
119 String name = graph.getRelatedValue2(mapping, L0.HasName);
120 result.put(name, mapping);
121 } catch (DatabaseException e) {
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()));
134 Resource currentMapping = graph.getSingleObject(element, property);
136 return new HasMappingEnumerationModifier(Simantics.getSession(), element, property, enums, currentMapping);
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));
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));
153 return variable.getRepresents(graph);
156 private static EnumeratedValue<Resource> createEnumeratedValue(ReadGraph graph, Resource resource) {
158 String label = NameLabelUtil.modalName(graph, resource);
159 return new EnumeratedValue<Resource>(label, resource);
160 } catch (DatabaseException e) {
161 throw new RuntimeDatabaseException(e);
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();
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);
180 @SCLValue(type = "Resource -> String -> Resource -> Resource")
181 public static Resource compositeInstantiator(final Resource compositeType, final String defaultName, final Resource target) throws DatabaseException {
183 return TypicalUtil.syncExec(procedure -> {
184 if (!SWTUtils.asyncExec(PlatformUI.getWorkbench().getDisplay(), () -> {
186 queryInitialValuesAndCreateComposite(compositeType, target, defaultName, procedure);
187 } catch (Throwable t) {
188 procedure.exception(t);
191 procedure.execute(null);
196 private static class DefaultMappingsDialog extends SelectionStatusDialog {
198 private Combo vertexMappingCombo;
199 private Combo edgeMappingCombo;
200 private Combo crsCombo;
201 private Composite composite;
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<>();
210 private Resource defaultVertexMapping;
211 private Resource defaultEdgeMapping;
212 private Resource defaultCRS;
214 private Combo compositeMappingCombo;
215 private Combo componentMappingCombo;
217 protected DefaultMappingsDialog(Shell parentShell, Resource configuration) {
219 this.configuration = configuration;
220 setTitle("Select mappings for new DN diagram");
223 public Resource getDefaultVertexMapping() {
224 return defaultVertexMapping;
227 public Resource getDefaultEdgeMapping() {
228 return defaultEdgeMapping;
232 protected Control createDialogArea(Composite parent) {
233 composite = (Composite) super.createDialogArea(parent);
235 createMappingsGroup(composite);
236 createExistingCompositeGroup(composite);
237 createCRSSettingsGroup(composite);
239 // compute default values
240 Simantics.getSession().asyncRequest(new ReadRequest() {
243 public void run(ReadGraph graph) throws DatabaseException {
245 vertexMappings = getVertexMappings(graph, configuration);
246 edgeMappings = getEdgeMappings(graph, configuration);
248 composites = getComposites(graph, configuration);
249 if (composites.size() > 0) {
250 components = getComponents(graph, composites.get(0));
253 crss = getCRSs(graph, configuration);
255 composite.getDisplay().asyncExec(() -> {
257 vertexMappingCombo.setItems(vertexMappings.keySet().toArray(new String[vertexMappings.size()]));
258 edgeMappingCombo.setItems(edgeMappings.keySet().toArray(new String[edgeMappings.size()]));
260 crsCombo.setItems(crss.keySet().toArray(new String[crss.size()]));
262 compositeMappingCombo.setItems(composites.keySet().toArray(new String[composites.size()]));
263 vertexMappingCombo.select(0);
264 edgeMappingCombo.select(0);
268 if (!composites.isEmpty())
269 compositeMappingCombo.select(0);
277 protected Map<String, Map<String, Resource>> getComponents(ReadGraph graph, Resource resource) {
278 // TODO Auto-generated method stub
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 -> {
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");
292 }).collect(Collectors.toList());
293 Map<String, Resource> result = new HashMap<>(nonDistrictComposites.size());
294 Layer0 L0 = Layer0.getInstance(graph);
295 nonDistrictComposites.forEach(mapping -> {
297 String name = graph.getRelatedValue2(mapping, L0.HasName);
298 result.put(name, mapping);
299 } catch (DatabaseException e) {
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));
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));
317 Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
318 vertexMappingLabel.setText("Default vertex mapping");
320 vertexMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
321 GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
323 Label edgeMappingLabel = new Label(cmposite, SWT.NONE);
324 edgeMappingLabel.setText("Default edge mapping");
326 edgeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
327 GridDataFactory.fillDefaults().grab(true, false).applyTo(edgeMappingCombo);
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));
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));
341 Label compositeMappingLabel = new Label(cmposite, SWT.NONE);
342 compositeMappingLabel.setText("Select composite");
344 compositeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
345 GridDataFactory.fillDefaults().grab(true, false).applyTo(compositeMappingCombo);
346 compositeMappingCombo.addSelectionListener(new SelectionAdapter() {
349 public void widgetSelected(SelectionEvent e) {
350 super.widgetSelected(e);
351 recalculateMappapleComponents();
355 Label compojnentMappingLabel = new Label(cmposite, SWT.NONE);
356 compojnentMappingLabel.setText("Select component");
358 componentMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
359 GridDataFactory.fillDefaults().grab(true, false).applyTo(componentMappingCombo);
362 protected void recalculateMappapleComponents() {
363 Simantics.getSession().asyncRequest(new ReadRequest() {
366 public void run(ReadGraph graph) throws DatabaseException {
369 composite.getDisplay().asyncExec(() -> {
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));
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));
387 Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
388 vertexMappingLabel.setText("Default CRS");
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);
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()));
403 public Resource getCRS() {
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);
413 if (dialog.open() != Dialog.OK) {
414 procedure.execute(null);
417 Simantics.getSession().asyncRequest(
418 NewCompositeActionFactory.createCompositeRequest(target, defaultName, compositeType),
419 new Procedure<Resource>() {
421 public void execute(Resource composite) {
422 Simantics.getSession().asyncRequest(new WriteRequest() {
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());
433 DefaultActions.asyncPerformDefaultAction(Simantics.getSession(), composite, false, false, true);
434 procedure.execute(composite);
438 public void exception(Throwable t) {
439 LOGGER.error("Failed to create composite, see exception for details.", t);
440 procedure.exception(t);