]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.diagram/src/org/simantics/diagram/profile/TextGridStyle.java
997ace1d63f12a87db7fc6fcaaec5f630fc92be3
[simantics/platform.git] / bundles / org.simantics.diagram / src / org / simantics / diagram / profile / TextGridStyle.java
1 package org.simantics.diagram.profile;
2
3 import java.awt.Color;
4 import java.awt.Font;
5 import java.awt.geom.AffineTransform;
6 import java.awt.geom.Point2D;
7 import java.awt.geom.Rectangle2D;
8
9 import org.simantics.databoard.Bindings;
10 import org.simantics.datatypes.literal.Vec2d;
11 import org.simantics.db.ReadGraph;
12 import org.simantics.db.Resource;
13 import org.simantics.db.exception.DatabaseException;
14 import org.simantics.db.layer0.variable.RVI;
15 import org.simantics.db.layer0.variable.Variable;
16 import org.simantics.diagram.elements.ITextListener;
17 import org.simantics.diagram.elements.TextGridNode;
18 import org.simantics.diagram.elements.TextNode;
19 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
20 import org.simantics.g2d.utils.Alignment;
21 import org.simantics.modeling.ModelingResources;
22 import org.simantics.scenegraph.INode;
23 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
24 import org.simantics.scenegraph.profile.EvaluationContext;
25 import org.simantics.scenegraph.profile.common.ProfileVariables;
26 import org.simantics.scenegraph.utils.GeometryUtils;
27 import org.simantics.scenegraph.utils.NodeUtil;
28 import org.simantics.scl.runtime.function.Function1;
29 import org.simantics.ui.colors.Colors;
30
31 /**
32  * @author Antti Villberg
33  * @author Tuukka Lehtonen
34  */
35 public abstract class TextGridStyle extends StyleBase<MonitorTextGridResult> {
36
37         private final Font  FONT             = Font.decode("Arial 12");
38         private final Color BACKGROUND_COLOR = new Color(255, 255, 255, 192);
39         private static final Rectangle2D EMPTY_BOUNDS = new Rectangle2D.Double(0, 0, 0, 0);
40
41         protected double xOffset;
42         protected double yOffset;
43
44         public TextGridStyle(Resource r) {
45                 this(r, 0.0, 2.1);
46         }
47
48         public TextGridStyle(Resource r, double xOffset, double yOffset) {
49             super(r);
50                 this.xOffset = xOffset;
51                 this.yOffset = yOffset;
52         }
53
54         public Resource getPropertyRelation(ReadGraph g, Resource module) {
55         throw new Error("Fix this");
56         }
57
58         /**
59          * @return the name of the scene graph node to create to represent the text
60          *         element created by this style
61          */
62         public String getNodeName() {
63                 return getClass().getSimpleName();
64         }
65
66         /**
67          * Override to customize.
68          * 
69          * @param graph
70          * @param element
71          * @return
72          * @throws DatabaseException
73          */
74         protected Resource getConfigurationComponent(ReadGraph graph, Resource element) throws DatabaseException {
75                 ModelingResources mr = ModelingResources.getInstance(graph);
76                 Resource config = graph.getPossibleObject(element, mr.ElementToComponent);
77                 return config;
78         }
79
80         /**
81          * Override to customize.
82          * 
83          * @param graph
84          * @param element
85          * @return
86          * @throws DatabaseException
87          */
88         protected String getConfigurationComponentNameForElement(ReadGraph graph, Resource element) throws DatabaseException {
89                 Resource config = getConfigurationComponent(graph, element);
90                 if (config == null)
91                         return null;
92                 String name = graph.getPossibleRelatedValue(config, getPropertyRelation(graph,element), Bindings.STRING);
93                 return name;
94         }
95
96         public AffineTransform getTransform(INode node, AffineTransform parentTransform, Rectangle2D elementBounds, int location, boolean up) {
97                 return getTransform(parentTransform, elementBounds, location, up);
98         }
99
100         public AffineTransform getTransform(AffineTransform parentTransform, Rectangle2D elementBounds, int location, boolean up) {
101
102                 double scale = GeometryUtils.getScale(parentTransform);
103
104                 AffineTransform at = AffineTransform.getTranslateInstance(
105                                 parentTransform.getTranslateX() + elementBounds.getCenterX() * scale + xOffset,
106                                 parentTransform.getTranslateY() + elementBounds.getMinY() * scale + yOffset*(location-1) + (up ? 0.0 : (2.0*yOffset) + elementBounds.getHeight() * scale) 
107                                 );
108                 at.scale(0.15, 0.15);
109
110                 return at;
111
112         }
113
114         protected String rowId() {
115                 return "";
116         }
117
118         @Override
119         public MonitorTextGridResult calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource element, Variable configuration)
120                         throws DatabaseException {
121                 String name = getConfigurationComponentNameForElement(graph, element);
122                 if (name == null)
123                         return null;
124                 AffineTransform transform = DiagramGraphUtil.getDynamicAffineTransform(graph, runtimeDiagram, element);
125                 Vec2d offset = DiagramGraphUtil.getOffset(graph, element);
126                 boolean enabled = !DiagramGraphUtil.getProfileMonitorsHidden(graph, element);
127                 boolean up = DiagramGraphUtil.getProfileMonitorsUp(graph, element);
128                 double spacing = DiagramGraphUtil.getProfileMonitorSpacing(graph, element);
129                 return new MonitorTextGridResult(rowId(), name, "", "", enabled, up, spacing, null, null, null, transform, offset);
130         }
131
132         // Not to be modified
133         protected final static Point2D[] DEFAULT_CELL_OFFSETS = new Point2D[] {
134                         new Point2D.Double(-45, 0),
135                         new Point2D.Double(22, 0),
136                         new Point2D.Double(24, 0)
137         };
138
139         // Not to be modified
140         protected final static Point2D[] ZERO_CELL_OFFSETS = new Point2D[] {
141                         new Point2D.Double(0, 0),
142                         new Point2D.Double(0, 0),
143                         new Point2D.Double(0, 0)
144         };
145
146         protected Point2D[] getCellOffsets() {
147                 return DEFAULT_CELL_OFFSETS;
148         }
149
150         @Override
151         public void applyStyleForNode(EvaluationContext observer, INode _node, MonitorTextGridResult result) {
152
153                 String value = result != null ? result.getText1() : null;
154                 boolean enabled = result != null ? result.getEnabled() : false;
155
156                 if (value != null && enabled) {
157
158                         //        if (value != null && !value.isEmpty() && !value.trim().isEmpty()) {
159
160                         String value2 = result != null ? result.getText2() : null;
161                         String value3 = result != null ? result.getText3() : null;
162
163                         double spacing = result.getSpacing();
164
165                         final Function1<String, String> modifier = result != null ? result.getModifier() : null;
166                         final Function1<String, String> validator = result != null ? result.getValidator() : null;
167                         final Function1<Vec2d, Boolean> translator = result != null ? result.getTranslator() : null;
168                         final RVI rvi = result != null ? result.getRVI() : null;
169
170                         final TextGridNode node = ProfileVariables.claimChild(_node, "", "TextGridStyle", TextGridNode.class, observer);
171                         if (node == null)
172                                 return;
173
174                         // This assumes that this TextGridStyle instance will be devoted to
175                         // this row ID until the end of its life.
176 //                      String id = result.getRowId();
177 //                      System.out.println(this + " ID: " + id);
178 //                      if (!id.equals(this.id)) {
179 //                              System.out.println(this + " SET ID: " + this.id + " -> " + id);
180 //                              this.id = id;
181 //                      }
182
183                         Integer newRow = observer.getTemporaryProperty(_node, "location");
184                         if (newRow == null)
185                                 newRow = 1;
186
187                         // Remove from existing row to add to another row if necessary.
188                         Integer row = getCurrentRowNumber(observer, _node);
189                         if (row != null && row != newRow) {
190                                 String actualId = node.getRowId(row);
191                                 String id = observer.getProperty(_node, rowIdKey());
192                                 if (id.equals(actualId)) {
193                                         node.removeRow(row);
194                                 }
195                         }
196                         row = newRow;
197
198                         node.setRowId(row, result.getRowId());
199
200                         setCurrentRowNumber(observer, _node, result.getRowId(), row);
201
202                         observer.setTemporaryProperty(_node, "location", row + 1);
203
204                         node.setText(2, row, value2);
205                         node.setUp(result.getUp());
206
207                         MonitorTextGridResult cache = node.getCache(1, row);
208                         if(cache != null && cache.sameStructure(result)) return;
209
210                         node.setCache(1, row, result);
211
212                         boolean isConnection = _node instanceof ConnectionNode;
213
214                         Rectangle2D elementBounds = isConnection ? EMPTY_BOUNDS : NodeUtil.getLocalElementBounds(_node);
215                         if(elementBounds == null) {
216                                 new Exception("Cannot get local element bounds for node " + _node.toString()).printStackTrace();
217                                 // This is here for checking why getLocalElementBounds failed in the debugger.
218                                 NodeUtil.getLocalElementBounds(_node);
219                                 return;
220                         }
221
222                         //            System.err.println("elementBounds " + elementBounds);
223                         //            System.err.println("parentTransform " + result.getParentTransform());
224
225                         AffineTransform at = getTransform(_node,result.getParentTransform(), elementBounds, row, result.getUp());
226                         Vec2d offset = result.getOffset();
227
228                         Point2D[] cellOffsets = getCellOffsets();
229
230                         AffineTransform at1 = new AffineTransform(at);
231                         at1.translate(cellOffsets[0].getX(),cellOffsets[0].getY());
232                         AffineTransform at2 = new AffineTransform(at);
233                         at2.translate(cellOffsets[1].getX()+spacing,cellOffsets[1].getY());
234                         AffineTransform at3 = new AffineTransform(at);
235                         at3.translate(cellOffsets[2].getX()+spacing,cellOffsets[2].getY());
236
237                         at1.translate(offset.x, offset.y);
238                         at2.translate(offset.x, offset.y);
239                         at3.translate(offset.x, offset.y);
240
241                         node.setTransform(1, row, at1);
242                         node.setTransform(2, row, at2);
243                         node.setTransform(3, row, at3);
244
245                         Alignment[] alignments = result.getAlignments();
246                         if(alignments != null) {
247                                 node.setHorizontalAlignment(1, row, (byte) alignments[0].ordinal());
248                                 node.setHorizontalAlignment(2, row, (byte) alignments[1].ordinal());
249                                 node.setHorizontalAlignment(3, row, (byte) alignments[2].ordinal());
250                         } else {
251                                 node.setHorizontalAlignment(1, row, (byte) getAlignment(1).ordinal());
252                                 node.setHorizontalAlignment(2, row, (byte) getAlignment(2).ordinal());
253                                 node.setHorizontalAlignment(3, row, (byte) getAlignment(3).ordinal());
254                         }
255
256                         Alignment[] verticalAlignments = result.getVerticalAlignments();
257                         if(verticalAlignments != null) {
258                                 node.setVerticalAlignment(1, row, (byte) verticalAlignments[0].ordinal());
259                                 node.setVerticalAlignment(2, row, (byte) verticalAlignments[1].ordinal());
260                                 node.setVerticalAlignment(3, row, (byte) verticalAlignments[2].ordinal());
261                         } else {
262                                 node.setVerticalAlignment(1, row, (byte) getVerticalAlignment(1).ordinal());
263                                 node.setVerticalAlignment(2, row, (byte) getVerticalAlignment(2).ordinal());
264                                 node.setVerticalAlignment(3, row, (byte) getVerticalAlignment(3).ordinal());
265                         }
266
267                         node.setZIndex(3000);
268
269                         org.simantics.common.color.Color color = result.getColor();
270                         Color awtColor = color != null ? Colors.awt(color) : Color.DARK_GRAY;
271                         Color bgColor = getBackgroundColor();
272                         Font font = getFont();
273
274                         setTextNodeData(node, 1, row, value, font, awtColor, bgColor);
275                         setTextNodeData(node, 2, row, value2, result.getPending(), font, awtColor, bgColor);
276                         setTextNodeData(node, 3, row, value3, font, awtColor, bgColor);
277
278                         node.setEditable(1, row, false);
279                         node.setForceEventListening(2, row, true);
280                         node.setEditable(2, row, modifier != null);
281                         node.setEditable(3, row, false);
282
283                         final int finalRow = row;
284
285                         if (modifier != null) {
286                                 node.setTextListener(2, row, new ITextListener() {
287                                         @Override
288                                         public void textChanged() {}
289
290                                         @Override
291                                         public void textEditingStarted() {}
292
293                                         @Override
294                                         public void textEditingCancelled() {
295                                         }
296
297                                         @Override
298                                         public void textEditingEnded() {
299
300                                                 TextNode t = node.get(2, finalRow);
301                                                 if (t == null)
302                                                         return;
303
304                                                 if(!t.getText().equals(t.getTextBeforeEdit()))
305                                                         modifier.apply(t.getText());
306
307                                         }
308                                 });
309                         } else {
310                                 node.setTextListener(2,  row,  null);
311                         }
312
313                         node.setInputValidator(2, row, validator);
314                         node.setTranslator(translator);
315
316                         node.setRVI(2, row, rvi);
317
318                         postProcessNode(node, row);
319
320                 } else {
321                         cleanupStyleForNode(observer, _node);
322                 }
323         }
324
325         private void setTextNodeData(TextGridNode node, int x, int y, String text, Font font, Color fgColor, Color bgColor) {
326                 if (text != null) {
327                         node.setText(x, y, text);
328                         node.setFont(x, y, font);
329                         node.setColor(x, y, fgColor);
330                         node.setBackgroundColor(x, y, bgColor);
331                 } else {
332                         // Prevent rendering of the node.
333                         node.setFont(x, y, null);
334                 }
335         }
336
337         private void setTextNodeData(TextGridNode node, int x, int y, String text, boolean pending, Font font, Color fgColor, Color bgColor) {
338                 setTextNodeData(node, x, y, text, font, fgColor, bgColor);
339                 node.setPending(x, y, pending);
340         }
341
342         protected Font getFont() {
343                 return FONT;
344         }
345
346         protected Color getBackgroundColor() {
347                 return BACKGROUND_COLOR;
348         }
349
350         protected Alignment getAlignment(int column) {
351                 switch(column) {
352                 case 1: return Alignment.TRAILING;
353                 case 2: return Alignment.TRAILING;
354                 case 3: return Alignment.LEADING;
355                 default: return Alignment.LEADING;
356                 }
357         }
358
359         protected Alignment getVerticalAlignment(int column) {
360                 return Alignment.TRAILING;
361         }
362
363         @Override
364         protected void cleanupStyleForNode(EvaluationContext observer, INode _node) {
365                 Integer row = getCurrentRowNumber(observer, _node);
366                 //System.out.println(this + " cleanup(" + id + ", " + row + ")");
367                 //System.out.println(element);
368                 if (row == null)
369                         return;
370                 clearCurrentRowNumber(observer, _node);
371                 TextGridNode node = ProfileVariables.browseChild(_node, "TextGridStyle");
372                 if (node != null)
373                         node.removeRow(row);
374         }
375
376         private Integer getCurrentRowNumber(EvaluationContext observer, INode _node) {
377                 String rowId = observer.getProperty(_node, rowIdKey());
378                 return observer.getProperty(_node, rowId);
379         }
380
381         private void setCurrentRowNumber(EvaluationContext observer, INode _node, String rowId, int row) {
382                 // Mapping style identity -> rowId (resourceId)
383                 observer.setProperty(_node, rowIdKey(), rowId);
384                 // Mapping rowId (resourceId) -> row number
385                 observer.setProperty(_node, rowId, row);
386         }
387
388         private void clearCurrentRowNumber(EvaluationContext observer, INode _node) {
389                 String rowId = observer.getProperty(_node, rowIdKey());
390                 if(rowId != null) {
391                         observer.setProperty(_node, rowIdKey(), null);
392                         Integer row = observer.getProperty(_node, rowId);
393                         if(row != null) {
394                                 observer.setProperty(_node, rowId, null);
395                         }
396                 }
397         }
398
399         protected void postProcessNode(TextGridNode node, int row) {
400         }
401
402         private String rowIdKey() {
403                 return "style" + getIdentity().toString();
404         }
405
406 }