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