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