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