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