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