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