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 System.out.println(graph.getURI(resource));
97 System.out.println(context.getURI(graph));
99 Resource diagram = resolveElement(graph, context);
100 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
101 return baseMappingModifier(graph, diagram, DN.VertexDefaultMapping, DN.Mapping_VertexMapping, context);
104 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
105 public static Object mappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
107 Resource element = resolveElement(graph, context);
108 Resource mappingType = resolveMappingType(graph, element);
109 return baseMappingModifier(graph, element, DistrictNetworkResource.getInstance(graph).HasMapping, mappingType, context);
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);
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);
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);
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 -> {
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);
139 } catch (DatabaseException e) {
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()));
152 Resource currentMapping = graph.getSingleObject(element, property);
154 return new HasMappingEnumerationModifier(Simantics.getSession(), element, property, enums, currentMapping);
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));
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));
171 return variable.getRepresents(graph);
174 private static EnumeratedValue<Resource> createEnumeratedValue(ReadGraph graph, Resource resource) {
176 String label = NameLabelUtil.modalName(graph, resource);
177 return new EnumeratedValue<Resource>(label, resource);
178 } catch (DatabaseException e) {
179 throw new RuntimeDatabaseException(e);
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();
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);
196 label = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
201 @SCLValue(type = "Resource -> String -> Resource -> Resource")
202 public static Resource compositeInstantiator(final Resource compositeType, final String defaultName, final Resource target) throws DatabaseException {
204 return TypicalUtil.syncExec(procedure -> {
205 if (!SWTUtils.asyncExec(PlatformUI.getWorkbench().getDisplay(), () -> {
207 queryInitialValuesAndCreateComposite(compositeType, target, defaultName, procedure);
208 } catch (Throwable t) {
209 procedure.exception(t);
212 procedure.execute(null);
217 private static class DefaultMappingsDialog extends SelectionStatusDialog {
219 private Combo vertexMappingCombo;
220 private Combo edgeMappingCombo;
221 private Combo crsCombo;
222 private Composite composite;
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<>();
230 private Resource defaultVertexMapping;
231 private Resource defaultEdgeMapping;
232 private Resource defaultCRS;
234 private Combo compositeMappingCombo;
235 private Combo componentMappingCombo;
237 protected DefaultMappingsDialog(Shell parentShell, Resource configuration) {
239 this.configuration = configuration;
240 setTitle("Select mappings for new DN diagram");
243 public Resource getDefaultVertexMapping() {
244 return defaultVertexMapping;
247 public Resource getDefaultEdgeMapping() {
248 return defaultEdgeMapping;
252 protected Control createDialogArea(Composite parent) {
253 composite = (Composite) super.createDialogArea(parent);
255 createMappingsGroup(composite);
256 createExistingCompositeGroup(composite);
257 createCRSSettingsGroup(composite);
259 // compute default values
260 Simantics.getSession().asyncRequest(new ReadRequest() {
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);
268 composites = getComposites(graph, configuration);
270 crss = getCRSs(graph, configuration);
272 composite.getDisplay().asyncExec(() -> {
274 vertexMappingCombo.setItems(vertexMappings.keySet().toArray(new String[vertexMappings.size()]));
275 edgeMappingCombo.setItems(edgeMappings.keySet().toArray(new String[edgeMappings.size()]));
277 crsCombo.setItems(crss.keySet().toArray(new String[crss.size()]));
279 compositeMappingCombo.setItems(composites.keySet().toArray(new String[composites.size()]));
280 vertexMappingCombo.select(0);
281 edgeMappingCombo.select(0);
285 if (!composites.isEmpty())
286 compositeMappingCombo.select(0);
294 protected Map<String, Resource> getComposites(ReadGraph graph, Resource element) throws DatabaseException {
295 List<Resource> nonDistrictComposites = composites.values().stream().filter(comp -> {
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");
302 }).collect(Collectors.toList());
303 Map<String, Resource> result = new HashMap<>(nonDistrictComposites.size());
304 Layer0 L0 = Layer0.getInstance(graph);
305 nonDistrictComposites.forEach(mapping -> {
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);
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));
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));
327 Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
328 vertexMappingLabel.setText("Default vertex mapping");
330 vertexMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
331 GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
333 Label edgeMappingLabel = new Label(cmposite, SWT.NONE);
334 edgeMappingLabel.setText("Default edge mapping");
336 edgeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
337 GridDataFactory.fillDefaults().grab(true, false).applyTo(edgeMappingCombo);
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));
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));
351 Label compositeMappingLabel = new Label(cmposite, SWT.NONE);
352 compositeMappingLabel.setText("Select composite");
354 compositeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
355 GridDataFactory.fillDefaults().grab(true, false).applyTo(compositeMappingCombo);
356 compositeMappingCombo.addSelectionListener(new SelectionAdapter() {
359 public void widgetSelected(SelectionEvent e) {
360 super.widgetSelected(e);
361 recalculateMappapleComponents();
365 Label compojnentMappingLabel = new Label(cmposite, SWT.NONE);
366 compojnentMappingLabel.setText("Select component");
368 componentMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
369 GridDataFactory.fillDefaults().grab(true, false).applyTo(componentMappingCombo);
372 protected void recalculateMappapleComponents() {
373 Simantics.getSession().asyncRequest(new ReadRequest() {
376 public void run(ReadGraph graph) throws DatabaseException {
379 composite.getDisplay().asyncExec(() -> {
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));
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));
397 Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
398 vertexMappingLabel.setText("Default CRS");
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);
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()));
413 public Resource getCRS() {
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);
423 if (dialog.open() != Dialog.OK) {
424 procedure.execute(null);
427 Simantics.getSession().asyncRequest(
428 NewCompositeActionFactory.createCompositeRequest(target, defaultName, compositeType),
429 new Procedure<Resource>() {
431 public void execute(Resource composite) {
432 Simantics.getSession().asyncRequest(new WriteRequest() {
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());
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()));
447 DefaultActions.asyncPerformDefaultAction(Simantics.getSession(), composite, false, false, true);
448 procedure.execute(composite);
452 public void exception(Throwable t) {
453 LOGGER.error("Failed to create composite, see exception for details.", t);
454 procedure.exception(t);
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);
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());
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);
487 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
488 public static Object nodeScalePropertyEnumerationValues(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
489 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
490 return listInstanceNames(graph, context, DN.Vertex_ScaleProperty);
493 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
494 public static Object edgeThicknessPropertyModifier(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
495 Resource diagram = resolveElement(graph, context);
496 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
497 return baseMappingModifier(graph, diagram, DN.Diagram_edgeThicknessProperty, DN.Edge_ThicknessProperty, context);
500 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
501 public static Object nodeScalePropertyModifier(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
502 Resource diagram = resolveElement(graph, context);
503 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
504 return baseMappingModifier(graph, diagram, DN.Diagram_nodeScaleProperty, DN.Vertex_ScaleProperty, context);
507 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
508 public static Function1<Resource, Double> hasDiameterValue(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
509 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Edge_HasDiameter, 0);
512 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
513 public static Function1<Resource, Double> hasNominalMassFlowValue(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
514 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Edge_HasNominalMassFlow, 0);
517 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
518 public static Function1<Resource, Double> hasNominalSupplyPressure(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
519 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Vertex_HasSupplyPressure, 0);
522 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
523 public static Function1<Resource, Double> hasElevation(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
524 return directPropertyValueFunction(DistrictNetworkResource.getInstance(graph).Vertex_HasElevation, 0);
527 private static final Function1<Resource, Double> ONE = new FunctionImpl1<Resource, Double>() {
528 private final Double ONE = 1.0;
530 public Double apply(Resource edge) {
534 public String toString() {
539 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
540 public static Function1<Resource, Double> constantOne(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
544 private static Function1<Resource, Double> directPropertyValueFunction(Resource property, double defaultValue) throws DatabaseException {
545 Double def = defaultValue;
546 return new FunctionImpl1<Resource, Double>() {
548 public Double apply(Resource edge) {
549 ReadGraph graph = (ReadGraph) SCLContext.getCurrent().get("graph");
551 Double d = graph.getPossibleRelatedValue(edge, property, Bindings.DOUBLE);
552 return d != null ? d : def;
553 } catch (DatabaseException e) {
554 LOGGER.error("Failed to evaluate property value", e);
561 private static class RangeValidator implements Function1<String, String> {
564 public RangeValidator(double min, double max) {
569 public String apply(String s) {
571 double d = Double.parseDouble(s);
573 return "Value must be greater than or equal to " + min;
575 return "Value must be less than or equal to " + max;
577 } catch (NumberFormatException e) {
578 return "Specified value is not a number";
583 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
584 public static Object hueValidator(ReadGraph graph, Resource r, Variable context) throws DatabaseException {
585 return new RangeValidator(0, 360);
588 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
589 public static Object saturationValidator(ReadGraph graph, Resource r, Variable context) throws DatabaseException {
590 return new RangeValidator(0, 100);
593 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
594 public static Object brightnessValidator(ReadGraph graph, Resource r, Variable context) throws DatabaseException {
595 String importEntry = null;
596 Resource root = Variables.getPossibleIndexRoot(graph, context);
598 Resource sclmain = Layer0Utils.getPossibleChild(graph, root, "SCLMain");
599 if (sclmain != null) {
600 importEntry = graph.getPossibleURI(sclmain);
603 SCLContext ctx = SCLContext.getCurrent();
604 Object oldGraph = ctx.put("graph", graph);
606 return new BrightnessExpressionValidator(
608 ? Arrays.asList(importEntry)
609 : Collections.emptyList());
611 ctx.put("graph", oldGraph);
615 private static class BrightnessExpressionValidator implements Function1<String, String> {
616 private CommandSession session;
618 public BrightnessExpressionValidator(List<String> importEntries) {
619 this.session = new CommandSession(SCLOsgi.MODULE_REPOSITORY, SCLReportingHandler.DEFAULT);
620 this.session.setImportEntries(imports(importEntries));
623 private ArrayList<CommandSessionImportEntry> imports(List<String> entries) {
624 ArrayList<CommandSessionImportEntry> result = new ArrayList<>();
625 entries.stream().map(CommandSessionImportEntry::new).forEach(result::add);
626 if (entries.isEmpty())
627 result.add(new CommandSessionImportEntry("Simantics/District/SCLMain"));
632 public String apply(String s) {
634 if (!s.startsWith("="))
635 return "Expression expected, must start with '='";
636 CompilationError[] errors = session.validate(s.substring(1));
637 if(errors.length == 0)
639 return errors[0].description;