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