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