1 package org.simantics.spreadsheet.graph.adapter;
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.Collections;
7 import org.simantics.databoard.Bindings;
8 import org.simantics.databoard.binding.Binding;
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.ConstantChildVariable;
13 import org.simantics.db.layer0.variable.Variable;
14 import org.simantics.db.layer0.variable.VariableFactory;
15 import org.simantics.db.layer0.variable.Variables;
16 import org.simantics.spreadsheet.Spreadsheets;
17 import org.simantics.spreadsheet.resource.SpreadsheetResource;
19 public class StringArrayCells implements VariableFactory {
21 private Resource configuration;
23 public StringArrayCells(Resource configuration) {
24 this.configuration = configuration;
27 final String[] propertyNames = { Variables.LABEL, "immutable" };
28 final Binding[] bindings = { Bindings.STRING, Bindings.BOOLEAN };
30 private Collection<Variable> toVariables(ReadGraph graph, Variable variable, String[] data, int width) throws DatabaseException {
32 SpreadsheetResource sr = SpreadsheetResource.getInstance(graph);
33 String location = graph.getPossibleRelatedValue(configuration, sr.HasLocation, Bindings.STRING);
34 if(location == null) return Collections.emptyList();
36 int rows = data.length / width;
38 ArrayList<Variable> result = new ArrayList<Variable>();
39 for(int offset=0,i=0;i<rows;i++) {
40 for(int j=0;j<width;j++) {
41 String value = data[offset++];
42 String valueLocation = Spreadsheets.offset(location, i, j);
43 result.add(new ConstantChildVariable(variable, valueLocation, propertyNames, bindings, new Object[] { value, true }));
50 private Collection<Variable> error(ReadGraph graph, Variable variable, String message) throws DatabaseException {
52 SpreadsheetResource sr = SpreadsheetResource.getInstance(graph);
53 String location = graph.getPossibleRelatedValue(configuration, sr.HasLocation, Bindings.STRING);
54 if(location == null) return Collections.emptyList();
56 return Collections.<Variable>singletonList(new ConstantChildVariable(variable, location, propertyNames, bindings, new Object[] { message }));
61 public Collection<Variable> evaluate(ReadGraph graph, Variable variable) throws DatabaseException {
63 SpreadsheetResource sr = SpreadsheetResource.getInstance(graph);
64 String[] data = graph.getPossibleRelatedValue(configuration, sr.StringArrayCell_HasStringArray, Bindings.STRING_ARRAY);
65 if(data == null) return error(graph, variable, "No string array data.");
66 Integer width = graph.getPossibleRelatedValue(configuration, sr.StringArrayCell_HasWidth, Bindings.INTEGER);
67 if(width == null) return error(graph, variable, "Invalid width for string array.");
69 return toVariables(graph, variable, data, width);