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        // Do nothing
670    }
671
672    /**
673     * sets the mapmode according to key modifiers and if there are any
674     * selectables nearby. Everything has to be pre-determined for this
675     * function; its main purpose is to centralize what the modifiers do.
676     * @param hasSelectionNearby {@code true} if some primitves are selectable nearby
677     */
678    private void determineMapMode(boolean hasSelectionNearby) {
679        if (shift && ctrl) {
680            mode = Mode.ROTATE;
681        } else if (alt && ctrl) {
682            mode = Mode.SCALE;
683        } else if (hasSelectionNearby || dragInProgress()) {
684            mode = Mode.MOVE;
685        } else {
686            mode = Mode.SELECT;
687        }
688    }
689
690    /**
691     * Determines whenever elements have been grabbed and moved (i.e. the initial
692     * thresholds have been exceeded) and is still in progress (i.e. mouse button still pressed)
693     * @return true if a drag is in progress
694     */
695    private boolean dragInProgress() {
696        return didMouseDrag && startingDraggingPos != null;
697    }
698
699    /**
700     * Create or update data modification command while dragging mouse - implementation of
701     * continuous moving, scaling and rotation
702     * @param currentEN - mouse position
703     * @return status of action (<code>true</code> when action was performed)
704     */
705    private boolean updateCommandWhileDragging(EastNorth currentEN) {
706        // Currently we support only transformations which do not affect relations.
707        // So don't add them in the first place to make handling easier
708        Collection<OsmPrimitive> selection = getCurrentDataSet().getSelectedNodesAndWays();
709        if (selection.isEmpty()) { // if nothing was selected to drag, just select nearest node/way to the cursor
710            OsmPrimitive nearestPrimitive = mv.getNearestNodeOrWay(mv.getPoint(startEN), mv.isSelectablePredicate, true);
711            getCurrentDataSet().setSelected(nearestPrimitive);
712        }
713
714        Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
715        // for these transformations, having only one node makes no sense - quit silently
716        if (affectedNodes.size() < 2 && (mode == Mode.ROTATE || mode == Mode.SCALE)) {
717            return false;
718        }
719        Command c = getLastCommand();
720        if (mode == Mode.MOVE) {
721            if (startEN == null) return false; // fix #8128
722            getCurrentDataSet().beginUpdate();
723            if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
724                ((MoveCommand) c).saveCheckpoint();
725                ((MoveCommand) c).applyVectorTo(currentEN);
726            } else {
727                c = new MoveCommand(selection, startEN, currentEN);
728                Main.main.undoRedo.add(c);
729            }
730            for (Node n : affectedNodes) {
731                LatLon ll = n.getCoor();
732                if (ll != null && ll.isOutSideWorld()) {
733                    // Revert move
734                    ((MoveCommand) c).resetToCheckpoint();
735                    getCurrentDataSet().endUpdate();
736                    JOptionPane.showMessageDialog(
737                            Main.parent,
738                            tr("Cannot move objects outside of the world."),
739                            tr("Warning"),
740                            JOptionPane.WARNING_MESSAGE);
741                    mv.setNewCursor(cursor, this);
742                    return false;
743                }
744            }
745        } else {
746            startEN = currentEN; // drag can continue after scaling/rotation
747
748            if (mode != Mode.ROTATE && mode != Mode.SCALE) {
749                return false;
750            }
751
752            getCurrentDataSet().beginUpdate();
753
754            if (mode == Mode.ROTATE) {
755                if (c instanceof RotateCommand && affectedNodes.equals(((RotateCommand) c).getTransformedNodes())) {
756                    ((RotateCommand) c).handleEvent(currentEN);
757                } else {
758                    Main.main.undoRedo.add(new RotateCommand(selection, currentEN));
759                }
760            } else if (mode == Mode.SCALE) {
761                if (c instanceof ScaleCommand && affectedNodes.equals(((ScaleCommand) c).getTransformedNodes())) {
762                    ((ScaleCommand) c).handleEvent(currentEN);
763                } else {
764                    Main.main.undoRedo.add(new ScaleCommand(selection, currentEN));
765                }
766            }
767
768            Collection<Way> ways = getCurrentDataSet().getSelectedWays();
769            if (doesImpactStatusLine(affectedNodes, ways)) {
770                Main.map.statusLine.setDist(ways);
771            }
772        }
773        getCurrentDataSet().endUpdate();
774        return true;
775    }
776
777    private static boolean doesImpactStatusLine(Collection<Node> affectedNodes, Collection<Way> selectedWays) {
778        for (Way w : selectedWays) {
779            for (Node n : w.getNodes()) {
780                if (affectedNodes.contains(n)) {
781                    return true;
782                }
783            }
784        }
785        return false;
786    }
787
788    /**
789     * Adapt last move command (if it is suitable) to work with next drag, started at point startEN
790     */
791    private void useLastMoveCommandIfPossible() {
792        Command c = getLastCommand();
793        Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(getCurrentDataSet().getSelected());
794        if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
795            // old command was created with different base point of movement, we need to recalculate it
796            ((MoveCommand) c).changeStartPoint(startEN);
797        }
798    }
799
800    /**
801     * Obtain command in undoRedo stack to "continue" when dragging
802     * @return last command
803     */
804    private static Command getLastCommand() {
805        Command c = !Main.main.undoRedo.commands.isEmpty()
806                ? Main.main.undoRedo.commands.getLast() : null;
807        if (c instanceof SequenceCommand) {
808            c = ((SequenceCommand) c).getLastCommand();
809        }
810        return c;
811    }
812
813    /**
814     * Present warning in the following cases and undo unwanted movements: <ul>
815     * <li>large and possibly unwanted movements</li>
816     * <li>movement of node with attached ways that are hidden by filters</li>
817     * </ul>
818     *
819     * @param e the mouse event causing the action (mouse released)
820     */
821    private void confirmOrUndoMovement(MouseEvent e) {
822        if (movesHiddenWay()) {
823            final ExtendedDialog ed = new ConfirmMoveDialog();
824            ed.setContent(tr("Are you sure that you want to move elements with attached ways that are hidden by filters?"));
825            ed.toggleEnable("movedHiddenElements");
826            ed.showDialog();
827            if (ed.getValue() != 1) {
828                Main.main.undoRedo.undo();
829            }
830        }
831        int max = Main.pref.getInteger("warn.move.maxelements", 20), limit = max;
832        for (OsmPrimitive osm : getCurrentDataSet().getSelected()) {
833            if (osm instanceof Way) {
834                limit -= ((Way) osm).getNodes().size();
835            }
836            if (--limit < 0) {
837                break;
838            }
839        }
840        if (limit < 0) {
841            final ExtendedDialog ed = new ConfirmMoveDialog();
842            ed.setContent(
843                    /* for correct i18n of plural forms - see #9110 */
844                    trn("You moved more than {0} element. " + "Moving a large number of elements is often an error.\n" + "Really move them?",
845                        "You moved more than {0} elements. " + "Moving a large number of elements is often an error.\n" + "Really move them?",
846                        max, max));
847            ed.toggleEnable("movedManyElements");
848            ed.showDialog();
849
850            if (ed.getValue() != 1) {
851                Main.main.undoRedo.undo();
852            }
853        } else {
854            // if small number of elements were moved,
855            updateKeyModifiers(e);
856            if (ctrl) mergePrims(e.getPoint());
857        }
858        getCurrentDataSet().fireSelectionChanged();
859    }
860
861    static class ConfirmMoveDialog extends ExtendedDialog {
862        ConfirmMoveDialog() {
863            super(Main.parent,
864                    tr("Move elements"),
865                    new String[]{tr("Move them"), tr("Undo move")});
866            setButtonIcons(new String[]{"reorder", "cancel"});
867            setCancelButton(2);
868        }
869    }
870
871    private static boolean movesHiddenWay() {
872        final Collection<OsmPrimitive> elementsToTest = new HashSet<>(getCurrentDataSet().getSelected());
873        for (Way osm : Utils.filteredCollection(getCurrentDataSet().getSelected(), Way.class)) {
874            elementsToTest.addAll(osm.getNodes());
875        }
876        for (OsmPrimitive node : Utils.filteredCollection(elementsToTest, Node.class)) {
877            for (Way ref : Utils.filteredCollection(node.getReferrers(), Way.class)) {
878                if (ref.isDisabledAndHidden()) {
879                    return true;
880                }
881            }
882        }
883        return false;
884    }
885
886    /**
887     * Merges the selected nodes to the one closest to the given mouse position if the control
888     * key is pressed. If there is no such node, no action will be done and no error will be
889     * reported. If there is, it will execute the merge and add it to the undo buffer.
890     * @param p mouse position
891     */
892    private void mergePrims(Point p) {
893        Collection<Node> selNodes = getCurrentDataSet().getSelectedNodes();
894        if (selNodes.isEmpty())
895            return;
896
897        Node target = findNodeToMergeTo(p);
898        if (target == null)
899            return;
900
901        if (selNodes.size() == 1) {
902            // Move all selected primitive to preserve shape #10748
903            Collection<OsmPrimitive> selection =
904                getCurrentDataSet().getSelectedNodesAndWays();
905            Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
906            Command c = getLastCommand();
907            getCurrentDataSet().beginUpdate();
908            if (c instanceof MoveCommand
909                && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
910                Node selectedNode = selNodes.iterator().next();
911                EastNorth selectedEN = selectedNode.getEastNorth();
912                EastNorth targetEN = target.getEastNorth();
913                ((MoveCommand) c).moveAgain(targetEN.getX() - selectedEN.getX(),
914                                            targetEN.getY() - selectedEN.getY());
915            }
916            getCurrentDataSet().endUpdate();
917        }
918
919        Collection<Node> nodesToMerge = new LinkedList<>(selNodes);
920        nodesToMerge.add(target);
921        mergeNodes(Main.main.getEditLayer(), nodesToMerge, target);
922    }
923
924    /**
925     * Merge nodes using {@code MergeNodesAction}.
926     * Can be overridden for testing purpose.
927     * @param layer layer the reference data layer. Must not be null
928     * @param nodes the collection of nodes. Ignored if null
929     * @param targetLocationNode this node's location will be used for the target node
930     */
931    public void mergeNodes(OsmDataLayer layer, Collection<Node> nodes,
932                           Node targetLocationNode) {
933        MergeNodesAction.doMergeNodes(layer, nodes, targetLocationNode);
934    }
935
936    /**
937     * Tries to find a node to merge to when in move-merge mode for the current mouse
938     * position. Either returns the node or null, if no suitable one is nearby.
939     * @param p mouse position
940     * @return node to merge to, or null
941     */
942    private Node findNodeToMergeTo(Point p) {
943        Collection<Node> target = mv.getNearestNodes(p,
944                getCurrentDataSet().getSelectedNodes(),
945                mv.isSelectablePredicate);
946        return target.isEmpty() ? null : target.iterator().next();
947    }
948
949    private void selectPrims(Collection<OsmPrimitive> prims, boolean released, boolean area) {
950        DataSet ds = getCurrentDataSet();
951
952        // not allowed together: do not change dataset selection, return early
953        // Virtual Ways: if non-empty the cursor is above a virtual node. So don't highlight
954        // anything if about to drag the virtual node (i.e. !released) but continue if the
955        // cursor is only released above a virtual node by accident (i.e. released). See #7018
956        if (ds == null || (shift && ctrl) || (ctrl && !released) || (virtualManager.hasVirtualWaysToBeConstructed() && !released))
957            return;
958
959        if (!released) {
960            // Don't replace the selection if the user clicked on a
961            // selected object (it breaks moving of selected groups).
962            // Do it later, on mouse release.
963            shift |= ds.getSelected().containsAll(prims);
964        }
965
966        if (ctrl) {
967            // Ctrl on an item toggles its selection status,
968            // but Ctrl on an *area* just clears those items
969            // out of the selection.
970            if (area) {
971                ds.clearSelection(prims);
972            } else {
973                ds.toggleSelected(prims);
974            }
975        } else if (shift) {
976            // add prims to an existing selection
977            ds.addSelected(prims);
978        } else {
979            // clear selection, then select the prims clicked
980            ds.setSelected(prims);
981        }
982    }
983
984    /**
985     * Returns the current select mode.
986     * @return the select mode
987     * @since 7543
988     */
989    public final Mode getMode() {
990        return mode;
991    }
992
993    @Override
994    public String getModeHelpText() {
995        if (mouseDownButton == MouseEvent.BUTTON1 && mouseReleaseTime < mouseDownTime) {
996            if (mode == Mode.SELECT)
997                return tr("Release the mouse button to select the objects in the rectangle.");
998            else if (mode == Mode.MOVE && (System.currentTimeMillis() - mouseDownTime >= initialMoveDelay)) {
999                final boolean canMerge = getCurrentDataSet() != null && !getCurrentDataSet().getSelectedNodes().isEmpty();
1000                final String mergeHelp = canMerge ? ' ' + tr("Ctrl to merge with nearest node.") : "";
1001                return tr("Release the mouse button to stop moving.") + mergeHelp;
1002            } else if (mode == Mode.ROTATE)
1003                return tr("Release the mouse button to stop rotating.");
1004            else if (mode == Mode.SCALE)
1005                return tr("Release the mouse button to stop scaling.");
1006        }
1007        return tr("Move objects by dragging; Shift to add to selection (Ctrl to toggle); Shift-Ctrl to rotate selected; " +
1008                  "Alt-Ctrl to scale selected; or change selection");
1009    }
1010
1011    @Override
1012    public boolean layerIsSupported(Layer l) {
1013        return l instanceof OsmDataLayer;
1014    }
1015
1016    /**
1017     * Enable or diable the lasso mode
1018     * @param lassoMode true to enable the lasso mode, false otherwise
1019     */
1020    public void setLassoMode(boolean lassoMode) {
1021        this.selectionManager.setLassoMode(lassoMode);
1022        this.lassoMode = lassoMode;
1023    }
1024
1025    private final transient CycleManager cycleManager = new CycleManager();
1026    private final transient VirtualManager virtualManager = new VirtualManager();
1027
1028    private class CycleManager {
1029
1030        private Collection<OsmPrimitive> cycleList = Collections.emptyList();
1031        private boolean cyclePrims;
1032        private OsmPrimitive cycleStart;
1033        private boolean waitForMouseUpParameter;
1034        private boolean multipleMatchesParameter;
1035        /**
1036         * read preferences
1037         */
1038        private void init() {
1039            waitForMouseUpParameter = Main.pref.getBoolean("mappaint.select.waits-for-mouse-up", false);
1040            multipleMatchesParameter = Main.pref.getBoolean("selectaction.cycles.multiple.matches", false);
1041        }
1042
1043        /**
1044         * Determine primitive to be selected and build cycleList
1045         * @param nearest primitive found by simple method
1046         * @param p point where user clicked
1047         * @return OsmPrimitive to be selected
1048         */
1049        private OsmPrimitive cycleSetup(OsmPrimitive nearest, Point p) {
1050            OsmPrimitive osm = null;
1051
1052            if (nearest != null) {
1053                osm = nearest;
1054
1055                if (!(alt || multipleMatchesParameter)) {
1056                    // no real cycling, just one element in cycle list
1057                    cycleList = asColl(osm);
1058
1059                    if (waitForMouseUpParameter) {
1060                        // prefer a selected nearest node or way, if possible
1061                        osm = mv.getNearestNodeOrWay(p, mv.isSelectablePredicate, true);
1062                    }
1063                } else {
1064                    // Alt + left mouse button pressed: we need to build cycle list
1065                    cycleList = mv.getAllNearest(p, mv.isSelectablePredicate);
1066
1067                    if (cycleList.size() > 1) {
1068                        cyclePrims = false;
1069
1070                        // find first already selected element in cycle list
1071                        OsmPrimitive old = osm;
1072                        for (OsmPrimitive o : cycleList) {
1073                            if (o.isSelected()) {
1074                                cyclePrims = true;
1075                                osm = o;
1076                                break;
1077                            }
1078                        }
1079
1080                        // special case:  for cycle groups of 2, we can toggle to the
1081                        // true nearest primitive on mousePressed right away
1082                        if (cycleList.size() == 2 && !waitForMouseUpParameter) {
1083                            if (!(osm.equals(old) || osm.isNew() || ctrl)) {
1084                                cyclePrims = false;
1085                                osm = old;
1086                            } // else defer toggling to mouseRelease time in those cases:
1087                            /*
1088                             * osm == old -- the true nearest node is the
1089                             * selected one osm is a new node -- do not break
1090                             * unglue ways in ALT mode ctrl is pressed -- ctrl
1091                             * generally works on mouseReleased
1092                             */
1093                        }
1094                    }
1095                }
1096            }
1097            return osm;
1098        }
1099
1100        /**
1101         * Modifies current selection state and returns the next element in a
1102         * selection cycle given by
1103         * <code>cycleList</code> field
1104         * @return the next element of cycle list
1105         */
1106        private Collection<OsmPrimitive> cyclePrims() {
1107            if (cycleList.size() <= 1) {
1108                // no real cycling, just return one-element collection with nearest primitive in it
1109                return cycleList;
1110            }
1111            // updateKeyModifiers() already called before!
1112
1113            DataSet ds = getCurrentDataSet();
1114            OsmPrimitive first = cycleList.iterator().next(), foundInDS = null;
1115            OsmPrimitive nxt = first;
1116
1117            if (cyclePrims && shift) {
1118                for (Iterator<OsmPrimitive> i = cycleList.iterator(); i.hasNext();) {
1119                    nxt = i.next();
1120                    if (!nxt.isSelected()) {
1121                        break; // take first primitive in cycleList not in sel
1122                    }
1123                }
1124                // if primitives 1,2,3 are under cursor, [Alt-press] [Shift-release] gives 1 -> 12 -> 123
1125            } else {
1126                for (Iterator<OsmPrimitive> i = cycleList.iterator(); i.hasNext();) {
1127                    nxt = i.next();
1128                    if (nxt.isSelected()) {
1129                        foundInDS = nxt;
1130                        // first selected primitive in cycleList is found
1131                        if (cyclePrims || ctrl) {
1132                            ds.clearSelection(foundInDS); // deselect it
1133                            nxt = i.hasNext() ? i.next() : first;
1134                            // return next one in cycle list (last->first)
1135                        }
1136                        break; // take next primitive in cycleList
1137                    }
1138                }
1139            }
1140
1141            // if "no-alt-cycling" is enabled, Ctrl-Click arrives here.
1142            if (ctrl) {
1143                // a member of cycleList was found in the current dataset selection
1144                if (foundInDS != null) {
1145                    // mouse was moved to a different selection group w/ a previous sel
1146                    if (!cycleList.contains(cycleStart)) {
1147                        ds.clearSelection(cycleList);
1148                        cycleStart = foundInDS;
1149                    } else if (cycleStart.equals(nxt)) {
1150                        // loop detected, insert deselect step
1151                        ds.addSelected(nxt);
1152                    }
1153                } else {
1154                    // setup for iterating a sel group again or a new, different one..
1155                    nxt = cycleList.contains(cycleStart) ? cycleStart : first;
1156                    cycleStart = nxt;
1157                }
1158            } else {
1159                cycleStart = null;
1160            }
1161            // return one-element collection with one element to be selected (or added  to selection)
1162            return asColl(nxt);
1163        }
1164    }
1165
1166    private class VirtualManager {
1167
1168        private Node virtualNode;
1169        private Collection<WaySegment> virtualWays = new LinkedList<>();
1170        private int nodeVirtualSize;
1171        private int virtualSnapDistSq2;
1172        private int virtualSpace;
1173
1174        private void init() {
1175            nodeVirtualSize = Main.pref.getInteger("mappaint.node.virtual-size", 8);
1176            int virtualSnapDistSq = Main.pref.getInteger("mappaint.node.virtual-snap-distance", 8);
1177            virtualSnapDistSq2 = virtualSnapDistSq*virtualSnapDistSq;
1178            virtualSpace = Main.pref.getInteger("mappaint.node.virtual-space", 70);
1179        }
1180
1181        /**
1182         * Calculate a virtual node if there is enough visual space to draw a
1183         * crosshair node and the middle of a way segment is clicked. If the
1184         * user drags the crosshair node, it will be added to all ways in
1185         * <code>virtualWays</code>.
1186         *
1187         * @param p the point clicked
1188         * @return whether
1189         * <code>virtualNode</code> and
1190         * <code>virtualWays</code> were setup.
1191         */
1192        private boolean activateVirtualNodeNearPoint(Point p) {
1193            if (nodeVirtualSize > 0) {
1194
1195                Collection<WaySegment> selVirtualWays = new LinkedList<>();
1196                Pair<Node, Node> vnp = null, wnp = new Pair<>(null, null);
1197
1198                for (WaySegment ws : mv.getNearestWaySegments(p, mv.isSelectablePredicate)) {
1199                    Way w = ws.way;
1200
1201                    wnp.a = w.getNode(ws.lowerIndex);
1202                    wnp.b = w.getNode(ws.lowerIndex + 1);
1203                    Point2D p1 = mv.getPoint2D(wnp.a);
1204                    Point2D p2 = mv.getPoint2D(wnp.b);
1205                    if (WireframeMapRenderer.isLargeSegment(p1, p2, virtualSpace)) {
1206                        Point2D pc = new Point2D.Double((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2);
1207                        if (p.distanceSq(pc) < virtualSnapDistSq2) {
1208                            // Check that only segments on top of each other get added to the
1209                            // virtual ways list. Otherwise ways that coincidentally have their
1210                            // virtual node at the same spot will be joined which is likely unwanted
1211                            Pair.sort(wnp);
1212                            if (vnp == null) {
1213                                vnp = new Pair<>(wnp.a, wnp.b);
1214                                virtualNode = new Node(mv.getLatLon(pc.getX(), pc.getY()));
1215                            }
1216                            if (vnp.equals(wnp)) {
1217                                // if mutiple line segments have the same points,
1218                                // add all segments to be splitted to virtualWays list
1219                                // if some lines are selected, only their segments will go to virtualWays
1220                                (w.isSelected() ? selVirtualWays : virtualWays).add(ws);
1221                            }
1222                        }
1223                    }
1224                }
1225
1226                if (!selVirtualWays.isEmpty()) {
1227                    virtualWays = selVirtualWays;
1228                }
1229            }
1230
1231            return !virtualWays.isEmpty();
1232        }
1233
1234        private void createMiddleNodeFromVirtual(EastNorth currentEN) {
1235            Collection<Command> virtualCmds = new LinkedList<>();
1236            virtualCmds.add(new AddCommand(virtualNode));
1237            for (WaySegment virtualWay : virtualWays) {
1238                Way w = virtualWay.way;
1239                Way wnew = new Way(w);
1240                wnew.addNode(virtualWay.lowerIndex + 1, virtualNode);
1241                virtualCmds.add(new ChangeCommand(w, wnew));
1242            }
1243            virtualCmds.add(new MoveCommand(virtualNode, startEN, currentEN));
1244            String text = trn("Add and move a virtual new node to way",
1245                    "Add and move a virtual new node to {0} ways", virtualWays.size(),
1246                    virtualWays.size());
1247            Main.main.undoRedo.add(new SequenceCommand(text, virtualCmds));
1248            getCurrentDataSet().setSelected(Collections.singleton((OsmPrimitive) virtualNode));
1249            clear();
1250        }
1251
1252        private void clear() {
1253            virtualWays.clear();
1254            virtualNode = null;
1255        }
1256
1257        private boolean hasVirtualNode() {
1258            return virtualNode != null;
1259        }
1260
1261        private boolean hasVirtualWaysToBeConstructed() {
1262            return !virtualWays.isEmpty();
1263        }
1264    }
1265
1266    /**
1267     * Returns {@code o} as collection of {@code o}'s type.
1268     * @param <T> object type
1269     * @param o any object
1270     * @return {@code o} as collection of {@code o}'s type.
1271     */
1272    protected static <T> Collection<T> asColl(T o) {
1273        if (o == null)
1274            return Collections.emptySet();
1275        return Collections.singleton(o);
1276    }
1277}