001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions.mapmode;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.tr;
006import static org.openstreetmap.josm.tools.I18n.trc;
007import static org.openstreetmap.josm.tools.I18n.trn;
008
009import java.awt.Cursor;
010import java.awt.Point;
011import java.awt.Rectangle;
012import java.awt.event.InputEvent;
013import java.awt.event.KeyEvent;
014import java.awt.event.MouseEvent;
015import java.awt.geom.Point2D;
016import java.util.Collection;
017import java.util.Collections;
018import java.util.HashSet;
019import java.util.Iterator;
020import java.util.LinkedList;
021import java.util.List;
022import java.util.Objects;
023import java.util.Optional;
024
025import javax.swing.JOptionPane;
026import javax.swing.SwingUtilities;
027
028import org.openstreetmap.josm.actions.MergeNodesAction;
029import org.openstreetmap.josm.command.AddCommand;
030import org.openstreetmap.josm.command.ChangeNodesCommand;
031import org.openstreetmap.josm.command.Command;
032import org.openstreetmap.josm.command.MoveCommand;
033import org.openstreetmap.josm.command.RotateCommand;
034import org.openstreetmap.josm.command.ScaleCommand;
035import org.openstreetmap.josm.command.SequenceCommand;
036import org.openstreetmap.josm.data.SystemOfMeasurement;
037import org.openstreetmap.josm.data.UndoRedoHandler;
038import org.openstreetmap.josm.data.coor.EastNorth;
039import org.openstreetmap.josm.data.osm.DataSet;
040import org.openstreetmap.josm.data.osm.Node;
041import org.openstreetmap.josm.data.osm.OsmData;
042import org.openstreetmap.josm.data.osm.OsmPrimitive;
043import org.openstreetmap.josm.data.osm.Way;
044import org.openstreetmap.josm.data.osm.WaySegment;
045import org.openstreetmap.josm.data.osm.visitor.AllNodesVisitor;
046import org.openstreetmap.josm.data.osm.visitor.paint.AbstractMapRenderer;
047import org.openstreetmap.josm.data.preferences.BooleanProperty;
048import org.openstreetmap.josm.data.preferences.CachingProperty;
049import org.openstreetmap.josm.gui.ExtendedDialog;
050import org.openstreetmap.josm.gui.MainApplication;
051import org.openstreetmap.josm.gui.MapFrame;
052import org.openstreetmap.josm.gui.MapView;
053import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
054import org.openstreetmap.josm.gui.SelectionManager;
055import org.openstreetmap.josm.gui.SelectionManager.SelectionEnded;
056import org.openstreetmap.josm.gui.layer.Layer;
057import org.openstreetmap.josm.gui.layer.OsmDataLayer;
058import org.openstreetmap.josm.gui.util.GuiHelper;
059import org.openstreetmap.josm.gui.util.KeyPressReleaseListener;
060import org.openstreetmap.josm.gui.util.ModifierExListener;
061import org.openstreetmap.josm.spi.preferences.Config;
062import org.openstreetmap.josm.tools.ImageProvider;
063import org.openstreetmap.josm.tools.Logging;
064import org.openstreetmap.josm.tools.Pair;
065import org.openstreetmap.josm.tools.PlatformManager;
066import org.openstreetmap.josm.tools.Shortcut;
067import org.openstreetmap.josm.tools.Utils;
068
069/**
070 * Move is an action that can move all kind of OsmPrimitives (except keys for now).
071 * <p>
072 * If an selected object is under the mouse when dragging, move all selected objects.
073 * If an unselected object is under the mouse when dragging, it becomes selected
074 * and will be moved.
075 * If no object is under the mouse, move all selected objects (if any)
076 * <p>
077 * On Mac OS X, Ctrl + mouse button 1 simulates right click (map move), so the
078 * feature "selection remove" is disabled on this platform.
079 */
080public class SelectAction extends MapMode implements ModifierExListener, KeyPressReleaseListener, SelectionEnded {
081
082    private static final String NORMAL = /* ICON(cursor/)*/ "normal";
083
084    /**
085     * Select action mode.
086     * @since 7543
087     */
088    public enum Mode {
089        /** "MOVE" means either dragging or select if no mouse movement occurs (i.e. just clicking) */
090        MOVE,
091        /** "ROTATE" allows to apply a rotation transformation on the selected object (see {@link RotateCommand}) */
092        ROTATE,
093        /** "SCALE" allows to apply a scaling transformation on the selected object (see {@link ScaleCommand}) */
094        SCALE,
095        /** "SELECT" means the selection rectangle */
096        SELECT
097    }
098
099    // contains all possible cases the cursor can be in the SelectAction
100    enum SelectActionCursor {
101
102        rect(NORMAL, /* ICON(cursor/modifier/)*/ "selection"),
103        rect_add(NORMAL, /* ICON(cursor/modifier/)*/ "select_add"),
104        rect_rm(NORMAL, /* ICON(cursor/modifier/)*/ "select_remove"),
105        way(NORMAL, /* ICON(cursor/modifier/)*/ "select_way"),
106        way_add(NORMAL, /* ICON(cursor/modifier/)*/ "select_way_add"),
107        way_rm(NORMAL, /* ICON(cursor/modifier/)*/ "select_way_remove"),
108        node(NORMAL, /* ICON(cursor/modifier/)*/ "select_node"),
109        node_add(NORMAL, /* ICON(cursor/modifier/)*/ "select_node_add"),
110        node_rm(NORMAL, /* ICON(cursor/modifier/)*/ "select_node_remove"),
111        virtual_node(NORMAL, /* ICON(cursor/modifier/)*/ "addnode"),
112        scale(/* ICON(cursor/)*/ "scale", null),
113        rotate(/* ICON(cursor/)*/ "rotate", null),
114        merge(/* ICON(cursor/)*/ "crosshair", null),
115        lasso(NORMAL, /* ICON(cursor/modifier/)*/ "rope"),
116        merge_to_node(/* ICON(cursor/)*/ "crosshair", /* ICON(cursor/modifier/)*/"joinnode"),
117        move(Cursor.MOVE_CURSOR);
118
119        @SuppressWarnings("ImmutableEnumChecker")
120        private final Cursor c;
121        SelectActionCursor(String main, String sub) {
122            c = ImageProvider.getCursor(main, sub);
123        }
124
125        SelectActionCursor(int systemCursor) {
126            c = Cursor.getPredefinedCursor(systemCursor);
127        }
128
129        /**
130         * Returns the action cursor.
131         * @return the cursor
132         */
133        public Cursor cursor() {
134            return c;
135        }
136    }
137
138    /** Whether nodes should be merged with other primitives by default when they are being dragged */
139    private static final CachingProperty<Boolean> MERGE_BY_DEFAULT
140            = new BooleanProperty("edit.move.merge-by-default", false).cached();
141
142    private boolean lassoMode;
143    private boolean repeatedKeySwitchLassoOption;
144
145    // Cache previous mouse event (needed when only the modifier keys are
146    // pressed but the mouse isn't moved)
147    private MouseEvent oldEvent;
148
149    private Mode mode;
150    private final transient SelectionManager selectionManager;
151    private boolean cancelDrawMode;
152    private boolean drawTargetHighlight;
153    private boolean didMouseDrag;
154    /**
155     * The component this SelectAction is associated with.
156     */
157    private final MapView mv;
158    /**
159     * The old cursor before the user pressed the mouse button.
160     */
161    private Point startingDraggingPos;
162    /**
163     * point where user pressed the mouse to start movement
164     */
165    private EastNorth startEN;
166    /**
167     * The last known position of the mouse.
168     */
169    private Point lastMousePos;
170    /**
171     * The time of the user mouse down event.
172     */
173    private long mouseDownTime;
174    /**
175     * The pressed button of the user mouse down event.
176     */
177    private int mouseDownButton;
178    /**
179     * The time of the user mouse down event.
180     */
181    private long mouseReleaseTime;
182    /**
183     * The time which needs to pass between click and release before something
184     * counts as a move, in milliseconds
185     */
186    private int initialMoveDelay;
187    /**
188     * The screen distance which needs to be travelled before something
189     * counts as a move, in pixels
190     */
191    private int initialMoveThreshold;
192    private boolean initialMoveThresholdExceeded;
193
194    /**
195     * elements that have been highlighted in the previous iteration. Used
196     * to remove the highlight from them again as otherwise the whole data
197     * set would have to be checked.
198     */
199    private transient OsmPrimitive currentHighlight;
200
201    /**
202     * Create a new SelectAction
203     * @param mapFrame The MapFrame this action belongs to.
204     */
205    public SelectAction(MapFrame mapFrame) {
206        super(tr("Select mode"), "move/move", tr("Select, move, scale and rotate objects"),
207                Shortcut.registerShortcut("mapmode:select", tr("Mode: {0}", tr("Select mode")), KeyEvent.VK_S, Shortcut.DIRECT),
208                ImageProvider.getCursor(NORMAL, "selection"));
209        mv = mapFrame.mapView;
210        setHelpId(ht("/Action/Select"));
211        selectionManager = new SelectionManager(this, false, mv);
212    }
213
214    @Override
215    public void enterMode() {
216        super.enterMode();
217        mv.addMouseListener(this);
218        mv.addMouseMotionListener(this);
219        mv.setVirtualNodesEnabled(Config.getPref().getInt("mappaint.node.virtual-size", 8) != 0);
220        drawTargetHighlight = Config.getPref().getBoolean("draw.target-highlight", true);
221        initialMoveDelay = Config.getPref().getInt("edit.initial-move-delay", 200);
222        initialMoveThreshold = Config.getPref().getInt("edit.initial-move-threshold", 5);
223        repeatedKeySwitchLassoOption = Config.getPref().getBoolean("mappaint.select.toggle-lasso-on-repeated-S", true);
224        cycleManager.init();
225        virtualManager.init();
226        // This is required to update the cursors when ctrl/shift/alt is pressed
227        MapFrame map = MainApplication.getMap();
228        map.keyDetector.addModifierExListener(this);
229        map.keyDetector.addKeyListener(this);
230    }
231
232    @Override
233    public void exitMode() {
234        super.exitMode();
235        cycleManager.cycleStart = null;
236        cycleManager.cycleList = asColl(null);
237        selectionManager.unregister(mv);
238        mv.removeMouseListener(this);
239        mv.removeMouseMotionListener(this);
240        mv.setVirtualNodesEnabled(false);
241        MapFrame map = MainApplication.getMap();
242        map.keyDetector.removeModifierExListener(this);
243        map.keyDetector.removeKeyListener(this);
244        removeHighlighting();
245        virtualManager.clear();
246    }
247
248    @Override
249    public void modifiersExChanged(int modifiers) {
250        if (!MainApplication.isDisplayingMapView() || oldEvent == null) return;
251        if (giveUserFeedback(oldEvent, modifiers)) {
252            mv.repaint();
253        }
254    }
255
256    /**
257     * handles adding highlights and updating the cursor for the given mouse event.
258     * Please note that the highlighting for merging while moving is handled via mouseDragged.
259     * @param e {@code MouseEvent} which should be used as base for the feedback
260     * @return {@code true} if repaint is required
261     */
262    private boolean giveUserFeedback(MouseEvent e) {
263        return giveUserFeedback(e, e.getModifiersEx());
264    }
265
266    /**
267     * handles adding highlights and updating the cursor for the given mouse event.
268     * Please note that the highlighting for merging while moving is handled via mouseDragged.
269     * @param e {@code MouseEvent} which should be used as base for the feedback
270     * @param modifiers define custom keyboard extended modifiers if the ones from MouseEvent are outdated or similar
271     * @return {@code true} if repaint is required
272     */
273    private boolean giveUserFeedback(MouseEvent e, int modifiers) {
274        if (isPanning()) {
275            return false;
276        }
277        Optional<OsmPrimitive> c = Optional.ofNullable(
278                mv.getNearestNodeOrWay(e.getPoint(), mv.isSelectablePredicate, true));
279
280        updateKeyModifiersEx(modifiers);
281        determineMapMode(c.isPresent());
282
283        virtualManager.clear();
284        if (mode == Mode.MOVE && !dragInProgress() && virtualManager.activateVirtualNodeNearPoint(e.getPoint())) {
285            DataSet ds = getLayerManager().getActiveDataSet();
286            if (ds != null && drawTargetHighlight) {
287                ds.setHighlightedVirtualNodes(virtualManager.virtualWays);
288            }
289            mv.setNewCursor(SelectActionCursor.virtual_node.cursor(), this);
290            // don't highlight anything else if a virtual node will be
291            return repaintIfRequired(null);
292        }
293
294        mv.setNewCursor(getCursor(c.orElse(null)), this);
295
296        // return early if there can't be any highlights
297        if (!drawTargetHighlight || (mode != Mode.MOVE && mode != Mode.SELECT) || !c.isPresent())
298            return repaintIfRequired(null);
299
300        // CTRL toggles selection, but if while dragging CTRL means merge
301        final boolean isToggleMode = platformMenuShortcutKeyMask && !dragInProgress();
302        OsmPrimitive newHighlight = null;
303        if (isToggleMode || !c.get().isSelected()) {
304            // only highlight primitives that will change the selection
305            // when clicked. I.e. don't highlight selected elements unless
306            // we are in toggle mode.
307            newHighlight = c.get();
308        }
309        return repaintIfRequired(newHighlight);
310    }
311
312    /**
313     * works out which cursor should be displayed for most of SelectAction's
314     * features. The only exception is the "move" cursor when actually dragging
315     * primitives.
316     * @param nearbyStuff primitives near the cursor
317     * @return the cursor that should be displayed
318     */
319    private Cursor getCursor(OsmPrimitive nearbyStuff) {
320        String c = "rect";
321        switch (mode) {
322        case MOVE:
323            if (virtualManager.hasVirtualNode()) {
324                c = "virtual_node";
325                break;
326            }
327            final OsmPrimitive osm = nearbyStuff;
328
329            if (dragInProgress()) {
330                // only consider merge if ctrl is pressed and there are nodes in
331                // the selection that could be merged
332                if (!isMergeRequested() || getLayerManager().getEditDataSet().getSelectedNodes().isEmpty()) {
333                    c = "move";
334                    break;
335                }
336                // only show merge to node cursor if nearby node and that node is currently
337                // not being dragged
338                final boolean hasTarget = osm instanceof Node && !osm.isSelected();
339                c = hasTarget ? "merge_to_node" : "merge";
340                break;
341            }
342
343            c = (osm instanceof Node) ? "node" : c;
344            c = (osm instanceof Way) ? "way" : c;
345            if (shift) {
346                c += "_add";
347            } else if (platformMenuShortcutKeyMask) {
348                c += osm == null || osm.isSelected() ? "_rm" : "_add";
349            }
350            break;
351        case ROTATE:
352            c = "rotate";
353            break;
354        case SCALE:
355            c = "scale";
356            break;
357        case SELECT:
358            if (lassoMode) {
359                c = "lasso";
360            } else if (shift) {
361                c = "rect_add";
362            } else if (platformMenuShortcutKeyMask) {
363                c = "rect_rm";
364            } else {
365                c = "rect";
366            }
367            break;
368        }
369        return SelectActionCursor.valueOf(c).cursor();
370    }
371
372    /**
373     * Removes all existing highlights.
374     * @return true if a repaint is required
375     */
376    private boolean removeHighlighting() {
377        boolean needsRepaint = false;
378        OsmData<?, ?, ?, ?> ds = getLayerManager().getActiveData();
379        if (ds != null && !ds.getHighlightedVirtualNodes().isEmpty()) {
380            needsRepaint = true;
381            ds.clearHighlightedVirtualNodes();
382        }
383        if (currentHighlight == null) {
384            return needsRepaint;
385        }
386        currentHighlight.setHighlighted(false);
387        currentHighlight = null;
388        return true;
389    }
390
391    private boolean repaintIfRequired(OsmPrimitive newHighlight) {
392        if (!drawTargetHighlight || Objects.equals(currentHighlight, newHighlight))
393            return false;
394        if (currentHighlight != null) {
395            currentHighlight.setHighlighted(false);
396        }
397        if (newHighlight != null) {
398            newHighlight.setHighlighted(true);
399        }
400        currentHighlight = newHighlight;
401        return true;
402    }
403
404    /**
405     * Look, whether any object is selected. If not, select the nearest node.
406     * If there are no nodes in the dataset, do nothing.
407     * <p>
408     * If the user did not press the left mouse button, do nothing.
409     * <p>
410     * Also remember the starting position of the movement and change the mouse
411     * cursor to movement.
412     */
413    @Override
414    public void mousePressed(MouseEvent e) {
415        mouseDownButton = e.getButton();
416        // return early
417        if (!mv.isActiveLayerVisible() || Boolean.FALSE.equals(this.getValue("active")) || mouseDownButton != MouseEvent.BUTTON1)
418            return;
419
420        // left-button mouse click only is processed here
421
422        // request focus in order to enable the expected keyboard shortcuts
423        mv.requestFocus();
424
425        // update which modifiers are pressed (shift, alt, ctrl)
426        updateKeyModifiers(e);
427
428        // We don't want to change to draw tool if the user tries to (de)select
429        // stuff but accidentally clicks in an empty area when selection is empty
430        cancelDrawMode = shift || platformMenuShortcutKeyMask;
431        didMouseDrag = false;
432        initialMoveThresholdExceeded = false;
433        mouseDownTime = System.currentTimeMillis();
434        lastMousePos = e.getPoint();
435        startEN = mv.getEastNorth(lastMousePos.x, lastMousePos.y);
436
437        // primitives under cursor are stored in c collection
438
439        OsmPrimitive nearestPrimitive = mv.getNearestNodeOrWay(e.getPoint(), mv.isSelectablePredicate, true);
440
441        determineMapMode(nearestPrimitive != null);
442
443        switch (mode) {
444        case ROTATE:
445        case SCALE:
446            //  if nothing was selected, select primitive under cursor for scaling or rotating
447            DataSet ds = getLayerManager().getEditDataSet();
448            if (ds.selectionEmpty()) {
449                ds.setSelected(asColl(nearestPrimitive));
450            }
451
452            // Mode.select redraws when selectPrims is called
453            // Mode.move   redraws when mouseDragged is called
454            // Mode.rotate redraws here
455            // Mode.scale redraws here
456            break;
457        case MOVE:
458            // also include case when some primitive is under cursor and no shift+ctrl / alt+ctrl is pressed
459            // so this is not movement, but selection on primitive under cursor
460            if (!cancelDrawMode && nearestPrimitive instanceof Way) {
461                virtualManager.activateVirtualNodeNearPoint(e.getPoint());
462            }
463            OsmPrimitive toSelect = cycleManager.cycleSetup(nearestPrimitive, e.getPoint());
464            selectPrims(asColl(toSelect), false, false);
465            useLastMoveCommandIfPossible();
466            // Schedule a timer to update status line "initialMoveDelay+1" ms in the future
467            GuiHelper.scheduleTimer(initialMoveDelay+1, evt -> updateStatusLine(), false);
468            break;
469        case SELECT:
470            if (!(ctrl && PlatformManager.isPlatformOsx())) {
471                // start working with rectangle or lasso
472                selectionManager.register(mv, lassoMode);
473                selectionManager.mousePressed(e);
474                break;
475            }
476        }
477        if (giveUserFeedback(e)) {
478            mv.repaint();
479        }
480        updateStatusLine();
481    }
482
483    @Override
484    public void mouseMoved(MouseEvent e) {
485        oldEvent = e;
486        if (giveUserFeedback(e)) {
487            mv.repaint();
488        }
489    }
490
491    /**
492     * If the left mouse button is pressed, move all currently selected
493     * objects (if one of them is under the mouse) or the current one under the
494     * mouse (which will become selected).
495     */
496    @Override
497    public void mouseDragged(MouseEvent e) {
498        if (!mv.isActiveLayerVisible())
499            return;
500
501        // Swing sends random mouseDragged events when closing dialogs by double-clicking their top-left icon on Windows
502        // Ignore such false events to prevent issues like #7078
503        if (mouseDownButton == MouseEvent.BUTTON1 && mouseReleaseTime > mouseDownTime)
504            return;
505
506        updateKeyModifiers(e);
507
508        cancelDrawMode = true;
509        if (mode == Mode.SELECT) {
510            // Unregisters selectionManager if ctrl has been pressed after mouse click on Mac OS X in order to move the map
511            if (ctrl && PlatformManager.isPlatformOsx()) {
512                selectionManager.unregister(mv);
513                // Make sure correct cursor is displayed
514                mv.setNewCursor(Cursor.MOVE_CURSOR, this);
515            }
516            return;
517        }
518
519        // do not count anything as a move if it lasts less than 100 milliseconds.
520        if ((mode == Mode.MOVE) && (System.currentTimeMillis() - mouseDownTime < initialMoveDelay))
521            return;
522
523        if (mode != Mode.ROTATE && mode != Mode.SCALE && (e.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK) == 0) {
524            // button is pressed in rotate mode
525            return;
526        }
527
528        if (mode == Mode.MOVE) {
529            // If ctrl is pressed we are in merge mode. Look for a nearby node,
530            // highlight it and adjust the cursor accordingly.
531            final boolean canMerge = isMergeRequested() && !getLayerManager().getEditDataSet().getSelectedNodes().isEmpty();
532            final OsmPrimitive p = canMerge ? findNodeToMergeTo(e.getPoint()) : null;
533            boolean needsRepaint = removeHighlighting();
534            if (p != null) {
535                p.setHighlighted(true);
536                currentHighlight = p;
537                needsRepaint = true;
538            }
539            mv.setNewCursor(getCursor(p), this);
540            // also update the stored mouse event, so we can display the correct cursor
541            // when dragging a node onto another one and then press CTRL to merge
542            oldEvent = e;
543            if (needsRepaint) {
544                mv.repaint();
545            }
546        }
547
548        if (startingDraggingPos == null) {
549            startingDraggingPos = new Point(e.getX(), e.getY());
550        }
551
552        if (lastMousePos == null) {
553            lastMousePos = e.getPoint();
554            return;
555        }
556
557        if (!initialMoveThresholdExceeded) {
558            int dp = (int) lastMousePos.distance(e.getX(), e.getY());
559            if (dp < initialMoveThreshold)
560                return; // ignore small drags
561            initialMoveThresholdExceeded = true; //no more ignoring until next mouse press
562        }
563        if (e.getPoint().equals(lastMousePos))
564            return;
565
566        EastNorth currentEN = mv.getEastNorth(e.getX(), e.getY());
567
568        if (virtualManager.hasVirtualWaysToBeConstructed()) {
569            virtualManager.createMiddleNodeFromVirtual(currentEN);
570        } else {
571            if (!updateCommandWhileDragging(e, currentEN)) return;
572        }
573
574        mv.repaint();
575        if (mode != Mode.SCALE) {
576            lastMousePos = e.getPoint();
577        }
578
579        didMouseDrag = true;
580    }
581
582    @Override
583    public void mouseExited(MouseEvent e) {
584        if (removeHighlighting()) {
585            mv.repaint();
586        }
587    }
588
589    @Override
590    public void mouseReleased(MouseEvent e) {
591        if (!mv.isActiveLayerVisible())
592            return;
593
594        startingDraggingPos = null;
595        mouseReleaseTime = System.currentTimeMillis();
596        MapFrame map = MainApplication.getMap();
597
598        if (mode == Mode.SELECT) {
599            if (e.getButton() != MouseEvent.BUTTON1) {
600                return;
601            }
602            selectionManager.endSelecting(e);
603            selectionManager.unregister(mv);
604
605            // Select Draw Tool if no selection has been made
606            if (!cancelDrawMode && getLayerManager().getActiveDataSet().selectionEmpty()) {
607                map.selectDrawTool(true);
608                updateStatusLine();
609                return;
610            }
611        }
612
613        if (mode == Mode.MOVE && e.getButton() == MouseEvent.BUTTON1 && !didMouseDrag) {
614            // only built in move mode
615            virtualManager.clear();
616            // do nothing if the click was to short too be recognized as a drag,
617            // but the release position is farther than 10px away from the press position
618            if (lastMousePos == null || lastMousePos.distanceSq(e.getPoint()) < 100) {
619                DataSet ds = getLayerManager().getEditDataSet();
620                updateKeyModifiers(e);
621                selectPrims(cycleManager.cyclePrims(), true, false);
622
623                // If the user double-clicked a node, change to draw mode
624                Collection<OsmPrimitive> c = ds.getSelected();
625                if (e.getClickCount() >= 2 && c.size() == 1 && c.iterator().next() instanceof Node) {
626                    // We need to do it like this as otherwise drawAction will see a double
627                    // click and switch back to SelectMode
628                    MainApplication.worker.execute(() -> map.selectDrawTool(true));
629                    return;
630                }
631            }
632        }
633
634        if ((mode == Mode.MOVE || mode == Mode.ROTATE || mode == Mode.SCALE) && e.getButton() == MouseEvent.BUTTON1
635                && didMouseDrag) {
636            confirmOrUndoMovement(e);
637        }
638
639        mode = null;
640
641        // simply remove any highlights if the middle click popup is active because
642        // the highlights don't depend on the cursor position there. If something was
643        // selected beforehand this would put us into move mode as well, which breaks
644        // the cycling through primitives on top of each other (see #6739).
645        if (e.getButton() == MouseEvent.BUTTON2) {
646            removeHighlighting();
647        } else {
648            giveUserFeedback(e);
649        }
650        updateStatusLine();
651    }
652
653    @Override
654    public void selectionEnded(Rectangle r, MouseEvent e) {
655        updateKeyModifiers(e);
656        selectPrims(selectionManager.getSelectedObjects(alt), true, true);
657    }
658
659    @Override
660    public void doKeyPressed(KeyEvent e) {
661        if (!repeatedKeySwitchLassoOption || !MainApplication.isDisplayingMapView() || !getShortcut().isEvent(e))
662            return;
663        if (Logging.isDebugEnabled()) {
664            Logging.debug("{0} consuming event {1}", getClass().getName(), e);
665        }
666        e.consume();
667        MapFrame map = MainApplication.getMap();
668        if (!lassoMode) {
669            map.selectMapMode(map.mapModeSelectLasso);
670        } else {
671            map.selectMapMode(map.mapModeSelect);
672        }
673    }
674
675    @Override
676    public void doKeyReleased(KeyEvent e) {
677        // Do nothing
678    }
679
680    /**
681     * sets the mapmode according to key modifiers and if there are any
682     * selectables nearby. Everything has to be pre-determined for this
683     * function; its main purpose is to centralize what the modifiers do.
684     * @param hasSelectionNearby {@code true} if some primitves are selectable nearby
685     */
686    private void determineMapMode(boolean hasSelectionNearby) {
687        if (getLayerManager().getEditDataSet() != null) {
688            if (shift && platformMenuShortcutKeyMask) {
689                mode = Mode.ROTATE;
690            } else if (alt && platformMenuShortcutKeyMask) {
691                mode = Mode.SCALE;
692            } else if (hasSelectionNearby || dragInProgress()) {
693                mode = Mode.MOVE;
694            } else {
695                mode = Mode.SELECT;
696            }
697        } else {
698            mode = Mode.SELECT;
699        }
700    }
701
702    /**
703     * Determines whenever elements have been grabbed and moved (i.e. the initial
704     * thresholds have been exceeded) and is still in progress (i.e. mouse button still pressed)
705     * @return true if a drag is in progress
706     */
707    private boolean dragInProgress() {
708        return didMouseDrag && startingDraggingPos != null;
709    }
710
711    /**
712     * Create or update data modification command while dragging mouse - implementation of
713     * continuous moving, scaling and rotation
714     * @param mouseEvent The triggering mouse event
715     * @param currentEN - mouse position
716     * @return status of action (<code>true</code> when action was performed)
717     */
718    private boolean updateCommandWhileDragging(MouseEvent mouseEvent, EastNorth currentEN) {
719        // Currently we support only transformations which do not affect relations.
720        // So don't add them in the first place to make handling easier
721        DataSet ds = getLayerManager().getEditDataSet();
722        Collection<OsmPrimitive> selection = ds.getSelectedNodesAndWays();
723        if (selection.isEmpty()) { // if nothing was selected to drag, just select nearest node/way to the cursor
724            ds.setSelected(mv.getNearestNodeOrWay(mv.getPoint(startEN), mv.isSelectablePredicate, true));
725        }
726
727        Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
728        // for these transformations, having only one node makes no sense - quit silently
729        if (affectedNodes.size() < 2 && (mode == Mode.ROTATE || mode == Mode.SCALE)) {
730            return false;
731        }
732        Command c = getLastCommandInDataset(ds);
733        if (mode == Mode.MOVE) {
734            if (startEN == null) return false; // fix #8128
735            return ds.update(() -> {
736                MoveCommand moveCmd = null;
737                if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
738                    EastNorth clampedEastNorth = currentEN;
739                    if (platformMenuShortcutKeyMask) {
740                        Way w = ds.getLastSelectedWay();
741                        if (w != null && w.getNodesCount() == 2) {
742                            double clamph = w.firstNode().getEastNorth().heading(w.lastNode().getEastNorth());
743                            double dh = startEN.heading(currentEN, clamph);
744                            switch ((int) (dh / (Math.PI/4))) {
745                            case 1:
746                            case 2:
747                                dh -= Math.PI/2;
748                                break;
749                            case 3:
750                            case 4:
751                                dh += Math.PI;
752                                break;
753                            case 5:
754                            case 6:
755                                dh += Math.PI/2;
756                                break;
757                            default:
758                                // Just in case we cannot clamp
759                            }
760                            clampedEastNorth = currentEN.rotate(startEN, -dh);
761                        }
762                    }
763                    moveCmd = (MoveCommand) c;
764                    moveCmd.saveCheckpoint();
765                    moveCmd.applyVectorTo(clampedEastNorth);
766                } else if (!selection.isEmpty()) {
767                    moveCmd = new MoveCommand(selection, startEN, currentEN);
768                    UndoRedoHandler.getInstance().add(moveCmd);
769                }
770                for (Node n : affectedNodes) {
771                    if (n.isOutSideWorld()) {
772                        // Revert move
773                        if (moveCmd != null) {
774                            moveCmd.resetToCheckpoint();
775                        }
776                        // TODO: We might use a simple notification in the lower left corner.
777                        JOptionPane.showMessageDialog(
778                                MainApplication.getMainFrame(),
779                                tr("Cannot move objects outside of the world."),
780                                tr("Warning"),
781                                JOptionPane.WARNING_MESSAGE);
782                        mv.setNewCursor(cursor, this);
783                        return false;
784                    }
785                }
786                return true;
787            });
788        } else {
789            startEN = currentEN; // drag can continue after scaling/rotation
790
791            if ((mode != Mode.ROTATE && mode != Mode.SCALE) || SwingUtilities.isRightMouseButton(mouseEvent)) {
792                return false;
793            }
794
795            return ds.update(() -> {
796                if (mode == Mode.ROTATE) {
797                    if (c instanceof RotateCommand && affectedNodes.equals(((RotateCommand) c).getTransformedNodes())) {
798                        if (didMouseDrag) {
799                            ((RotateCommand) c).handleEvent(currentEN);
800                        } else {
801                            ((RotateCommand) c).handleUpdate(currentEN);
802                        }
803                    } else {
804                        UndoRedoHandler.getInstance().add(new RotateCommand(selection, currentEN));
805                    }
806                } else if (mode == Mode.SCALE) {
807                    if (c instanceof ScaleCommand && affectedNodes.equals(((ScaleCommand) c).getTransformedNodes())) {
808                        if (didMouseDrag) {
809                            ((ScaleCommand) c).handleEvent(currentEN);
810                        } else {
811                            ((ScaleCommand) c).handleUpdate(currentEN);
812                        }
813                    } else {
814                        UndoRedoHandler.getInstance().add(new ScaleCommand(selection, currentEN));
815                    }
816                }
817
818                Collection<Way> ways = ds.getSelectedWays();
819                if (doesImpactStatusLine(affectedNodes, ways)) {
820                    MainApplication.getMap().statusLine.setDist(ways);
821                }
822                if (c instanceof RotateCommand) {
823                    double angle = Utils.toDegrees(((RotateCommand) c).getRotationAngle());
824                    MainApplication.getMap().statusLine.setAngleNaN(angle);
825                } else if (c instanceof ScaleCommand) {
826                    // U+00D7 MULTIPLICATION SIGN
827                    String angle = String.format("%.2f", ((ScaleCommand) c).getScalingFactor()) + " \u00d7";
828                    MainApplication.getMap().statusLine.setAngleText(angle);
829                }
830                return true;
831            });
832        }
833    }
834
835    private static boolean doesImpactStatusLine(Collection<Node> affectedNodes, Collection<Way> selectedWays) {
836        return selectedWays.stream()
837                .flatMap(w -> w.getNodes().stream())
838                .anyMatch(affectedNodes::contains);
839    }
840
841    /**
842     * Adapt last move command (if it is suitable) to work with next drag, started at point startEN
843     */
844    private void useLastMoveCommandIfPossible() {
845        DataSet dataSet = getLayerManager().getEditDataSet();
846        if (dataSet == null) {
847            // It may happen that there is no edit layer.
848            return;
849        }
850        Command c = getLastCommandInDataset(dataSet);
851        Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(dataSet.getSelected());
852        if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
853            // old command was created with different base point of movement, we need to recalculate it
854            ((MoveCommand) c).changeStartPoint(startEN);
855        }
856    }
857
858    /**
859     * Obtain command in undoRedo stack to "continue" when dragging
860     * @param ds The data set the command needs to be in.
861     * @return last command
862     */
863    private static Command getLastCommandInDataset(DataSet ds) {
864        Command lastCommand = UndoRedoHandler.getInstance().getLastCommand();
865        if (lastCommand instanceof SequenceCommand) {
866            lastCommand = ((SequenceCommand) lastCommand).getLastCommand();
867        }
868        if (lastCommand != null && ds.equals(lastCommand.getAffectedDataSet())) {
869            return lastCommand;
870        } else {
871            return null;
872        }
873    }
874
875    /**
876     * Present warning in the following cases and undo unwanted movements: <ul>
877     * <li>large and possibly unwanted movements</li>
878     * <li>movement of node with attached ways that are hidden by filters</li>
879     * </ul>
880     *
881     * @param e the mouse event causing the action (mouse released)
882     */
883    private void confirmOrUndoMovement(MouseEvent e) {
884        if (movesHiddenWay()) {
885            final ConfirmMoveDialog ed = new ConfirmMoveDialog();
886            ed.setContent(tr("Are you sure that you want to move elements with attached ways that are hidden by filters?"));
887            ed.toggleEnable("movedHiddenElements");
888            showConfirmMoveDialog(ed);
889        }
890
891        final Command lastCommand = UndoRedoHandler.getInstance().getLastCommand();
892        if (lastCommand == null) {
893            Logging.warn("No command found in undo/redo history, skipping confirmOrUndoMovement");
894            return;
895        }
896
897        SelectAction.checkCommandForLargeDistance(lastCommand);
898
899        // check if move was cancelled
900        if (UndoRedoHandler.getInstance().getLastCommand() != lastCommand)
901            return;
902
903        final int moveCount = lastCommand.getParticipatingPrimitives().size();
904        final int max = Config.getPref().getInt("warn.move.maxelements", 20);
905        if (moveCount > max) {
906            final ConfirmMoveDialog ed = new ConfirmMoveDialog();
907            ed.setContent(
908                    /* for correct i18n of plural forms - see #9110 */
909                    trn("You moved more than {0} element. " + "Moving a large number of elements is often an error.\n" + "Really move them?",
910                        "You moved more than {0} elements. " + "Moving a large number of elements is often an error.\n" + "Really move them?",
911                        max, max));
912            ed.toggleEnable("movedManyElements");
913            showConfirmMoveDialog(ed);
914        } else {
915            // if small number of elements were moved,
916            updateKeyModifiers(e);
917            if (isMergeRequested()) mergePrims(e.getPoint());
918        }
919    }
920
921    static void checkCommandForLargeDistance(Command lastCommand) {
922        if (lastCommand == null) {
923            return;
924        }
925        final int moveCount = lastCommand.getParticipatingPrimitives().size();
926        if (lastCommand instanceof MoveCommand) {
927            final double moveDistance = ((MoveCommand) lastCommand).getDistance(n -> !n.isNew());
928            if (Double.isFinite(moveDistance) && moveDistance > Config.getPref().getInt("warn.move.maxdistance", 200)) {
929                final ConfirmMoveDialog ed = new ConfirmMoveDialog();
930                ed.setContent(trn(
931                        "You moved {0} element by a distance of {1}. "
932                                + "Moving elements by a large distance is often an error.\n" + "Really move it?",
933                        "You moved {0} elements by a distance of {1}. "
934                                + "Moving elements by a large distance is often an error.\n" + "Really move them?",
935                        moveCount, moveCount, SystemOfMeasurement.getSystemOfMeasurement().getDistText(moveDistance)));
936                ed.toggleEnable("movedLargeDistance");
937                showConfirmMoveDialog(ed);
938            }
939        }
940    }
941
942    private static void showConfirmMoveDialog(ConfirmMoveDialog ed) {
943        if (ed.showDialog().getValue() != 1) {
944            UndoRedoHandler.getInstance().undo();
945        }
946    }
947
948    static class ConfirmMoveDialog extends ExtendedDialog {
949        ConfirmMoveDialog() {
950            super(MainApplication.getMainFrame(),
951                    tr("Move elements"),
952                    tr("Move them"), tr("Undo move"));
953            setButtonIcons("reorder", "cancel");
954            setCancelButton(2);
955        }
956    }
957
958    private boolean movesHiddenWay() {
959        DataSet ds = getLayerManager().getEditDataSet();
960        final Collection<Node> elementsToTest = new HashSet<>(ds.getSelectedNodes());
961        for (Way osm : ds.getSelectedWays()) {
962            elementsToTest.addAll(osm.getNodes());
963        }
964        return elementsToTest.stream()
965                .flatMap(n -> n.referrers(Way.class))
966                .anyMatch(Way::isDisabledAndHidden);
967    }
968
969    /**
970     * Check if dragged node should be merged when moving it over another primitive
971     * @return true if merge is requested
972     */
973    private boolean isMergeRequested() {
974        return MERGE_BY_DEFAULT.get() ^ platformMenuShortcutKeyMask;
975    }
976
977    /**
978     * Merges the selected nodes to the one closest to the given mouse position if the control
979     * key is pressed. If there is no such node, no action will be done and no error will be
980     * reported. If there is, it will execute the merge and add it to the undo buffer.
981     * @param p mouse position
982     */
983    private void mergePrims(Point p) {
984        DataSet ds = getLayerManager().getEditDataSet();
985        Collection<Node> selNodes = ds.getSelectedNodes();
986        if (selNodes.isEmpty())
987            return;
988
989        Node target = findNodeToMergeTo(p);
990        if (target == null)
991            return;
992
993        if (selNodes.size() == 1) {
994            // Move all selected primitive to preserve shape #10748
995            Collection<OsmPrimitive> selection = ds.getSelectedNodesAndWays();
996            Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
997            Command c = getLastCommandInDataset(ds);
998            ds.update(() -> {
999                if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
1000                    Node selectedNode = selNodes.iterator().next();
1001                    EastNorth selectedEN = selectedNode.getEastNorth();
1002                    EastNorth targetEN = target.getEastNorth();
1003                    ((MoveCommand) c).moveAgain(targetEN.getX() - selectedEN.getX(),
1004                                                targetEN.getY() - selectedEN.getY());
1005                }
1006            });
1007        }
1008
1009        Collection<Node> nodesToMerge = new LinkedList<>(selNodes);
1010        nodesToMerge.add(target);
1011        mergeNodes(MainApplication.getLayerManager().getEditLayer(), nodesToMerge, target);
1012    }
1013
1014    /**
1015     * Merge nodes using {@code MergeNodesAction}.
1016     * Can be overridden for testing purpose.
1017     * @param layer layer the reference data layer. Must not be null
1018     * @param nodes the collection of nodes. Ignored if null
1019     * @param targetLocationNode this node's location will be used for the target node
1020     */
1021    public void mergeNodes(OsmDataLayer layer, Collection<Node> nodes,
1022                           Node targetLocationNode) {
1023        MergeNodesAction.doMergeNodes(layer, nodes, targetLocationNode);
1024    }
1025
1026    /**
1027     * Tries to find a node to merge to when in move-merge mode for the current mouse
1028     * position. Either returns the node or null, if no suitable one is nearby.
1029     * @param p mouse position
1030     * @return node to merge to, or null
1031     */
1032    private Node findNodeToMergeTo(Point p) {
1033        Collection<Node> target = mv.getNearestNodes(p,
1034                getLayerManager().getEditDataSet().getSelectedNodes(),
1035                mv.isSelectablePredicate);
1036        return target.isEmpty() ? null : target.iterator().next();
1037    }
1038
1039    private void selectPrims(Collection<OsmPrimitive> prims, boolean released, boolean area) {
1040        DataSet ds = getLayerManager().getActiveDataSet();
1041
1042        // not allowed together: do not change dataset selection, return early
1043        // Virtual Ways: if non-empty the cursor is above a virtual node. So don't highlight
1044        // anything if about to drag the virtual node (i.e. !released) but continue if the
1045        // cursor is only released above a virtual node by accident (i.e. released). See #7018
1046        if (ds == null || (shift && platformMenuShortcutKeyMask) || (platformMenuShortcutKeyMask && !released)
1047                || (virtualManager.hasVirtualWaysToBeConstructed() && !released))
1048            return;
1049
1050        if (!released) {
1051            // Don't replace the selection if the user clicked on a
1052            // selected object (it breaks moving of selected groups).
1053            // Do it later, on mouse release.
1054            shift |= ds.getSelected().containsAll(prims);
1055        }
1056
1057        if (platformMenuShortcutKeyMask) {
1058            // Ctrl on an item toggles its selection status,
1059            // but Ctrl on an *area* just clears those items
1060            // out of the selection.
1061            if (area) {
1062                ds.clearSelection(prims);
1063            } else {
1064                ds.toggleSelected(prims);
1065            }
1066        } else if (shift) {
1067            // add prims to an existing selection
1068            ds.addSelected(prims);
1069        } else {
1070            // clear selection, then select the prims clicked
1071            ds.setSelected(prims);
1072        }
1073    }
1074
1075    /**
1076     * Returns the current select mode.
1077     * @return the select mode
1078     * @since 7543
1079     */
1080    public final Mode getMode() {
1081        return mode;
1082    }
1083
1084    @Override
1085    public String getModeHelpText() {
1086        // There needs to be a better way
1087        final String menuKey;
1088        switch (PlatformManager.getPlatform().getMenuShortcutKeyMaskEx()) {
1089        case InputEvent.CTRL_DOWN_MASK:
1090            menuKey = trc("SelectAction help", "Ctrl");
1091            break;
1092        case InputEvent.META_DOWN_MASK:
1093            menuKey = trc("SelectAction help", "Meta");
1094            break;
1095        default:
1096            throw new IllegalStateException("Unknown platform menu shortcut key for " + PlatformManager.getPlatform().getOSDescription());
1097        }
1098        final String type = this.lassoMode ? trc("SelectAction help", "lasso") : trc("SelectAction help", "rectangle");
1099        if (mouseDownButton == MouseEvent.BUTTON1 && mouseReleaseTime < mouseDownTime) {
1100            if (mode == Mode.SELECT)
1101                return tr("Release the mouse button to select the objects in the {0}.", type);
1102            else if (mode == Mode.MOVE && (System.currentTimeMillis() - mouseDownTime >= initialMoveDelay)) {
1103                final DataSet ds = getLayerManager().getEditDataSet();
1104                final boolean canMerge = ds != null && !ds.getSelectedNodes().isEmpty();
1105                final String mergeHelp = canMerge ? (' ' + tr("{0} to merge with nearest node.", menuKey)) : "";
1106                return tr("Release the mouse button to stop moving.") + mergeHelp;
1107            } else if (mode == Mode.ROTATE)
1108                return tr("Release the mouse button to stop rotating.");
1109            else if (mode == Mode.SCALE)
1110                return tr("Release the mouse button to stop scaling.");
1111        }
1112        return tr("Move objects by dragging; Shift to add to selection ({0} to toggle); Shift-{0} to rotate selected; " +
1113                "Alt-{0} to scale selected; or change selection", menuKey);
1114    }
1115
1116    @Override
1117    public boolean layerIsSupported(Layer l) {
1118        return l instanceof OsmDataLayer;
1119    }
1120
1121    /**
1122     * Enable or diable the lasso mode
1123     * @param lassoMode true to enable the lasso mode, false otherwise
1124     */
1125    public void setLassoMode(boolean lassoMode) {
1126        this.selectionManager.setLassoMode(lassoMode);
1127        this.lassoMode = lassoMode;
1128    }
1129
1130    private final transient CycleManager cycleManager = new CycleManager();
1131    private final transient VirtualManager virtualManager = new VirtualManager();
1132
1133    private final class CycleManager {
1134
1135        private Collection<OsmPrimitive> cycleList = Collections.emptyList();
1136        private boolean cyclePrims;
1137        private OsmPrimitive cycleStart;
1138        private boolean waitForMouseUpParameter;
1139        private boolean multipleMatchesParameter;
1140        /**
1141         * read preferences
1142         */
1143        private void init() {
1144            waitForMouseUpParameter = Config.getPref().getBoolean("mappaint.select.waits-for-mouse-up", false);
1145            multipleMatchesParameter = Config.getPref().getBoolean("selectaction.cycles.multiple.matches", false);
1146        }
1147
1148        /**
1149         * Determine primitive to be selected and build cycleList
1150         * @param nearest primitive found by simple method
1151         * @param p point where user clicked
1152         * @return OsmPrimitive to be selected
1153         */
1154        private OsmPrimitive cycleSetup(OsmPrimitive nearest, Point p) {
1155            OsmPrimitive osm = null;
1156
1157            if (nearest != null) {
1158                osm = nearest;
1159
1160                if (!(alt || multipleMatchesParameter)) {
1161                    // no real cycling, just one element in cycle list
1162                    cycleList = asColl(osm);
1163
1164                    if (waitForMouseUpParameter) {
1165                        // prefer a selected nearest node or way, if possible
1166                        osm = mv.getNearestNodeOrWay(p, mv.isSelectablePredicate, true);
1167                    }
1168                } else {
1169                    // Alt + left mouse button pressed: we need to build cycle list
1170                    cycleList = mv.getAllNearest(p, mv.isSelectablePredicate);
1171
1172                    if (cycleList.size() > 1) {
1173                        cyclePrims = false;
1174
1175                        // find first already selected element in cycle list
1176                        OsmPrimitive old = osm;
1177                        for (OsmPrimitive o : cycleList) {
1178                            if (o.isSelected()) {
1179                                cyclePrims = true;
1180                                osm = o;
1181                                break;
1182                            }
1183                        }
1184
1185                        // special case:  for cycle groups of 2, we can toggle to the
1186                        // true nearest primitive on mousePressed right away
1187                        if (cycleList.size() == 2 && !waitForMouseUpParameter
1188                                // This was a nested if statement (see commented code below)
1189                                && !(osm.equals(old) || osm.isNew() || platformMenuShortcutKeyMask)) {
1190                                cyclePrims = false;
1191                                osm = old;
1192                                // else defer toggling to mouseRelease time in those cases:
1193                                /*
1194                                 * osm == old -- the true nearest node is the
1195                                 * selected one osm is a new node -- do not break
1196                                 * unglue ways in ALT mode ctrl is pressed -- ctrl
1197                                 * generally works on mouseReleased
1198                                 */
1199                        }
1200                    }
1201                }
1202            }
1203            return osm;
1204        }
1205
1206        /**
1207         * Modifies current selection state and returns the next element in a
1208         * selection cycle given by
1209         * <code>cycleList</code> field
1210         * @return the next element of cycle list
1211         */
1212        private Collection<OsmPrimitive> cyclePrims() {
1213            if (cycleList.size() <= 1) {
1214                // no real cycling, just return one-element collection with nearest primitive in it
1215                return cycleList;
1216            }
1217            // updateKeyModifiers() already called before!
1218
1219            DataSet ds = getLayerManager().getActiveDataSet();
1220            OsmPrimitive first = cycleList.iterator().next(), foundInDS = null;
1221            OsmPrimitive nxt = first;
1222
1223            if (cyclePrims && shift) {
1224                for (OsmPrimitive osmPrimitive : cycleList) {
1225                    nxt = osmPrimitive;
1226                    if (!nxt.isSelected()) {
1227                        break; // take first primitive in cycleList not in sel
1228                    }
1229                }
1230                // if primitives 1,2,3 are under cursor, [Alt-press] [Shift-release] gives 1 -> 12 -> 123
1231            } else {
1232                for (Iterator<OsmPrimitive> i = cycleList.iterator(); i.hasNext();) {
1233                    nxt = i.next();
1234                    if (nxt.isSelected()) {
1235                        foundInDS = nxt;
1236                        // first selected primitive in cycleList is found
1237                        if (cyclePrims || platformMenuShortcutKeyMask) {
1238                            ds.clearSelection(foundInDS); // deselect it
1239                            nxt = i.hasNext() ? i.next() : first;
1240                            // return next one in cycle list (last->first)
1241                        }
1242                        break; // take next primitive in cycleList
1243                    }
1244                }
1245            }
1246
1247            // if "no-alt-cycling" is enabled, Ctrl-Click arrives here.
1248            if (platformMenuShortcutKeyMask) {
1249                // a member of cycleList was found in the current dataset selection
1250                if (foundInDS != null) {
1251                    // mouse was moved to a different selection group w/ a previous sel
1252                    if (!cycleList.contains(cycleStart)) {
1253                        ds.clearSelection(cycleList);
1254                        cycleStart = foundInDS;
1255                    } else if (cycleStart.equals(nxt)) {
1256                        // loop detected, insert deselect step
1257                        ds.addSelected(nxt);
1258                    }
1259                } else {
1260                    // setup for iterating a sel group again or a new, different one..
1261                    nxt = cycleList.contains(cycleStart) ? cycleStart : first;
1262                    cycleStart = nxt;
1263                }
1264            } else {
1265                cycleStart = null;
1266            }
1267            // return one-element collection with one element to be selected (or added  to selection)
1268            return asColl(nxt);
1269        }
1270    }
1271
1272    private final class VirtualManager {
1273
1274        private Node virtualNode;
1275        private Collection<WaySegment> virtualWays = new LinkedList<>();
1276        private int nodeVirtualSize;
1277        private int virtualSnapDistSq2;
1278        private int virtualSpace;
1279
1280        private void init() {
1281            nodeVirtualSize = Config.getPref().getInt("mappaint.node.virtual-size", 8);
1282            int virtualSnapDistSq = Config.getPref().getInt("mappaint.node.virtual-snap-distance", 8);
1283            virtualSnapDistSq2 = virtualSnapDistSq*virtualSnapDistSq;
1284            virtualSpace = Config.getPref().getInt("mappaint.node.virtual-space", 70);
1285        }
1286
1287        /**
1288         * Calculate a virtual node if there is enough visual space to draw a
1289         * crosshair node and the middle of a way segment is clicked. If the
1290         * user drags the crosshair node, it will be added to all ways in
1291         * <code>virtualWays</code>.
1292         *
1293         * @param p the point clicked
1294         * @return whether
1295         * <code>virtualNode</code> and
1296         * <code>virtualWays</code> were setup.
1297         */
1298        private boolean activateVirtualNodeNearPoint(Point p) {
1299            if (nodeVirtualSize > 0) {
1300
1301                Collection<WaySegment> selVirtualWays = new LinkedList<>();
1302                Pair<Node, Node> vnp = null, wnp = new Pair<>(null, null);
1303
1304                for (WaySegment ws : mv.getNearestWaySegments(p, mv.isSelectablePredicate)) {
1305                    Way w = ws.getWay();
1306
1307                    wnp.a = w.getNode(ws.getLowerIndex());
1308                    wnp.b = w.getNode(ws.getUpperIndex());
1309                    MapViewPoint p1 = mv.getState().getPointFor(wnp.a);
1310                    MapViewPoint p2 = mv.getState().getPointFor(wnp.b);
1311                    if (AbstractMapRenderer.isLargeSegment(p1, p2, virtualSpace)) {
1312                        Point2D pc = new Point2D.Double((p1.getInViewX() + p2.getInViewX()) / 2, (p1.getInViewY() + p2.getInViewY()) / 2);
1313                        if (p.distanceSq(pc) < virtualSnapDistSq2) {
1314                            // Check that only segments on top of each other get added to the
1315                            // virtual ways list. Otherwise ways that coincidentally have their
1316                            // virtual node at the same spot will be joined which is likely unwanted
1317                            Pair.sort(wnp);
1318                            if (vnp == null) {
1319                                vnp = new Pair<>(wnp.a, wnp.b);
1320                                virtualNode = new Node(mv.getLatLon(pc.getX(), pc.getY()));
1321                            }
1322                            if (vnp.equals(wnp)) {
1323                                // if mutiple line segments have the same points,
1324                                // add all segments to be splitted to virtualWays list
1325                                // if some lines are selected, only their segments will go to virtualWays
1326                                (w.isSelected() ? selVirtualWays : virtualWays).add(ws);
1327                            }
1328                        }
1329                    }
1330                }
1331
1332                if (!selVirtualWays.isEmpty()) {
1333                    virtualWays = selVirtualWays;
1334                }
1335            }
1336
1337            return !virtualWays.isEmpty();
1338        }
1339
1340        private void createMiddleNodeFromVirtual(EastNorth currentEN) {
1341            if (startEN == null) // #13724, #14712, #15087
1342                return;
1343            DataSet ds = getLayerManager().getEditDataSet();
1344            Collection<Command> virtualCmds = new LinkedList<>();
1345            virtualCmds.add(new AddCommand(ds, virtualNode));
1346            for (WaySegment virtualWay : virtualWays) {
1347                Way w = virtualWay.getWay();
1348                List<Node> modNodes = w.getNodes();
1349                modNodes.add(virtualWay.getUpperIndex(), virtualNode);
1350                virtualCmds.add(new ChangeNodesCommand(ds, w, modNodes));
1351            }
1352            virtualCmds.add(new MoveCommand(ds, virtualNode, startEN, currentEN));
1353            String text = trn("Add and move a virtual new node to way",
1354                    "Add and move a virtual new node to {0} ways", virtualWays.size(),
1355                    virtualWays.size());
1356            UndoRedoHandler.getInstance().add(new SequenceCommand(text, virtualCmds));
1357            ds.setSelected(Collections.singleton((OsmPrimitive) virtualNode));
1358            clear();
1359        }
1360
1361        private void clear() {
1362            virtualWays.clear();
1363            virtualNode = null;
1364        }
1365
1366        private boolean hasVirtualNode() {
1367            return virtualNode != null;
1368        }
1369
1370        private boolean hasVirtualWaysToBeConstructed() {
1371            return !virtualWays.isEmpty();
1372        }
1373    }
1374
1375    /**
1376     * Returns {@code o} as collection of {@code o}'s type.
1377     * @param <T> object type
1378     * @param o any object
1379     * @return {@code o} as collection of {@code o}'s type.
1380     */
1381    protected static <T> Collection<T> asColl(T o) {
1382        return o == null ? Collections.emptySet() : Collections.singleton(o);
1383    }
1384}