]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.g2d/src/org/simantics/g2d/diagram/participant/pointertool/TerminalUtil.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.g2d / src / org / simantics / g2d / diagram / participant / pointertool / TerminalUtil.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.g2d.diagram.participant.pointertool;
13
14 import java.awt.Shape;
15 import java.awt.geom.AffineTransform;
16 import java.awt.geom.Point2D;
17 import java.awt.geom.Rectangle2D;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.Comparator;
21 import java.util.List;
22
23 import org.simantics.g2d.diagram.DiagramUtils;
24 import org.simantics.g2d.diagram.IDiagram;
25 import org.simantics.g2d.diagram.handler.PickRequest;
26 import org.simantics.g2d.diagram.handler.Topology.Terminal;
27 import org.simantics.g2d.element.ElementUtils;
28 import org.simantics.g2d.element.IElement;
29 import org.simantics.g2d.element.handler.BendsHandler;
30 import org.simantics.g2d.element.handler.BendsHandler.Bend;
31 import org.simantics.g2d.element.handler.TerminalLayout;
32 import org.simantics.g2d.element.handler.TerminalTopology;
33 import org.simantics.g2d.utils.GeometryUtils;
34 import org.simantics.g2d.utils.geom.DirectionSet;
35
36 /**
37  * @author Toni Kalajainen
38  */
39 public class TerminalUtil {
40
41     /**
42      * Thread local terminal list for keeping memory allocations down.
43      */
44     private static final ThreadLocal<ArrayList<Terminal>> TERMINALS = new ThreadLocal<ArrayList<Terminal>>() {
45         @Override
46         protected ArrayList<Terminal> initialValue() {
47             return new ArrayList<Terminal>();
48         }
49     };
50
51     /**
52      * Thread local element list for keeping memory allocations down.
53      */
54     private static final ThreadLocal<ArrayList<IElement>> ELEMENTS = new ThreadLocal<ArrayList<IElement>>() {
55         @Override
56         protected ArrayList<IElement> initialValue() {
57             return new ArrayList<IElement>();
58         }
59     };
60
61     public static class TerminalInfo {
62         public IElement e;
63         public Terminal t;
64         public AffineTransform posElem; // on element
65         public AffineTransform posDia; // on diagram
66         public Shape shape; // Shape or null
67         public double distance; // Distance of terminal from pick point in millimeters
68
69         @Override
70         public String toString() {
71             StringBuilder sb = new StringBuilder();
72             sb.append('[')
73             .append("element=").append(e)
74             .append(", terminal=").append(t)
75             .append(", posDia=").append(posDia)
76             .append(", shape=").append(shape)
77             .append(", distance=").append(distance)
78             .append(']');
79             return sb.toString();
80         }
81
82         public static TerminalInfo create(Point2D p, IElement e, Terminal t, Shape terminalShape) {
83             AffineTransform at = AffineTransform.getTranslateInstance(p.getX(), p.getY());
84             TerminalInfo ti = new TerminalInfo();
85             ti.e = e;
86             ti.t = t;
87             ti.posElem = at;
88             ti.posDia = at;
89             ti.shape = terminalShape;
90             return ti;
91         }
92     }
93     private static final Rectangle2D POINT_PICK_SHAPE = new Rectangle2D.Double(0, 0, 0.001, 0.001);
94
95     public static final Comparator<TerminalInfo> ASCENDING_DISTANCE_ORDER = new Comparator<TerminalInfo>() {
96         @Override
97         public int compare(TerminalInfo o1, TerminalInfo o2) {
98             double d1 = o1.distance;
99             double d2 = o2.distance;
100             if (d1 < d2)
101                 return -1;
102             if (d1 > d2)
103                 return 1;
104             return 0;
105         }
106     };
107
108     public static class BendsInfo {
109         public IElement e;
110         public Bend b;
111     }
112
113     /**
114      * Pick terminals
115      * @param d diagram
116      * @param pickShape pick area or null for the whole canvas (return all terminals)
117      * @param pickPointTerminals pick terminals of a single point
118      * @param pickAreaTerminals pick terminals that have a shape
119      * @return terminals in z-order (bottom to top)
120      */
121     public static List<TerminalInfo> pickTerminals(IDiagram d, Shape pickShape, boolean pickPointTerminals, boolean pickAreaTerminals)
122     {
123         boolean clearElements = false;
124         List<IElement> elements = null;
125         // Pick
126         if (pickShape != null) {
127             elements = ELEMENTS.get();
128             elements.clear();
129             clearElements = true;
130             PickRequest req = new PickRequest(pickShape);
131             DiagramUtils.pick(d, req, elements);
132         } else {
133             // Select all terminals
134             elements = d.getElements();
135         }
136         if (elements.isEmpty())
137             return Collections.emptyList();
138
139         double pickCenterX = 0;
140         double pickCenterY = 0;
141         if (pickShape != null) {
142             Rectangle2D bounds = pickShape.getBounds2D();
143             pickCenterX = bounds.getCenterX();
144             pickCenterY = bounds.getCenterY();
145         }
146
147         List<TerminalInfo> result = new ArrayList<TerminalInfo>();
148         ArrayList<Terminal> terminals = TERMINALS.get();
149         for (IElement e : elements)
150         {
151             TerminalTopology tt = e.getElementClass().getAtMostOneItemOfClass(TerminalTopology.class);
152             if (tt==null) continue;
153             terminals.clear();
154             tt.getTerminals(e, terminals);
155             if (terminals.isEmpty()) continue;
156
157             List<TerminalLayout> tls = e.getElementClass().getItemsByClass(TerminalLayout.class);
158
159             for (Terminal t : terminals)
160             {
161                 Shape terminalShape = getTerminalShape(tls, e, t);
162                 if ( terminalShape==null /* point terminal */ && !pickPointTerminals ) continue;
163                 if ( terminalShape!=null /* are terminal */ && !pickAreaTerminals ) continue;
164                 AffineTransform terminalToDiagram = getTerminalPosOnDiagram(e, t);
165
166                 // Pick distance will is set to 0 if there was no pick shape,
167                 // i.e. everything is picked.
168                 double pickDist = 0;
169                 if (pickShape != null) {
170                     Shape pickTargetShape = terminalShape != null ? terminalShape : POINT_PICK_SHAPE;
171                     // Point Terminal uses a very small box as pick shape
172                     pickTargetShape = GeometryUtils.transformShape(pickTargetShape, terminalToDiagram);
173                     if (!GeometryUtils.intersects(pickShape, pickTargetShape)) continue;
174
175                     pickDist = Point2D.distance(pickCenterX, pickCenterY, terminalToDiagram.getTranslateX(), terminalToDiagram.getTranslateY());
176                 }
177
178                 AffineTransform terminalToElement = getTerminalPosOnElement(e, t);
179                 TerminalInfo ti = new TerminalInfo();
180                 ti.e = e;
181                 ti.posDia = terminalToDiagram;
182                 ti.posElem = terminalToElement;
183                 ti.t = t;
184                 ti.shape = terminalShape;
185                 ti.distance = pickDist;
186                 result.add(ti);
187             }
188         }
189
190         if (clearElements)
191             elements.clear();
192         terminals.clear();
193
194         return result;
195     }
196
197     /**
198      * Pick terminals
199      * @param d diagram
200      * @param pickShape pick area (in diagram coordinate system)
201      * @return terminals in z-order (bottom to top)
202      */
203     public static TerminalInfo pickTerminal(IDiagram diagram, Shape pickShape)
204     {
205         ArrayList<IElement> elements = ELEMENTS.get();
206         elements.clear();
207         PickRequest req = new PickRequest(pickShape);
208         DiagramUtils.pick(diagram, req, elements);
209         if (elements.isEmpty())
210             return null;
211
212         TerminalInfo  result = new TerminalInfo();
213         double        bestShortestDist = Double.MAX_VALUE;
214         Rectangle2D   bounds = pickShape.getBounds2D();
215         double        pickCenterX = bounds.getCenterX();
216         double        pickCenterY = bounds.getCenterY();
217
218         ArrayList<Terminal> terminals = TERMINALS.get();
219         for (IElement e : elements)
220         {
221             TerminalTopology tt = e.getElementClass().getAtMostOneItemOfClass(TerminalTopology.class);
222             if (tt==null) continue;
223             terminals.clear();
224             tt.getTerminals(e, terminals);
225             for (Terminal t : terminals)
226             {
227                 Shape terminalShape = getTerminalShape(e, t);
228                 AffineTransform terminalToDiagram = getTerminalPosOnDiagram(e, t);
229                 Shape pickTargetShape = terminalShape != null ? terminalShape : POINT_PICK_SHAPE;
230                 pickTargetShape = GeometryUtils.transformShape(pickTargetShape, terminalToDiagram);
231                 if (!GeometryUtils.intersects(pickShape, pickTargetShape)) continue;
232
233                 double pickDist = Point2D.distanceSq(pickCenterX, pickCenterY, terminalToDiagram.getTranslateX(), terminalToDiagram.getTranslateY());
234                 if (pickDist>bestShortestDist) continue;
235
236                 result.e = e;
237                 result.posDia = terminalToDiagram;
238                 result.posElem = getTerminalPosOnElement(e, t);
239                 result.t = t;
240                 result.shape = terminalShape;
241                 result.distance = Math.sqrt(pickDist);
242                 bestShortestDist = pickDist;
243             }
244         }
245         elements.clear();
246         terminals.clear();
247         if (bestShortestDist==Double.MAX_VALUE) return null;
248         return result;
249     }
250
251     /**
252      * Get directions
253      * @param e
254      * @param t
255      * @param directions null or direction set
256      * @return
257      */
258     public static DirectionSet getTerminalDirectionSet(IElement e, Terminal t, DirectionSet directions)
259     {
260         if (directions == null) directions = new DirectionSet();
261         for (TerminalLayout tl : e.getElementClass().getItemsByClass(TerminalLayout.class))
262             tl.getTerminalDirection(e, t, directions);
263         return directions;
264     }
265
266     /**
267      * Get directions
268      * @param e
269      * @param t
270      * @param directions null or direction set
271      * @return
272      */
273     public static DirectionSet getTerminalPosition(IElement e, Terminal t, DirectionSet directions)
274     {
275         if (directions == null) directions = new DirectionSet();
276         for (TerminalLayout tl : e.getElementClass().getItemsByClass(TerminalLayout.class))
277             tl.getTerminalDirection(e, t, directions);
278         return directions;
279     }
280
281     public static Point2D getTerminalCenterPosOnDiagram(IElement e, Terminal t)
282     {
283         Shape shape = getTerminalShape(e, t);
284         Point2D terminalCenterPos = new Point2D.Double();
285         if (shape!=null) {
286             Rectangle2D rect = shape.getBounds2D();
287             terminalCenterPos.setLocation(rect.getCenterX(), rect.getCenterY());
288         }
289         // Transform to diagram
290         AffineTransform at = getTerminalPosOnDiagram(e, t);
291         at.transform(terminalCenterPos, terminalCenterPos);
292         return terminalCenterPos;
293     }
294
295     /**
296      * Get position of a terminal on diagram
297      * @param e element
298      * @param t terminal
299      * @return position of a terminal on diagram
300      */
301     public static AffineTransform getTerminalPosOnDiagram(IElement e, Terminal t)
302     {
303         AffineTransform pos     = getTerminalPosOnElement(e, t);
304         AffineTransform at      = ElementUtils.getTransform(e);
305         AffineTransform result = new AffineTransform(at);
306         result.concatenate(pos);
307         return result;
308     }
309
310     /**
311      * Get position of a terminal in element
312      * @param e element
313      * @param t terminal
314      * @return Transform of a terminal
315      */
316     public static AffineTransform getTerminalPosOnElement(IElement e, Terminal t)
317     {
318         List<TerminalLayout>    tls = e.getElementClass().getItemsByClass(TerminalLayout.class);
319         AffineTransform                 result = null;
320         for (TerminalLayout tl : tls) {
321             result = tl.getTerminalPosition(e, t);
322             if (result!=null) return result;
323         }
324         return null;
325     }
326
327     /**
328      * Get terminal shape
329      * @param e element
330      * @param t terminal
331      * @return terminal shape or null
332      */
333     public static Shape getTerminalShape(IElement e, Terminal t)
334     {
335         List<TerminalLayout> tls = e.getElementClass().getItemsByClass(TerminalLayout.class);
336         return getTerminalShape(tls, e, t);
337     }
338
339     private static Shape getTerminalShape(List<TerminalLayout> tls, IElement e, Terminal t)
340     {
341         for (TerminalLayout tl : tls) {
342             Shape result = tl.getTerminalShape(e, t);
343             if (result != null) return result;
344         }
345         return null;
346     }
347
348     /**
349      * 
350      * @param diagram
351      * @param pickShape
352      * @return bends or null
353      */
354     public BendsInfo pickBends(IDiagram diagram, Shape pickShape)
355     {
356         BendsInfo               result = null;
357         double                  bestShortestDist = Double.MAX_VALUE;
358         Rectangle2D     pickShapeBounds = pickShape.getBounds2D();
359         Point2D                 pickShapeCenter = new Point2D.Double(pickShapeBounds.getCenterX(), pickShapeBounds.getCenterY());
360
361         ArrayList<IElement> elements = ELEMENTS.get();
362         elements.clear();
363         PickRequest req = new PickRequest(pickShape);
364         DiagramUtils.pick(diagram, req, elements);
365
366         ArrayList<Bend> bends = new ArrayList<Bend>();
367         Point2D bendPos = new Point2D.Double();
368         for (IElement e : diagram.getElements())
369         {
370             AffineTransform elementToDiagram = ElementUtils.getTransform(e);
371             BendsHandler bh = e.getElementClass().getSingleItem(BendsHandler.class);
372             if (bh==null) continue;
373             bends.clear(); bh.getBends(e, bends);
374             for (Bend b : bends)
375             {
376                 bh.getBendPosition(e, b, bendPos);
377                 elementToDiagram.transform(bendPos, bendPos);
378                 if (!pickShape.contains(bendPos)) continue;
379                 double dist = bendPos.distance(pickShapeCenter);
380                 if (dist>bestShortestDist) continue;
381                 dist = bestShortestDist;
382                 result = new BendsInfo();
383                 result.e = e;
384                 result.b = b;
385             }
386         }
387         elements.clear();
388         if (bestShortestDist==Double.MAX_VALUE) return null;
389         return result;
390     }
391
392     /**
393      * Checks whether the element/terminal information of the two specified
394      * TerminalInfo structures match.
395      * 
396      * @param t1
397      * @param t2
398      * @return <code>true</code> if the element and terminal instances of both
399      *         structures are the same, <code>false</code> otherwise
400      */
401     public static boolean isSameTerminal(TerminalInfo t1, TerminalInfo t2) {
402         if (t1 == null || t2 == null)
403             return false;
404         return t1.e.equals(t2.e) && t1.t.equals(t2.e);
405     }
406
407     /**
408      * Finds those terminals among the specified set that are
409      * <ol>
410      * <li>nearest and equal in distance (see TerminalInfo.distance)</li>
411      * <li>have the same absolute diagram position</li>
412      * </ol>
413      * 
414      * @param tis the picked terminals to examine
415      * @return the nearest position-wise overlapping terminals
416      */
417     public static List<TerminalInfo> findNearestOverlappingTerminals(List<TerminalInfo> tis) {
418         int len = tis.size();
419         if (len < 2)
420             return tis;
421
422         // Only gather the nearest terminals that are
423         // directly on top of each other
424
425         TerminalInfo nearest = null;
426         for (int i = 0; i < len; ++i) {
427             TerminalInfo ti = tis.get(i);
428             if (nearest == null || ti.distance < nearest.distance) {
429                 nearest = ti;
430             }
431         }
432
433         ArrayList<TerminalInfo> result = new ArrayList<TerminalInfo>(len);
434         for (int i = 0; i < len; ++i) {
435             TerminalInfo ti = tis.get(i);
436             if (ti.distance == nearest.distance
437                     //&& ti.e.equals(nearest.e)
438                     && ti.posDia.equals(nearest.posDia))
439             {
440                 result.add(ti);
441             }
442         }
443
444         return result;
445     }
446
447 }