1 package org.simantics.district.network.ui.function;
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.Collection;
6 import java.util.Collections;
7 import java.util.HashMap;
8 import java.util.HashSet;
12 import java.util.stream.Collectors;
14 import org.eclipse.jface.dialogs.Dialog;
15 import org.eclipse.jface.layout.GridDataFactory;
16 import org.eclipse.swt.SWT;
17 import org.eclipse.swt.events.SelectionAdapter;
18 import org.eclipse.swt.events.SelectionEvent;
19 import org.eclipse.swt.layout.GridData;
20 import org.eclipse.swt.layout.GridLayout;
21 import org.eclipse.swt.widgets.Combo;
22 import org.eclipse.swt.widgets.Composite;
23 import org.eclipse.swt.widgets.Control;
24 import org.eclipse.swt.widgets.Group;
25 import org.eclipse.swt.widgets.Label;
26 import org.eclipse.swt.widgets.Shell;
27 import org.eclipse.ui.PlatformUI;
28 import org.eclipse.ui.dialogs.SelectionStatusDialog;
29 import org.simantics.NameLabelUtil;
30 import org.simantics.Simantics;
31 import org.simantics.browsing.ui.common.modifiers.EnumeratedValue;
32 import org.simantics.browsing.ui.common.modifiers.Enumeration;
33 import org.simantics.browsing.ui.graph.impl.GraphEnumerationModifier;
34 import org.simantics.databoard.Bindings;
35 import org.simantics.db.ReadGraph;
36 import org.simantics.db.Resource;
37 import org.simantics.db.Session;
38 import org.simantics.db.WriteGraph;
39 import org.simantics.db.common.request.IndexRoot;
40 import org.simantics.db.common.request.ObjectsWithType;
41 import org.simantics.db.common.request.ReadRequest;
42 import org.simantics.db.common.request.WriteRequest;
43 import org.simantics.db.exception.DatabaseException;
44 import org.simantics.db.exception.RuntimeDatabaseException;
45 import org.simantics.db.exception.ServiceException;
46 import org.simantics.db.layer0.QueryIndexUtils;
47 import org.simantics.db.layer0.util.Layer0Utils;
48 import org.simantics.db.layer0.variable.Variable;
49 import org.simantics.db.layer0.variable.Variables;
50 import org.simantics.db.layer0.variable.Variables.Role;
51 import org.simantics.db.procedure.Procedure;
52 import org.simantics.district.network.ontology.DistrictNetworkResource;
53 import org.simantics.layer0.Layer0;
54 import org.simantics.modeling.ModelingResources;
55 import org.simantics.modeling.adapters.NewCompositeActionFactory;
56 import org.simantics.modeling.typicals.TypicalUtil;
57 import org.simantics.operation.Layer0X;
58 import org.simantics.scl.compiler.commands.CommandSession;
59 import org.simantics.scl.compiler.commands.CommandSessionImportEntry;
60 import org.simantics.scl.compiler.errors.CompilationError;
61 import org.simantics.scl.osgi.SCLOsgi;
62 import org.simantics.scl.reflection.annotations.SCLValue;
63 import org.simantics.scl.runtime.SCLContext;
64 import org.simantics.scl.runtime.function.Function1;
65 import org.simantics.scl.runtime.function.FunctionImpl1;
66 import org.simantics.scl.runtime.reporting.SCLReportingHandler;
67 import org.simantics.ui.workbench.action.DefaultActions;
68 import org.simantics.utils.ui.SWTUtils;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
72 public class Functions {
74 private static final Logger LOGGER = LoggerFactory.getLogger(Functions.class);
79 private static class HasMappingEnumerationModifier extends GraphEnumerationModifier {
81 public HasMappingEnumerationModifier(Session session, Resource subject, Resource relation, Enumeration<Resource> enumeration, Resource value) {
82 super(session, subject, relation, enumeration, value);
87 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
88 public static Object defaultEdgeMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
89 Resource diagram = resolveElement(graph, context);
90 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
91 return baseMappingModifier(graph, diagram, DN.EdgeDefaultMapping, DN.Mapping_EdgeMapping, context);
94 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
95 public static Object defaultVertexMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
96 Resource diagram = resolveElement(graph, context);
97 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
98 return baseMappingModifier(graph, diagram, DN.VertexDefaultMapping, DN.Mapping_VertexMapping, context);
101 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
102 public static Object rightClickVertexMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
103 Resource diagram = resolveElement(graph, context);
104 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
105 return baseMappingModifier(graph, diagram, DN.RightClickDefaultMapping, DN.Mapping_VertexMapping, context);
108 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
109 public static Object leftClickVertexMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
110 Resource diagram = resolveElement(graph, context);
111 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
112 return baseMappingModifier(graph, diagram, DN.LeftClickDefaultMapping, DN.Mapping_VertexMapping, context);
115 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
116 public static Object mappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
118 Resource element = resolveElement(graph, context);
119 Resource mappingType = resolveMappingType(graph, element);
120 return baseMappingModifier(graph, element, DistrictNetworkResource.getInstance(graph).HasMapping, mappingType, context);
123 public static Map<String, Resource> getVertexMappings(ReadGraph graph, Resource indexRoot) throws DatabaseException {
124 Map<String, Resource> second = getNetworkMappingsByType(graph, indexRoot, DistrictNetworkResource.getInstance(graph).Mapping_VertexMapping);
128 public static Map<String, Resource> getEdgeMappings(ReadGraph graph, Resource indexRoot) throws DatabaseException {
129 Map<String, Resource> second = getNetworkMappingsByType(graph, indexRoot, DistrictNetworkResource.getInstance(graph).Mapping_EdgeMapping);
133 public static Map<String, Resource> getCRSs(ReadGraph graph, Resource resource) throws DatabaseException {
134 Map<String, Resource> result = getNetworkMappingsByType(graph, graph.sync(new IndexRoot(resource)), DistrictNetworkResource.getInstance(graph).SpatialRefSystem);
139 public static Map<String, Resource> getNetworkMappingsByType(ReadGraph graph, Resource indexRoot, Resource mappingType) throws DatabaseException {
140 List<Resource> mappings = QueryIndexUtils.searchByType(graph, indexRoot, mappingType);
141 Map<String, Resource> result = new HashMap<>(mappings.size());
142 Layer0 L0 = Layer0.getInstance(graph);
143 mappings.forEach(mapping -> {
145 String name = graph.getRelatedValue2(mapping, L0.HasName);
146 Resource existing = result.put(name, mapping);
147 if (existing != null) {
148 LOGGER.warn("Duplicate mapping name! {} {} and existing is {}", name, mapping, existing);
150 } catch (DatabaseException e) {
157 private static Object baseMappingModifier(ReadGraph graph, Resource element, Resource property, Resource mappingType, Variable context) throws DatabaseException {
158 Resource indexRoot = graph.sync(new IndexRoot(element));
159 List<Resource> mappings = QueryIndexUtils.searchByType(graph, indexRoot, mappingType);
160 Enumeration<Resource> enums = Enumeration
161 .make(mappings.stream().map(m -> createEnumeratedValue(graph, m)).collect(Collectors.toList()));
163 Resource currentMapping = graph.getSingleObject(element, property);
165 return new HasMappingEnumerationModifier(Simantics.getSession(), element, property, enums, currentMapping);
168 private static Resource resolveMappingType(ReadGraph graph, Resource element) throws DatabaseException {
169 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
170 if (graph.isInstanceOf(element, DN.Edge))
171 return DN.Mapping_EdgeMapping;
172 else if (graph.isInstanceOf(element, DN.Vertex))
173 return DN.Mapping_VertexMapping;
174 throw new IllegalStateException("No mapping type found for element " + element + " : " + graph.getPossibleURI(element));
177 private static Resource resolveElement(ReadGraph graph, Variable variable) throws DatabaseException {
178 Role role = variable.getPossibleRole(graph);
179 if (role.equals(Role.PROPERTY))
180 return resolveElement(graph, variable.getParent(graph));
182 return variable.getRepresents(graph);
185 private static EnumeratedValue<Resource> createEnumeratedValue(ReadGraph graph, Resource resource) {
187 String label = NameLabelUtil.modalName(graph, resource);
188 return new EnumeratedValue<Resource>(label, resource);
189 } catch (DatabaseException e) {
190 throw new RuntimeDatabaseException(e);
194 @SCLValue(type = "ReadGraph -> Resource -> a -> b")
195 public static Object enumerationValues(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
196 Variable var = (Variable) context;
197 return Collections.emptyList();
200 @SCLValue(type = "ReadGraph -> Resource -> a -> b")
201 public static Object convertToValue(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
202 Layer0 L0 = Layer0.getInstance(graph);
203 String label = graph.getPossibleRelatedValue2(resource, L0.HasLabel, Bindings.STRING);
205 label = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
210 @SCLValue(type = "Resource -> String -> Resource -> Resource")
211 public static Resource compositeInstantiator(final Resource compositeType, final String defaultName, final Resource target) throws DatabaseException {
213 return TypicalUtil.syncExec(procedure -> {
214 if (!SWTUtils.asyncExec(PlatformUI.getWorkbench().getDisplay(), () -> {
216 queryInitialValuesAndCreateComposite(compositeType, target, defaultName, procedure);
217 } catch (Throwable t) {
218 procedure.exception(t);
221 procedure.execute(null);
226 private static class DefaultMappingsDialog extends SelectionStatusDialog {
228 private Combo vertexMappingCombo;
229 private Combo rightClickMappingCombo;
230 private Combo leftClickMappingCombo;
231 private Combo edgeMappingCombo;
232 //private Combo crsCombo;
233 private Composite composite;
235 private Resource configuration;
236 private Map<String, Resource> vertexMappings = new HashMap<>();
237 private Map<String, Resource> edgeMappings = new HashMap<>();
238 private Map<String, Resource> composites = new HashMap<>();
239 private Map<String, Resource> crss = new HashMap<>();
241 private Resource defaultVertexMapping;
242 private Resource defaultEdgeMapping;
243 private Resource rightClickVertexMapping;
244 private Resource leftClickVertexMapping;
245 //private Resource defaultCRS;
247 private Combo compositeMappingCombo;
248 private Combo componentMappingCombo;
250 protected DefaultMappingsDialog(Shell parentShell, Resource configuration) {
252 this.configuration = configuration;
253 setTitle("Select mappings for new DN diagram");
256 public Resource getDefaultVertexMapping() {
257 return defaultVertexMapping;
260 public Resource getRightClickVertexMapping() {
261 return rightClickVertexMapping;
264 public Resource getLeftClickVertexMapping() {
265 return leftClickVertexMapping;
268 public Resource getDefaultEdgeMapping() {
269 return defaultEdgeMapping;
273 protected Control createDialogArea(Composite parent) {
274 composite = (Composite) super.createDialogArea(parent);
276 createMappingsGroup(composite);
277 //createExistingCompositeGroup(composite);
278 //createCRSSettingsGroup(composite);
280 // compute default values
281 Simantics.getSession().asyncRequest(new ReadRequest() {
284 public void run(ReadGraph graph) throws DatabaseException {
285 Resource indexRoot = graph.sync(new IndexRoot(configuration));
286 vertexMappings = getVertexMappings(graph, indexRoot);
287 edgeMappings = getEdgeMappings(graph, indexRoot);
289 composites = getComposites(graph, configuration);
291 crss = getCRSs(graph, configuration);
293 composite.getDisplay().asyncExec(() -> {
295 vertexMappingCombo.setItems(vertexMappings.keySet().toArray(new String[vertexMappings.size()]));
296 rightClickMappingCombo.setItems(vertexMappings.keySet().toArray(new String[vertexMappings.size()]));
297 leftClickMappingCombo.setItems(vertexMappings.keySet().toArray(new String[vertexMappings.size()]));
298 edgeMappingCombo.setItems(edgeMappings.keySet().toArray(new String[edgeMappings.size()]));
300 //crsCombo.setItems(crss.keySet().toArray(new String[crss.size()]));
302 compositeMappingCombo.setItems(composites.keySet().toArray(new String[composites.size()]));
303 vertexMappingCombo.select(0);
304 rightClickMappingCombo.select(0);
305 leftClickMappingCombo.select(0);
306 edgeMappingCombo.select(0);
308 //crsCombo.select(0);
310 if (!composites.isEmpty())
311 compositeMappingCombo.select(0);
319 protected Map<String, Resource> getComposites(ReadGraph graph, Resource element) throws DatabaseException {
320 List<Resource> nonDistrictComposites = composites.values().stream().filter(comp -> {
322 return !graph.isInstanceOf(comp, DistrictNetworkResource.getInstance(graph).Composite);
323 } catch (ServiceException e1) {
324 LOGGER.error("Could not check if composite " + comp + " is instanceOf DistrictNetwork.composite");
327 }).collect(Collectors.toList());
328 Map<String, Resource> result = new HashMap<>(nonDistrictComposites.size());
329 Layer0 L0 = Layer0.getInstance(graph);
330 nonDistrictComposites.forEach(mapping -> {
332 String name = graph.getRelatedValue2(mapping, L0.HasName);
333 result.put(name, mapping);
334 } catch (DatabaseException e) {
335 LOGGER.error("Could not read name of " + mapping, e);
341 private void createMappingsGroup(Composite parent) {
342 Group group= new Group(parent, SWT.NONE);
343 group.setFont(parent.getFont());
344 group.setText("Default mappings");
345 GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
346 group.setLayout(new GridLayout(1, false));
348 Composite cmposite = new Composite(group, SWT.NONE);
349 cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
350 cmposite.setLayout(new GridLayout(2, false));
352 Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
353 vertexMappingLabel.setText("Default vertex mapping");
355 vertexMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
356 GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
358 Label rightClickMappingLabel = new Label(cmposite, SWT.NONE);
359 rightClickMappingLabel.setText("Default right click mapping");
361 rightClickMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
362 GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
364 Label leftClickMappingLabel = new Label(cmposite, SWT.NONE);
365 leftClickMappingLabel.setText("Default left click mapping");
367 leftClickMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
368 GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
370 Label edgeMappingLabel = new Label(cmposite, SWT.NONE);
371 edgeMappingLabel.setText("Default edge mapping");
373 edgeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
374 GridDataFactory.fillDefaults().grab(true, false).applyTo(edgeMappingCombo);
377 private void createExistingCompositeGroup(Composite parent) {
378 Group group= new Group(parent, SWT.NONE);
379 group.setFont(parent.getFont());
380 group.setText("Mapped composite");
381 GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
382 group.setLayout(new GridLayout(1, false));
384 Composite cmposite = new Composite(group, SWT.NONE);
385 cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
386 cmposite.setLayout(new GridLayout(2, false));
388 Label compositeMappingLabel = new Label(cmposite, SWT.NONE);
389 compositeMappingLabel.setText("Select composite");
391 compositeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
392 GridDataFactory.fillDefaults().grab(true, false).applyTo(compositeMappingCombo);
393 compositeMappingCombo.addSelectionListener(new SelectionAdapter() {
396 public void widgetSelected(SelectionEvent e) {
397 super.widgetSelected(e);
398 recalculateMappapleComponents();
402 Label compojnentMappingLabel = new Label(cmposite, SWT.NONE);
403 compojnentMappingLabel.setText("Select component");
405 componentMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
406 GridDataFactory.fillDefaults().grab(true, false).applyTo(componentMappingCombo);
409 protected void recalculateMappapleComponents() {
410 Simantics.getSession().asyncRequest(new ReadRequest() {
413 public void run(ReadGraph graph) throws DatabaseException {
416 composite.getDisplay().asyncExec(() -> {
423 private void createCRSSettingsGroup(Composite parent) {
424 Group group= new Group(parent, SWT.NONE);
425 group.setFont(parent.getFont());
426 group.setText("CRS settings");
427 GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
428 group.setLayout(new GridLayout(1, false));
430 Composite cmposite = new Composite(group, SWT.NONE);
431 cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
432 cmposite.setLayout(new GridLayout(2, false));
434 Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
435 vertexMappingLabel.setText("Default CRS");
437 //crsCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
438 //GridData textData = new GridData(SWT.FILL, SWT.CENTER, true, false);
439 //crsCombo.setLayoutData(textData);
444 protected void computeResult() {
445 defaultVertexMapping = vertexMappings.get(vertexMappingCombo.getItem(vertexMappingCombo.getSelectionIndex()));
446 defaultEdgeMapping = edgeMappings.get(edgeMappingCombo.getItem(edgeMappingCombo.getSelectionIndex()));
447 rightClickVertexMapping = vertexMappings.get(rightClickMappingCombo.getItem(rightClickMappingCombo.getSelectionIndex()));
448 leftClickVertexMapping = vertexMappings.get(leftClickMappingCombo.getItem(leftClickMappingCombo.getSelectionIndex()));
449 //defaultCRS = crss.get(crsCombo.getItem(crsCombo.getSelectionIndex()));
452 public Resource getCRS() {
453 return crss.get("EPSG_4326"); // this is only supported
458 private static void queryInitialValuesAndCreateComposite(final Resource compositeType, final Resource target,
459 String defaultName, final Procedure<Resource> procedure) {
460 DefaultMappingsDialog dialog = new DefaultMappingsDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), target);
462 if (dialog.open() != Dialog.OK) {
463 procedure.execute(null);
466 Simantics.getSession().asyncRequest(
467 NewCompositeActionFactory.createCompositeRequest(target, defaultName, compositeType),
468 new Procedure<Resource>() {
470 public void execute(Resource composite) {
471 Simantics.getSession().asyncRequest(new WriteRequest() {
474 public void perform(WriteGraph graph) throws DatabaseException {
475 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
476 Resource diagram = graph.getSingleObject(composite, ModelingResources.getInstance(graph).CompositeToDiagram);
477 graph.claim(diagram, DN.EdgeDefaultMapping, dialog.getDefaultEdgeMapping());
478 graph.claim(diagram, DN.VertexDefaultMapping, dialog.getDefaultVertexMapping());
479 graph.claim(diagram, DN.RightClickDefaultMapping, dialog.getRightClickVertexMapping());
480 graph.claim(diagram, DN.LeftClickDefaultMapping, dialog.getLeftClickVertexMapping());
481 graph.claim(diagram, DN.HasSpatialRefSystem, dialog.getCRS());
483 // Generated name prefix from composite name
484 String compositeName = graph.getRelatedValue2(composite, Layer0.getInstance(graph).HasName, Bindings.STRING);
485 graph.claimLiteral(diagram, Layer0X.getInstance(graph).HasGeneratedNamePrefix, "N" + compositeName.substring(compositeName.length() - 1, compositeName.length()));
488 DefaultActions.asyncPerformDefaultAction(Simantics.getSession(), composite, false, false, true);
489 procedure.execute(composite);
493 public void exception(Throwable t) {
494 LOGGER.error("Failed to create composite, see exception for details.", t);
495 procedure.exception(t);
500 public static Collection<Resource> getDistrictDiagrams(ReadGraph graph) throws DatabaseException {
501 Layer0 L0 = Layer0.getInstance(graph);
502 Collection<Resource> indexRoots = graph.sync(new ObjectsWithType(Simantics.getProjectResource(), L0.ConsistsOf, L0.IndexRoot));
503 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
504 Set<Resource> results = new HashSet<>();
505 for (Resource indexRoot : indexRoots) {
506 Collection<Resource> diagrams = QueryIndexUtils.searchByType(graph, indexRoot, DN.Diagram);
507 results.addAll(diagrams);
512 private static List<String> listInstanceNames(ReadGraph graph, Variable context, Resource type) throws DatabaseException {
513 Resource indexRoot = Variables.getIndexRoot(graph, context);
514 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
515 List<Resource> properties = QueryIndexUtils.searchByType(graph, indexRoot, DN.Vertex_ScaleProperty);
516 return properties.stream()
517 .map(m -> createEnumeratedValue(graph, m))
518 .map(EnumeratedValue::getName)
519 .collect(Collectors.toList());
522 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
523 public static Object edgeThicknessPropertyEnumerationValues(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
524 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
525 return listInstanceNames(graph, context, DN.Edge_ThicknessProperty);
528 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
529 public static Object arrowLengthPropertyEnumerationValues(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
530 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
531 return listInstanceNames(graph, context, DN.Edge_ArrowLengthProperty);
534 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
535 public static Object nodeScalePropertyEnumerationValues(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
536 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
537 return listInstanceNames(graph, context, DN.Vertex_ScaleProperty);
540 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
541 public static Object edgeThicknessPropertyModifier(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
542 Resource diagram = resolveElement(graph, context);
543 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
544 return baseMappingModifier(graph, diagram, DN.Diagram_edgeThicknessProperty, DN.Edge_ThicknessProperty, context);
547 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
548 public static Object arrowLengthPropertyModifier(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
549 Resource diagram = resolveElement(graph, context);
550 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
551 return baseMappingModifier(graph, diagram, DN.Diagram_arrowLengthProperty, DN.Edge_ArrowLengthProperty, context);
554 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
555 public static Object nodeScalePropertyModifier(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
556 Resource diagram = resolveElement(graph, context);
557 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
558 return baseMappingModifier(graph, diagram, DN.Diagram_nodeScaleProperty, DN.Vertex_ScaleProperty, context);
561 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
562 public static Function1<Resource, Double> hasDiameterValue(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
563 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Edge_HasDiameter, 0);
566 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
567 public static Function1<Resource, Double> hasNominalMassFlowValue(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
568 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Edge_HasNominalMassFlow, 0);
571 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
572 public static Function1<Resource, Double> hasNominalSupplyPressure(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
573 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Vertex_HasSupplyPressure, 0);
576 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
577 public static Function1<Resource, Double> hasElevation(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
578 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Vertex_HasElevation, 0);
581 private static final Function1<Resource, Double> ONE = new FunctionImpl1<Resource, Double>() {
582 private final Double ONE = 1.0;
584 public Double apply(Resource edge) {
588 public String toString() {
593 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
594 public static Function1<Resource, Double> constantOne(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
598 private static Function1<Resource, Double> directPropertyValueFunction(Resource property, double defaultValue) throws DatabaseException {
599 Double def = defaultValue;
600 return new FunctionImpl1<Resource, Double>() {
602 public Double apply(Resource edge) {
603 ReadGraph graph = (ReadGraph) SCLContext.getCurrent().get("graph");
605 Double d = graph.getPossibleRelatedValue(edge, property, Bindings.DOUBLE);
606 return d != null ? d : def;
607 } catch (DatabaseException e) {
608 LOGGER.error("Failed to evaluate property value", e);
615 private static class RangeValidator implements Function1<String, String> {
618 public RangeValidator(double min, double max) {
623 public String apply(String s) {
625 double d = Double.parseDouble(s);
627 return "Value must be greater than or equal to " + min;
629 return "Value must be less than or equal to " + max;
631 } catch (NumberFormatException e) {
632 return "Specified value is not a number";
637 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
638 public static Object hueValidator(ReadGraph graph, Resource r, Variable context) throws DatabaseException {
639 return new RangeValidator(0, 360);
642 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
643 public static Object saturationValidator(ReadGraph graph, Resource r, Variable context) throws DatabaseException {
644 return new RangeValidator(0, 100);
647 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
648 public static Object brightnessValidator(ReadGraph graph, Resource r, Variable context) throws DatabaseException {
649 String importEntry = null;
650 Resource root = Variables.getPossibleIndexRoot(graph, context);
652 Resource sclmain = Layer0Utils.getPossibleChild(graph, root, "SCLMain");
653 if (sclmain != null) {
654 importEntry = graph.getPossibleURI(sclmain);
657 SCLContext ctx = SCLContext.getCurrent();
658 Object oldGraph = ctx.put("graph", graph);
660 return new BrightnessExpressionValidator(
662 ? Arrays.asList(importEntry)
663 : Collections.emptyList());
665 ctx.put("graph", oldGraph);
669 private static class BrightnessExpressionValidator implements Function1<String, String> {
670 private CommandSession session;
672 public BrightnessExpressionValidator(List<String> importEntries) {
673 this.session = new CommandSession(SCLOsgi.MODULE_REPOSITORY, SCLReportingHandler.DEFAULT);
674 this.session.setImportEntries(imports(importEntries));
677 private ArrayList<CommandSessionImportEntry> imports(List<String> entries) {
678 ArrayList<CommandSessionImportEntry> result = new ArrayList<>();
679 entries.stream().map(CommandSessionImportEntry::new).forEach(result::add);
680 if (entries.isEmpty())
681 result.add(new CommandSessionImportEntry("Simantics/District/SCLMain"));
686 public String apply(String s) {
688 if (!s.startsWith("="))
689 return "Expression expected, must start with '='";
690 CompilationError[] errors = session.validate(s.substring(1));
691 if(errors.length == 0)
693 return errors[0].description;