1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.browsing.ui.graph.impl;
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;
50 * @author Tuukka Lehtonen
52 public class VariableModifier implements Modifier {
54 final protected Session session;
55 final protected UndoContext undoContext;
56 final protected Variable variable;
57 final protected String targetUnit;
59 private String initialValue;
60 protected Throwable modifierFailed;
61 private Datatype datatype;
62 protected Binding binding;
63 protected InputValidator variableInputValidator;
65 public VariableModifier(RequestProcessor processor, Variable variable) {
66 this(processor, variable, null);
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;
75 initializeModifier(processor);
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;
84 initializeModifier(processor);
87 protected void initializeModifier(RequestProcessor processor) {
89 processor.syncRequest(new ReadRequest() {
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) {
97 // This is here for some backwards compatibility.
98 datatype = variable.getInterface(graph, Datatype.class);
100 throw new org.simantics.db.exception.BindingException("no datatype for variable " + variable, null);
102 initialValue = getInitialValue(graph, datatype);
103 binding = Bindings.getBinding(datatype);
104 initializeValidator(graph, variable);
107 initialValue = "= " + expression;
108 binding = Bindings.STRING;
109 datatype = Datatypes.STRING;
113 } catch (DatabaseException e) {
114 ErrorLogger.defaultLogError("Modifier initialization failed, see exception for details.", e);
119 protected void initializeValidator(ReadGraph graph, Variable var) throws DatabaseException {
120 //System.out.println(var.getURI(graph));
122 Resource resource = var.getPossibleRepresents(graph);
123 // if (resource != null)
124 // System.out.println("represents: " + graph.getPossibleURI(resource));
126 Resource pr = variable.getPossiblePredicateResource(graph);
128 // Variable predicate = variable.getPossiblePropertyValue(graph, Variables.PREDICATE);
129 // if (predicate != null) {
130 // Resource pr = predicate.getPropertyValue(graph, Variables.REPRESENTS);
132 variableInputValidator = tryInputValidatorFactory(graph, var, resource, pr);
135 if (variableInputValidator == null) {
136 final Function1<String, String> validator = variable.getPossiblePropertyValue(graph, Variables.INPUT_VALIDATOR);
137 if (validator != null)
138 variableInputValidator = new InputValidator() {
141 public String isValid(Object newValue) {
142 return validator.apply((String)newValue);
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);
156 if (variableInputValidator == null)
157 variableInputValidator = var.getInterface(graph, InputValidator.class);
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)
166 //System.out.println("got validator factory: " + validatorFactory);
167 return validatorFactory.create(graph, var);
170 protected void doModify(final String label) {
171 if(label.startsWith("=")) {
172 session.asyncRequest(new WriteRequest() {
174 public void perform(WriteGraph graph) throws DatabaseException {
175 variable.setPropertyValue(graph, Variables.EXPRESSION,
176 label.substring(1).trim());
181 if(initialValue.startsWith("="))
183 session.syncRequest(new WriteRequest() {
185 public void perform(WriteGraph graph) throws DatabaseException {
186 variable.setPropertyValue(graph, Variables.EXPRESSION, null);
189 } catch (DatabaseException e) {
192 session.asyncRequest(new VariableWrite(variable, label, null, targetUnit), new Callback<DatabaseException>() {
194 public void run(DatabaseException parameter) {
195 if (parameter != null)
196 ErrorLogger.defaultLogError(parameter);
204 protected void modifySuccessful() {
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);
217 return FormattingUtils.US.engineeringFormat(value);
221 public String getValue() {
226 public String isValid(String label) {
227 if (label.startsWith("="))
230 if (modifierFailed != null)
231 return "Could not resolve validator for this value, modification denied. Reason: " + modifierFailed.getMessage();
233 if (variableInputValidator != null)
234 return variableInputValidator.isValid(label);
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));
243 binding.assertInstaceIsValid(label);
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;
257 binding.parseValue(label, new DataValueRepository());
261 } catch (IllegalArgumentException e) {
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();
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());