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.marktr; 006import static org.openstreetmap.josm.tools.I18n.tr; 007import static org.openstreetmap.josm.tools.I18n.trn; 008 009import java.awt.BasicStroke; 010import java.awt.Color; 011import java.awt.Cursor; 012import java.awt.Graphics2D; 013import java.awt.Point; 014import java.awt.event.ActionEvent; 015import java.awt.event.KeyEvent; 016import java.awt.event.MouseEvent; 017import java.awt.event.MouseListener; 018import java.util.ArrayList; 019import java.util.Arrays; 020import java.util.Collection; 021import java.util.Collections; 022import java.util.Comparator; 023import java.util.HashMap; 024import java.util.HashSet; 025import java.util.Iterator; 026import java.util.LinkedList; 027import java.util.List; 028import java.util.Map; 029import java.util.Set; 030import java.util.stream.DoubleStream; 031 032import javax.swing.AbstractAction; 033import javax.swing.JCheckBoxMenuItem; 034import javax.swing.JMenuItem; 035import javax.swing.JOptionPane; 036import javax.swing.JPopupMenu; 037 038import org.openstreetmap.josm.Main; 039import org.openstreetmap.josm.actions.JosmAction; 040import org.openstreetmap.josm.command.AddCommand; 041import org.openstreetmap.josm.command.ChangeCommand; 042import org.openstreetmap.josm.command.Command; 043import org.openstreetmap.josm.command.SequenceCommand; 044import org.openstreetmap.josm.data.Bounds; 045import org.openstreetmap.josm.data.SelectionChangedListener; 046import org.openstreetmap.josm.data.coor.EastNorth; 047import org.openstreetmap.josm.data.coor.LatLon; 048import org.openstreetmap.josm.data.osm.DataSet; 049import org.openstreetmap.josm.data.osm.Node; 050import org.openstreetmap.josm.data.osm.OsmPrimitive; 051import org.openstreetmap.josm.data.osm.Way; 052import org.openstreetmap.josm.data.osm.WaySegment; 053import org.openstreetmap.josm.data.osm.visitor.paint.ArrowPaintHelper; 054import org.openstreetmap.josm.data.osm.visitor.paint.PaintColors; 055import org.openstreetmap.josm.data.preferences.AbstractToStringProperty; 056import org.openstreetmap.josm.data.preferences.BooleanProperty; 057import org.openstreetmap.josm.data.preferences.CachingProperty; 058import org.openstreetmap.josm.data.preferences.ColorProperty; 059import org.openstreetmap.josm.data.preferences.DoubleProperty; 060import org.openstreetmap.josm.data.preferences.StrokeProperty; 061import org.openstreetmap.josm.gui.MainMenu; 062import org.openstreetmap.josm.gui.MapFrame; 063import org.openstreetmap.josm.gui.MapView; 064import org.openstreetmap.josm.gui.MapViewState; 065import org.openstreetmap.josm.gui.MapViewState.MapViewPoint; 066import org.openstreetmap.josm.gui.NavigatableComponent; 067import org.openstreetmap.josm.gui.draw.MapPath2D; 068import org.openstreetmap.josm.gui.draw.MapViewPath; 069import org.openstreetmap.josm.gui.draw.SymbolShape; 070import org.openstreetmap.josm.gui.layer.Layer; 071import org.openstreetmap.josm.gui.layer.MapViewPaintable; 072import org.openstreetmap.josm.gui.layer.OsmDataLayer; 073import org.openstreetmap.josm.gui.util.KeyPressReleaseListener; 074import org.openstreetmap.josm.gui.util.ModifierListener; 075import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher; 076import org.openstreetmap.josm.tools.Geometry; 077import org.openstreetmap.josm.tools.ImageProvider; 078import org.openstreetmap.josm.tools.Pair; 079import org.openstreetmap.josm.tools.Shortcut; 080import org.openstreetmap.josm.tools.Utils; 081 082/** 083 * Mapmode to add nodes, create and extend ways. 084 */ 085public class DrawAction extends MapMode implements MapViewPaintable, SelectionChangedListener, KeyPressReleaseListener, ModifierListener { 086 087 private static final Color ORANGE_TRANSPARENT = new Color(Color.ORANGE.getRed(), Color.ORANGE.getGreen(), Color.ORANGE.getBlue(), 128); 088 089 private static final ArrowPaintHelper START_WAY_INDICATOR = new ArrowPaintHelper(Math.toRadians(90), 8); 090 091 private static final CachingProperty<Boolean> USE_REPEATED_SHORTCUT 092 = new BooleanProperty("draw.anglesnap.toggleOnRepeatedA", true).cached(); 093 private static final CachingProperty<BasicStroke> RUBBER_LINE_STROKE 094 = new StrokeProperty("draw.stroke.helper-line", "3").cached(); 095 096 private static final CachingProperty<BasicStroke> HIGHLIGHT_STROKE 097 = new StrokeProperty("draw.anglesnap.stroke.highlight", "10").cached(); 098 private static final CachingProperty<BasicStroke> HELPER_STROKE 099 = new StrokeProperty("draw.anglesnap.stroke.helper", "1 4").cached(); 100 101 private static final CachingProperty<Double> SNAP_ANGLE_TOLERANCE 102 = new DoubleProperty("draw.anglesnap.tolerance", 5.0).cached(); 103 private static final CachingProperty<Boolean> DRAW_CONSTRUCTION_GEOMETRY 104 = new BooleanProperty("draw.anglesnap.drawConstructionGeometry", true).cached(); 105 private static final CachingProperty<Boolean> SHOW_PROJECTED_POINT 106 = new BooleanProperty("draw.anglesnap.drawProjectedPoint", true).cached(); 107 private static final CachingProperty<Boolean> SNAP_TO_PROJECTIONS 108 = new BooleanProperty("draw.anglesnap.projectionsnap", true).cached(); 109 110 private static final CachingProperty<Boolean> SHOW_ANGLE 111 = new BooleanProperty("draw.anglesnap.showAngle", true).cached(); 112 113 private static final CachingProperty<Color> SNAP_HELPER_COLOR 114 = new ColorProperty(marktr("draw angle snap"), Color.ORANGE).cached(); 115 116 private static final CachingProperty<Color> HIGHLIGHT_COLOR 117 = new ColorProperty(marktr("draw angle snap highlight"), ORANGE_TRANSPARENT).cached(); 118 119 private static final AbstractToStringProperty<Color> RUBBER_LINE_COLOR 120 = PaintColors.SELECTED.getProperty().getChildColor(marktr("helper line")); 121 122 private static final CachingProperty<Boolean> DRAW_HELPER_LINE 123 = new BooleanProperty("draw.helper-line", true).cached(); 124 private static final CachingProperty<Boolean> DRAW_TARGET_HIGHLIGHT 125 = new BooleanProperty("draw.target-highlight", true).cached(); 126 private static final CachingProperty<Double> SNAP_TO_INTERSECTION_THRESHOLD 127 = new DoubleProperty("edit.snap-intersection-threshold", 10).cached(); 128 129 private final Cursor cursorJoinNode; 130 private final Cursor cursorJoinWay; 131 132 private transient Node lastUsedNode; 133 private double toleranceMultiplier; 134 135 private transient Node mouseOnExistingNode; 136 private transient Set<Way> mouseOnExistingWays = new HashSet<>(); 137 // old highlights store which primitives are currently highlighted. This 138 // is true, even if target highlighting is disabled since the status bar 139 // derives its information from this list as well. 140 private transient Set<OsmPrimitive> oldHighlights = new HashSet<>(); 141 // new highlights contains a list of primitives that should be highlighted 142 // but haven't been so far. The idea is to compare old and new and only 143 // repaint if there are changes. 144 private transient Set<OsmPrimitive> newHighlights = new HashSet<>(); 145 private boolean wayIsFinished; 146 private Point mousePos; 147 private Point oldMousePos; 148 149 private transient Node currentBaseNode; 150 private transient Node previousNode; 151 private EastNorth currentMouseEastNorth; 152 153 private final transient SnapHelper snapHelper = new SnapHelper(); 154 155 private final transient Shortcut backspaceShortcut; 156 private final BackSpaceAction backspaceAction; 157 private final transient Shortcut snappingShortcut; 158 private boolean ignoreNextKeyRelease; 159 160 private final SnapChangeAction snapChangeAction; 161 private final JCheckBoxMenuItem snapCheckboxMenuItem; 162 private static final BasicStroke BASIC_STROKE = new BasicStroke(1); 163 164 private Point rightClickPressPos; 165 166 /** 167 * Constructs a new {@code DrawAction}. 168 * @param mapFrame Map frame 169 */ 170 public DrawAction(MapFrame mapFrame) { 171 super(tr("Draw"), "node/autonode", tr("Draw nodes"), 172 Shortcut.registerShortcut("mapmode:draw", tr("Mode: {0}", tr("Draw")), KeyEvent.VK_A, Shortcut.DIRECT), 173 mapFrame, ImageProvider.getCursor("crosshair", null)); 174 175 snappingShortcut = Shortcut.registerShortcut("mapmode:drawanglesnapping", 176 tr("Mode: Draw Angle snapping"), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE); 177 snapChangeAction = new SnapChangeAction(); 178 snapCheckboxMenuItem = addMenuItem(); 179 snapHelper.setMenuCheckBox(snapCheckboxMenuItem); 180 backspaceShortcut = Shortcut.registerShortcut("mapmode:backspace", 181 tr("Backspace in Add mode"), KeyEvent.VK_BACK_SPACE, Shortcut.DIRECT); 182 backspaceAction = new BackSpaceAction(); 183 cursorJoinNode = ImageProvider.getCursor("crosshair", "joinnode"); 184 cursorJoinWay = ImageProvider.getCursor("crosshair", "joinway"); 185 186 snapHelper.init(); 187 } 188 189 private JCheckBoxMenuItem addMenuItem() { 190 int n = Main.main.menu.editMenu.getItemCount(); 191 for (int i = n-1; i > 0; i--) { 192 JMenuItem item = Main.main.menu.editMenu.getItem(i); 193 if (item != null && item.getAction() != null && item.getAction() instanceof SnapChangeAction) { 194 Main.main.menu.editMenu.remove(i); 195 } 196 } 197 return MainMenu.addWithCheckbox(Main.main.menu.editMenu, snapChangeAction, MainMenu.WINDOW_MENU_GROUP.VOLATILE); 198 } 199 200 /** 201 * Checks if a map redraw is required and does so if needed. Also updates the status bar. 202 * @return true if a repaint is needed 203 */ 204 private boolean redrawIfRequired() { 205 updateStatusLine(); 206 // repaint required if the helper line is active. 207 boolean needsRepaint = DRAW_HELPER_LINE.get() && !wayIsFinished; 208 if (DRAW_TARGET_HIGHLIGHT.get()) { 209 // move newHighlights to oldHighlights; only update changed primitives 210 for (OsmPrimitive x : newHighlights) { 211 if (oldHighlights.contains(x)) { 212 continue; 213 } 214 x.setHighlighted(true); 215 needsRepaint = true; 216 } 217 oldHighlights.removeAll(newHighlights); 218 for (OsmPrimitive x : oldHighlights) { 219 x.setHighlighted(false); 220 needsRepaint = true; 221 } 222 } 223 // required in order to print correct help text 224 oldHighlights = newHighlights; 225 226 if (!needsRepaint && !DRAW_TARGET_HIGHLIGHT.get()) 227 return false; 228 229 // update selection to reflect which way being modified 230 OsmDataLayer editLayer = getLayerManager().getEditLayer(); 231 if (getCurrentBaseNode() != null && editLayer != null && !editLayer.data.selectionEmpty()) { 232 DataSet currentDataSet = editLayer.data; 233 Way continueFrom = getWayForNode(getCurrentBaseNode()); 234 if (alt && continueFrom != null && (!getCurrentBaseNode().isSelected() || continueFrom.isSelected())) { 235 addRemoveSelection(currentDataSet, getCurrentBaseNode(), continueFrom); 236 needsRepaint = true; 237 } else if (!alt && continueFrom != null && !continueFrom.isSelected()) { 238 currentDataSet.addSelected(continueFrom); 239 needsRepaint = true; 240 } 241 } 242 243 if (needsRepaint && editLayer != null) { 244 editLayer.invalidate(); 245 } 246 return needsRepaint; 247 } 248 249 private static void addRemoveSelection(DataSet ds, OsmPrimitive toAdd, OsmPrimitive toRemove) { 250 ds.beginUpdate(); // to prevent the selection listener to screw around with the state 251 ds.addSelected(toAdd); 252 ds.clearSelection(toRemove); 253 ds.endUpdate(); 254 } 255 256 @Override 257 public void enterMode() { 258 if (!isEnabled()) 259 return; 260 super.enterMode(); 261 readPreferences(); 262 263 // determine if selection is suitable to continue drawing. If it 264 // isn't, set wayIsFinished to true to avoid superfluous repaints. 265 determineCurrentBaseNodeAndPreviousNode(getLayerManager().getEditDataSet().getSelected()); 266 wayIsFinished = getCurrentBaseNode() == null; 267 268 toleranceMultiplier = 0.01 * NavigatableComponent.PROP_SNAP_DISTANCE.get(); 269 270 snapHelper.init(); 271 snapCheckboxMenuItem.getAction().setEnabled(true); 272 273 Main.map.statusLine.getAnglePanel().addMouseListener(snapHelper.anglePopupListener); 274 Main.registerActionShortcut(backspaceAction, backspaceShortcut); 275 276 Main.map.mapView.addMouseListener(this); 277 Main.map.mapView.addMouseMotionListener(this); 278 Main.map.mapView.addTemporaryLayer(this); 279 DataSet.addSelectionListener(this); 280 281 Main.map.keyDetector.addKeyListener(this); 282 Main.map.keyDetector.addModifierListener(this); 283 ignoreNextKeyRelease = true; 284 } 285 286 @Override 287 public void exitMode() { 288 super.exitMode(); 289 Main.map.mapView.removeMouseListener(this); 290 Main.map.mapView.removeMouseMotionListener(this); 291 Main.map.mapView.removeTemporaryLayer(this); 292 DataSet.removeSelectionListener(this); 293 Main.unregisterActionShortcut(backspaceAction, backspaceShortcut); 294 snapHelper.unsetFixedMode(); 295 snapCheckboxMenuItem.getAction().setEnabled(false); 296 297 Main.map.statusLine.getAnglePanel().removeMouseListener(snapHelper.anglePopupListener); 298 Main.map.statusLine.activateAnglePanel(false); 299 300 removeHighlighting(); 301 Main.map.keyDetector.removeKeyListener(this); 302 Main.map.keyDetector.removeModifierListener(this); 303 304 // when exiting we let everybody know about the currently selected 305 // primitives 306 // 307 DataSet ds = getLayerManager().getEditDataSet(); 308 if (ds != null) { 309 ds.fireSelectionChanged(); 310 } 311 } 312 313 /** 314 * redraw to (possibly) get rid of helper line if selection changes. 315 */ 316 @Override 317 public void modifiersChanged(int modifiers) { 318 if (!Main.isDisplayingMapView() || !Main.map.mapView.isActiveLayerDrawable()) 319 return; 320 updateKeyModifiers(modifiers); 321 computeHelperLine(); 322 addHighlighting(); 323 } 324 325 @Override 326 public void doKeyPressed(KeyEvent e) { 327 if (!snappingShortcut.isEvent(e) && !(USE_REPEATED_SHORTCUT.get() && getShortcut().isEvent(e))) 328 return; 329 snapHelper.setFixedMode(); 330 computeHelperLine(); 331 redrawIfRequired(); 332 } 333 334 @Override 335 public void doKeyReleased(KeyEvent e) { 336 if (!snappingShortcut.isEvent(e) && !(USE_REPEATED_SHORTCUT.get() && getShortcut().isEvent(e))) 337 return; 338 if (ignoreNextKeyRelease) { 339 ignoreNextKeyRelease = false; 340 return; 341 } 342 snapHelper.unFixOrTurnOff(); 343 computeHelperLine(); 344 redrawIfRequired(); 345 } 346 347 /** 348 * redraw to (possibly) get rid of helper line if selection changes. 349 */ 350 @Override 351 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) { 352 if (!Main.map.mapView.isActiveLayerDrawable()) 353 return; 354 computeHelperLine(); 355 addHighlighting(); 356 } 357 358 private void tryAgain(MouseEvent e) { 359 getLayerManager().getEditDataSet().setSelected(); 360 mouseReleased(e); 361 } 362 363 /** 364 * This function should be called when the user wishes to finish his current draw action. 365 * If Potlatch Style is enabled, it will switch to select tool, otherwise simply disable 366 * the helper line until the user chooses to draw something else. 367 */ 368 private void finishDrawing() { 369 // let everybody else know about the current selection 370 // 371 Main.getLayerManager().getEditDataSet().fireSelectionChanged(); 372 lastUsedNode = null; 373 wayIsFinished = true; 374 Main.map.selectSelectTool(true); 375 snapHelper.noSnapNow(); 376 377 // Redraw to remove the helper line stub 378 computeHelperLine(); 379 removeHighlighting(); 380 } 381 382 @Override 383 public void mousePressed(MouseEvent e) { 384 if (e.getButton() == MouseEvent.BUTTON3) { 385 rightClickPressPos = e.getPoint(); 386 } 387 } 388 389 /** 390 * If user clicked with the left button, add a node at the current mouse 391 * position. 392 * 393 * If in nodeway mode, insert the node into the way. 394 */ 395 @Override 396 public void mouseReleased(MouseEvent e) { 397 if (e.getButton() == MouseEvent.BUTTON3) { 398 Point curMousePos = e.getPoint(); 399 if (curMousePos.equals(rightClickPressPos)) { 400 tryToSetBaseSegmentForAngleSnap(); 401 } 402 return; 403 } 404 if (e.getButton() != MouseEvent.BUTTON1) 405 return; 406 if (!Main.map.mapView.isActiveLayerDrawable()) 407 return; 408 // request focus in order to enable the expected keyboard shortcuts 409 // 410 Main.map.mapView.requestFocus(); 411 412 if (e.getClickCount() > 1 && mousePos != null && mousePos.equals(oldMousePos)) { 413 // A double click equals "user clicked last node again, finish way" 414 // Change draw tool only if mouse position is nearly the same, as 415 // otherwise fast clicks will count as a double click 416 finishDrawing(); 417 return; 418 } 419 oldMousePos = mousePos; 420 421 // we copy ctrl/alt/shift from the event just in case our global 422 // keyDetector didn't make it through the security manager. Unclear 423 // if that can ever happen but better be safe. 424 updateKeyModifiers(e); 425 mousePos = e.getPoint(); 426 427 DataSet ds = getLayerManager().getEditDataSet(); 428 Collection<OsmPrimitive> selection = new ArrayList<>(ds.getSelected()); 429 430 boolean newNode = false; 431 Node n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive::isSelectable); 432 if (ctrl) { 433 Iterator<Way> it = ds.getSelectedWays().iterator(); 434 if (it.hasNext()) { 435 // ctrl-click on node of selected way = reuse node despite of ctrl 436 if (!it.next().containsNode(n)) n = null; 437 } else { 438 n = null; // ctrl-click + no selected way = new node 439 } 440 } 441 442 if (n != null && !snapHelper.isActive()) { 443 // user clicked on node 444 if (selection.isEmpty() || wayIsFinished) { 445 // select the clicked node and do nothing else 446 // (this is just a convenience option so that people don't 447 // have to switch modes) 448 449 ds.setSelected(n); 450 // If we extend/continue an existing way, select it already now to make it obvious 451 Way continueFrom = getWayForNode(n); 452 if (continueFrom != null) { 453 ds.addSelected(continueFrom); 454 } 455 456 // The user explicitly selected a node, so let him continue drawing 457 wayIsFinished = false; 458 return; 459 } 460 } else { 461 EastNorth newEN; 462 if (n != null) { 463 EastNorth foundPoint = n.getEastNorth(); 464 // project found node to snapping line 465 newEN = snapHelper.getSnapPoint(foundPoint); 466 // do not add new node if there is some node within snapping distance 467 double tolerance = Main.map.mapView.getDist100Pixel() * toleranceMultiplier; 468 if (foundPoint.distance(newEN) > tolerance) { 469 n = new Node(newEN); // point != projected, so we create new node 470 newNode = true; 471 } 472 } else { // n==null, no node found in clicked area 473 EastNorth mouseEN = Main.map.mapView.getEastNorth(e.getX(), e.getY()); 474 newEN = snapHelper.isSnapOn() ? snapHelper.getSnapPoint(mouseEN) : mouseEN; 475 n = new Node(newEN); //create node at clicked point 476 newNode = true; 477 } 478 snapHelper.unsetFixedMode(); 479 } 480 481 Collection<Command> cmds = new LinkedList<>(); 482 Collection<OsmPrimitive> newSelection = new LinkedList<>(ds.getSelected()); 483 List<Way> reuseWays = new ArrayList<>(); 484 List<Way> replacedWays = new ArrayList<>(); 485 486 if (newNode) { 487 if (n.getCoor().isOutSideWorld()) { 488 JOptionPane.showMessageDialog( 489 Main.parent, 490 tr("Cannot add a node outside of the world."), 491 tr("Warning"), 492 JOptionPane.WARNING_MESSAGE 493 ); 494 return; 495 } 496 cmds.add(new AddCommand(n)); 497 498 if (!ctrl) { 499 // Insert the node into all the nearby way segments 500 List<WaySegment> wss = Main.map.mapView.getNearestWaySegments( 501 Main.map.mapView.getPoint(n), OsmPrimitive::isSelectable); 502 if (snapHelper.isActive()) { 503 tryToMoveNodeOnIntersection(wss, n); 504 } 505 insertNodeIntoAllNearbySegments(wss, n, newSelection, cmds, replacedWays, reuseWays); 506 } 507 } 508 // now "n" is newly created or reused node that shoud be added to some way 509 510 // This part decides whether or not a "segment" (i.e. a connection) is made to an existing node. 511 512 // For a connection to be made, the user must either have a node selected (connection 513 // is made to that node), or he must have a way selected *and* one of the endpoints 514 // of that way must be the last used node (connection is made to last used node), or 515 // he must have a way and a node selected (connection is made to the selected node). 516 517 // If the above does not apply, the selection is cleared and a new try is started 518 519 boolean extendedWay = false; 520 boolean wayIsFinishedTemp = wayIsFinished; 521 wayIsFinished = false; 522 523 // don't draw lines if shift is held 524 if (!selection.isEmpty() && !shift) { 525 Node selectedNode = null; 526 Way selectedWay = null; 527 528 for (OsmPrimitive p : selection) { 529 if (p instanceof Node) { 530 if (selectedNode != null) { 531 // Too many nodes selected to do something useful 532 tryAgain(e); 533 return; 534 } 535 selectedNode = (Node) p; 536 } else if (p instanceof Way) { 537 if (selectedWay != null) { 538 // Too many ways selected to do something useful 539 tryAgain(e); 540 return; 541 } 542 selectedWay = (Way) p; 543 } 544 } 545 546 // the node from which we make a connection 547 Node n0 = findNodeToContinueFrom(selectedNode, selectedWay); 548 // We have a selection but it isn't suitable. Try again. 549 if (n0 == null) { 550 tryAgain(e); 551 return; 552 } 553 if (!wayIsFinishedTemp) { 554 if (isSelfContainedWay(selectedWay, n0, n)) 555 return; 556 557 // User clicked last node again, finish way 558 if (n0 == n) { 559 finishDrawing(); 560 return; 561 } 562 563 // Ok we know now that we'll insert a line segment, but will it connect to an 564 // existing way or make a new way of its own? The "alt" modifier means that the 565 // user wants a new way. 566 Way way = alt ? null : (selectedWay != null ? selectedWay : getWayForNode(n0)); 567 Way wayToSelect; 568 569 // Don't allow creation of self-overlapping ways 570 if (way != null) { 571 int nodeCount = 0; 572 for (Node p : way.getNodes()) { 573 if (p.equals(n0)) { 574 nodeCount++; 575 } 576 } 577 if (nodeCount > 1) { 578 way = null; 579 } 580 } 581 582 if (way == null) { 583 way = new Way(); 584 way.addNode(n0); 585 cmds.add(new AddCommand(way)); 586 wayToSelect = way; 587 } else { 588 int i; 589 if ((i = replacedWays.indexOf(way)) != -1) { 590 way = reuseWays.get(i); 591 wayToSelect = way; 592 } else { 593 wayToSelect = way; 594 Way wnew = new Way(way); 595 cmds.add(new ChangeCommand(way, wnew)); 596 way = wnew; 597 } 598 } 599 600 // Connected to a node that's already in the way 601 if (way.containsNode(n)) { 602 wayIsFinished = true; 603 selection.clear(); 604 } 605 606 // Add new node to way 607 if (way.getNode(way.getNodesCount() - 1) == n0) { 608 way.addNode(n); 609 } else { 610 way.addNode(0, n); 611 } 612 613 extendedWay = true; 614 newSelection.clear(); 615 newSelection.add(wayToSelect); 616 } 617 } 618 if (!extendedWay && !newNode) { 619 return; // We didn't do anything. 620 } 621 622 String title = getTitle(newNode, n, newSelection, reuseWays, extendedWay); 623 624 Command c = new SequenceCommand(title, cmds); 625 626 Main.main.undoRedo.add(c); 627 if (!wayIsFinished) { 628 lastUsedNode = n; 629 } 630 631 ds.setSelected(newSelection); 632 633 // "viewport following" mode for tracing long features 634 // from aerial imagery or GPS tracks. 635 if (Main.map.mapView.viewportFollowing) { 636 Main.map.mapView.smoothScrollTo(n.getEastNorth()); 637 } 638 computeHelperLine(); 639 removeHighlighting(); 640 } 641 642 private static String getTitle(boolean newNode, Node n, Collection<OsmPrimitive> newSelection, List<Way> reuseWays, 643 boolean extendedWay) { 644 String title; 645 if (!extendedWay) { 646 if (reuseWays.isEmpty()) { 647 title = tr("Add node"); 648 } else { 649 title = tr("Add node into way"); 650 for (Way w : reuseWays) { 651 newSelection.remove(w); 652 } 653 } 654 newSelection.clear(); 655 newSelection.add(n); 656 } else if (!newNode) { 657 title = tr("Connect existing way to node"); 658 } else if (reuseWays.isEmpty()) { 659 title = tr("Add a new node to an existing way"); 660 } else { 661 title = tr("Add node into way and connect"); 662 } 663 return title; 664 } 665 666 private void insertNodeIntoAllNearbySegments(List<WaySegment> wss, Node n, Collection<OsmPrimitive> newSelection, 667 Collection<Command> cmds, List<Way> replacedWays, List<Way> reuseWays) { 668 Map<Way, List<Integer>> insertPoints = new HashMap<>(); 669 for (WaySegment ws : wss) { 670 List<Integer> is; 671 if (insertPoints.containsKey(ws.way)) { 672 is = insertPoints.get(ws.way); 673 } else { 674 is = new ArrayList<>(); 675 insertPoints.put(ws.way, is); 676 } 677 678 is.add(ws.lowerIndex); 679 } 680 681 Set<Pair<Node, Node>> segSet = new HashSet<>(); 682 683 for (Map.Entry<Way, List<Integer>> insertPoint : insertPoints.entrySet()) { 684 Way w = insertPoint.getKey(); 685 List<Integer> is = insertPoint.getValue(); 686 687 Way wnew = new Way(w); 688 689 pruneSuccsAndReverse(is); 690 for (int i : is) { 691 segSet.add(Pair.sort(new Pair<>(w.getNode(i), w.getNode(i+1)))); 692 wnew.addNode(i + 1, n); 693 } 694 695 // If ALT is pressed, a new way should be created and that new way should get 696 // selected. This works everytime unless the ways the nodes get inserted into 697 // are already selected. This is the case when creating a self-overlapping way 698 // but pressing ALT prevents this. Therefore we must de-select the way manually 699 // here so /only/ the new way will be selected after this method finishes. 700 if (alt) { 701 newSelection.add(insertPoint.getKey()); 702 } 703 704 cmds.add(new ChangeCommand(insertPoint.getKey(), wnew)); 705 replacedWays.add(insertPoint.getKey()); 706 reuseWays.add(wnew); 707 } 708 709 adjustNode(segSet, n); 710 } 711 712 /** 713 * Prevent creation of ways that look like this: <----> 714 * This happens if users want to draw a no-exit-sideway from the main way like this: 715 * ^ 716 * |<----> 717 * | 718 * The solution isn't ideal because the main way will end in the side way, which is bad for 719 * navigation software ("drive straight on") but at least easier to fix. Maybe users will fix 720 * it on their own, too. At least it's better than producing an error. 721 * 722 * @param selectedWay the way to check 723 * @param currentNode the current node (i.e. the one the connection will be made from) 724 * @param targetNode the target node (i.e. the one the connection will be made to) 725 * @return {@code true} if this would create a selfcontaining way, {@code false} otherwise. 726 */ 727 private boolean isSelfContainedWay(Way selectedWay, Node currentNode, Node targetNode) { 728 if (selectedWay != null) { 729 int posn0 = selectedWay.getNodes().indexOf(currentNode); 730 // CHECKSTYLE.OFF: SingleSpaceSeparator 731 if ((posn0 != -1 && // n0 is part of way 732 (posn0 >= 1 && targetNode.equals(selectedWay.getNode(posn0-1)))) || // previous node 733 (posn0 < selectedWay.getNodesCount()-1 && targetNode.equals(selectedWay.getNode(posn0+1)))) { // next node 734 getLayerManager().getEditDataSet().setSelected(targetNode); 735 lastUsedNode = targetNode; 736 return true; 737 } 738 // CHECKSTYLE.ON: SingleSpaceSeparator 739 } 740 741 return false; 742 } 743 744 /** 745 * Finds a node to continue drawing from. Decision is based upon given node and way. 746 * @param selectedNode Currently selected node, may be null 747 * @param selectedWay Currently selected way, may be null 748 * @return Node if a suitable node is found, null otherwise 749 */ 750 private Node findNodeToContinueFrom(Node selectedNode, Way selectedWay) { 751 // No nodes or ways have been selected, this occurs when a relation 752 // has been selected or the selection is empty 753 if (selectedNode == null && selectedWay == null) 754 return null; 755 756 if (selectedNode == null) { 757 if (selectedWay.isFirstLastNode(lastUsedNode)) 758 return lastUsedNode; 759 760 // We have a way selected, but no suitable node to continue from. Start anew. 761 return null; 762 } 763 764 if (selectedWay == null) 765 return selectedNode; 766 767 if (selectedWay.isFirstLastNode(selectedNode)) 768 return selectedNode; 769 770 // We have a way and node selected, but it's not at the start/end of the way. Start anew. 771 return null; 772 } 773 774 @Override 775 public void mouseDragged(MouseEvent e) { 776 mouseMoved(e); 777 } 778 779 @Override 780 public void mouseMoved(MouseEvent e) { 781 if (!Main.map.mapView.isActiveLayerDrawable()) 782 return; 783 784 // we copy ctrl/alt/shift from the event just in case our global 785 // keyDetector didn't make it through the security manager. Unclear 786 // if that can ever happen but better be safe. 787 updateKeyModifiers(e); 788 mousePos = e.getPoint(); 789 if (snapHelper.isSnapOn() && ctrl) 790 tryToSetBaseSegmentForAngleSnap(); 791 792 computeHelperLine(); 793 addHighlighting(); 794 } 795 796 /** 797 * This method is used to detect segment under mouse and use it as reference for angle snapping 798 */ 799 private void tryToSetBaseSegmentForAngleSnap() { 800 WaySegment seg = Main.map.mapView.getNearestWaySegment(mousePos, OsmPrimitive::isSelectable); 801 if (seg != null) { 802 snapHelper.setBaseSegment(seg); 803 } 804 } 805 806 /** 807 * This method prepares data required for painting the "helper line" from 808 * the last used position to the mouse cursor. It duplicates some code from 809 * mouseReleased() (FIXME). 810 */ 811 private void computeHelperLine() { 812 if (mousePos == null) { 813 // Don't draw the line. 814 currentMouseEastNorth = null; 815 currentBaseNode = null; 816 return; 817 } 818 819 Collection<OsmPrimitive> selection = getLayerManager().getEditDataSet().getSelected(); 820 821 MapView mv = Main.map.mapView; 822 Node currentMouseNode = null; 823 mouseOnExistingNode = null; 824 mouseOnExistingWays = new HashSet<>(); 825 826 showStatusInfo(-1, -1, -1, snapHelper.isSnapOn()); 827 828 if (!ctrl && mousePos != null) { 829 currentMouseNode = mv.getNearestNode(mousePos, OsmPrimitive::isSelectable); 830 } 831 832 // We need this for highlighting and we'll only do so if we actually want to re-use 833 // *and* there is no node nearby (because nodes beat ways when re-using) 834 if (!ctrl && currentMouseNode == null) { 835 List<WaySegment> wss = mv.getNearestWaySegments(mousePos, OsmPrimitive::isSelectable); 836 for (WaySegment ws : wss) { 837 mouseOnExistingWays.add(ws.way); 838 } 839 } 840 841 if (currentMouseNode != null) { 842 // user clicked on node 843 if (selection.isEmpty()) return; 844 currentMouseEastNorth = currentMouseNode.getEastNorth(); 845 mouseOnExistingNode = currentMouseNode; 846 } else { 847 // no node found in clicked area 848 currentMouseEastNorth = mv.getEastNorth(mousePos.x, mousePos.y); 849 } 850 851 determineCurrentBaseNodeAndPreviousNode(selection); 852 if (previousNode == null) { 853 snapHelper.noSnapNow(); 854 } 855 856 if (getCurrentBaseNode() == null || getCurrentBaseNode() == currentMouseNode) 857 return; // Don't create zero length way segments. 858 859 860 double curHdg = Math.toDegrees(getCurrentBaseNode().getEastNorth() 861 .heading(currentMouseEastNorth)); 862 double baseHdg = -1; 863 if (previousNode != null) { 864 EastNorth en = previousNode.getEastNorth(); 865 if (en != null) { 866 baseHdg = Math.toDegrees(en.heading(getCurrentBaseNode().getEastNorth())); 867 } 868 } 869 870 snapHelper.checkAngleSnapping(currentMouseEastNorth, baseHdg, curHdg); 871 872 // status bar was filled by snapHelper 873 } 874 875 private static void showStatusInfo(double angle, double hdg, double distance, boolean activeFlag) { 876 Main.map.statusLine.setAngle(angle); 877 Main.map.statusLine.activateAnglePanel(activeFlag); 878 Main.map.statusLine.setHeading(hdg); 879 Main.map.statusLine.setDist(distance); 880 } 881 882 /** 883 * Helper function that sets fields currentBaseNode and previousNode 884 * @param selection 885 * uses also lastUsedNode field 886 */ 887 private void determineCurrentBaseNodeAndPreviousNode(Collection<OsmPrimitive> selection) { 888 Node selectedNode = null; 889 Way selectedWay = null; 890 for (OsmPrimitive p : selection) { 891 if (p instanceof Node) { 892 if (selectedNode != null) 893 return; 894 selectedNode = (Node) p; 895 } else if (p instanceof Way) { 896 if (selectedWay != null) 897 return; 898 selectedWay = (Way) p; 899 } 900 } 901 // we are here, if not more than 1 way or node is selected, 902 903 // the node from which we make a connection 904 currentBaseNode = null; 905 previousNode = null; 906 907 // Try to find an open way to measure angle from it. The way is not to be continued! 908 // warning: may result in changes of currentBaseNode and previousNode 909 // please remove if bugs arise 910 if (selectedWay == null && selectedNode != null) { 911 for (OsmPrimitive p: selectedNode.getReferrers()) { 912 if (p.isUsable() && p instanceof Way && ((Way) p).isFirstLastNode(selectedNode)) { 913 if (selectedWay != null) { // two uncontinued ways, nothing to take as reference 914 selectedWay = null; 915 break; 916 } else { 917 // set us ~continue this way (measure angle from it) 918 selectedWay = (Way) p; 919 } 920 } 921 } 922 } 923 924 if (selectedNode == null) { 925 if (selectedWay == null) 926 return; 927 continueWayFromNode(selectedWay, lastUsedNode); 928 } else if (selectedWay == null) { 929 currentBaseNode = selectedNode; 930 } else if (!selectedWay.isDeleted()) { // fix #7118 931 continueWayFromNode(selectedWay, selectedNode); 932 } 933 } 934 935 /** 936 * if one of the ends of {@code way} is given {@code node}, 937 * then set currentBaseNode = node and previousNode = adjacent node of way 938 * @param way way to continue 939 * @param node starting node 940 */ 941 private void continueWayFromNode(Way way, Node node) { 942 int n = way.getNodesCount(); 943 if (node == way.firstNode()) { 944 currentBaseNode = node; 945 if (n > 1) previousNode = way.getNode(1); 946 } else if (node == way.lastNode()) { 947 currentBaseNode = node; 948 if (n > 1) previousNode = way.getNode(n-2); 949 } 950 } 951 952 /** 953 * Repaint on mouse exit so that the helper line goes away. 954 */ 955 @Override 956 public void mouseExited(MouseEvent e) { 957 OsmDataLayer editLayer = Main.getLayerManager().getEditLayer(); 958 if (editLayer == null) 959 return; 960 mousePos = e.getPoint(); 961 snapHelper.noSnapNow(); 962 boolean repaintIssued = removeHighlighting(); 963 // force repaint in case snapHelper needs one. If removeHighlighting 964 // caused one already, don't do it again. 965 if (!repaintIssued) { 966 editLayer.invalidate(); 967 } 968 } 969 970 /** 971 * @param n node 972 * @return If the node is the end of exactly one way, return this. 973 * <code>null</code> otherwise. 974 */ 975 public static Way getWayForNode(Node n) { 976 Way way = null; 977 for (Way w : Utils.filteredCollection(n.getReferrers(), Way.class)) { 978 if (!w.isUsable() || w.getNodesCount() < 1) { 979 continue; 980 } 981 Node firstNode = w.getNode(0); 982 Node lastNode = w.getNode(w.getNodesCount() - 1); 983 if ((firstNode == n || lastNode == n) && (firstNode != lastNode)) { 984 if (way != null) 985 return null; 986 way = w; 987 } 988 } 989 return way; 990 } 991 992 /** 993 * Replies the current base node, after having checked it is still usable (see #11105). 994 * @return the current base node (can be null). If not-null, it's guaranteed the node is usable 995 */ 996 public Node getCurrentBaseNode() { 997 if (currentBaseNode != null && (currentBaseNode.getDataSet() == null || !currentBaseNode.isUsable())) { 998 currentBaseNode = null; 999 } 1000 return currentBaseNode; 1001 } 1002 1003 private static void pruneSuccsAndReverse(List<Integer> is) { 1004 Set<Integer> is2 = new HashSet<>(); 1005 for (int i : is) { 1006 if (!is2.contains(i - 1) && !is2.contains(i + 1)) { 1007 is2.add(i); 1008 } 1009 } 1010 is.clear(); 1011 is.addAll(is2); 1012 Collections.sort(is); 1013 Collections.reverse(is); 1014 } 1015 1016 /** 1017 * Adjusts the position of a node to lie on a segment (or a segment 1018 * intersection). 1019 * 1020 * If one or more than two segments are passed, the node is adjusted 1021 * to lie on the first segment that is passed. 1022 * 1023 * If two segments are passed, the node is adjusted to be at their 1024 * intersection. 1025 * 1026 * No action is taken if no segments are passed. 1027 * 1028 * @param segs the segments to use as a reference when adjusting 1029 * @param n the node to adjust 1030 */ 1031 private static void adjustNode(Collection<Pair<Node, Node>> segs, Node n) { 1032 1033 switch (segs.size()) { 1034 case 0: 1035 return; 1036 case 2: 1037 // This computes the intersection between the two segments and adjusts the node position. 1038 Iterator<Pair<Node, Node>> i = segs.iterator(); 1039 Pair<Node, Node> seg = i.next(); 1040 EastNorth pA = seg.a.getEastNorth(); 1041 EastNorth pB = seg.b.getEastNorth(); 1042 seg = i.next(); 1043 EastNorth pC = seg.a.getEastNorth(); 1044 EastNorth pD = seg.b.getEastNorth(); 1045 1046 double u = det(pB.east() - pA.east(), pB.north() - pA.north(), pC.east() - pD.east(), pC.north() - pD.north()); 1047 1048 // Check for parallel segments and do nothing if they are 1049 // In practice this will probably only happen when a way has been duplicated 1050 1051 if (u == 0) 1052 return; 1053 1054 // q is a number between 0 and 1 1055 // It is the point in the segment where the intersection occurs 1056 // if the segment is scaled to lenght 1 1057 1058 double q = det(pB.north() - pC.north(), pB.east() - pC.east(), pD.north() - pC.north(), pD.east() - pC.east()) / u; 1059 EastNorth intersection = new EastNorth( 1060 pB.east() + q * (pA.east() - pB.east()), 1061 pB.north() + q * (pA.north() - pB.north())); 1062 1063 1064 // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise 1065 // fall through to default action. 1066 // (for semi-parallel lines, intersection might be miles away!) 1067 if (Main.map.mapView.getPoint2D(n).distance(Main.map.mapView.getPoint2D(intersection)) < SNAP_TO_INTERSECTION_THRESHOLD.get()) { 1068 n.setEastNorth(intersection); 1069 return; 1070 } 1071 default: 1072 EastNorth p = n.getEastNorth(); 1073 seg = segs.iterator().next(); 1074 pA = seg.a.getEastNorth(); 1075 pB = seg.b.getEastNorth(); 1076 double a = p.distanceSq(pB); 1077 double b = p.distanceSq(pA); 1078 double c = pA.distanceSq(pB); 1079 q = (a - b + c) / (2*c); 1080 n.setEastNorth(new EastNorth(pB.east() + q * (pA.east() - pB.east()), pB.north() + q * (pA.north() - pB.north()))); 1081 } 1082 } 1083 1084 // helper for adjustNode 1085 static double det(double a, double b, double c, double d) { 1086 return a * d - b * c; 1087 } 1088 1089 private void tryToMoveNodeOnIntersection(List<WaySegment> wss, Node n) { 1090 if (wss.isEmpty()) 1091 return; 1092 WaySegment ws = wss.get(0); 1093 EastNorth p1 = ws.getFirstNode().getEastNorth(); 1094 EastNorth p2 = ws.getSecondNode().getEastNorth(); 1095 if (snapHelper.dir2 != null && getCurrentBaseNode() != null) { 1096 EastNorth xPoint = Geometry.getSegmentSegmentIntersection(p1, p2, snapHelper.dir2, 1097 getCurrentBaseNode().getEastNorth()); 1098 if (xPoint != null) { 1099 n.setEastNorth(xPoint); 1100 } 1101 } 1102 } 1103 1104 /** 1105 * Takes the data from computeHelperLine to determine which ways/nodes should be highlighted 1106 * (if feature enabled). Also sets the target cursor if appropriate. It adds the to-be- 1107 * highlighted primitives to newHighlights but does not actually highlight them. This work is 1108 * done in redrawIfRequired. This means, calling addHighlighting() without redrawIfRequired() 1109 * will leave the data in an inconsistent state. 1110 * 1111 * The status bar derives its information from oldHighlights, so in order to update the status 1112 * bar both addHighlighting() and repaintIfRequired() are needed, since former fills newHighlights 1113 * and latter processes them into oldHighlights. 1114 */ 1115 private void addHighlighting() { 1116 newHighlights = new HashSet<>(); 1117 1118 // if ctrl key is held ("no join"), don't highlight anything 1119 if (ctrl) { 1120 Main.map.mapView.setNewCursor(cursor, this); 1121 redrawIfRequired(); 1122 return; 1123 } 1124 1125 // This happens when nothing is selected, but we still want to highlight the "target node" 1126 if (mouseOnExistingNode == null && getLayerManager().getEditDataSet().selectionEmpty() && mousePos != null) { 1127 mouseOnExistingNode = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive::isSelectable); 1128 } 1129 1130 if (mouseOnExistingNode != null) { 1131 Main.map.mapView.setNewCursor(cursorJoinNode, this); 1132 newHighlights.add(mouseOnExistingNode); 1133 redrawIfRequired(); 1134 return; 1135 } 1136 1137 // Insert the node into all the nearby way segments 1138 if (mouseOnExistingWays.isEmpty()) { 1139 Main.map.mapView.setNewCursor(cursor, this); 1140 redrawIfRequired(); 1141 return; 1142 } 1143 1144 Main.map.mapView.setNewCursor(cursorJoinWay, this); 1145 newHighlights.addAll(mouseOnExistingWays); 1146 redrawIfRequired(); 1147 } 1148 1149 /** 1150 * Removes target highlighting from primitives. Issues repaint if required. 1151 * @return true if a repaint has been issued. 1152 */ 1153 private boolean removeHighlighting() { 1154 newHighlights = new HashSet<>(); 1155 return redrawIfRequired(); 1156 } 1157 1158 @Override 1159 public void paint(Graphics2D g, MapView mv, Bounds box) { 1160 // sanity checks 1161 if (Main.map.mapView == null || mousePos == null 1162 // don't draw line if we don't know where from or where to 1163 || getCurrentBaseNode() == null || currentMouseEastNorth == null 1164 // don't draw line if mouse is outside window 1165 || !Main.map.mapView.getBounds().contains(mousePos)) 1166 return; 1167 1168 Graphics2D g2 = g; 1169 snapHelper.drawIfNeeded(g2, mv.getState()); 1170 if (!DRAW_HELPER_LINE.get() || wayIsFinished || shift) 1171 return; 1172 1173 if (!snapHelper.isActive()) { 1174 g2.setColor(RUBBER_LINE_COLOR.get()); 1175 g2.setStroke(RUBBER_LINE_STROKE.get()); 1176 paintConstructionGeometry(mv, g2); 1177 } else if (DRAW_CONSTRUCTION_GEOMETRY.get()) { 1178 // else use color and stoke from snapHelper.draw 1179 paintConstructionGeometry(mv, g2); 1180 } 1181 } 1182 1183 private void paintConstructionGeometry(MapView mv, Graphics2D g2) { 1184 MapPath2D b = new MapPath2D(); 1185 MapViewPoint p1 = mv.getState().getPointFor(getCurrentBaseNode()); 1186 MapViewPoint p2 = mv.getState().getPointFor(currentMouseEastNorth); 1187 1188 b.moveTo(p1); 1189 b.lineTo(p2); 1190 1191 // if alt key is held ("start new way"), draw a little perpendicular line 1192 if (alt) { 1193 START_WAY_INDICATOR.paintArrowAt(b, p1, p2); 1194 } 1195 1196 g2.draw(b); 1197 g2.setStroke(BASIC_STROKE); 1198 } 1199 1200 @Override 1201 public String getModeHelpText() { 1202 StringBuilder rv; 1203 /* 1204 * No modifiers: all (Connect, Node Re-Use, Auto-Weld) 1205 * CTRL: disables node re-use, auto-weld 1206 * Shift: do not make connection 1207 * ALT: make connection but start new way in doing so 1208 */ 1209 1210 /* 1211 * Status line text generation is split into two parts to keep it maintainable. 1212 * First part looks at what will happen to the new node inserted on click and 1213 * the second part will look if a connection is made or not. 1214 * 1215 * Note that this help text is not absolutely accurate as it doesn't catch any special 1216 * cases (e.g. when preventing <---> ways). The only special that it catches is when 1217 * a way is about to be finished. 1218 * 1219 * First check what happens to the new node. 1220 */ 1221 1222 // oldHighlights stores the current highlights. If this 1223 // list is empty we can assume that we won't do any joins 1224 if (ctrl || oldHighlights.isEmpty()) { 1225 rv = new StringBuilder(tr("Create new node.")); 1226 } else { 1227 // oldHighlights may store a node or way, check if it's a node 1228 OsmPrimitive x = oldHighlights.iterator().next(); 1229 if (x instanceof Node) { 1230 rv = new StringBuilder(tr("Select node under cursor.")); 1231 } else { 1232 rv = new StringBuilder(trn("Insert new node into way.", "Insert new node into {0} ways.", 1233 oldHighlights.size(), oldHighlights.size())); 1234 } 1235 } 1236 1237 /* 1238 * Check whether a connection will be made 1239 */ 1240 if (getCurrentBaseNode() != null && !wayIsFinished) { 1241 if (alt) { 1242 rv.append(' ').append(tr("Start new way from last node.")); 1243 } else { 1244 rv.append(' ').append(tr("Continue way from last node.")); 1245 } 1246 if (snapHelper.isSnapOn()) { 1247 rv.append(' ').append(tr("Angle snapping active.")); 1248 } 1249 } 1250 1251 Node n = mouseOnExistingNode; 1252 DataSet ds = getLayerManager().getEditDataSet(); 1253 /* 1254 * Handle special case: Highlighted node == selected node => finish drawing 1255 */ 1256 if (n != null && ds != null && ds.getSelectedNodes().contains(n)) { 1257 if (wayIsFinished) { 1258 rv = new StringBuilder(tr("Select node under cursor.")); 1259 } else { 1260 rv = new StringBuilder(tr("Finish drawing.")); 1261 } 1262 } 1263 1264 /* 1265 * Handle special case: Self-Overlapping or closing way 1266 */ 1267 if (ds != null && !ds.getSelectedWays().isEmpty() && !wayIsFinished && !alt) { 1268 Way w = ds.getSelectedWays().iterator().next(); 1269 for (Node m : w.getNodes()) { 1270 if (m.equals(mouseOnExistingNode) || mouseOnExistingWays.contains(w)) { 1271 rv.append(' ').append(tr("Finish drawing.")); 1272 break; 1273 } 1274 } 1275 } 1276 return rv.toString(); 1277 } 1278 1279 /** 1280 * Get selected primitives, while draw action is in progress. 1281 * 1282 * While drawing a way, technically the last node is selected. 1283 * This is inconvenient when the user tries to add/edit tags to the way. 1284 * For this case, this method returns the current way as selection, 1285 * to work around this issue. 1286 * Otherwise the normal selection of the current data layer is returned. 1287 * @return selected primitives, while draw action is in progress 1288 */ 1289 public Collection<OsmPrimitive> getInProgressSelection() { 1290 DataSet ds = getLayerManager().getEditDataSet(); 1291 if (ds == null) return null; 1292 if (getCurrentBaseNode() != null && !ds.selectionEmpty()) { 1293 Way continueFrom = getWayForNode(getCurrentBaseNode()); 1294 if (continueFrom != null) 1295 return Collections.<OsmPrimitive>singleton(continueFrom); 1296 } 1297 return ds.getSelected(); 1298 } 1299 1300 @Override 1301 public boolean layerIsSupported(Layer l) { 1302 return l instanceof OsmDataLayer; 1303 } 1304 1305 @Override 1306 protected void updateEnabledState() { 1307 setEnabled(getLayerManager().getEditLayer() != null); 1308 } 1309 1310 @Override 1311 public void destroy() { 1312 super.destroy(); 1313 snapChangeAction.destroy(); 1314 } 1315 1316 public class BackSpaceAction extends AbstractAction { 1317 1318 @Override 1319 public void actionPerformed(ActionEvent e) { 1320 Main.main.undoRedo.undo(); 1321 Command lastCmd = Main.main.undoRedo.commands.peekLast(); 1322 if (lastCmd == null) return; 1323 Node n = null; 1324 for (OsmPrimitive p: lastCmd.getParticipatingPrimitives()) { 1325 if (p instanceof Node) { 1326 if (n == null) { 1327 n = (Node) p; // found one node 1328 wayIsFinished = false; 1329 } else { 1330 // if more than 1 node were affected by previous command, 1331 // we have no way to continue, so we forget about found node 1332 n = null; 1333 break; 1334 } 1335 } 1336 } 1337 // select last added node - maybe we will continue drawing from it 1338 if (n != null) { 1339 getLayerManager().getEditDataSet().addSelected(n); 1340 } 1341 } 1342 } 1343 1344 private class SnapHelper { 1345 private static final String DRAW_ANGLESNAP_ANGLES = "draw.anglesnap.angles"; 1346 1347 private final class AnglePopupMenu extends JPopupMenu { 1348 1349 private final JCheckBoxMenuItem repeatedCb = new JCheckBoxMenuItem( 1350 new AbstractAction(tr("Toggle snapping by {0}", getShortcut().getKeyText())) { 1351 @Override 1352 public void actionPerformed(ActionEvent e) { 1353 boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState(); 1354 USE_REPEATED_SHORTCUT.put(sel); 1355 } 1356 }); 1357 1358 private final JCheckBoxMenuItem helperCb = new JCheckBoxMenuItem( 1359 new AbstractAction(tr("Show helper geometry")) { 1360 @Override 1361 public void actionPerformed(ActionEvent e) { 1362 boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState(); 1363 DRAW_CONSTRUCTION_GEOMETRY.put(sel); 1364 SHOW_PROJECTED_POINT.put(sel); 1365 SHOW_ANGLE.put(sel); 1366 enableSnapping(); 1367 } 1368 }); 1369 1370 private final JCheckBoxMenuItem projectionCb = new JCheckBoxMenuItem( 1371 new AbstractAction(tr("Snap to node projections")) { 1372 @Override 1373 public void actionPerformed(ActionEvent e) { 1374 boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState(); 1375 SNAP_TO_PROJECTIONS.put(sel); 1376 enableSnapping(); 1377 } 1378 }); 1379 1380 private AnglePopupMenu() { 1381 helperCb.setState(DRAW_CONSTRUCTION_GEOMETRY.get()); 1382 projectionCb.setState(SNAP_TO_PROJECTIONS.get()); 1383 repeatedCb.setState(USE_REPEATED_SHORTCUT.get()); 1384 add(repeatedCb); 1385 add(helperCb); 1386 add(projectionCb); 1387 add(new AbstractAction(tr("Disable")) { 1388 @Override public void actionPerformed(ActionEvent e) { 1389 saveAngles("180"); 1390 init(); 1391 enableSnapping(); 1392 } 1393 }); 1394 add(new AbstractAction(tr("0,90,...")) { 1395 @Override public void actionPerformed(ActionEvent e) { 1396 saveAngles("0", "90", "180"); 1397 init(); 1398 enableSnapping(); 1399 } 1400 }); 1401 add(new AbstractAction(tr("0,45,90,...")) { 1402 @Override public void actionPerformed(ActionEvent e) { 1403 saveAngles("0", "45", "90", "135", "180"); 1404 init(); 1405 enableSnapping(); 1406 } 1407 }); 1408 add(new AbstractAction(tr("0,30,45,60,90,...")) { 1409 @Override public void actionPerformed(ActionEvent e) { 1410 saveAngles("0", "30", "45", "60", "90", "120", "135", "150", "180"); 1411 init(); 1412 enableSnapping(); 1413 } 1414 }); 1415 } 1416 } 1417 1418 private boolean snapOn; // snapping is turned on 1419 1420 private boolean active; // snapping is active for current mouse position 1421 private boolean fixed; // snap angle is fixed 1422 private boolean absoluteFix; // snap angle is absolute 1423 1424 private EastNorth dir2; 1425 private EastNorth projected; 1426 private String labelText; 1427 private double lastAngle; 1428 1429 private double customBaseHeading = -1; // angle of base line, if not last segment) 1430 private EastNorth segmentPoint1; // remembered first point of base segment 1431 private EastNorth segmentPoint2; // remembered second point of base segment 1432 private EastNorth projectionSource; // point that we are projecting to the line 1433 1434 private double[] snapAngles; 1435 1436 private double pe, pn; // (pe, pn) - direction of snapping line 1437 private double e0, n0; // (e0, n0) - origin of snapping line 1438 1439 private final String fixFmt = "%d "+tr("FIX"); 1440 1441 private JCheckBoxMenuItem checkBox; 1442 1443 private final MouseListener anglePopupListener = new PopupMenuLauncher(new AnglePopupMenu()) { 1444 @Override 1445 public void mouseClicked(MouseEvent e) { 1446 super.mouseClicked(e); 1447 if (e.getButton() == MouseEvent.BUTTON1) { 1448 toggleSnapping(); 1449 updateStatusLine(); 1450 } 1451 } 1452 }; 1453 1454 /** 1455 * Set the initial state 1456 */ 1457 public void init() { 1458 snapOn = false; 1459 checkBox.setState(snapOn); 1460 fixed = false; 1461 absoluteFix = false; 1462 1463 computeSnapAngles(); 1464 Main.pref.addWeakKeyPreferenceChangeListener(DRAW_ANGLESNAP_ANGLES, e -> this.computeSnapAngles()); 1465 } 1466 1467 private void computeSnapAngles() { 1468 snapAngles = Main.pref.getCollection(DRAW_ANGLESNAP_ANGLES, 1469 Arrays.asList("0", "30", "45", "60", "90", "120", "135", "150", "180")) 1470 .stream() 1471 .mapToDouble(this::parseSnapAngle) 1472 .flatMap(s -> DoubleStream.of(s, 360-s)) 1473 .toArray(); 1474 } 1475 1476 private double parseSnapAngle(String string) { 1477 try { 1478 return Double.parseDouble(string); 1479 } catch (NumberFormatException e) { 1480 Main.warn("Incorrect number in draw.anglesnap.angles preferences: {0}", string); 1481 return 0; 1482 } 1483 } 1484 1485 /** 1486 * Save the snap angles 1487 * @param angles The angles 1488 */ 1489 public void saveAngles(String ... angles) { 1490 Main.pref.putCollection(DRAW_ANGLESNAP_ANGLES, Arrays.asList(angles)); 1491 } 1492 1493 public void setMenuCheckBox(JCheckBoxMenuItem checkBox) { 1494 this.checkBox = checkBox; 1495 } 1496 1497 /** 1498 * Draw the snap hint line. 1499 * @param g2 graphics 1500 * @param mv MapView state 1501 * @since 10874 1502 */ 1503 public void drawIfNeeded(Graphics2D g2, MapViewState mv) { 1504 if (!snapOn || !active) 1505 return; 1506 MapViewPoint p1 = mv.getPointFor(getCurrentBaseNode()); 1507 MapViewPoint p2 = mv.getPointFor(dir2); 1508 MapViewPoint p3 = mv.getPointFor(projected); 1509 if (DRAW_CONSTRUCTION_GEOMETRY.get()) { 1510 g2.setColor(SNAP_HELPER_COLOR.get()); 1511 g2.setStroke(HELPER_STROKE.get()); 1512 1513 MapViewPath b = new MapViewPath(mv); 1514 b.moveTo(p2); 1515 if (absoluteFix) { 1516 b.lineTo(p2.interpolate(p1, 2)); // bi-directional line 1517 } else { 1518 b.lineTo(p3); 1519 } 1520 g2.draw(b); 1521 } 1522 if (projectionSource != null) { 1523 g2.setColor(SNAP_HELPER_COLOR.get()); 1524 g2.setStroke(HELPER_STROKE.get()); 1525 MapViewPath b = new MapViewPath(mv); 1526 b.moveTo(p3); 1527 b.lineTo(projectionSource); 1528 g2.draw(b); 1529 } 1530 1531 if (customBaseHeading >= 0) { 1532 g2.setColor(HIGHLIGHT_COLOR.get()); 1533 g2.setStroke(HIGHLIGHT_STROKE.get()); 1534 MapViewPath b = new MapViewPath(mv); 1535 b.moveTo(segmentPoint1); 1536 b.lineTo(segmentPoint2); 1537 g2.draw(b); 1538 } 1539 1540 g2.setColor(RUBBER_LINE_COLOR.get()); 1541 g2.setStroke(RUBBER_LINE_STROKE.get()); 1542 MapViewPath b = new MapViewPath(mv); 1543 b.moveTo(p1); 1544 b.lineTo(p3); 1545 g2.draw(b); 1546 1547 g2.drawString(labelText, (int) p3.getInViewX()-5, (int) p3.getInViewY()+20); 1548 if (SHOW_PROJECTED_POINT.get()) { 1549 g2.setStroke(RUBBER_LINE_STROKE.get()); 1550 g2.draw(new MapViewPath(mv).shapeAround(p3, SymbolShape.CIRCLE, 10)); // projected point 1551 } 1552 1553 g2.setColor(SNAP_HELPER_COLOR.get()); 1554 g2.setStroke(HELPER_STROKE.get()); 1555 } 1556 1557 /** 1558 * If mouse position is close to line at 15-30-45-... angle, remembers this direction 1559 * @param currentEN Current position 1560 * @param baseHeading The heading 1561 * @param curHeading The current mouse heading 1562 */ 1563 public void checkAngleSnapping(EastNorth currentEN, double baseHeading, double curHeading) { 1564 EastNorth p0 = getCurrentBaseNode().getEastNorth(); 1565 EastNorth snapPoint = currentEN; 1566 double angle = -1; 1567 1568 double activeBaseHeading = (customBaseHeading >= 0) ? customBaseHeading : baseHeading; 1569 1570 if (snapOn && (activeBaseHeading >= 0)) { 1571 angle = curHeading - activeBaseHeading; 1572 if (angle < 0) { 1573 angle += 360; 1574 } 1575 if (angle > 360) { 1576 angle = 0; 1577 } 1578 1579 double nearestAngle; 1580 if (fixed) { 1581 nearestAngle = lastAngle; // if direction is fixed use previous angle 1582 active = true; 1583 } else { 1584 nearestAngle = getNearestAngle(angle); 1585 if (getAngleDelta(nearestAngle, angle) < SNAP_ANGLE_TOLERANCE.get()) { 1586 active = customBaseHeading >= 0 || Math.abs(nearestAngle - 180) > 1e-3; 1587 // if angle is to previous segment, exclude 180 degrees 1588 lastAngle = nearestAngle; 1589 } else { 1590 active = false; 1591 } 1592 } 1593 1594 if (active) { 1595 double phi; 1596 e0 = p0.east(); 1597 n0 = p0.north(); 1598 buildLabelText((nearestAngle <= 180) ? nearestAngle : (nearestAngle-360)); 1599 1600 phi = (nearestAngle + activeBaseHeading) * Math.PI / 180; 1601 // (pe,pn) - direction of snapping line 1602 pe = Math.sin(phi); 1603 pn = Math.cos(phi); 1604 double scale = 20 * Main.map.mapView.getDist100Pixel(); 1605 dir2 = new EastNorth(e0 + scale * pe, n0 + scale * pn); 1606 snapPoint = getSnapPoint(currentEN); 1607 } else { 1608 noSnapNow(); 1609 } 1610 } 1611 1612 // find out the distance, in metres, between the base point and projected point 1613 LatLon mouseLatLon = Main.map.mapView.getProjection().eastNorth2latlon(snapPoint); 1614 double distance = getCurrentBaseNode().getCoor().greatCircleDistance(mouseLatLon); 1615 double hdg = Math.toDegrees(p0.heading(snapPoint)); 1616 // heading of segment from current to calculated point, not to mouse position 1617 1618 if (baseHeading >= 0) { // there is previous line segment with some heading 1619 angle = hdg - baseHeading; 1620 if (angle < 0) { 1621 angle += 360; 1622 } 1623 if (angle > 360) { 1624 angle = 0; 1625 } 1626 } 1627 showStatusInfo(angle, hdg, distance, isSnapOn()); 1628 } 1629 1630 private void buildLabelText(double nearestAngle) { 1631 if (SHOW_ANGLE.get()) { 1632 if (fixed) { 1633 if (absoluteFix) { 1634 labelText = "="; 1635 } else { 1636 labelText = String.format(fixFmt, (int) nearestAngle); 1637 } 1638 } else { 1639 labelText = String.format("%d", (int) nearestAngle); 1640 } 1641 } else { 1642 if (fixed) { 1643 if (absoluteFix) { 1644 labelText = "="; 1645 } else { 1646 labelText = String.format(tr("FIX"), 0); 1647 } 1648 } else { 1649 labelText = ""; 1650 } 1651 } 1652 } 1653 1654 /** 1655 * Gets a snap point close to p. Stores the result for display. 1656 * @param p The point 1657 * @return The snap point close to p. 1658 */ 1659 public EastNorth getSnapPoint(EastNorth p) { 1660 if (!active) 1661 return p; 1662 double de = p.east()-e0; 1663 double dn = p.north()-n0; 1664 double l = de*pe+dn*pn; 1665 double delta = Main.map.mapView.getDist100Pixel()/20; 1666 if (!absoluteFix && l < delta) { 1667 active = false; 1668 return p; 1669 } // do not go backward! 1670 1671 projectionSource = null; 1672 if (SNAP_TO_PROJECTIONS.get()) { 1673 DataSet ds = getLayerManager().getEditDataSet(); 1674 Collection<Way> selectedWays = ds.getSelectedWays(); 1675 if (selectedWays.size() == 1) { 1676 Way w = selectedWays.iterator().next(); 1677 Collection<EastNorth> pointsToProject = new ArrayList<>(); 1678 if (w.getNodesCount() < 1000) { 1679 for (Node n: w.getNodes()) { 1680 pointsToProject.add(n.getEastNorth()); 1681 } 1682 } 1683 if (customBaseHeading >= 0) { 1684 pointsToProject.add(segmentPoint1); 1685 pointsToProject.add(segmentPoint2); 1686 } 1687 EastNorth enOpt = null; 1688 double dOpt = 1e5; 1689 for (EastNorth en: pointsToProject) { // searching for besht projection 1690 double l1 = (en.east()-e0)*pe+(en.north()-n0)*pn; 1691 double d1 = Math.abs(l1-l); 1692 if (d1 < delta && d1 < dOpt) { 1693 l = l1; 1694 enOpt = en; 1695 dOpt = d1; 1696 } 1697 } 1698 if (enOpt != null) { 1699 projectionSource = enOpt; 1700 } 1701 } 1702 } 1703 projected = new EastNorth(e0+l*pe, n0+l*pn); 1704 return projected; 1705 } 1706 1707 /** 1708 * Disables snapping 1709 */ 1710 public void noSnapNow() { 1711 active = false; 1712 dir2 = null; 1713 projected = null; 1714 labelText = null; 1715 } 1716 1717 public void setBaseSegment(WaySegment seg) { 1718 if (seg == null) return; 1719 segmentPoint1 = seg.getFirstNode().getEastNorth(); 1720 segmentPoint2 = seg.getSecondNode().getEastNorth(); 1721 1722 double hdg = segmentPoint1.heading(segmentPoint2); 1723 hdg = Math.toDegrees(hdg); 1724 if (hdg < 0) { 1725 hdg += 360; 1726 } 1727 if (hdg > 360) { 1728 hdg -= 360; 1729 } 1730 customBaseHeading = hdg; 1731 } 1732 1733 /** 1734 * Enable snapping. 1735 */ 1736 private void enableSnapping() { 1737 snapOn = true; 1738 checkBox.setState(snapOn); 1739 customBaseHeading = -1; 1740 unsetFixedMode(); 1741 } 1742 1743 private void toggleSnapping() { 1744 snapOn = !snapOn; 1745 checkBox.setState(snapOn); 1746 customBaseHeading = -1; 1747 unsetFixedMode(); 1748 } 1749 1750 public void setFixedMode() { 1751 if (active) { 1752 fixed = true; 1753 } 1754 } 1755 1756 public void unsetFixedMode() { 1757 fixed = false; 1758 absoluteFix = false; 1759 lastAngle = 0; 1760 active = false; 1761 } 1762 1763 public boolean isActive() { 1764 return active; 1765 } 1766 1767 public boolean isSnapOn() { 1768 return snapOn; 1769 } 1770 1771 private double getNearestAngle(double angle) { 1772 double bestAngle = DoubleStream.of(snapAngles).boxed() 1773 .min(Comparator.comparing(snapAngle -> getAngleDelta(angle, snapAngle))).orElse(0.0); 1774 if (Math.abs(bestAngle-360) < 1e-3) { 1775 bestAngle = 0; 1776 } 1777 return bestAngle; 1778 } 1779 1780 private double getAngleDelta(double a, double b) { 1781 double delta = Math.abs(a-b); 1782 if (delta > 180) 1783 return 360-delta; 1784 else 1785 return delta; 1786 } 1787 1788 private void unFixOrTurnOff() { 1789 if (absoluteFix) { 1790 unsetFixedMode(); 1791 } else { 1792 toggleSnapping(); 1793 } 1794 } 1795 } 1796 1797 private class SnapChangeAction extends JosmAction { 1798 /** 1799 * Constructs a new {@code SnapChangeAction}. 1800 */ 1801 SnapChangeAction() { 1802 super(tr("Angle snapping"), /* ICON() */ "anglesnap", 1803 tr("Switch angle snapping mode while drawing"), null, false); 1804 putValue("help", ht("/Action/Draw/AngleSnap")); 1805 } 1806 1807 @Override 1808 public void actionPerformed(ActionEvent e) { 1809 if (snapHelper != null) { 1810 snapHelper.toggleSnapping(); 1811 } 1812 } 1813 1814 @Override 1815 protected void updateEnabledState() { 1816 setEnabled(Main.map != null && Main.map.mapMode instanceof DrawAction); 1817 } 1818 } 1819}