]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.g2d/src/org/simantics/g2d/element/handler/impl/ShapePick.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.g2d / src / org / simantics / g2d / element / handler / impl / ShapePick.java
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
3  * in Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.g2d.element.handler.impl;\r
13 \r
14 import java.awt.Shape;\r
15 import java.awt.geom.PathIterator;\r
16 import java.awt.geom.Rectangle2D;\r
17 import java.util.ArrayList;\r
18 import java.util.Collection;\r
19 \r
20 import org.simantics.g2d.diagram.handler.PickRequest.PickPolicy;\r
21 import org.simantics.g2d.element.ElementUtils;\r
22 import org.simantics.g2d.element.IElement;\r
23 import org.simantics.g2d.element.handler.Pick;\r
24 import org.simantics.g2d.utils.PathUtils;\r
25 \r
26 public class ShapePick implements Pick {\r
27 \r
28     public final static ShapePick INSTANCE = new ShapePick();\r
29 \r
30     private static final long serialVersionUID = 1L;\r
31 \r
32     @Override\r
33     public boolean pickTest(IElement e, Shape s, PickPolicy policy) {\r
34         Rectangle2D pickRect = null;\r
35         if (s instanceof Rectangle2D)\r
36             pickRect = (Rectangle2D) s;\r
37         else\r
38             // FIXME: suboptimal, but works.\r
39             pickRect = s.getBounds2D();\r
40 \r
41         Shape es = ElementUtils.getElementShapeOrBounds(e);\r
42         PathIterator iter = es.getPathIterator(null);\r
43         Collection<double[]> segments = new ArrayList<double[]>();\r
44         PathUtils.toLineSegments(iter, segments);\r
45 \r
46         switch (policy) {\r
47             case PICK_CONTAINED_OBJECTS:\r
48                 for (double[] seg : segments) {\r
49                     if (!pickRect.contains(seg[0], seg[1]) || !pickRect.contains(seg[2], seg[3]))\r
50                         return false;\r
51                 }\r
52                 return true;\r
53 \r
54             case PICK_INTERSECTING_OBJECTS:\r
55                 for (double[] seg : segments) {\r
56                     if (pickRect.intersectsLine(seg[0], seg[1], seg[2], seg[3]))\r
57                         return true;\r
58                 }\r
59                 return false;\r
60         }\r
61 \r
62         return false;\r
63     }\r
64 \r
65 }\r