]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.diagram/src/org/simantics/diagram/function/All.java
Fix NPE from flagTransform
[simantics/platform.git] / bundles / org.simantics.diagram / src / org / simantics / diagram / function / All.java
1 package org.simantics.diagram.function;
2
3 import java.awt.geom.AffineTransform;
4 import java.awt.geom.Point2D;
5 import java.util.Arrays;
6 import java.util.Collection;
7 import java.util.List;
8 import java.util.function.Consumer;
9
10 import org.eclipse.swt.SWT;
11 import org.eclipse.swt.graphics.FontData;
12 import org.eclipse.swt.widgets.Control;
13 import org.eclipse.swt.widgets.FontDialog;
14 import org.simantics.Simantics;
15 import org.simantics.browsing.ui.NodeContext;
16 import org.simantics.browsing.ui.content.Labeler.DialogModifier;
17 import org.simantics.databoard.Bindings;
18 import org.simantics.db.ReadGraph;
19 import org.simantics.db.Resource;
20 import org.simantics.db.WriteGraph;
21 import org.simantics.db.common.request.PossibleIndexRoot;
22 import org.simantics.db.common.request.UniqueRead;
23 import org.simantics.db.common.request.WriteRequest;
24 import org.simantics.db.exception.DatabaseException;
25 import org.simantics.db.layer0.exception.MissingVariableException;
26 import org.simantics.db.layer0.request.PossibleConfiguration;
27 import org.simantics.db.layer0.variable.Variable;
28 import org.simantics.db.layer0.variable.Variables;
29 import org.simantics.diagram.content.ElementContext;
30 import org.simantics.diagram.stubs.DiagramResource;
31 import org.simantics.diagram.stubs.G2DResource;
32 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
33 import org.simantics.issues.common.IssueUtils;
34 import org.simantics.layer0.Layer0;
35 import org.simantics.modeling.ModelingResources;
36 import org.simantics.modeling.template2d.ontology.Template2dResource;
37 import org.simantics.scenegraph.loader.SceneGraphContext;
38 import org.simantics.scenegraph.loader.ScenegraphLoaderUtils;
39 import org.simantics.scl.reflection.annotations.SCLValue;
40 import org.simantics.ui.fonts.Fonts;
41 import org.simantics.utils.ui.AdaptionUtils;
42 import org.simantics.utils.ui.ErrorLogger;
43
44
45 public class All {
46
47     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
48     public static Variable defaultRuntimeVariable(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
49
50         SceneGraphContext vc = ScenegraphLoaderUtils.getContext(graph, context);
51         if(vc == null) return null;
52
53         DiagramResource DIA = DiagramResource.getInstance(graph);
54         String uri = graph.getRelatedValue(vc.getRuntime(), DIA.RuntimeDiagram_HasVariable, Bindings.STRING);
55         return Variables.getVariable(graph, uri);
56
57     }
58
59     @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")
60     public static String referenceText(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
61
62         //DiagramResource DIA = DiagramResource.getInstance(graph);
63
64         //Resource runtime = ScenegraphLoaderUtils.getRuntime(graph, context);
65         String path = context.getParent(graph).getPropertyValue(graph, "reference", Bindings.STRING);
66
67         // diagram uri and diagram variable
68 //        String diagramURI = graph.getRelatedValue(runtime, DIA.RuntimeDiagram_HasVariable, Bindings.STRING);
69 //        Variable diagramVariable = org.simantics.db.layer0.variable.Variables.getVariable(graph, diagramURI);
70
71 //        Variable property = diagramVariable.browse(graph, path);
72
73         try {
74             Variable selection = ScenegraphLoaderUtils.getPossibleVariableSelection(graph, context);
75                 PredefinedVariables vars = PredefinedVariables.getInstance();
76                 Variable property = vars.getVariable(graph, path, converter, selection);
77                 if (property  != null)
78                         return property.getValue(graph).toString();
79         } catch (MissingVariableException e){
80                 return "Invalid path.";
81         }
82         return null;
83     }
84
85     @SCLValue(type = "ReadGraph -> Resource -> ElementContext -> a")
86     public static Object modelledTransform(ReadGraph graph, Resource converter, ElementContext context) throws DatabaseException {
87         return graph.getRelatedValue(context.element, G2DResource.getInstance(graph).HasTransform, Bindings.DOUBLE_ARRAY);
88     }
89     
90     @SCLValue(type = "ReadGraph -> Resource -> ElementContext -> a")
91     public static Object flagTransform(ReadGraph graph, Resource converter, ElementContext context) throws DatabaseException {
92                 Layer0 L0 = Layer0.getInstance(graph);
93                 DiagramResource DIA = DiagramResource.getInstance(graph);
94         Template2dResource TEMPLATE2D = Template2dResource.getInstance(graph);
95
96                 Resource flag = context.element;
97                 Resource runtimeDiagram = context.runtime;
98                 if (runtimeDiagram == null)
99                         return flagTransformImpl(graph, converter, context);
100
101                 Resource diagram = graph.getPossibleObject(runtimeDiagram, DIA.RuntimeDiagram_HasConfiguration);
102                 if (diagram == null)
103                         return flagTransformImpl(graph, converter, context);
104
105                 Resource template = getTemplateFromDiagram(graph, diagram);
106                 if (template == null)
107                         return flagTransformImpl(graph, converter, context);
108                 
109                 double gridSize = DiagramGraphUtil.getGridSize(graph, diagram, 0.0);
110
111                 String tableName = graph.getPossibleRelatedValue(flag, DIA.Flag_HasIOTableBinding, Bindings.STRING);
112                 Integer rowIndex = graph.getPossibleRelatedValue(flag, DIA.Flag_HasIOTableRowIndex, Bindings.INTEGER);
113 //        double[] mat = graph.getRelatedValue(flag, DIA.HasTransform, Bindings.DOUBLE_ARRAY);
114         
115         
116         Collection<Resource> slotTables = graph.getObjects(template, L0.ConsistsOf);
117         for (Resource slotTable:slotTables){
118                 if (!graph.isInstanceOf(slotTable, TEMPLATE2D.FlagTable))
119                         continue;
120                 String name = graph.getPossibleRelatedValue(slotTable, L0.HasName, Bindings.STRING);
121                 if (!name.equals(tableName))
122                         continue;
123                 
124             double[] transform = graph.getPossibleRelatedValue2(slotTable, DIA.Scenegraph_Composite_transform, Bindings.getBindingUnchecked(double[].class));
125                 Resource align = graph.getPossibleObject(slotTable, TEMPLATE2D.FlagTable_HasAlignment);
126                 boolean isRightAlignment = false;
127                 if (align.equals(TEMPLATE2D.FlagTable_Alignment_Right))
128                         isRightAlignment = true;
129                 Float width = graph.getPossibleRelatedValue(slotTable, TEMPLATE2D.FlagTable_HasWidth, Bindings.FLOAT);
130                 Float rowHeight = graph.getPossibleRelatedValue(slotTable, TEMPLATE2D.FlagTable_HasRowHeigth, Bindings.FLOAT);
131                 //Integer rowCount = g.getPossibleRelatedValue(slotTable, TEMPLATE2D.FlagTable_HasRowCount, Bindings.INTEGER);
132                 
133 //                      Rectangle2D rowBounds = new Rectangle2D.Double(0, rowHeight*rowIndex, width, rowHeight);
134 //                      rowBounds = GeometryUtils.transformShape(rowBounds, new AffineTransform(transform)).getBounds2D();
135 //            e.setHint(FlagClass.KEY_FLAG_BOUNDS, rowBounds);
136             
137             double[] flagTransform = graph.getRelatedValue(flag, DIA.HasTransform, Bindings.DOUBLE_ARRAY);
138             return calcTransform(transform, flagTransform, rowHeight, width, isRightAlignment, rowIndex, gridSize);
139         }
140
141         return flagTransformImpl(graph, converter, context);
142     }
143
144     private static Object flagTransformImpl(ReadGraph graph, Resource converter, ElementContext context) throws DatabaseException {
145         double[] mat = graph.getRelatedValue(context.element, G2DResource.getInstance(graph).HasTransform, Bindings.DOUBLE_ARRAY);
146         return mat;
147     }
148
149         private static double[] calcTransform(double[] tableTransform, double[] flagTransform, Float rowHeight, Float tableWidth, boolean isRightAlignment, Integer flagRowIndex, double gridSize) {
150                 double scale = tableTransform[3];
151                 double scaledRowHeigth = scale*rowHeight;
152
153                 // move to coordinate system of parent of iotable
154                 double rowMiddleY = tableTransform[5]+(flagRowIndex+0.5F)*scaledRowHeigth;
155                 if (gridSize != 0.0) {
156                         double modulo = rowMiddleY%gridSize;
157                         int count =(int) (rowMiddleY/gridSize);
158                         double gridOnRow = (modulo > (gridSize/2))?gridSize*(1+count):gridSize*count;
159                         double diff = (gridOnRow > rowMiddleY)? gridOnRow - rowMiddleY:rowMiddleY-gridOnRow;
160                         if (diff < (scaledRowHeigth/2))
161                                 rowMiddleY = gridOnRow; 
162                 }
163                 // move back to iotable coordinate system
164                 rowMiddleY = (rowMiddleY-tableTransform[5])/scale;
165
166                 double xx = isRightAlignment ? tableWidth : 0.0; 
167
168                 AffineTransform trans = new AffineTransform(new double[]{tableTransform[0],tableTransform[1],tableTransform[2],tableTransform[3],0.0,0.0});
169                 Point2D point = new Point2D.Double(xx, rowMiddleY);
170                 trans.transform(point, point);
171
172                 double[] copy = Arrays.copyOf(flagTransform, flagTransform.length);
173                 copy[4] = tableTransform[4] + point.getX();
174                 copy[5] = tableTransform[5] + point.getY();
175                 return copy;
176         }
177
178     public static Resource getTemplate(ReadGraph graph, Resource runtimeDiagram) throws DatabaseException {
179         DiagramResource DIA = DiagramResource.getInstance(graph);
180         Resource diagram = graph.getPossibleObject(runtimeDiagram, DIA.RuntimeDiagram_HasConfiguration);
181         if (diagram == null)
182             return null;
183         return getTemplateFromDiagram(graph, diagram);
184     }
185
186     public static Resource getTemplateFromDiagram(ReadGraph graph, Resource diagram) throws DatabaseException {
187         Template2dResource TEMPLATE2D = Template2dResource.getInstance(graph);
188         Resource template = graph.getPossibleObject(diagram, TEMPLATE2D.HasDrawingTemplate);
189         return template;
190     }
191
192     @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")
193     public static String diagramElementIssuePath(ReadGraph graph, Resource converter, Variable property) throws DatabaseException {
194         Layer0 L0 = Layer0.getInstance(graph);
195         ModelingResources MOD = ModelingResources.getInstance(graph);
196         DiagramResource DIA = DiagramResource.getInstance(graph);
197
198         List<Resource> contexts = IssueUtils.getContextsForProperty(graph, property);
199         if(contexts.isEmpty()) return "";
200
201         Resource context = contexts.get(0);
202
203         Resource mapped = graph.getPossibleObject(context, MOD.ComponentToElement);
204         if(mapped != null) context = mapped;
205         mapped = graph.getPossibleObject(context, MOD.ConnectionToDiagramConnection);
206         if(mapped != null) context = mapped;
207
208         if(!graph.isInstanceOf(context, DIA.Element)) return "";
209
210         Resource configuration = graph.sync(new PossibleConfiguration(context));
211         if(configuration == null) return "";
212
213         Resource diagram = graph.getPossibleObject(context, L0.PartOf);
214         if(diagram == null) return "";
215
216         Resource composite = graph.getPossibleObject(diagram, MOD.DiagramToComposite);
217         if(composite == null) return "";
218
219         Resource issueRoot = Variables.getPossibleIndexRoot(graph, property);
220         if(issueRoot == null) return "";
221         Resource contextRoot = graph.sync(new PossibleIndexRoot(composite));
222         if(contextRoot == null) return "";
223         if(issueRoot.equals(contextRoot)) {
224             String uri = graph.getURI(composite);
225             String modelURI = graph.getURI(contextRoot);
226             return IssueUtils.pathString(uri, modelURI.length()+1);
227         } else {
228             String uri = graph.getURI(composite);
229             String modelURI = graph.getURI(graph.getRootLibrary());
230             return IssueUtils.pathString(uri, modelURI.length()+1);
231         }
232     }
233
234     @SCLValue(type = "ReadGraph -> Resource -> Variable -> a")
235     public static Object fontModifier(ReadGraph graph, Resource r, final Variable variable) throws DatabaseException {
236         return new DialogModifier() {
237
238                 @Override
239                 public String getValue() {
240                         return null;
241                 }
242
243                 @Override
244                 public String isValid(String label) {
245                         return null;
246                 }
247
248                 @Override
249                 public void modify(final String label) {
250                         Simantics.getSession().async(new WriteRequest() {
251
252                                 @Override
253                                 public void perform(WriteGraph graph) throws DatabaseException {
254                                         Variable displayValue = variable.getParent(graph);
255                                         displayValue.setValue(graph, label, Bindings.STRING);
256                                 }
257
258                         });
259                 }
260
261                 public String query(Object parentControl, Object controlItem, int columnIndex, NodeContext context, Consumer<String> applyCallback) {
262                         
263                         Control ctrl = (Control) parentControl;
264                         FontData[] initialValue = null;
265                         
266                         try {
267                                 String font = Simantics.getSession().syncRequest(new UniqueRead<String>() {
268                                         @Override
269                                         public String perform(ReadGraph graph) throws DatabaseException {
270                                                 Variable v = AdaptionUtils.adaptToSingle(context, Variable.class);
271                                                 if(v == null) return null;
272                                                 String displayValue = v.getPossiblePropertyValue(graph, "HasDisplayValue", Bindings.STRING);
273                                                 return displayValue;
274                                         }
275                                 });
276                                 if (font != null) {
277                                         String[] fields = font.split(",");
278                                         if (fields.length == 3) {
279                                                 int size = 14;
280                                                 try {
281                                                         size = Integer.parseInt(fields[1]);
282                                                 } catch (NumberFormatException e) {
283                                                         ErrorLogger.defaultLogError(e);
284                                                 }
285                                                 int style = SWT.NORMAL;
286                                                 try {
287                                                         style = Fonts.swtStyle(fields[2]);
288                                                 } catch (RuntimeException e) {
289                                                         ErrorLogger.defaultLogError(e);
290                                                 }
291                                                 initialValue = new FontData[] { new FontData(fields[0], size, style) };
292                                         }
293                                 }
294                         } catch (DatabaseException e) {
295                                 ErrorLogger.defaultLogError(e);
296                         }
297
298                         FontDialog dialog = new FontDialog(ctrl.getShell());
299                         if (initialValue != null)
300                                 dialog.setFontList(initialValue);
301                         FontData font = dialog.open();
302                         if (font != null)
303                                 applyCallback.accept(font.getName() + "," + font.getHeight() + "," + Fonts.fromSwtStyle(font.getStyle()));
304                         return null;
305                 }
306
307         };
308         
309     }
310     
311 }