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