]> gerrit.simantics Code Review - simantics/platform.git/blob
c5d2f81b42c36c74ac29eb304a99d9d1d86ef62d
[simantics/platform.git] /
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.browsing.ui.graph.impl;
13
14 import org.simantics.browsing.ui.content.Labeler.Modifier;
15 import org.simantics.databoard.Bindings;
16 import org.simantics.databoard.Datatypes;
17 import org.simantics.databoard.binding.Binding;
18 import org.simantics.databoard.binding.NumberBinding;
19 import org.simantics.databoard.binding.StringBinding;
20 import org.simantics.databoard.binding.error.BindingException;
21 import org.simantics.databoard.binding.mutable.MutableStringBinding;
22 import org.simantics.databoard.parser.repository.DataTypeSyntaxError;
23 import org.simantics.databoard.parser.repository.DataValueRepository;
24 import org.simantics.databoard.primitives.MutableString;
25 import org.simantics.databoard.type.Datatype;
26 import org.simantics.databoard.type.NumberType;
27 import org.simantics.databoard.units.IUnitConverter;
28 import org.simantics.databoard.util.Range;
29 import org.simantics.db.ReadGraph;
30 import org.simantics.db.RequestProcessor;
31 import org.simantics.db.Resource;
32 import org.simantics.db.Session;
33 import org.simantics.db.UndoContext;
34 import org.simantics.db.WriteGraph;
35 import org.simantics.db.common.request.ReadRequest;
36 import org.simantics.db.common.request.WriteRequest;
37 import org.simantics.db.exception.DatabaseException;
38 import org.simantics.db.layer0.util.PrimitiveValueParser;
39 import org.simantics.db.layer0.variable.InputValidator;
40 import org.simantics.db.layer0.variable.InputValidatorFactory;
41 import org.simantics.db.layer0.variable.Variable;
42 import org.simantics.db.layer0.variable.VariableWrite;
43 import org.simantics.db.layer0.variable.Variables;
44 import org.simantics.scl.runtime.function.Function1;
45 import org.simantics.utils.datastructures.Callback;
46 import org.simantics.utils.format.FormattingUtils;
47 import org.simantics.utils.ui.ErrorLogger;
48
49 /**
50  * @author Tuukka Lehtonen
51  */
52 public class VariableModifier implements Modifier {
53
54     final protected Session     session;
55     final protected UndoContext undoContext;
56     final protected Variable    variable;
57     final protected String      targetUnit;
58
59     private String              initialValue;
60     protected Throwable         modifierFailed;
61     private Datatype            datatype;
62     protected Binding           binding;
63     protected InputValidator    variableInputValidator;
64
65     public VariableModifier(RequestProcessor processor, Variable variable) {
66         this(processor, variable, null);
67     }
68
69     public VariableModifier(RequestProcessor processor, Variable variable, String targetUnit) {
70         this.variable = variable;
71         this.session = processor.getSession();
72         this.undoContext = null;
73         this.targetUnit = targetUnit;
74
75         initializeModifier(processor);
76     }
77
78     public VariableModifier(RequestProcessor processor, UndoContext undoContext, Variable variable, String targetUnit) {
79         this.variable = variable;
80         this.undoContext = undoContext;
81         this.session = processor.getSession();
82         this.targetUnit = targetUnit;
83
84         initializeModifier(processor);
85     }
86
87     protected void initializeModifier(RequestProcessor processor) {
88         try {
89             processor.syncRequest(new ReadRequest() {
90                 @Override
91                 public void run(ReadGraph graph) throws DatabaseException {
92                         String expression = variable.getPossiblePropertyValue(graph, Variables.EXPRESSION);
93                         if(expression == null) {
94                             datatype = variable.getPossibleDatatype(graph);
95                             if (datatype == null) {
96                                 // Deprecated.
97                                 // This is here for some backwards compatibility.
98                                 datatype = variable.getInterface(graph, Datatype.class);
99                                 if (datatype == null)
100                                     throw new org.simantics.db.exception.BindingException("no datatype for variable " + variable, null);
101                             }
102                             initialValue = getInitialValue(graph, datatype);
103                             binding = Bindings.getBinding(datatype);
104                             initializeValidator(graph, variable);
105                         }
106                         else {
107                                 initialValue = "= " + expression;
108                                 binding = Bindings.STRING;
109                                 datatype = Datatypes.STRING;
110                         }
111                 }
112             });
113         } catch (DatabaseException e) {
114             ErrorLogger.defaultLogError("Modifier initialization failed, see exception for details.", e);
115             modifierFailed = e;
116         }
117     }
118
119     protected void initializeValidator(ReadGraph graph, Variable var) throws DatabaseException {
120         //System.out.println(var.getURI(graph));
121
122         Resource resource = var.getPossibleRepresents(graph);
123 //        if (resource != null)
124 //            System.out.println("represents: " + graph.getPossibleURI(resource));
125
126         Resource pr = variable.getPossiblePredicateResource(graph);
127         
128 //        Variable predicate = variable.getPossiblePropertyValue(graph, Variables.PREDICATE);
129 //        if (predicate != null) {
130 //            Resource pr = predicate.getPropertyValue(graph, Variables.REPRESENTS);
131             if (pr != null)
132                 variableInputValidator = tryInputValidatorFactory(graph, var, resource, pr);
133 //        }
134
135         if (variableInputValidator == null) {
136             final Function1<String, String> validator = variable.getPossiblePropertyValue(graph, Variables.INPUT_VALIDATOR);
137             if (validator != null)
138                 variableInputValidator = new InputValidator() {
139                     
140                     @Override
141                     public String isValid(Object newValue) {
142                         return validator.apply((String)newValue);
143                     }
144                 };
145         }
146
147         if (variableInputValidator == null) {
148             Variable parent = variable.getParent(graph);
149             if (parent != null) {
150                 Resource parentResource = parent.getPossibleRepresents(graph);
151                 if (parentResource != null)
152                     variableInputValidator = tryInputValidatorFactory(graph, var, resource, parentResource);
153             }
154         }
155
156         if (variableInputValidator == null)
157             variableInputValidator = var.getInterface(graph, InputValidator.class);
158         
159     }
160
161     private InputValidator tryInputValidatorFactory(ReadGraph graph, Variable var, Resource varRepresents, Resource r) throws DatabaseException {
162         //System.out.println("tryInputValidatorFactory(" + var.getURI(graph) + ", " + NameUtils.getSafeName(graph, varRepresents) + ", " + NameUtils.getSafeName(graph, r) + ")");
163         InputValidatorFactory validatorFactory = graph.getPossibleAdapter(r, InputValidatorFactory.class);
164         if (validatorFactory == null)
165             return null;
166         //System.out.println("got validator factory: " + validatorFactory);
167         return validatorFactory.create(graph, var);
168     }
169
170     protected void doModify(final String label) {
171         if(label.startsWith("=")) {
172                 session.asyncRequest(new WriteRequest() {
173                                 @Override
174                                 public void perform(WriteGraph graph) throws DatabaseException {
175                                         variable.setPropertyValue(graph, Variables.EXPRESSION, 
176                                                         label.substring(1).trim());
177                                 }
178                         });
179         }
180         else {
181                 if(initialValue.startsWith("="))
182                                 try {
183                                         session.syncRequest(new WriteRequest() {
184                                                 @Override
185                                                 public void perform(WriteGraph graph) throws DatabaseException {
186                                                         variable.setPropertyValue(graph, Variables.EXPRESSION, null);
187                                                 }
188                                         });
189                                 } catch (DatabaseException e) {
190                                         e.printStackTrace();
191                                 }
192                 session.asyncRequest(new VariableWrite(variable, label, null, targetUnit), new Callback<DatabaseException>() {
193                     @Override               
194                     public void run(DatabaseException parameter) {
195                         if (parameter != null)
196                             ErrorLogger.defaultLogError(parameter);
197                         else
198                                 modifySuccessful();
199                     }
200                 });
201         }
202     }
203
204     protected void modifySuccessful() {
205         }
206
207         protected String getInitialValue(ReadGraph graph, Datatype dataType) throws DatabaseException {
208         // TODO: more generic support through DataValuePrinter
209         Object value = variable.getPossibleValue(graph);
210         if(value == null) return "";
211         String unit = Variables.getPossibleUnit(graph, variable);
212         //String unit = variable.getPossiblePropertyValue(graph, Variables.UNIT);
213         if(value instanceof Double && unit != null && targetUnit != null) {
214             IUnitConverter converter = VariableWrite.converter(unit, targetUnit);
215             value = converter.convert((Double)value);
216         }
217         return FormattingUtils.US.engineeringFormat(value);
218     }
219
220     @Override
221     public String getValue() {
222         return initialValue;
223     }
224
225     @Override
226     public String isValid(String label) {
227         if (label.startsWith("="))
228             return null;
229
230         if (modifierFailed != null)
231             return "Could not resolve validator for this value, modification denied. Reason: " + modifierFailed.getMessage();
232
233         if (variableInputValidator != null)
234             return variableInputValidator.isValid(label);
235
236         try {
237             if (binding instanceof StringBinding) {
238                 // Use the binding to validate strings since they might have
239                 // mime-types and/or patterns attached.
240                 if (binding instanceof MutableStringBinding) {
241                     binding.assertInstaceIsValid(new MutableString(label));
242                 } else {
243                     binding.assertInstaceIsValid(label);
244                 }
245             } else {
246                 if (binding instanceof NumberBinding) {
247                     // Numbers are always parsed in US locale, although both ',' and
248                     // '.' are accepted as decimal separators.
249                     label = label.replace(",", ".");
250                     //Object value = binding.parseValue(label, new DataValueRepository());
251                     Object value = PrimitiveValueParser.parse(label, datatype);
252                     NumberType numberType = (NumberType) datatype;
253                     Range range = numberType.getRange();
254                     if (range != null && !range.contains((Number) value))
255                         return "Value is not in range " + range;
256                 } else {
257                     binding.parseValue(label, new DataValueRepository());
258                 }
259             }
260             return null;
261         } catch (IllegalArgumentException e) {
262             // Parsing failed.
263             return e.getLocalizedMessage();
264         } catch (DataTypeSyntaxError e) {
265             // Failed to parse label with binding
266             return e.getLocalizedMessage();
267         } catch (BindingException e) {
268             return e.getLocalizedMessage();
269         }
270     }
271
272     @Override
273     public final void modify(String label) {
274         if (modifierFailed != null)
275             // Should never end up here, isValid should prevent it.
276             throw new Error("modifier failed: " + modifierFailed.getMessage());
277         doModify(label);
278     }
279
280 };