001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui;
003
004import static org.openstreetmap.josm.tools.I18n.marktr;
005
006import java.awt.Color;
007import java.awt.Graphics2D;
008import java.awt.Point;
009import java.awt.Polygon;
010import java.awt.Rectangle;
011import java.awt.event.InputEvent;
012import java.awt.event.MouseEvent;
013import java.awt.event.MouseListener;
014import java.awt.event.MouseMotionListener;
015import java.beans.PropertyChangeEvent;
016import java.beans.PropertyChangeListener;
017import java.util.Collection;
018import java.util.LinkedList;
019
020import javax.swing.Action;
021
022import org.openstreetmap.josm.actions.SelectByInternalPointAction;
023import org.openstreetmap.josm.data.Bounds;
024import org.openstreetmap.josm.data.osm.BBox;
025import org.openstreetmap.josm.data.osm.DataSet;
026import org.openstreetmap.josm.data.osm.Node;
027import org.openstreetmap.josm.data.osm.OsmPrimitive;
028import org.openstreetmap.josm.data.osm.Way;
029import org.openstreetmap.josm.data.osm.visitor.paint.PaintColors;
030import org.openstreetmap.josm.data.preferences.NamedColorProperty;
031import org.openstreetmap.josm.gui.layer.AbstractMapViewPaintable;
032import org.openstreetmap.josm.tools.ColorHelper;
033import org.openstreetmap.josm.tools.PlatformManager;
034
035/**
036 * Manages the selection of a rectangle or a lasso loop. Listening to left and right mouse button
037 * presses and to mouse motions and draw the rectangle accordingly.
038 *
039 * Left mouse button selects a rectangle from the press until release. Pressing
040 * right mouse button while left is still pressed enable the selection area to move
041 * around. Releasing the left button fires an action event to the listener given
042 * at constructor, except if the right is still pressed, which just remove the
043 * selection rectangle and does nothing.
044 *
045 * It is possible to switch between lasso selection and rectangle selection by using {@link #setLassoMode(boolean)}.
046 *
047 * The point where the left mouse button was pressed and the current mouse
048 * position are two opposite corners of the selection rectangle.
049 *
050 * For rectangle mode, it is possible to specify an aspect ratio (width per height) which the
051 * selection rectangle always must have. In this case, the selection rectangle
052 * will be the largest window with this aspect ratio, where the position the left
053 * mouse button was pressed and the corner of the current mouse position are at
054 * opposite sites (the mouse position corner is the corner nearest to the mouse
055 * cursor).
056 *
057 * When the left mouse button was released, an ActionEvent is send to the
058 * ActionListener given at constructor. The source of this event is this manager.
059 *
060 * @author imi
061 */
062public class SelectionManager implements MouseListener, MouseMotionListener, PropertyChangeListener {
063
064    private final transient NamedColorProperty LASSO_COLOR = new NamedColorProperty(
065            /* I18n: color description for color of lasso select mode */
066            marktr("Lasso"),
067            ColorHelper.complement(PaintColors.getBackgroundColor()));
068    /**
069     * This is the interface that an user of SelectionManager has to implement
070     * to get informed when a selection closes.
071     * @author imi
072     */
073    public interface SelectionEnded extends Action {
074        /**
075         * Called, when the left mouse button was released.
076         * @param r The rectangle that encloses the current selection.
077         * @param e The mouse event.
078         * @see InputEvent#getModifiersEx()
079         * @see SelectionManager#getSelectedObjects(boolean)
080         */
081        void selectionEnded(Rectangle r, MouseEvent e);
082    }
083
084    /**
085     * This draws the selection hint (rectangle or lasso polygon) on the screen.
086     *
087     * @author Michael Zangl
088     */
089    private final class SelectionHintLayer extends AbstractMapViewPaintable {
090        @Override
091        public void paint(Graphics2D g, MapView mv, Bounds bbox) {
092            if (mousePos == null || mousePosStart == null || mousePos == mousePosStart)
093                return;
094            Color color = LASSO_COLOR.get();
095            g.setColor(color);
096            if (lassoMode) {
097                g.drawPolygon(lasso);
098
099                g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha() / 8));
100                g.fillPolygon(lasso);
101            } else {
102                Rectangle paintRect = getSelectionRectangle();
103                g.drawRect(paintRect.x, paintRect.y, paintRect.width, paintRect.height);
104            }
105        }
106    }
107
108    /**
109     * The listener that receives the events after left mouse button is released.
110     */
111    private final SelectionEnded selectionEndedListener;
112    /**
113     * Position of the map when the mouse button was pressed.
114     * If this is not <code>null</code>, a rectangle/lasso line is drawn on screen.
115     * If this is <code>null</code>, no selection is active.
116     */
117    private Point mousePosStart;
118    /**
119     * The last position of the mouse while the mouse button was pressed.
120     */
121    private Point mousePos;
122    /**
123     * The Component that provides us with OSM data and the aspect is taken from.
124     */
125    private final NavigatableComponent nc;
126    /**
127     * Whether the selection rectangle must obtain the aspect ratio of the drawComponent.
128     */
129    private final boolean aspectRatio;
130
131    /**
132     * <code>true</code> if we should paint a lasso instead of a rectangle.
133     */
134    private boolean lassoMode;
135    /**
136     * The polygon to store the selection outline if {@link #lassoMode} is used.
137     */
138    private final Polygon lasso = new Polygon();
139
140    /**
141     * The result of the last selection.
142     */
143    private Polygon selectionResult = new Polygon();
144
145    private final SelectionHintLayer selectionHintLayer = new SelectionHintLayer();
146
147    /**
148     * Create a new SelectionManager.
149     *
150     * @param selectionEndedListener The action listener that receives the event when
151     *      the left button is released.
152     * @param aspectRatio If true, the selection window must obtain the aspect
153     *      ratio of the drawComponent.
154     * @param navComp The component that provides us with OSM data and the aspect is taken from.
155     */
156    public SelectionManager(SelectionEnded selectionEndedListener, boolean aspectRatio, NavigatableComponent navComp) {
157        this.selectionEndedListener = selectionEndedListener;
158        this.aspectRatio = aspectRatio;
159        this.nc = navComp;
160    }
161
162    /**
163     * Register itself at the given event source and add a hint layer.
164     * @param eventSource The emitter of the mouse events.
165     * @param lassoMode {@code true} to enable lasso mode, {@code false} to disable it.
166     */
167    public void register(MapView eventSource, boolean lassoMode) {
168       this.lassoMode = lassoMode;
169        eventSource.addMouseListener(this);
170        eventSource.addMouseMotionListener(this);
171        selectionEndedListener.addPropertyChangeListener(this);
172        eventSource.addPropertyChangeListener("scale", evt -> abortSelecting());
173        eventSource.addTemporaryLayer(selectionHintLayer);
174    }
175
176    /**
177     * Unregister itself from the given event source and hide the selection hint layer.
178     *
179     * @param eventSource The emitter of the mouse events.
180     */
181    public void unregister(MapView eventSource) {
182        abortSelecting();
183        eventSource.removeTemporaryLayer(selectionHintLayer);
184        eventSource.removeMouseListener(this);
185        eventSource.removeMouseMotionListener(this);
186        selectionEndedListener.removePropertyChangeListener(this);
187    }
188
189    /**
190     * If the correct button, from the "drawing rectangle" mode
191     */
192    @Override
193    public void mousePressed(MouseEvent e) {
194        if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() > 1 && MainApplication.getLayerManager().getActiveDataSet() != null) {
195            SelectByInternalPointAction.performSelection(MainApplication.getMap().mapView.getEastNorth(e.getX(), e.getY()),
196                    (e.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) != 0,
197                    (e.getModifiersEx() & PlatformManager.getPlatform().getMenuShortcutKeyMaskEx()) != 0);
198        } else if (e.getButton() == MouseEvent.BUTTON1) {
199            mousePosStart = mousePos = e.getPoint();
200
201            lasso.reset();
202            lasso.addPoint(mousePosStart.x, mousePosStart.y);
203        }
204    }
205
206    /**
207     * If the correct button is hold, draw the rectangle.
208     */
209    @Override
210    public void mouseDragged(MouseEvent e) {
211        int buttonPressed = e.getModifiersEx() & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON3_DOWN_MASK);
212
213        if (buttonPressed != 0) {
214            if (mousePosStart == null) {
215                mousePosStart = mousePos = e.getPoint();
216            }
217            selectionAreaChanged();
218        }
219
220        if (buttonPressed == InputEvent.BUTTON1_DOWN_MASK) {
221            mousePos = e.getPoint();
222            addLassoPoint(e.getPoint());
223            selectionAreaChanged();
224        } else if (buttonPressed == (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON3_DOWN_MASK)) {
225            moveSelection(e.getX()-mousePos.x, e.getY()-mousePos.y);
226            mousePos = e.getPoint();
227            selectionAreaChanged();
228        }
229    }
230
231    /**
232     * Moves the current selection by some pixels.
233     * @param dx How much to move it in x direction.
234     * @param dy How much to move it in y direction.
235     */
236    private void moveSelection(int dx, int dy) {
237        mousePosStart.x += dx;
238        mousePosStart.y += dy;
239        lasso.translate(dx, dy);
240    }
241
242    /**
243     * Check the state of the keys and buttons and set the selection accordingly.
244     */
245    @Override
246    public void mouseReleased(MouseEvent e) {
247        if (e.getButton() == MouseEvent.BUTTON1) {
248            endSelecting(e);
249        }
250    }
251
252    /**
253     * Ends the selection of the current area. This simulates a release of mouse button 1.
254     * @param e A mouse event that caused this. Needed for backward compatibility.
255     */
256    public void endSelecting(MouseEvent e) {
257        mousePos = e.getPoint();
258        if (lassoMode) {
259            addLassoPoint(e.getPoint());
260        }
261
262        // Left mouse was released while right is still pressed.
263        boolean rightMouseStillPressed = (e.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0;
264
265        if (!rightMouseStillPressed) {
266            selectingDone(e);
267        }
268        abortSelecting();
269    }
270
271    private void addLassoPoint(Point point) {
272        if (isNoSelection()) {
273            return;
274        }
275        lasso.addPoint(point.x, point.y);
276    }
277
278    private boolean isNoSelection() {
279        return mousePos == null || mousePosStart == null || mousePos == mousePosStart;
280    }
281
282    /**
283     * Calculate and return the current selection rectangle
284     * @return A rectangle that spans from mousePos to mouseStartPos
285     */
286    private Rectangle getSelectionRectangle() {
287        int x = mousePosStart.x;
288        int y = mousePosStart.y;
289        int w = mousePos.x - mousePosStart.x;
290        int h = mousePos.y - mousePosStart.y;
291        if (w < 0) {
292            x += w;
293            w = -w;
294        }
295        if (h < 0) {
296            y += h;
297            h = -h;
298        }
299
300        if (aspectRatio) {
301            /* Keep the aspect ratio by growing the rectangle; the
302             * rectangle is always under the cursor. */
303            double aspectRatio = (double) nc.getWidth()/nc.getHeight();
304            if ((double) w/h < aspectRatio) {
305                int neww = (int) (h*aspectRatio);
306                if (mousePos.x < mousePosStart.x) {
307                    x += w - neww;
308                }
309                w = neww;
310            } else {
311                int newh = (int) (w/aspectRatio);
312                if (mousePos.y < mousePosStart.y) {
313                    y += h - newh;
314                }
315                h = newh;
316            }
317        }
318
319        return new Rectangle(x, y, w, h);
320    }
321
322    /**
323     * If the action goes inactive, remove the selection rectangle from screen
324     */
325    @Override
326    public void propertyChange(PropertyChangeEvent evt) {
327        if ("active".equals(evt.getPropertyName()) && Boolean.FALSE.equals(evt.getNewValue())) {
328            abortSelecting();
329        }
330    }
331
332    /**
333     * Stores the  current selection and stores the result in {@link #selectionResult} to  be retrieved by
334     * {@link #getSelectedObjects(boolean)} later.
335     * @param e The mouse event that caused the selection to be finished.
336     */
337    private void selectingDone(MouseEvent e) {
338        if (isNoSelection()) {
339            // Nothing selected.
340            return;
341        }
342        Rectangle r;
343        if (lassoMode) {
344            r = lasso.getBounds();
345
346            selectionResult = new Polygon(lasso.xpoints, lasso.ypoints, lasso.npoints);
347        } else {
348            r = getSelectionRectangle();
349
350            selectionResult = rectToPolygon(r);
351        }
352        selectionEndedListener.selectionEnded(r, e);
353    }
354
355    private void abortSelecting() {
356        if (mousePosStart != null) {
357            mousePos = mousePosStart = null;
358            lasso.reset();
359            selectionAreaChanged();
360        }
361    }
362
363    private void selectionAreaChanged() {
364        selectionHintLayer.invalidate();
365    }
366
367    /**
368     * Return a list of all objects in the active/last selection, respecting the different
369     * modifier.
370     *
371     * @param alt Whether the alt key was pressed, which means select all
372     * objects that are touched, instead those which are completely covered.
373     * @return The collection of selected objects.
374     */
375    public Collection<OsmPrimitive> getSelectedObjects(boolean alt) {
376        Collection<OsmPrimitive> selection = new LinkedList<>();
377
378        // whether user only clicked, not dragged.
379        boolean clicked = false;
380        Rectangle bounding = selectionResult.getBounds();
381        if (bounding.height <= 2 && bounding.width <= 2) {
382            clicked = true;
383        }
384
385        DataSet ds = MainApplication.getLayerManager().getActiveDataSet();
386        if (clicked) {
387            Point center = new Point(selectionResult.xpoints[0], selectionResult.ypoints[0]);
388            OsmPrimitive osm = nc.getNearestNodeOrWay(center, OsmPrimitive::isSelectable, false);
389            if (osm != null) {
390                selection.add(osm);
391            }
392        } else if (ds != null) {
393            final BBox bbox = nc.getLatLonBounds(bounding).toBBox();
394            // nodes
395            for (Node n : ds.searchNodes(bbox)) {
396                if (n.isSelectable() && selectionResult.contains(nc.getPoint2D(n))) {
397                    selection.add(n);
398                }
399            }
400
401            // ways
402            for (Way w : ds.searchWays(bbox)) {
403                if (!w.isSelectable() || w.isEmpty()) {
404                    continue;
405                }
406                if (alt) {
407                    if (w.getNodes().stream().anyMatch(n -> !n.isIncomplete() && selectionResult.contains(nc.getPoint2D(n)))) {
408                        selection.add(w);
409                    }
410                } else {
411                    boolean allIn = w.getNodes().stream().allMatch(n -> n.isIncomplete() || selectionResult.contains(nc.getPoint(n)));
412                    if (allIn) {
413                        selection.add(w);
414                    }
415                }
416            }
417        }
418        return selection;
419    }
420
421    private static Polygon rectToPolygon(Rectangle r) {
422        Polygon poly = new Polygon();
423
424        poly.addPoint(r.x, r.y);
425        poly.addPoint(r.x, r.y + r.height);
426        poly.addPoint(r.x + r.width, r.y + r.height);
427        poly.addPoint(r.x + r.width, r.y);
428
429        return poly;
430    }
431
432    /**
433     * Enables or disables the lasso mode.
434     * @param lassoMode {@code true} to enable lasso mode, {@code false} to disable it.
435     */
436    public void setLassoMode(boolean lassoMode) {
437        this.lassoMode = lassoMode;
438    }
439
440    @Override
441    public void mouseClicked(MouseEvent e) {
442        // Do nothing
443    }
444
445    @Override
446    public void mouseEntered(MouseEvent e) {
447        // Do nothing
448    }
449
450    @Override
451    public void mouseExited(MouseEvent e) {
452        // Do nothing
453    }
454
455    @Override
456    public void mouseMoved(MouseEvent e) {
457        // Do nothing
458    }
459}