1 package org.simantics.district.network.ui.function;
3 import java.util.Collection;
4 import java.util.Collections;
5 import java.util.HashMap;
6 import java.util.HashSet;
10 import java.util.stream.Collectors;
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.QueryIndexUtils;
45 import org.simantics.db.layer0.variable.Variable;
46 import org.simantics.db.layer0.variable.Variables;
47 import org.simantics.db.layer0.variable.Variables.Role;
48 import org.simantics.db.procedure.Procedure;
49 import org.simantics.district.network.ontology.DistrictNetworkResource;
50 import org.simantics.layer0.Layer0;
51 import org.simantics.modeling.ModelingResources;
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.scl.runtime.SCLContext;
57 import org.simantics.scl.runtime.function.Function1;
58 import org.simantics.scl.runtime.function.FunctionImpl1;
59 import org.simantics.ui.workbench.action.DefaultActions;
60 import org.simantics.utils.ui.SWTUtils;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 public class Functions {
66 private static final Logger LOGGER = LoggerFactory.getLogger(Functions.class);
71 private static class HasMappingEnumerationModifier extends GraphEnumerationModifier {
73 public HasMappingEnumerationModifier(Session session, Resource subject, Resource relation, Enumeration<Resource> enumeration, Resource value) {
74 super(session, subject, relation, enumeration, value);
79 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
80 public static Object defaultEdgeMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
81 Resource diagram = resolveElement(graph, context);
82 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
83 return baseMappingModifier(graph, diagram, DN.EdgeDefaultMapping, DN.Mapping_EdgeMapping, context);
86 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
87 public static Object defaultVertexMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
88 System.out.println(graph.getURI(resource));
89 System.out.println(context.getURI(graph));
91 Resource diagram = resolveElement(graph, context);
92 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
93 return baseMappingModifier(graph, diagram, DN.VertexDefaultMapping, DN.Mapping_VertexMapping, context);
96 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
97 public static Object mappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
99 Resource element = resolveElement(graph, context);
100 Resource mappingType = resolveMappingType(graph, element);
101 return baseMappingModifier(graph, element, DistrictNetworkResource.getInstance(graph).HasMapping, mappingType, context);
104 public static Map<String, Resource> getVertexMappings(ReadGraph graph, Resource resource) throws DatabaseException {
105 Map<String, Resource> second = getNetworkMappingsByType(graph, resource , DistrictNetworkResource.getInstance(graph).Mapping_VertexMapping);
109 public static Map<String, Resource> getEdgeMappings(ReadGraph graph, Resource resource) throws DatabaseException {
110 Map<String, Resource> second = getNetworkMappingsByType(graph, resource , DistrictNetworkResource.getInstance(graph).Mapping_EdgeMapping);
114 public static Map<String, Resource> getCRSs(ReadGraph graph, Resource resource) throws DatabaseException {
115 Map<String, Resource> result = getNetworkMappingsByType(graph, resource, DistrictNetworkResource.getInstance(graph).SpatialRefSystem);
120 public static Map<String, Resource> getNetworkMappingsByType(ReadGraph graph, Resource element, Resource mappingType) throws DatabaseException {
121 Resource indexRoot = graph.sync(new IndexRoot(element));
122 List<Resource> mappings = QueryIndexUtils.searchByType(graph, indexRoot, mappingType);
123 Map<String, Resource> result = new HashMap<>(mappings.size());
124 Layer0 L0 = Layer0.getInstance(graph);
125 mappings.forEach(mapping -> {
127 String name = graph.getRelatedValue2(mapping, L0.HasName);
128 Resource existing = result.put(name, mapping);
129 if (existing != null) {
130 LOGGER.warn("Duplicate mapping name! {} {} and existing is {}", name, mapping, existing);
132 } catch (DatabaseException e) {
139 private static Object baseMappingModifier(ReadGraph graph, Resource element, Resource property, Resource mappingType, Variable context) throws DatabaseException {
140 Resource indexRoot = graph.sync(new IndexRoot(element));
141 List<Resource> mappings = QueryIndexUtils.searchByType(graph, indexRoot, mappingType);
142 Enumeration<Resource> enums = Enumeration
143 .make(mappings.stream().map(m -> createEnumeratedValue(graph, m)).collect(Collectors.toList()));
145 Resource currentMapping = graph.getSingleObject(element, property);
147 return new HasMappingEnumerationModifier(Simantics.getSession(), element, property, enums, currentMapping);
150 private static Resource resolveMappingType(ReadGraph graph, Resource element) throws DatabaseException {
151 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
152 if (graph.isInstanceOf(element, DN.Edge))
153 return DN.Mapping_EdgeMapping;
154 else if (graph.isInstanceOf(element, DN.Vertex))
155 return DN.Mapping_VertexMapping;
156 throw new IllegalStateException("No mapping type found for element " + element + " : " + graph.getPossibleURI(element));
159 private static Resource resolveElement(ReadGraph graph, Variable variable) throws DatabaseException {
160 Role role = variable.getPossibleRole(graph);
161 if (role.equals(Role.PROPERTY))
162 return resolveElement(graph, variable.getParent(graph));
164 return variable.getRepresents(graph);
167 private static EnumeratedValue<Resource> createEnumeratedValue(ReadGraph graph, Resource resource) {
169 String label = NameLabelUtil.modalName(graph, resource);
170 return new EnumeratedValue<Resource>(label, resource);
171 } catch (DatabaseException e) {
172 throw new RuntimeDatabaseException(e);
176 @SCLValue(type = "ReadGraph -> Resource -> a -> b")
177 public static Object enumerationValues(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
178 Variable var = (Variable) context;
179 System.out.println(graph.getURI(resource));
180 System.out.println(var.getURI(graph));
181 return Collections.emptyList();
184 @SCLValue(type = "ReadGraph -> Resource -> a -> b")
185 public static Object convertToValue(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
186 Layer0 L0 = Layer0.getInstance(graph);
187 String label = graph.getPossibleRelatedValue2(resource, L0.HasLabel, Bindings.STRING);
189 label = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
194 @SCLValue(type = "Resource -> String -> Resource -> Resource")
195 public static Resource compositeInstantiator(final Resource compositeType, final String defaultName, final Resource target) throws DatabaseException {
197 return TypicalUtil.syncExec(procedure -> {
198 if (!SWTUtils.asyncExec(PlatformUI.getWorkbench().getDisplay(), () -> {
200 queryInitialValuesAndCreateComposite(compositeType, target, defaultName, procedure);
201 } catch (Throwable t) {
202 procedure.exception(t);
205 procedure.execute(null);
210 private static class DefaultMappingsDialog extends SelectionStatusDialog {
212 private Combo vertexMappingCombo;
213 private Combo edgeMappingCombo;
214 private Combo crsCombo;
215 private Composite composite;
217 private Resource configuration;
218 private Map<String, Resource> vertexMappings = new HashMap<>();
219 private Map<String, Resource> edgeMappings = new HashMap<>();
220 private Map<String, Resource> composites = new HashMap<>();
221 private Map<String, Resource> crss = new HashMap<>();
223 private Resource defaultVertexMapping;
224 private Resource defaultEdgeMapping;
225 private Resource defaultCRS;
227 private Combo compositeMappingCombo;
228 private Combo componentMappingCombo;
230 protected DefaultMappingsDialog(Shell parentShell, Resource configuration) {
232 this.configuration = configuration;
233 setTitle("Select mappings for new DN diagram");
236 public Resource getDefaultVertexMapping() {
237 return defaultVertexMapping;
240 public Resource getDefaultEdgeMapping() {
241 return defaultEdgeMapping;
245 protected Control createDialogArea(Composite parent) {
246 composite = (Composite) super.createDialogArea(parent);
248 createMappingsGroup(composite);
249 createExistingCompositeGroup(composite);
250 createCRSSettingsGroup(composite);
252 // compute default values
253 Simantics.getSession().asyncRequest(new ReadRequest() {
256 public void run(ReadGraph graph) throws DatabaseException {
258 vertexMappings = getVertexMappings(graph, configuration);
259 edgeMappings = getEdgeMappings(graph, configuration);
261 composites = getComposites(graph, configuration);
263 crss = getCRSs(graph, configuration);
265 composite.getDisplay().asyncExec(() -> {
267 vertexMappingCombo.setItems(vertexMappings.keySet().toArray(new String[vertexMappings.size()]));
268 edgeMappingCombo.setItems(edgeMappings.keySet().toArray(new String[edgeMappings.size()]));
270 crsCombo.setItems(crss.keySet().toArray(new String[crss.size()]));
272 compositeMappingCombo.setItems(composites.keySet().toArray(new String[composites.size()]));
273 vertexMappingCombo.select(0);
274 edgeMappingCombo.select(0);
278 if (!composites.isEmpty())
279 compositeMappingCombo.select(0);
287 protected Map<String, Resource> getComposites(ReadGraph graph, Resource element) throws DatabaseException {
288 List<Resource> nonDistrictComposites = composites.values().stream().filter(comp -> {
290 return !graph.isInstanceOf(comp, DistrictNetworkResource.getInstance(graph).Composite);
291 } catch (ServiceException e1) {
292 LOGGER.error("Could not check if composite " + comp + " is instanceOf DistrictNetwork.composite");
295 }).collect(Collectors.toList());
296 Map<String, Resource> result = new HashMap<>(nonDistrictComposites.size());
297 Layer0 L0 = Layer0.getInstance(graph);
298 nonDistrictComposites.forEach(mapping -> {
300 String name = graph.getRelatedValue2(mapping, L0.HasName);
301 result.put(name, mapping);
302 } catch (DatabaseException e) {
303 LOGGER.error("Could not read name of " + mapping, e);
309 private void createMappingsGroup(Composite parent) {
310 Group group= new Group(parent, SWT.NONE);
311 group.setFont(parent.getFont());
312 group.setText("Default mappings");
313 GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
314 group.setLayout(new GridLayout(1, false));
316 Composite cmposite = new Composite(group, SWT.NONE);
317 cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
318 cmposite.setLayout(new GridLayout(2, false));
320 Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
321 vertexMappingLabel.setText("Default vertex mapping");
323 vertexMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
324 GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
326 Label edgeMappingLabel = new Label(cmposite, SWT.NONE);
327 edgeMappingLabel.setText("Default edge mapping");
329 edgeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
330 GridDataFactory.fillDefaults().grab(true, false).applyTo(edgeMappingCombo);
333 private void createExistingCompositeGroup(Composite parent) {
334 Group group= new Group(parent, SWT.NONE);
335 group.setFont(parent.getFont());
336 group.setText("Mapped composite");
337 GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
338 group.setLayout(new GridLayout(1, false));
340 Composite cmposite = new Composite(group, SWT.NONE);
341 cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
342 cmposite.setLayout(new GridLayout(2, false));
344 Label compositeMappingLabel = new Label(cmposite, SWT.NONE);
345 compositeMappingLabel.setText("Select composite");
347 compositeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
348 GridDataFactory.fillDefaults().grab(true, false).applyTo(compositeMappingCombo);
349 compositeMappingCombo.addSelectionListener(new SelectionAdapter() {
352 public void widgetSelected(SelectionEvent e) {
353 super.widgetSelected(e);
354 recalculateMappapleComponents();
358 Label compojnentMappingLabel = new Label(cmposite, SWT.NONE);
359 compojnentMappingLabel.setText("Select component");
361 componentMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
362 GridDataFactory.fillDefaults().grab(true, false).applyTo(componentMappingCombo);
365 protected void recalculateMappapleComponents() {
366 Simantics.getSession().asyncRequest(new ReadRequest() {
369 public void run(ReadGraph graph) throws DatabaseException {
372 composite.getDisplay().asyncExec(() -> {
379 private void createCRSSettingsGroup(Composite parent) {
380 Group group= new Group(parent, SWT.NONE);
381 group.setFont(parent.getFont());
382 group.setText("CRS settings");
383 GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
384 group.setLayout(new GridLayout(1, false));
386 Composite cmposite = new Composite(group, SWT.NONE);
387 cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
388 cmposite.setLayout(new GridLayout(2, false));
390 Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
391 vertexMappingLabel.setText("Default CRS");
393 crsCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
394 GridData textData = new GridData(SWT.FILL, SWT.CENTER, true, false);
395 crsCombo.setLayoutData(textData);
400 protected void computeResult() {
401 defaultVertexMapping = vertexMappings.get(vertexMappingCombo.getItem(vertexMappingCombo.getSelectionIndex()));
402 defaultEdgeMapping = edgeMappings.get(edgeMappingCombo.getItem(edgeMappingCombo.getSelectionIndex()));
403 defaultCRS = crss.get(crsCombo.getItem(crsCombo.getSelectionIndex()));
406 public Resource getCRS() {
412 private static void queryInitialValuesAndCreateComposite(final Resource compositeType, final Resource target,
413 String defaultName, final Procedure<Resource> procedure) {
414 DefaultMappingsDialog dialog = new DefaultMappingsDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), target);
416 if (dialog.open() != Dialog.OK) {
417 procedure.execute(null);
420 Simantics.getSession().asyncRequest(
421 NewCompositeActionFactory.createCompositeRequest(target, defaultName, compositeType),
422 new Procedure<Resource>() {
424 public void execute(Resource composite) {
425 Simantics.getSession().asyncRequest(new WriteRequest() {
428 public void perform(WriteGraph graph) throws DatabaseException {
429 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
430 Resource diagram = graph.getSingleObject(composite, ModelingResources.getInstance(graph).CompositeToDiagram);
431 graph.claim(diagram, DN.EdgeDefaultMapping, dialog.getDefaultEdgeMapping());
432 graph.claim(diagram, DN.VertexDefaultMapping, dialog.getDefaultVertexMapping());
433 graph.claim(diagram, DN.HasSpatialRefSystem, dialog.getCRS());
435 // Generated name prefix from composite name
436 String compositeName = graph.getRelatedValue2(composite, Layer0.getInstance(graph).HasName, Bindings.STRING);
437 graph.claimLiteral(diagram, Layer0X.getInstance(graph).HasGeneratedNamePrefix, "N" + compositeName.substring(compositeName.length() - 1, compositeName.length()));
440 DefaultActions.asyncPerformDefaultAction(Simantics.getSession(), composite, false, false, true);
441 procedure.execute(composite);
445 public void exception(Throwable t) {
446 LOGGER.error("Failed to create composite, see exception for details.", t);
447 procedure.exception(t);
452 public static Collection<Resource> getDistrictDiagrams(ReadGraph graph) throws DatabaseException {
453 Layer0 L0 = Layer0.getInstance(graph);
454 Collection<Resource> indexRoots = graph.sync(new ObjectsWithType(Simantics.getProjectResource(), L0.ConsistsOf, L0.IndexRoot));
455 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
456 Set<Resource> results = new HashSet<>();
457 for (Resource indexRoot : indexRoots) {
458 Collection<Resource> diagrams = QueryIndexUtils.searchByType(graph, indexRoot, DN.Diagram);
459 results.addAll(diagrams);
464 private static List<String> listInstanceNames(ReadGraph graph, Variable context, Resource type) throws DatabaseException {
465 Resource indexRoot = Variables.getIndexRoot(graph, context);
466 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
467 List<Resource> properties = QueryIndexUtils.searchByType(graph, indexRoot, DN.Vertex_ScaleProperty);
468 return properties.stream()
469 .map(m -> createEnumeratedValue(graph, m))
470 .map(EnumeratedValue::getName)
471 .collect(Collectors.toList());
474 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
475 public static Object edgeThicknessPropertyEnumerationValues(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
476 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
477 return listInstanceNames(graph, context, DN.Edge_ThicknessProperty);
480 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
481 public static Object nodeScalePropertyEnumerationValues(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
482 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
483 return listInstanceNames(graph, context, DN.Vertex_ScaleProperty);
486 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
487 public static Object edgeThicknessPropertyModifier(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
488 Resource diagram = resolveElement(graph, context);
489 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
490 return baseMappingModifier(graph, diagram, DN.Diagram_edgeThicknessProperty, DN.Edge_ThicknessProperty, context);
493 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
494 public static Object nodeScalePropertyModifier(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
495 Resource diagram = resolveElement(graph, context);
496 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
497 return baseMappingModifier(graph, diagram, DN.Diagram_nodeScaleProperty, DN.Vertex_ScaleProperty, context);
500 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
501 public static Function1<Resource, Double> hasDiameterValue(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
502 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Edge_HasDiameter, 0);
505 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
506 public static Function1<Resource, Double> hasNominalMassFlowValue(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
507 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Edge_HasNominalMassFlow, 0);
510 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
511 public static Function1<Resource, Double> hasNominalSupplyPressure(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
512 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Vertex_HasSupplyPressure, 0);
515 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
516 public static Function1<Resource, Double> hasElevation(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
517 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Vertex_HasElevation, 0);
520 private static final Function1<Resource, Double> ONE = new FunctionImpl1<Resource, Double>() {
521 private final Double ONE = 1.0;
523 public Double apply(Resource edge) {
528 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
529 public static Function1<Resource, Double> constantOne(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
533 private static Function1<Resource, Double> directPropertyValueFunction(Resource property, double defaultValue) throws DatabaseException {
534 Double def = defaultValue;
535 return new FunctionImpl1<Resource, Double>() {
537 public Double apply(Resource edge) {
538 ReadGraph graph = (ReadGraph) SCLContext.getCurrent().get("graph");
540 Double d = graph.getPossibleRelatedValue(edge, property, Bindings.DOUBLE);
541 return d != null ? d : def;
542 } catch (DatabaseException e) {
543 LOGGER.error("Failed to evaluate property value", e);