]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling/src/org/simantics/modeling/adapters/SCLLabelRule.java
e0bff0fe126331208d1331f58de18381e66bba3f
[simantics/platform.git] / bundles / org.simantics.modeling / src / org / simantics / modeling / adapters / SCLLabelRule.java
1 package org.simantics.modeling.adapters;
2
3 import java.util.Collections;
4 import java.util.HashMap;
5 import java.util.List;
6 import java.util.Map;
7
8 import org.simantics.browsing.ui.model.labels.LabelRule;
9 import org.simantics.db.ReadGraph;
10 import org.simantics.db.Resource;
11 import org.simantics.db.exception.DatabaseException;
12 import org.simantics.db.layer0.variable.Variable;
13 import org.simantics.db.layer0.variable.Variables;
14 import org.simantics.modeling.ModelingResources;
15 import org.simantics.scl.runtime.SCLContext;
16 import org.simantics.scl.runtime.function.Function1;
17
18 public class SCLLabelRule implements LabelRule {
19
20     private Resource rule;
21     
22     public SCLLabelRule(ReadGraph graph, Resource rule) {
23         this.rule = rule;
24     }
25     
26     @Override
27     public boolean isCompatible(Class<?> contentType) {
28         return contentType.equals(Resource.class) || contentType.equals(Variable.class);
29     }
30
31     @Override
32     public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {
33         ModelingResources MOD = ModelingResources.getInstance(graph);
34         
35         Variable ruleVariable = Variables.getVariable(graph, rule);
36
37         Function1<Object,List<String>> getLabels = ruleVariable.getPossiblePropertyValue(graph, MOD.SCLLabelRule_getLabels);
38         if(getLabels == null) return Collections.emptyMap();
39
40         SCLContext sclContext = SCLContext.getCurrent();
41         Object oldGraph = sclContext.get("graph");
42         try {
43             sclContext.put("graph", graph);
44             List<String> value = getLabels.apply(content);
45             Map<String,String> result = new HashMap<>();
46             for(int i=0;i<value.size();i+=2) {
47                 result.put(value.get(i), value.get(i+1));
48             }
49             return result;
50         } catch (Throwable t) {
51                 throw new DatabaseException(t);
52         } finally {
53             sclContext.put("graph", oldGraph);
54         }
55     }
56
57 }