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