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