]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network.ui/src/org/simantics/district/network/ui/function/Functions.java
89878c5b60c59041986f3a572fec0d96bc558236
[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         Resource diagram = resolveElement(graph, context);
97         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
98         return baseMappingModifier(graph, diagram, DN.VertexDefaultMapping, DN.Mapping_VertexMapping, context);
99     }
100
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);
106     }
107
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);
113     }
114
115     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
116     public static Object mappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
117         
118         Resource element = resolveElement(graph, context);
119         Resource mappingType = resolveMappingType(graph, element);
120         return baseMappingModifier(graph, element, DistrictNetworkResource.getInstance(graph).HasMapping, mappingType, context);
121     }
122
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);
125         return second;
126     }
127
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);
130         return second;
131     }
132     
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);
135         return result;
136         
137     }
138
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 -> {
144             try {
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);
149                 }
150             } catch (DatabaseException e) {
151                 e.printStackTrace();
152             }
153         });
154         return result;
155     }
156     
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()));
162         
163         Resource currentMapping = graph.getSingleObject(element, property);
164         
165         return new HasMappingEnumerationModifier(Simantics.getSession(), element, property, enums, currentMapping);
166     }
167     
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));
175     }
176
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));
181         else
182             return variable.getRepresents(graph);
183     }
184
185     private static EnumeratedValue<Resource> createEnumeratedValue(ReadGraph graph, Resource resource) {
186         try {
187             String label = NameLabelUtil.modalName(graph, resource);
188             return new EnumeratedValue<Resource>(label, resource);
189         } catch (DatabaseException e) {
190             throw new RuntimeDatabaseException(e);
191         }
192     }
193     
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();
198     }
199     
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);
204         if (label == null)
205             label = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
206         return label;
207     }
208     
209     
210     @SCLValue(type = "Resource -> String -> Resource -> Resource")
211     public static Resource compositeInstantiator(final Resource compositeType, final String defaultName, final Resource target) throws DatabaseException {
212         
213         return TypicalUtil.syncExec(procedure -> {
214             if (!SWTUtils.asyncExec(PlatformUI.getWorkbench().getDisplay(), () -> {
215                 try {
216                     queryInitialValuesAndCreateComposite(compositeType, target, defaultName, procedure);
217                 } catch (Throwable t) {
218                     procedure.exception(t);
219                 }
220             })) {
221                 procedure.execute(null);
222             }
223         });
224     }
225
226     private static class DefaultMappingsDialog extends SelectionStatusDialog {
227
228         private Combo vertexMappingCombo;
229         private Combo rightClickMappingCombo;
230         private Combo leftClickMappingCombo;
231         private Combo edgeMappingCombo;
232         //private Combo crsCombo;
233         private Composite composite;
234         
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<>();
240         
241         private Resource defaultVertexMapping;
242         private Resource defaultEdgeMapping;
243         private Resource rightClickVertexMapping;
244         private Resource leftClickVertexMapping;
245         //private Resource defaultCRS;
246         
247         private Combo compositeMappingCombo;
248         private Combo componentMappingCombo;
249
250         protected DefaultMappingsDialog(Shell parentShell, Resource configuration) {
251             super(parentShell);
252             this.configuration = configuration;
253             setTitle("Select mappings for new DN diagram");
254         }
255
256         public Resource getDefaultVertexMapping() {
257             return defaultVertexMapping;
258         }
259
260                 public Resource getRightClickVertexMapping() {
261                         return rightClickVertexMapping;
262                 }
263
264                 public Resource getLeftClickVertexMapping() {
265                         return leftClickVertexMapping;
266                 }
267
268         public Resource getDefaultEdgeMapping() {
269             return defaultEdgeMapping;
270         }
271
272         @Override
273         protected Control createDialogArea(Composite parent) {
274             composite = (Composite) super.createDialogArea(parent);
275             
276             createMappingsGroup(composite);
277             //createExistingCompositeGroup(composite);
278             //createCRSSettingsGroup(composite);
279             
280             // compute default values
281             Simantics.getSession().asyncRequest(new ReadRequest() {
282
283                 @Override
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);
288                     
289                     composites = getComposites(graph, configuration);
290                   
291                     crss = getCRSs(graph, configuration);
292                     
293                     composite.getDisplay().asyncExec(() -> {
294                         
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()]));
299                         
300                         //crsCombo.setItems(crss.keySet().toArray(new String[crss.size()]));
301                         
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);
307                         
308                         //crsCombo.select(0);
309                         
310                         if (!composites.isEmpty())
311                             compositeMappingCombo.select(0);
312                     }); 
313                     
314                 }
315             });
316             return composite;
317         }
318         
319         protected Map<String, Resource> getComposites(ReadGraph graph, Resource element) throws DatabaseException {
320             List<Resource> nonDistrictComposites = composites.values().stream().filter(comp -> {
321                 try {
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");
325                     return false;
326                 }
327             }).collect(Collectors.toList());
328             Map<String, Resource> result = new HashMap<>(nonDistrictComposites.size());
329             Layer0 L0 = Layer0.getInstance(graph);
330             nonDistrictComposites.forEach(mapping -> {
331                 try {
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);
336                 }
337             });
338             return result;
339         }
340
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));
347             
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));
351             
352             Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
353             vertexMappingLabel.setText("Default vertex mapping");
354
355             vertexMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
356             GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
357
358             Label rightClickMappingLabel = new Label(cmposite, SWT.NONE);
359             rightClickMappingLabel.setText("Default right click mapping");
360
361             rightClickMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
362             GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
363
364             Label leftClickMappingLabel = new Label(cmposite, SWT.NONE);
365             leftClickMappingLabel.setText("Default left click mapping");
366
367             leftClickMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
368             GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
369
370             Label edgeMappingLabel = new Label(cmposite, SWT.NONE);
371             edgeMappingLabel.setText("Default edge mapping");
372
373             edgeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
374             GridDataFactory.fillDefaults().grab(true, false).applyTo(edgeMappingCombo);
375         }
376         
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));
383             
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));
387             
388             Label compositeMappingLabel = new Label(cmposite, SWT.NONE);
389             compositeMappingLabel.setText("Select composite");
390
391             compositeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
392             GridDataFactory.fillDefaults().grab(true, false).applyTo(compositeMappingCombo);
393             compositeMappingCombo.addSelectionListener(new SelectionAdapter() {
394                 
395                 @Override
396                 public void widgetSelected(SelectionEvent e) {
397                     super.widgetSelected(e);
398                     recalculateMappapleComponents();
399                 }
400             });
401             
402             Label compojnentMappingLabel = new Label(cmposite, SWT.NONE);
403             compojnentMappingLabel.setText("Select component");
404             
405             componentMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
406             GridDataFactory.fillDefaults().grab(true, false).applyTo(componentMappingCombo);
407         }
408         
409         protected void recalculateMappapleComponents() {
410             Simantics.getSession().asyncRequest(new ReadRequest() {
411                 
412                 @Override
413                 public void run(ReadGraph graph) throws DatabaseException {
414                     
415                     
416                     composite.getDisplay().asyncExec(() -> {
417                         
418                     }); 
419                 }
420             });
421         }
422
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));
429             
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));
433             
434             Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
435             vertexMappingLabel.setText("Default CRS");
436
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);
440         }
441         
442
443         @Override
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()));
450         }
451
452         public Resource getCRS() {
453             return crss.get("EPSG_4326"); // this is only supported
454         }
455         
456     }
457     
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);
461
462         if (dialog.open() != Dialog.OK) {
463             procedure.execute(null);
464             return;
465         }
466         Simantics.getSession().asyncRequest(
467                 NewCompositeActionFactory.createCompositeRequest(target, defaultName, compositeType),
468                 new Procedure<Resource>() {
469                     @Override
470                     public void execute(Resource composite) {
471                         Simantics.getSession().asyncRequest(new WriteRequest() {
472                             
473                             @Override
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());
482                                 
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()));
486                             }
487                         });
488                         DefaultActions.asyncPerformDefaultAction(Simantics.getSession(), composite, false, false, true);
489                         procedure.execute(composite);
490                     }
491
492                     @Override
493                     public void exception(Throwable t) {
494                         LOGGER.error("Failed to create composite, see exception for details.", t);
495                         procedure.exception(t);
496                     }
497                 });
498     }
499
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);
508         }
509         return results;
510     }
511
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());
520     }
521
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);
526     }
527     
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);
532     }
533     
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);
538     }
539
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);
545     }
546
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);
552     }
553     
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);
559     }
560
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);
564     }
565
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);
569     }
570
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);
574     }
575
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);
579     }
580
581     private static final Function1<Resource, Double> ONE = new FunctionImpl1<Resource, Double>() {
582         private final Double ONE = 1.0;
583         @Override
584         public Double apply(Resource edge) {
585             return ONE;
586         }
587         @Override
588         public String toString() {
589             return "1";
590         }
591     };
592
593     @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
594     public static Function1<Resource, Double> constantOne(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
595         return ONE;
596     }
597
598     private static Function1<Resource, Double> directPropertyValueFunction(Resource property, double defaultValue) throws DatabaseException {
599         Double def = defaultValue;
600         return new FunctionImpl1<Resource, Double>() {
601             @Override
602             public Double apply(Resource edge) {
603                 ReadGraph graph = (ReadGraph) SCLContext.getCurrent().get("graph");
604                 try {
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);
609                     return def;
610                 }
611             }
612         };
613     }
614
615     private static class RangeValidator implements Function1<String, String> {
616         private double min;
617         private double max;
618         public RangeValidator(double min, double max) {
619             this.min = min;
620             this.max = max;
621         }
622         @Override
623         public String apply(String s) {
624             try {
625                 double d = Double.parseDouble(s);
626                 if (d < min)
627                     return "Value must be greater than or equal to " + min;
628                 if (d > max)
629                     return "Value must be less than or equal to " + max;
630                 return null;
631             } catch (NumberFormatException e) {
632                 return "Specified value is not a number";
633             }
634         }
635     }
636
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);
640     }
641
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);
645     }
646
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);
651         if (root != null) {
652             Resource sclmain = Layer0Utils.getPossibleChild(graph, root, "SCLMain");
653             if (sclmain != null) {
654                 importEntry = graph.getPossibleURI(sclmain);
655             }
656         }
657         SCLContext ctx = SCLContext.getCurrent();
658         Object oldGraph = ctx.put("graph", graph);
659         try {
660             return new BrightnessExpressionValidator(
661                     importEntry != null
662                     ? Arrays.asList(importEntry)
663                     : Collections.emptyList());
664         } finally {
665             ctx.put("graph", oldGraph);
666         }
667     }
668
669     private static class BrightnessExpressionValidator implements Function1<String, String> {
670         private CommandSession session;
671
672         public BrightnessExpressionValidator(List<String> importEntries) {
673             this.session = new CommandSession(SCLOsgi.MODULE_REPOSITORY, SCLReportingHandler.DEFAULT);
674             this.session.setImportEntries(imports(importEntries));
675         }
676
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"));
682             return result;
683         }
684
685         @Override
686         public String apply(String s) {
687             s = s.trim();
688             if (!s.startsWith("="))
689                 return "Expression expected, must start with '='";
690             CompilationError[] errors = session.validate(s.substring(1));
691             if(errors.length == 0)
692                 return null;
693             return errors[0].description;
694         }
695     }
696
697 }