source: josm/trunk/src/org/openstreetmap/josm/gui/SelectionManager.java@ 9444

Last change on this file since 9444 was 9078, checked in by Don-vip, 9 years ago

sonar - Immutable Field

  • Property svn:eol-style set to native
File size: 16.1 KB
RevLine 
[6380]1// License: GPL. For details, see LICENSE file.
[4]2package org.openstreetmap.josm.gui;
[3]3
[8550]4import java.awt.Color;
5import java.awt.Graphics2D;
[3]6import java.awt.Point;
[5152]7import java.awt.Polygon;
[3]8import java.awt.Rectangle;
9import java.awt.event.InputEvent;
10import java.awt.event.MouseEvent;
11import java.awt.event.MouseListener;
12import java.awt.event.MouseMotionListener;
[7]13import java.beans.PropertyChangeEvent;
14import java.beans.PropertyChangeListener;
15import java.util.Collection;
16import java.util.LinkedList;
[3]17
[7144]18import org.openstreetmap.josm.Main;
[7146]19import org.openstreetmap.josm.actions.SelectByInternalPointAction;
[8550]20import org.openstreetmap.josm.data.Bounds;
[7]21import org.openstreetmap.josm.data.osm.Node;
22import org.openstreetmap.josm.data.osm.OsmPrimitive;
[64]23import org.openstreetmap.josm.data.osm.Way;
[8550]24import org.openstreetmap.josm.data.osm.visitor.paint.PaintColors;
25import org.openstreetmap.josm.gui.layer.MapViewPaintable;
26import org.openstreetmap.josm.tools.Utils;
[7]27
[3]28/**
[8550]29 * Manages the selection of a rectangle or a lasso loop. Listening to left and right mouse button
[3]30 * presses and to mouse motions and draw the rectangle accordingly.
[1169]31 *
[3]32 * Left mouse button selects a rectangle from the press until release. Pressing
[8550]33 * right mouse button while left is still pressed enable the selection area to move
[3]34 * around. Releasing the left button fires an action event to the listener given
35 * at constructor, except if the right is still pressed, which just remove the
36 * selection rectangle and does nothing.
[1169]37 *
[8550]38 * It is possible to switch between lasso selection and rectangle selection by using {@link #setLassoMode(boolean)}.
39 *
[1169]40 * The point where the left mouse button was pressed and the current mouse
[3]41 * position are two opposite corners of the selection rectangle.
[1169]42 *
[8550]43 * For rectangle mode, it is possible to specify an aspect ratio (width per height) which the
[3]44 * selection rectangle always must have. In this case, the selection rectangle
45 * will be the largest window with this aspect ratio, where the position the left
[1169]46 * mouse button was pressed and the corner of the current mouse position are at
[3]47 * opposite sites (the mouse position corner is the corner nearest to the mouse
[1169]48 * cursor).
49 *
50 * When the left mouse button was released, an ActionEvent is send to the
[3]51 * ActionListener given at constructor. The source of this event is this manager.
[1169]52 *
[3]53 * @author imi
54 */
[7]55public class SelectionManager implements MouseListener, MouseMotionListener, PropertyChangeListener {
[3]56
[1169]57 /**
58 * This is the interface that an user of SelectionManager has to implement
59 * to get informed when a selection closes.
60 * @author imi
61 */
62 public interface SelectionEnded {
63 /**
64 * Called, when the left mouse button was released.
[8550]65 * @param r The rectangle that encloses the current selection.
[5500]66 * @param e The mouse event.
[1169]67 * @see InputEvent#getModifiersEx()
[8550]68 * @see SelectionManager#getSelectedObjects(boolean)
[1169]69 */
[8512]70 void selectionEnded(Rectangle r, MouseEvent e);
71
[1169]72 /**
73 * Called to register the selection manager for "active" property.
74 * @param listener The listener to register
75 */
[8512]76 void addPropertyChangeListener(PropertyChangeListener listener);
77
[1169]78 /**
79 * Called to remove the selection manager from the listener list
80 * for "active" property.
81 * @param listener The listener to register
82 */
[8512]83 void removePropertyChangeListener(PropertyChangeListener listener);
[1169]84 }
[8550]85
[1169]86 /**
[8550]87 * This draws the selection hint (rectangle or lasso polygon) on the screen.
88 *
89 * @author Michael Zangl
90 */
91 private class SelectionHintLayer implements MapViewPaintable {
92 @Override
93 public void paint(Graphics2D g, MapView mv, Bounds bbox) {
94 if (mousePos == null || mousePosStart == null || mousePos == mousePosStart)
95 return;
96 Color color = Utils.complement(PaintColors.getBackgroundColor());
97 g.setColor(color);
98 if (lassoMode) {
99 g.drawPolygon(lasso);
100
101 g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha() / 8));
102 g.fillPolygon(lasso);
103 } else {
104 Rectangle paintRect = getSelectionRectangle();
105 g.drawRect(paintRect.x, paintRect.y, paintRect.width, paintRect.height);
106 }
107 }
108 }
109
110 /**
[1169]111 * The listener that receives the events after left mouse button is released.
112 */
113 private final SelectionEnded selectionEndedListener;
114 /**
115 * Position of the map when the mouse button was pressed.
[8550]116 * If this is not <code>null</code>, a rectangle/lasso line is drawn on screen.
117 * If this is <code>null</code>, no selection is active.
[1169]118 */
119 private Point mousePosStart;
120 /**
[8550]121 * The last position of the mouse while the mouse button was pressed.
[1169]122 */
123 private Point mousePos;
124 /**
[8550]125 * The Component that provides us with OSM data and the aspect is taken from.
[1169]126 */
127 private final NavigatableComponent nc;
128 /**
[9078]129 * Whether the selection rectangle must obtain the aspect ratio of the drawComponent.
[1169]130 */
[9078]131 private final boolean aspectRatio;
[3]132
[8550]133 /**
134 * <code>true</code> if we should paint a lasso instead of a rectangle.
135 */
[5152]136 private boolean lassoMode;
[8550]137 /**
138 * The polygon to store the selection outline if {@link #lassoMode} is used.
139 */
[9078]140 private final Polygon lasso = new Polygon();
[5152]141
[1169]142 /**
[8550]143 * The result of the last selection.
144 */
145 private Polygon selectionResult = new Polygon();
146
147 private final SelectionHintLayer selectionHintLayer = new SelectionHintLayer();
148
149 /**
[1169]150 * Create a new SelectionManager.
151 *
152 * @param selectionEndedListener The action listener that receives the event when
153 * the left button is released.
154 * @param aspectRatio If true, the selection window must obtain the aspect
155 * ratio of the drawComponent.
[8550]156 * @param navComp The component that provides us with OSM data and the aspect is taken from.
[1169]157 */
158 public SelectionManager(SelectionEnded selectionEndedListener, boolean aspectRatio, NavigatableComponent navComp) {
159 this.selectionEndedListener = selectionEndedListener;
160 this.aspectRatio = aspectRatio;
161 this.nc = navComp;
162 }
163
164 /**
[8550]165 * Register itself at the given event source and add a hint layer.
[1169]166 * @param eventSource The emitter of the mouse events.
[5500]167 * @param lassoMode {@code true} to enable lasso mode, {@code false} to disable it.
[1169]168 */
[8550]169 public void register(MapView eventSource, boolean lassoMode) {
[5152]170 this.lassoMode = lassoMode;
[1169]171 eventSource.addMouseListener(this);
172 eventSource.addMouseMotionListener(this);
173 selectionEndedListener.addPropertyChangeListener(this);
[8510]174 eventSource.addPropertyChangeListener("scale", new PropertyChangeListener() {
[6084]175 @Override
[1169]176 public void propertyChange(PropertyChangeEvent evt) {
[8550]177 abortSelecting();
[100]178 }
179 });
[8550]180 eventSource.addTemporaryLayer(selectionHintLayer);
[1169]181 }
[9059]182
[1169]183 /**
[8550]184 * Unregister itself from the given event source and hide the selection hint layer.
[1169]185 *
186 * @param eventSource The emitter of the mouse events.
187 */
[8550]188 public void unregister(MapView eventSource) {
189 abortSelecting();
190 eventSource.removeTemporaryLayer(selectionHintLayer);
[1169]191 eventSource.removeMouseListener(this);
192 eventSource.removeMouseMotionListener(this);
193 selectionEndedListener.removePropertyChangeListener(this);
194 }
[3]195
[1169]196 /**
197 * If the correct button, from the "drawing rectangle" mode
198 */
[6084]199 @Override
[1169]200 public void mousePressed(MouseEvent e) {
[7921]201 if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() > 1 && Main.main.getCurrentDataSet() != null) {
[7146]202 SelectByInternalPointAction.performSelection(Main.map.mapView.getEastNorth(e.getX(), e.getY()),
[7144]203 (e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) > 0,
204 (e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) > 0);
205 } else if (e.getButton() == MouseEvent.BUTTON1) {
[1169]206 mousePosStart = mousePos = e.getPoint();
[5152]207
208 lasso.reset();
209 lasso.addPoint(mousePosStart.x, mousePosStart.y);
[1911]210 }
[1169]211 }
[3]212
[1169]213 /**
214 * If the correct button is hold, draw the rectangle.
215 */
[6084]216 @Override
[1169]217 public void mouseDragged(MouseEvent e) {
218 int buttonPressed = e.getModifiersEx() & (MouseEvent.BUTTON1_DOWN_MASK | MouseEvent.BUTTON3_DOWN_MASK);
[3]219
[1169]220 if (buttonPressed != 0) {
[1911]221 if (mousePosStart == null) {
[1169]222 mousePosStart = mousePos = e.getPoint();
[1911]223 }
[8550]224 selectionAreaChanged();
[1169]225 }
[7]226
[1169]227 if (buttonPressed == MouseEvent.BUTTON1_DOWN_MASK) {
228 mousePos = e.getPoint();
[8550]229 addLassoPoint(e.getPoint());
230 selectionAreaChanged();
[1169]231 } else if (buttonPressed == (MouseEvent.BUTTON1_DOWN_MASK | MouseEvent.BUTTON3_DOWN_MASK)) {
[8550]232 moveSelection(e.getX()-mousePos.x, e.getY()-mousePos.y);
[1169]233 mousePos = e.getPoint();
[8550]234 selectionAreaChanged();
[1169]235 }
236 }
[3]237
[1169]238 /**
[8550]239 * Moves the current selection by some pixels.
240 * @param dx How much to move it in x direction.
241 * @param dy How much to move it in y direction.
242 */
243 private void moveSelection(int dx, int dy) {
244 mousePosStart.x += dx;
245 mousePosStart.y += dy;
246 lasso.translate(dx, dy);
247 }
248
249 /**
[1169]250 * Check the state of the keys and buttons and set the selection accordingly.
251 */
[6084]252 @Override
[1169]253 public void mouseReleased(MouseEvent e) {
[8550]254 if (e.getButton() == MouseEvent.BUTTON1) {
255 endSelecting(e);
[5152]256 }
[1169]257 }
[3]258
[1169]259 /**
[8550]260 * Ends the selection of the current area. This simulates a release of mouse button 1.
261 * @param e A mouse event that caused this. Needed for backward compatibility.
[1169]262 */
[8550]263 public void endSelecting(MouseEvent e) {
264 mousePos = e.getPoint();
265 if (lassoMode) {
266 addLassoPoint(e.getPoint());
267 }
268
269 // Left mouse was released while right is still pressed.
270 boolean rightMouseStillPressed = (e.getModifiersEx() & MouseEvent.BUTTON3_DOWN_MASK) != 0;
271
272 if (!rightMouseStillPressed) {
273 selectingDone(e);
274 }
275 abortSelecting();
[1169]276 }
[6070]277
[8550]278 private void addLassoPoint(Point point) {
279 if (isNoSelection()) {
[5152]280 return;
281 }
[8550]282 lasso.addPoint(point.x, point.y);
[5152]283 }
284
[8550]285 private boolean isNoSelection() {
286 return mousePos == null || mousePosStart == null || mousePos == mousePosStart;
287 }
288
[1169]289 /**
290 * Calculate and return the current selection rectangle
291 * @return A rectangle that spans from mousePos to mouseStartPos
292 */
293 private Rectangle getSelectionRectangle() {
294 int x = mousePosStart.x;
295 int y = mousePosStart.y;
296 int w = mousePos.x - mousePosStart.x;
297 int h = mousePos.y - mousePosStart.y;
298 if (w < 0) {
299 x += w;
300 w = -w;
301 }
302 if (h < 0) {
303 y += h;
304 h = -h;
305 }
[7]306
[1169]307 if (aspectRatio) {
308 /* Keep the aspect ratio by growing the rectangle; the
309 * rectangle is always under the cursor. */
[8510]310 double aspectRatio = (double) nc.getWidth()/nc.getHeight();
311 if ((double) w/h < aspectRatio) {
312 int neww = (int) (h*aspectRatio);
[1911]313 if (mousePos.x < mousePosStart.x) {
[1169]314 x += w - neww;
[1911]315 }
[1169]316 w = neww;
317 } else {
[8510]318 int newh = (int) (w/aspectRatio);
[1911]319 if (mousePos.y < mousePosStart.y) {
[1169]320 y += h - newh;
[1911]321 }
[1169]322 h = newh;
323 }
324 }
325
[8510]326 return new Rectangle(x, y, w, h);
[1169]327 }
328
329 /**
330 * If the action goes inactive, remove the selection rectangle from screen
331 */
[6084]332 @Override
[1169]333 public void propertyChange(PropertyChangeEvent evt) {
[8557]334 if ("active".equals(evt.getPropertyName()) && !(Boolean) evt.getNewValue()) {
[8550]335 abortSelecting();
[1169]336 }
337 }
338
339 /**
[8557]340 * Stores the current selection and stores the result in {@link #selectionResult} to be retrieved by
341 * {@link #getSelectedObjects(boolean)} later.
[8550]342 * @param e The mouse event that caused the selection to be finished.
343 */
344 private void selectingDone(MouseEvent e) {
345 if (isNoSelection()) {
346 // Nothing selected.
347 return;
348 }
349 Rectangle r;
350 if (lassoMode) {
351 r = lasso.getBounds();
352
353 selectionResult = new Polygon(lasso.xpoints, lasso.ypoints, lasso.npoints);
354 } else {
355 r = getSelectionRectangle();
356
357 selectionResult = rectToPolygon(r);
358 }
359 selectionEndedListener.selectionEnded(r, e);
360 }
361
362 private void abortSelecting() {
363 if (mousePosStart != null) {
364 mousePos = mousePosStart = null;
365 lasso.reset();
366 selectionAreaChanged();
367 }
368 }
369
[8870]370 private static void selectionAreaChanged() {
[8550]371 // Trigger a redraw of the map view.
372 // A nicer way would be to provide change events for the temporary layer.
373 Main.map.mapView.repaint();
374 }
375
376 /**
377 * Return a list of all objects in the active/last selection, respecting the different
[1169]378 * modifier.
[5152]379 *
380 * @param alt Whether the alt key was pressed, which means select all
381 * objects that are touched, instead those which are completely covered.
[5500]382 * @return The collection of selected objects.
[1169]383 */
[5152]384 public Collection<OsmPrimitive> getSelectedObjects(boolean alt) {
385
[7005]386 Collection<OsmPrimitive> selection = new LinkedList<>();
[1169]387
388 // whether user only clicked, not dragged.
[5152]389 boolean clicked = false;
[8550]390 Rectangle bounding = selectionResult.getBounds();
[5152]391 if (bounding.height <= 2 && bounding.width <= 2) {
392 clicked = true;
393 }
[1169]394
395 if (clicked) {
[8550]396 Point center = new Point(selectionResult.xpoints[0], selectionResult.ypoints[0]);
[3642]397 OsmPrimitive osm = nc.getNearestNodeOrWay(center, OsmPrimitive.isSelectablePredicate, false);
[1911]398 if (osm != null) {
[1169]399 selection.add(osm);
[1911]400 }
[1169]401 } else {
402 // nodes
[2381]403 for (Node n : nc.getCurrentDataSet().getNodes()) {
[8550]404 if (n.isSelectable() && selectionResult.contains(nc.getPoint2D(n))) {
[1169]405 selection.add(n);
[1911]406 }
[1169]407 }
408
409 // ways
[2381]410 for (Way w : nc.getCurrentDataSet().getWays()) {
[3198]411 if (!w.isSelectable() || w.getNodesCount() == 0) {
[1911]412 continue;
413 }
[1169]414 if (alt) {
[1910]415 for (Node n : w.getNodes()) {
[8550]416 if (!n.isIncomplete() && selectionResult.contains(nc.getPoint2D(n))) {
[1169]417 selection.add(w);
418 break;
419 }
420 }
421 } else {
422 boolean allIn = true;
[1910]423 for (Node n : w.getNodes()) {
[8550]424 if (!n.isIncomplete() && !selectionResult.contains(nc.getPoint(n))) {
[1169]425 allIn = false;
426 break;
427 }
428 }
[1911]429 if (allIn) {
430 selection.add(w);
431 }
[1169]432 }
433 }
434 }
435 return selection;
436 }
437
[8870]438 private static Polygon rectToPolygon(Rectangle r) {
[5152]439 Polygon poly = new Polygon();
440
441 poly.addPoint(r.x, r.y);
442 poly.addPoint(r.x, r.y + r.height);
443 poly.addPoint(r.x + r.width, r.y + r.height);
444 poly.addPoint(r.x + r.width, r.y);
445
446 return poly;
447 }
448
[5500]449 /**
450 * Enables or disables the lasso mode.
451 * @param lassoMode {@code true} to enable lasso mode, {@code false} to disable it.
452 */
[5152]453 public void setLassoMode(boolean lassoMode) {
454 this.lassoMode = lassoMode;
455 }
456
[6084]457 @Override
[1169]458 public void mouseClicked(MouseEvent e) {}
[8510]459
[6084]460 @Override
[1169]461 public void mouseEntered(MouseEvent e) {}
[8510]462
[6084]463 @Override
[1169]464 public void mouseExited(MouseEvent e) {}
[8510]465
[6084]466 @Override
[1169]467 public void mouseMoved(MouseEvent e) {}
[3]468}
Note: See TracBrowser for help on using the repository browser.