]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network.ui/src/org/simantics/district/network/ui/adapters/DistrictNetworkEdgeElement.java
Fix dynamic visualisations UI color bars disappearing
[simantics/district.git] / org.simantics.district.network.ui / src / org / simantics / district / network / ui / adapters / DistrictNetworkEdgeElement.java
1 package org.simantics.district.network.ui.adapters;
2
3 import java.awt.Color;
4 import java.awt.Shape;
5 import java.awt.geom.AffineTransform;
6 import java.awt.geom.Line2D;
7 import java.awt.geom.Path2D;
8 import java.awt.geom.PathIterator;
9 import java.awt.geom.Point2D;
10 import java.awt.geom.Rectangle2D;
11 import java.util.Collection;
12 import java.util.Collections;
13
14 import org.simantics.district.network.ModelledCRS;
15 import org.simantics.district.network.ui.DistrictNetworkEdge;
16 import org.simantics.district.network.ui.nodes.DistrictNetworkEdgeNode;
17 import org.simantics.g2d.connection.handler.ConnectionHandler;
18 import org.simantics.g2d.diagram.handler.PickRequest.PickPolicy;
19 import org.simantics.g2d.diagram.handler.Topology.Connection;
20 import org.simantics.g2d.element.ElementClass;
21 import org.simantics.g2d.element.ElementUtils;
22 import org.simantics.g2d.element.IElement;
23 import org.simantics.g2d.element.SceneGraphNodeKey;
24 import org.simantics.g2d.element.handler.InternalSize;
25 import org.simantics.g2d.element.handler.Outline;
26 import org.simantics.g2d.element.handler.Pick;
27 import org.simantics.g2d.element.handler.SceneGraph;
28 import org.simantics.g2d.element.handler.impl.ConnectionSelectionOutline;
29 import org.simantics.g2d.element.handler.impl.DefaultTransform;
30 import org.simantics.g2d.element.handler.impl.SimpleElementLayers;
31 import org.simantics.maps.MapScalingTransform;
32 import org.simantics.scenegraph.g2d.G2DParentNode;
33 import org.simantics.scenegraph.g2d.nodes.SVGNode;
34 import org.simantics.scenegraph.utils.NodeUtil;
35 import org.simantics.utils.datastructures.hints.IHintContext.Key;
36 import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public class DistrictNetworkEdgeElement {
41
42     public static final Key KEY_DN_EDGE = new KeyOf(DistrictNetworkEdge.class, "DN_EDGE");
43     public static final Key KEY_DN_EDGE_NODE = new SceneGraphNodeKey(DistrictNetworkEdgeNode.class, "DN_EDGE_NODE");
44     public static final Key KEY_DN_EDGE_SYMBOL_NODE = new SceneGraphNodeKey(DistrictNetworkEdgeNode.class, "DN_EDGE_SYMBOL_NODE");
45
46     public static final ElementClass CLASS =
47             ElementClass.compile(
48                     DefaultTransform.INSTANCE,
49                     DNEdgeInternalSize.INSTANCE,
50                     DNEdgeSceneGraph.INSTANCE,
51                     DNEdgeConnectionHandler.INSTANCE,
52                     SimpleElementLayers.INSTANCE,
53                     // TODO: do we need this and does it work?
54                     ConnectionSelectionOutline.INSTANCE,
55                     DistrictNetworkAdditionalColor.INSTANCE
56             ).setId(DistrictNetworkEdgeElement.class.getSimpleName());
57
58     static final class DNEdgeSceneGraph implements SceneGraph {
59
60         public static final DNEdgeSceneGraph INSTANCE = new DNEdgeSceneGraph();
61
62         private static final long serialVersionUID = 68135568495835923L;
63
64         @Override
65         public void init(IElement edgeElement, G2DParentNode parent) {
66             DistrictNetworkEdge edge = edgeElement.getHint(KEY_DN_EDGE);
67             if (edge == null) {
68                 cleanup(edgeElement);
69             } else {
70                 DistrictNetworkEdgeNode node = edgeElement.getHint(KEY_DN_EDGE_NODE);
71                 if (node == null) {
72                     node = parent.addNode(ElementUtils.generateNodeId(edgeElement), DistrictNetworkEdgeNode.class);
73                     edgeElement.setHint(KEY_DN_EDGE_NODE, node);
74                     
75                     SVGNode symbol = node.addNode(ElementUtils.generateNodeId(edgeElement), SVGNode.class);
76                     edgeElement.setHint(KEY_DN_EDGE_SYMBOL_NODE, symbol);
77                 }
78                 
79                 node.setColor(ElementUtils.getAdditionalColor(edgeElement, Color.BLUE));
80                 
81                 node.setDNEdge(edge);
82                 AffineTransform at = ElementUtils.getTransform(edgeElement);
83                 if (at != null)
84                     node.setTransform(at);
85             }
86         }
87
88         @Override
89         public void cleanup(IElement edge) {
90             ElementUtils.removePossibleNode(edge, KEY_DN_EDGE_SYMBOL_NODE);
91             ElementUtils.removePossibleNode(edge, KEY_DN_EDGE_NODE);
92             edge.removeHint(KEY_DN_EDGE_NODE);
93             edge.removeHint(KEY_DN_EDGE_SYMBOL_NODE);
94         }
95     }
96
97     static final class DNEdgeInternalSize implements InternalSize, Outline, Pick {
98
99         private static final Logger LOGGER = LoggerFactory.getLogger(DNEdgeInternalSize.class);
100
101         private static final long serialVersionUID = -7346653820911240628L;
102
103         public static final DNEdgeInternalSize INSTANCE = new DNEdgeInternalSize();
104
105         private ThreadLocal<Path2D> path = new ThreadLocal<Path2D>() {
106             protected Path2D initialValue() { return new Path2D.Double(); }
107         };
108
109         @Override
110         public Rectangle2D getBounds(IElement e, Rectangle2D size) {
111             DistrictNetworkEdge edge = e.getHint(KEY_DN_EDGE);
112             if (size == null)
113                 size = new Rectangle2D.Double();
114             if (edge != null)
115                 size.setFrame(DistrictNetworkEdgeNode.calculatePath(edge, path.get(), false).getBounds2D());
116             else
117                 LOGGER.debug("Element {} does not have edge!", e);
118
119             return size;
120         }
121
122         @Override
123         public Shape getElementShape(IElement e) {
124             DistrictNetworkEdge edge = e.getHint(KEY_DN_EDGE);
125             if (edge != null) {
126                 return DistrictNetworkEdgeNode.calculatePath(edge, null, false);
127             } else {
128                 return getBounds(e, null);
129             }
130         }
131
132         @Override
133         public boolean pickTest(IElement e, Shape s, PickPolicy policy) {
134             DistrictNetworkEdge edge = e.getHint(KEY_DN_EDGE);
135             if (edge != null) {
136                 Rectangle2D bounds = getBounds(s);
137                 switch (policy) {
138                 case PICK_CONTAINED_OBJECTS:    return pickContainedObjects(edge, bounds);
139                 case PICK_INTERSECTING_OBJECTS: return pickIntersectingObjects(e, edge, bounds);
140                 }
141                 return false;
142             }
143
144             return false;
145         }
146
147         private boolean pickContainedObjects(DistrictNetworkEdge edge, Rectangle2D bounds) {
148             double bminx = bounds.getMinX() / MapScalingTransform.getScaleX();
149             double bminy = bounds.getMinY() / MapScalingTransform.getScaleY();
150             double bmaxx = bounds.getMaxX() / MapScalingTransform.getScaleX();
151             double bmaxy = bounds.getMaxY() / MapScalingTransform.getScaleY();
152
153             double bsminx = ModelledCRS.xToLongitude(bminx);
154             double bsminy = ModelledCRS.yToLatitude(-bminy); // Invert for Simantics diagram coordinate system
155             double bsmaxx = ModelledCRS.xToLongitude(bmaxx);
156             double bsmaxy = ModelledCRS.yToLatitude(-bmaxy); // Invert for Simantics diagram coordinate system
157
158             double boundsMinY = Math.min(bsminy, bsmaxy);
159             double boundsMaxY = Math.max(bsminy, bsmaxy);
160
161             Point2D start = edge.getStartPoint();
162             Point2D end = edge.getEndPoint();
163
164             double eminx = Math.min(start.getX(), end.getX());
165             double eminy = Math.min(start.getY(), end.getY());
166             double emaxx = Math.max(start.getX(), end.getX());
167             double emaxy = Math.max(start.getY(), end.getY());
168
169             return eminx >= bsminx && eminy >= boundsMinY && emaxx <= bsmaxx && emaxy <= boundsMaxY;
170         }
171
172         private boolean pickIntersectingObjects(IElement e, DistrictNetworkEdge edge, Rectangle2D bounds) {
173             double dx = bounds.getWidth() / MapScalingTransform.getScaleX();
174             double dy = bounds.getHeight() / MapScalingTransform.getScaleY();
175             
176             // Half the diagonal + half of the line width
177             DistrictNetworkEdgeNode node = e.getHint(KEY_DN_EDGE_NODE);
178             AffineTransform at = NodeUtil.getLocalToGlobalTransform(node);
179             
180             Path2D path = node.getPath();
181             if (path == null)
182                 return false;
183             
184             double lineWidth = node.getStrokeWidth(at, true);
185             double tolerance = Math.sqrt(dx * dx + dy * dy) / 2 + lineWidth / 2;
186             
187             double sx = bounds.getCenterX() / MapScalingTransform.getScaleX();
188             double sy = bounds.getCenterY() / MapScalingTransform.getScaleY();
189             
190             double coords[] = new double[6];
191             Point2D prevPoint = new Point2D.Double(), curPoint = new Point2D.Double();
192             Line2D line = new Line2D.Double();
193             for (PathIterator it = path.getPathIterator(null); !it.isDone(); it.next()) {
194                 int type = it.currentSegment(coords);
195                 switch (type) {
196                 case PathIterator.SEG_MOVETO:
197                     curPoint.setLocation(coords[0], coords[1]);
198                     break;
199                 case PathIterator.SEG_LINETO:
200                     prevPoint.setLocation(curPoint);
201                     curPoint.setLocation(coords[0], coords[1]);
202                     line.setLine(prevPoint, curPoint);
203                     double distSq = line.ptSegDistSq(sx, sy);
204 //                    System.out.println("s: " + sx + ", " + sy);
205 //                    System.out.println("ss: " + ssx + ", " + ssy);
206 //                    System.out.println("p1: " + edge.getStartPoint());
207 //                    System.out.println("p2: " + edge.getEndPoint());
208 //                    System.out.println("line: " + "(" + line.getX1() + ", " + line.getY1() + ", " + line.getX2() + ", " + line.getY2() + ")");
209 //                    System.out.println("distance from line is " + Math.sqrt(distSq) + " with tolerance " + tolerance);
210                     if (distSq <= tolerance * tolerance)
211                         return true; 
212                     break;
213                 default:
214                     LOGGER.error("Invalid edge path", new IllegalStateException());
215                     return false;
216                 }
217             }
218             
219             return false;
220         }
221
222         private Rectangle2D getBounds(Shape shape) {
223             if (shape instanceof Rectangle2D)
224                 return (Rectangle2D) shape;
225             return shape.getBounds2D();
226         }
227
228     }
229
230     static class DNEdgeConnectionHandler implements ConnectionHandler {
231
232         private static final long serialVersionUID = -6882671891381761687L;
233
234         public static final DNEdgeConnectionHandler INSTANCE = new DNEdgeConnectionHandler();
235
236         @Override
237         public Collection<IElement> getChildren(IElement connection, Collection<IElement> result) {
238             return Collections.emptyList();
239         }
240
241         @Override
242         public Collection<IElement> getBranchPoints(IElement connection, Collection<IElement> result) {
243             return Collections.emptyList();
244         }
245
246         @Override
247         public Collection<IElement> getSegments(IElement connection, Collection<IElement> result) {
248             return Collections.emptyList();
249         }
250
251         @Override
252         public Collection<Connection> getTerminalConnections(IElement connection, Collection<Connection> result) {
253             return Collections.emptyList();
254         }
255     }
256
257 }