]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network.ui/src/org/simantics/district/network/ui/function/Functions.java
Arrow length indicators for flow magnitude
[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.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;
9 import java.util.List;
10 import java.util.Map;
11 import java.util.Set;
12 import java.util.stream.Collectors;
13
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;
71
72 public class Functions {
73
74     private static final Logger LOGGER = LoggerFactory.getLogger(Functions.class);
75     
76     private Functions() {
77     }
78
79     private static class HasMappingEnumerationModifier extends GraphEnumerationModifier {
80
81         public HasMappingEnumerationModifier(Session session, Resource subject, Resource relation, Enumeration<Resource> enumeration, Resource value) {
82             super(session, subject, relation, enumeration, value);
83         }
84
85     }
86
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);
92     }
93     
94     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
95     public static Object defaultVertexMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
96         System.out.println(graph.getURI(resource));
97         System.out.println(context.getURI(graph));
98         
99         Resource diagram = resolveElement(graph, context);
100         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
101         return baseMappingModifier(graph, diagram, DN.VertexDefaultMapping, DN.Mapping_VertexMapping, context);
102     }
103     
104     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
105     public static Object mappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
106         
107         Resource element = resolveElement(graph, context);
108         Resource mappingType = resolveMappingType(graph, element);
109         return baseMappingModifier(graph, element, DistrictNetworkResource.getInstance(graph).HasMapping, mappingType, context);
110     }
111
112     public static Map<String, Resource> getVertexMappings(ReadGraph graph, Resource indexRoot) throws DatabaseException {
113         Map<String, Resource> second = getNetworkMappingsByType(graph, indexRoot, DistrictNetworkResource.getInstance(graph).Mapping_VertexMapping);
114         return second;
115     }
116
117     public static Map<String, Resource> getEdgeMappings(ReadGraph graph, Resource indexRoot) throws DatabaseException {
118         Map<String, Resource> second = getNetworkMappingsByType(graph, indexRoot, DistrictNetworkResource.getInstance(graph).Mapping_EdgeMapping);
119         return second;
120     }
121     
122     public static Map<String, Resource> getCRSs(ReadGraph graph, Resource resource) throws DatabaseException {
123         Map<String, Resource> result = getNetworkMappingsByType(graph, graph.sync(new IndexRoot(resource)), DistrictNetworkResource.getInstance(graph).SpatialRefSystem);
124         return result;
125         
126     }
127
128     public static Map<String, Resource> getNetworkMappingsByType(ReadGraph graph, Resource indexRoot, Resource mappingType) throws DatabaseException {
129         List<Resource> mappings = QueryIndexUtils.searchByType(graph, indexRoot, mappingType);
130         Map<String, Resource> result = new HashMap<>(mappings.size());
131         Layer0 L0 = Layer0.getInstance(graph);
132         mappings.forEach(mapping -> {
133             try {
134                 String name = graph.getRelatedValue2(mapping, L0.HasName);
135                 Resource existing = result.put(name, mapping);
136                 if (existing != null) {
137                     LOGGER.warn("Duplicate mapping name! {} {} and existing is {}", name, mapping, existing);
138                 }
139             } catch (DatabaseException e) {
140                 e.printStackTrace();
141             }
142         });
143         return result;
144     }
145     
146     private static Object baseMappingModifier(ReadGraph graph, Resource element, Resource property, Resource mappingType, Variable context) throws DatabaseException {
147         Resource indexRoot = graph.sync(new IndexRoot(element));
148         List<Resource> mappings = QueryIndexUtils.searchByType(graph, indexRoot, mappingType);
149         Enumeration<Resource> enums = Enumeration
150                 .make(mappings.stream().map(m -> createEnumeratedValue(graph, m)).collect(Collectors.toList()));
151         
152         Resource currentMapping = graph.getSingleObject(element, property);
153         
154         return new HasMappingEnumerationModifier(Simantics.getSession(), element, property, enums, currentMapping);
155     }
156     
157     private static Resource resolveMappingType(ReadGraph graph, Resource element) throws DatabaseException {
158         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
159         if (graph.isInstanceOf(element, DN.Edge))
160             return DN.Mapping_EdgeMapping;
161         else if (graph.isInstanceOf(element, DN.Vertex))
162             return DN.Mapping_VertexMapping;
163         throw new IllegalStateException("No mapping type found for element " + element + " : " + graph.getPossibleURI(element));
164     }
165
166     private static Resource resolveElement(ReadGraph graph, Variable variable) throws DatabaseException {
167         Role role = variable.getPossibleRole(graph);
168         if (role.equals(Role.PROPERTY))
169             return resolveElement(graph, variable.getParent(graph));
170         else
171             return variable.getRepresents(graph);
172     }
173
174     private static EnumeratedValue<Resource> createEnumeratedValue(ReadGraph graph, Resource resource) {
175         try {
176             String label = NameLabelUtil.modalName(graph, resource);
177             return new EnumeratedValue<Resource>(label, resource);
178         } catch (DatabaseException e) {
179             throw new RuntimeDatabaseException(e);
180         }
181     }
182     
183     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
184     public static Object enumerationValues(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
185         Variable var = (Variable) context;
186         System.out.println(graph.getURI(resource));
187         System.out.println(var.getURI(graph));
188         return Collections.emptyList();
189     }
190     
191     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
192     public static Object convertToValue(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
193         Layer0 L0 = Layer0.getInstance(graph);
194         String label = graph.getPossibleRelatedValue2(resource, L0.HasLabel, Bindings.STRING);
195         if (label == null)
196             label = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
197         return label;
198     }
199     
200     
201     @SCLValue(type = "Resource -> String -> Resource -> Resource")
202     public static Resource compositeInstantiator(final Resource compositeType, final String defaultName, final Resource target) throws DatabaseException {
203         
204         return TypicalUtil.syncExec(procedure -> {
205             if (!SWTUtils.asyncExec(PlatformUI.getWorkbench().getDisplay(), () -> {
206                 try {
207                     queryInitialValuesAndCreateComposite(compositeType, target, defaultName, procedure);
208                 } catch (Throwable t) {
209                     procedure.exception(t);
210                 }
211             })) {
212                 procedure.execute(null);
213             }
214         });
215     }
216
217     private static class DefaultMappingsDialog extends SelectionStatusDialog {
218
219         private Combo vertexMappingCombo;
220         private Combo edgeMappingCombo;
221         private Combo crsCombo;
222         private Composite composite;
223         
224         private Resource configuration;
225         private Map<String, Resource> vertexMappings = new HashMap<>();
226         private Map<String, Resource> edgeMappings = new HashMap<>();
227         private Map<String, Resource> composites = new HashMap<>();
228         private Map<String, Resource> crss = new HashMap<>();
229         
230         private Resource defaultVertexMapping;
231         private Resource defaultEdgeMapping;
232         private Resource defaultCRS;
233         
234         private Combo compositeMappingCombo;
235         private Combo componentMappingCombo;
236
237         protected DefaultMappingsDialog(Shell parentShell, Resource configuration) {
238             super(parentShell);
239             this.configuration = configuration;
240             setTitle("Select mappings for new DN diagram");
241         }
242
243         public Resource getDefaultVertexMapping() {
244             return defaultVertexMapping;
245         }
246
247         public Resource getDefaultEdgeMapping() {
248             return defaultEdgeMapping;
249         }
250
251         @Override
252         protected Control createDialogArea(Composite parent) {
253             composite = (Composite) super.createDialogArea(parent);
254             
255             createMappingsGroup(composite);
256             createExistingCompositeGroup(composite);
257             createCRSSettingsGroup(composite);
258             
259             // compute default values
260             Simantics.getSession().asyncRequest(new ReadRequest() {
261
262                 @Override
263                 public void run(ReadGraph graph) throws DatabaseException {
264                     Resource indexRoot = graph.sync(new IndexRoot(configuration));
265                     vertexMappings = getVertexMappings(graph, indexRoot);
266                     edgeMappings = getEdgeMappings(graph, indexRoot);
267                     
268                     composites = getComposites(graph, configuration);
269                   
270                     crss = getCRSs(graph, configuration);
271                     
272                     composite.getDisplay().asyncExec(() -> {
273                         
274                         vertexMappingCombo.setItems(vertexMappings.keySet().toArray(new String[vertexMappings.size()]));
275                         edgeMappingCombo.setItems(edgeMappings.keySet().toArray(new String[edgeMappings.size()]));
276                         
277                         crsCombo.setItems(crss.keySet().toArray(new String[crss.size()]));
278                         
279                         compositeMappingCombo.setItems(composites.keySet().toArray(new String[composites.size()]));
280                         vertexMappingCombo.select(0);
281                         edgeMappingCombo.select(0);
282                         
283                         crsCombo.select(0);
284                         
285                         if (!composites.isEmpty())
286                             compositeMappingCombo.select(0);
287                     }); 
288                     
289                 }
290             });
291             return composite;
292         }
293         
294         protected Map<String, Resource> getComposites(ReadGraph graph, Resource element) throws DatabaseException {
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 = QueryIndexUtils.searchByType(graph, indexRoot, DN.Diagram);
466             results.addAll(diagrams);
467         }
468         return results;
469     }
470
471     private static List<String> listInstanceNames(ReadGraph graph, Variable context, Resource type) throws DatabaseException {
472         Resource indexRoot = Variables.getIndexRoot(graph, context);
473         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
474         List<Resource> properties = QueryIndexUtils.searchByType(graph, indexRoot, DN.Vertex_ScaleProperty);
475         return properties.stream()
476                 .map(m -> createEnumeratedValue(graph, m))
477                 .map(EnumeratedValue::getName)
478                 .collect(Collectors.toList());
479     }
480
481     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
482     public static Object edgeThicknessPropertyEnumerationValues(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
483         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
484         return listInstanceNames(graph, context, DN.Edge_ThicknessProperty);
485     }
486     
487     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
488     public static Object arrowLengthPropertyEnumerationValues(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
489         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
490         return listInstanceNames(graph, context, DN.Edge_ArrowLengthProperty);
491     }
492     
493     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
494     public static Object nodeScalePropertyEnumerationValues(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
495         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
496         return listInstanceNames(graph, context, DN.Vertex_ScaleProperty);
497     }
498
499     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
500     public static Object edgeThicknessPropertyModifier(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
501         Resource diagram = resolveElement(graph, context);
502         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
503         return baseMappingModifier(graph, diagram, DN.Diagram_edgeThicknessProperty, DN.Edge_ThicknessProperty, context);
504     }
505
506     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
507     public static Object arrowLengthPropertyModifier(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
508         Resource diagram = resolveElement(graph, context);
509         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
510         return baseMappingModifier(graph, diagram, DN.Diagram_arrowLengthProperty, DN.Edge_ArrowLengthProperty, context);
511     }
512     
513     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
514     public static Object nodeScalePropertyModifier(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
515         Resource diagram = resolveElement(graph, context);
516         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
517         return baseMappingModifier(graph, diagram, DN.Diagram_nodeScaleProperty, DN.Vertex_ScaleProperty, context);
518     }
519
520     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
521     public static Function1<Resource, Double> hasDiameterValue(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
522         return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Edge_HasDiameter, 0);
523     }
524
525     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
526     public static Function1<Resource, Double> hasNominalMassFlowValue(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
527         return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Edge_HasNominalMassFlow, 0);
528     }
529
530     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
531     public static Function1<Resource, Double> hasNominalSupplyPressure(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
532         return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Vertex_HasSupplyPressure, 0);
533     }
534
535     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
536     public static Function1<Resource, Double> hasElevation(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
537         return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Vertex_HasElevation, 0);
538     }
539
540     private static final Function1<Resource, Double> ONE = new FunctionImpl1<Resource, Double>() {
541         private final Double ONE = 1.0;
542         @Override
543         public Double apply(Resource edge) {
544             return ONE;
545         }
546         @Override
547         public String toString() {
548             return "1";
549         }
550     };
551
552     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
553     public static Function1<Resource, Double> constantOne(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
554         return ONE;
555     }
556
557     private static Function1<Resource, Double> directPropertyValueFunction(Resource property, double defaultValue) throws DatabaseException {
558         Double def = defaultValue;
559         return new FunctionImpl1<Resource, Double>() {
560             @Override
561             public Double apply(Resource edge) {
562                 ReadGraph graph = (ReadGraph) SCLContext.getCurrent().get("graph");
563                 try {
564                     Double d = graph.getPossibleRelatedValue(edge, property, Bindings.DOUBLE);
565                     return d != null ? d : def;
566                 } catch (DatabaseException e) {
567                     LOGGER.error("Failed to evaluate property value", e);
568                     return def;
569                 }
570             }
571         };
572     }
573
574     private static class RangeValidator implements Function1<String, String> {
575         private double min;
576         private double max;
577         public RangeValidator(double min, double max) {
578             this.min = min;
579             this.max = max;
580         }
581         @Override
582         public String apply(String s) {
583             try {
584                 double d = Double.parseDouble(s);
585                 if (d < min)
586                     return "Value must be greater than or equal to " + min;
587                 if (d > max)
588                     return "Value must be less than or equal to " + max;
589                 return null;
590             } catch (NumberFormatException e) {
591                 return "Specified value is not a number";
592             }
593         }
594     }
595
596     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
597     public static Object hueValidator(ReadGraph graph, Resource r, Variable context) throws DatabaseException {
598         return new RangeValidator(0, 360);
599     }
600
601     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
602     public static Object saturationValidator(ReadGraph graph, Resource r, Variable context) throws DatabaseException {
603         return new RangeValidator(0, 100);
604     }
605
606     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
607     public static Object brightnessValidator(ReadGraph graph, Resource r, Variable context) throws DatabaseException {
608         String importEntry = null;
609         Resource root = Variables.getPossibleIndexRoot(graph, context);
610         if (root != null) {
611             Resource sclmain = Layer0Utils.getPossibleChild(graph, root, "SCLMain");
612             if (sclmain != null) {
613                 importEntry = graph.getPossibleURI(sclmain);
614             }
615         }
616         SCLContext ctx = SCLContext.getCurrent();
617         Object oldGraph = ctx.put("graph", graph);
618         try {
619             return new BrightnessExpressionValidator(
620                     importEntry != null
621                     ? Arrays.asList(importEntry)
622                     : Collections.emptyList());
623         } finally {
624             ctx.put("graph", oldGraph);
625         }
626     }
627
628     private static class BrightnessExpressionValidator implements Function1<String, String> {
629         private CommandSession session;
630
631         public BrightnessExpressionValidator(List<String> importEntries) {
632             this.session = new CommandSession(SCLOsgi.MODULE_REPOSITORY, SCLReportingHandler.DEFAULT);
633             this.session.setImportEntries(imports(importEntries));
634         }
635
636         private ArrayList<CommandSessionImportEntry> imports(List<String> entries) {
637             ArrayList<CommandSessionImportEntry> result = new ArrayList<>();
638             entries.stream().map(CommandSessionImportEntry::new).forEach(result::add);
639             if (entries.isEmpty())
640                 result.add(new CommandSessionImportEntry("Simantics/District/SCLMain"));
641             return result;
642         }
643
644         @Override
645         public String apply(String s) {
646             s = s.trim();
647             if (!s.startsWith("="))
648                 return "Expression expected, must start with '='";
649             CompilationError[] errors = session.validate(s.substring(1));
650             if(errors.length == 0)
651                 return null;
652             return errors[0].description;
653         }
654     }
655
656 }