source: josm/trunk/src/org/openstreetmap/josm/actions/mapmode/DrawAction.java@ 12346

Last change on this file since 12346 was 12330, checked in by michael2402, 7 years ago

Fix #14854: Run DrawAction selection listener and related UI updates in EDT.

  • Property svn:eol-style set to native
File size: 52.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions.mapmode;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.marktr;
6import static org.openstreetmap.josm.tools.I18n.tr;
7import static org.openstreetmap.josm.tools.I18n.trn;
8
9import java.awt.BasicStroke;
10import java.awt.Color;
11import java.awt.Cursor;
12import java.awt.Graphics2D;
13import java.awt.Point;
14import java.awt.event.ActionEvent;
15import java.awt.event.KeyEvent;
16import java.awt.event.MouseEvent;
17import java.util.ArrayList;
18import java.util.Collection;
19import java.util.Collections;
20import java.util.HashMap;
21import java.util.HashSet;
22import java.util.Iterator;
23import java.util.LinkedList;
24import java.util.List;
25import java.util.Map;
26import java.util.Set;
27
28import javax.swing.AbstractAction;
29import javax.swing.JCheckBoxMenuItem;
30import javax.swing.JMenuItem;
31import javax.swing.JOptionPane;
32
33import org.openstreetmap.josm.Main;
34import org.openstreetmap.josm.actions.JosmAction;
35import org.openstreetmap.josm.command.AddCommand;
36import org.openstreetmap.josm.command.ChangeCommand;
37import org.openstreetmap.josm.command.Command;
38import org.openstreetmap.josm.command.SequenceCommand;
39import org.openstreetmap.josm.data.Bounds;
40import org.openstreetmap.josm.data.coor.EastNorth;
41import org.openstreetmap.josm.data.osm.DataSelectionListener;
42import org.openstreetmap.josm.data.osm.DataSet;
43import org.openstreetmap.josm.data.osm.Node;
44import org.openstreetmap.josm.data.osm.OsmPrimitive;
45import org.openstreetmap.josm.data.osm.Way;
46import org.openstreetmap.josm.data.osm.WaySegment;
47import org.openstreetmap.josm.data.osm.event.SelectionEventManager;
48import org.openstreetmap.josm.data.osm.visitor.paint.ArrowPaintHelper;
49import org.openstreetmap.josm.data.osm.visitor.paint.PaintColors;
50import org.openstreetmap.josm.data.preferences.AbstractToStringProperty;
51import org.openstreetmap.josm.data.preferences.BooleanProperty;
52import org.openstreetmap.josm.data.preferences.CachingProperty;
53import org.openstreetmap.josm.data.preferences.ColorProperty;
54import org.openstreetmap.josm.data.preferences.DoubleProperty;
55import org.openstreetmap.josm.data.preferences.StrokeProperty;
56import org.openstreetmap.josm.gui.MainMenu;
57import org.openstreetmap.josm.gui.MapView;
58import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
59import org.openstreetmap.josm.gui.NavigatableComponent;
60import org.openstreetmap.josm.gui.draw.MapPath2D;
61import org.openstreetmap.josm.gui.layer.Layer;
62import org.openstreetmap.josm.gui.layer.MapViewPaintable;
63import org.openstreetmap.josm.gui.layer.OsmDataLayer;
64import org.openstreetmap.josm.gui.util.KeyPressReleaseListener;
65import org.openstreetmap.josm.gui.util.ModifierListener;
66import org.openstreetmap.josm.tools.Geometry;
67import org.openstreetmap.josm.tools.ImageProvider;
68import org.openstreetmap.josm.tools.Pair;
69import org.openstreetmap.josm.tools.Shortcut;
70import org.openstreetmap.josm.tools.Utils;
71
72/**
73 * Mapmode to add nodes, create and extend ways.
74 */
75public class DrawAction extends MapMode implements MapViewPaintable, DataSelectionListener, KeyPressReleaseListener, ModifierListener {
76
77 /**
78 * If this property is set, the draw action moves the viewport when adding new points.
79 * @since 12182
80 */
81 public static final CachingProperty<Boolean> VIEWPORT_FOLLOWING = new BooleanProperty("draw.viewport.following", false).cached();
82
83 private static final Color ORANGE_TRANSPARENT = new Color(Color.ORANGE.getRed(), Color.ORANGE.getGreen(), Color.ORANGE.getBlue(), 128);
84
85 private static final ArrowPaintHelper START_WAY_INDICATOR = new ArrowPaintHelper(Utils.toRadians(90), 8);
86
87 static final CachingProperty<Boolean> USE_REPEATED_SHORTCUT
88 = new BooleanProperty("draw.anglesnap.toggleOnRepeatedA", true).cached();
89 static final CachingProperty<BasicStroke> RUBBER_LINE_STROKE
90 = new StrokeProperty("draw.stroke.helper-line", "3").cached();
91
92 static final CachingProperty<BasicStroke> HIGHLIGHT_STROKE
93 = new StrokeProperty("draw.anglesnap.stroke.highlight", "10").cached();
94 static final CachingProperty<BasicStroke> HELPER_STROKE
95 = new StrokeProperty("draw.anglesnap.stroke.helper", "1 4").cached();
96
97 static final CachingProperty<Double> SNAP_ANGLE_TOLERANCE
98 = new DoubleProperty("draw.anglesnap.tolerance", 5.0).cached();
99 static final CachingProperty<Boolean> DRAW_CONSTRUCTION_GEOMETRY
100 = new BooleanProperty("draw.anglesnap.drawConstructionGeometry", true).cached();
101 static final CachingProperty<Boolean> SHOW_PROJECTED_POINT
102 = new BooleanProperty("draw.anglesnap.drawProjectedPoint", true).cached();
103 static final CachingProperty<Boolean> SNAP_TO_PROJECTIONS
104 = new BooleanProperty("draw.anglesnap.projectionsnap", true).cached();
105
106 static final CachingProperty<Boolean> SHOW_ANGLE
107 = new BooleanProperty("draw.anglesnap.showAngle", true).cached();
108
109 static final CachingProperty<Color> SNAP_HELPER_COLOR
110 = new ColorProperty(marktr("draw angle snap"), Color.ORANGE).cached();
111
112 static final CachingProperty<Color> HIGHLIGHT_COLOR
113 = new ColorProperty(marktr("draw angle snap highlight"), ORANGE_TRANSPARENT).cached();
114
115 static final AbstractToStringProperty<Color> RUBBER_LINE_COLOR
116 = PaintColors.SELECTED.getProperty().getChildColor(marktr("helper line"));
117
118 static final CachingProperty<Boolean> DRAW_HELPER_LINE
119 = new BooleanProperty("draw.helper-line", true).cached();
120 static final CachingProperty<Boolean> DRAW_TARGET_HIGHLIGHT
121 = new BooleanProperty("draw.target-highlight", true).cached();
122 static final CachingProperty<Double> SNAP_TO_INTERSECTION_THRESHOLD
123 = new DoubleProperty("edit.snap-intersection-threshold", 10).cached();
124
125 private final Cursor cursorJoinNode;
126 private final Cursor cursorJoinWay;
127
128 private transient Node lastUsedNode;
129 private double toleranceMultiplier;
130
131 private transient Node mouseOnExistingNode;
132 private transient Set<Way> mouseOnExistingWays = new HashSet<>();
133 // old highlights store which primitives are currently highlighted. This
134 // is true, even if target highlighting is disabled since the status bar
135 // derives its information from this list as well.
136 private transient Set<OsmPrimitive> oldHighlights = new HashSet<>();
137 // new highlights contains a list of primitives that should be highlighted
138 // but haven't been so far. The idea is to compare old and new and only
139 // repaint if there are changes.
140 private transient Set<OsmPrimitive> newHighlights = new HashSet<>();
141 private boolean wayIsFinished;
142 private Point mousePos;
143 private Point oldMousePos;
144
145 private transient Node currentBaseNode;
146 private transient Node previousNode;
147 private EastNorth currentMouseEastNorth;
148
149 private final transient DrawSnapHelper snapHelper = new DrawSnapHelper(this);
150
151 private final transient Shortcut backspaceShortcut;
152 private final BackSpaceAction backspaceAction;
153 private final transient Shortcut snappingShortcut;
154 private boolean ignoreNextKeyRelease;
155
156 private final SnapChangeAction snapChangeAction;
157 private final JCheckBoxMenuItem snapCheckboxMenuItem;
158 private static final BasicStroke BASIC_STROKE = new BasicStroke(1);
159
160 private Point rightClickPressPos;
161
162 /**
163 * Constructs a new {@code DrawAction}.
164 * @since 11713
165 */
166 public DrawAction() {
167 super(tr("Draw"), "node/autonode", tr("Draw nodes"),
168 Shortcut.registerShortcut("mapmode:draw", tr("Mode: {0}", tr("Draw")), KeyEvent.VK_A, Shortcut.DIRECT),
169 ImageProvider.getCursor("crosshair", null));
170
171 snappingShortcut = Shortcut.registerShortcut("mapmode:drawanglesnapping",
172 tr("Mode: Draw Angle snapping"), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE);
173 snapChangeAction = new SnapChangeAction();
174 snapCheckboxMenuItem = addMenuItem();
175 snapHelper.setMenuCheckBox(snapCheckboxMenuItem);
176 backspaceShortcut = Shortcut.registerShortcut("mapmode:backspace",
177 tr("Backspace in Add mode"), KeyEvent.VK_BACK_SPACE, Shortcut.DIRECT);
178 backspaceAction = new BackSpaceAction();
179 cursorJoinNode = ImageProvider.getCursor("crosshair", "joinnode");
180 cursorJoinWay = ImageProvider.getCursor("crosshair", "joinway");
181
182 snapHelper.init();
183 }
184
185 private JCheckBoxMenuItem addMenuItem() {
186 int n = Main.main.menu.editMenu.getItemCount();
187 for (int i = n-1; i > 0; i--) {
188 JMenuItem item = Main.main.menu.editMenu.getItem(i);
189 if (item != null && item.getAction() != null && item.getAction() instanceof SnapChangeAction) {
190 Main.main.menu.editMenu.remove(i);
191 }
192 }
193 return MainMenu.addWithCheckbox(Main.main.menu.editMenu, snapChangeAction, MainMenu.WINDOW_MENU_GROUP.VOLATILE);
194 }
195
196 /**
197 * Checks if a map redraw is required and does so if needed. Also updates the status bar.
198 * @return true if a repaint is needed
199 */
200 private boolean redrawIfRequired() {
201 updateStatusLine();
202 // repaint required if the helper line is active.
203 boolean needsRepaint = DRAW_HELPER_LINE.get() && !wayIsFinished;
204 if (DRAW_TARGET_HIGHLIGHT.get()) {
205 // move newHighlights to oldHighlights; only update changed primitives
206 for (OsmPrimitive x : newHighlights) {
207 if (oldHighlights.contains(x)) {
208 continue;
209 }
210 x.setHighlighted(true);
211 needsRepaint = true;
212 }
213 oldHighlights.removeAll(newHighlights);
214 for (OsmPrimitive x : oldHighlights) {
215 x.setHighlighted(false);
216 needsRepaint = true;
217 }
218 }
219 // required in order to print correct help text
220 oldHighlights = newHighlights;
221
222 if (!needsRepaint && !DRAW_TARGET_HIGHLIGHT.get())
223 return false;
224
225 // update selection to reflect which way being modified
226 OsmDataLayer editLayer = getLayerManager().getEditLayer();
227 if (editLayer != null && getCurrentBaseNode() != null && !editLayer.data.selectionEmpty()) {
228 DataSet currentDataSet = editLayer.data;
229 Way continueFrom = getWayForNode(getCurrentBaseNode());
230 if (alt && continueFrom != null && (!getCurrentBaseNode().isSelected() || continueFrom.isSelected())) {
231 addRemoveSelection(currentDataSet, getCurrentBaseNode(), continueFrom);
232 needsRepaint = true;
233 } else if (!alt && continueFrom != null && !continueFrom.isSelected()) {
234 currentDataSet.addSelected(continueFrom);
235 needsRepaint = true;
236 }
237 }
238
239 if (needsRepaint && editLayer != null) {
240 editLayer.invalidate();
241 }
242 return needsRepaint;
243 }
244
245 private static void addRemoveSelection(DataSet ds, OsmPrimitive toAdd, OsmPrimitive toRemove) {
246 ds.beginUpdate(); // to prevent the selection listener to screw around with the state
247 try {
248 ds.addSelected(toAdd);
249 ds.clearSelection(toRemove);
250 } finally {
251 ds.endUpdate();
252 }
253 }
254
255 @Override
256 public void enterMode() {
257 if (!isEnabled())
258 return;
259 super.enterMode();
260 readPreferences();
261
262 // determine if selection is suitable to continue drawing. If it
263 // isn't, set wayIsFinished to true to avoid superfluous repaints.
264 determineCurrentBaseNodeAndPreviousNode(getLayerManager().getEditDataSet().getSelected());
265 wayIsFinished = getCurrentBaseNode() == null;
266
267 toleranceMultiplier = 0.01 * NavigatableComponent.PROP_SNAP_DISTANCE.get();
268
269 snapHelper.init();
270 snapCheckboxMenuItem.getAction().setEnabled(true);
271
272 Main.map.statusLine.getAnglePanel().addMouseListener(snapHelper.anglePopupListener);
273 Main.registerActionShortcut(backspaceAction, backspaceShortcut);
274
275 Main.map.mapView.addMouseListener(this);
276 Main.map.mapView.addMouseMotionListener(this);
277 Main.map.mapView.addTemporaryLayer(this);
278 SelectionEventManager.getInstance().addSelectionListenerForEdt(this);
279
280 Main.map.keyDetector.addKeyListener(this);
281 Main.map.keyDetector.addModifierListener(this);
282 ignoreNextKeyRelease = true;
283 }
284
285 @Override
286 public void exitMode() {
287 super.exitMode();
288 Main.map.mapView.removeMouseListener(this);
289 Main.map.mapView.removeMouseMotionListener(this);
290 Main.map.mapView.removeTemporaryLayer(this);
291 SelectionEventManager.getInstance().removeSelectionListener(this);
292 Main.unregisterActionShortcut(backspaceAction, backspaceShortcut);
293 snapHelper.unsetFixedMode();
294 snapCheckboxMenuItem.getAction().setEnabled(false);
295
296 Main.map.statusLine.getAnglePanel().removeMouseListener(snapHelper.anglePopupListener);
297 Main.map.statusLine.activateAnglePanel(false);
298
299 removeHighlighting();
300 Main.map.keyDetector.removeKeyListener(this);
301 Main.map.keyDetector.removeModifierListener(this);
302 }
303
304 /**
305 * redraw to (possibly) get rid of helper line if selection changes.
306 */
307 @Override
308 public void modifiersChanged(int modifiers) {
309 if (!Main.isDisplayingMapView() || !Main.map.mapView.isActiveLayerDrawable())
310 return;
311 updateKeyModifiers(modifiers);
312 computeHelperLine();
313 addHighlighting();
314 }
315
316 @Override
317 public void doKeyPressed(KeyEvent e) {
318 if (!snappingShortcut.isEvent(e) && !(USE_REPEATED_SHORTCUT.get() && getShortcut().isEvent(e)))
319 return;
320 snapHelper.setFixedMode();
321 computeHelperLine();
322 redrawIfRequired();
323 }
324
325 @Override
326 public void doKeyReleased(KeyEvent e) {
327 if (!snappingShortcut.isEvent(e) && !(USE_REPEATED_SHORTCUT.get() && getShortcut().isEvent(e)))
328 return;
329 if (ignoreNextKeyRelease) {
330 ignoreNextKeyRelease = false;
331 return;
332 }
333 snapHelper.unFixOrTurnOff();
334 computeHelperLine();
335 redrawIfRequired();
336 }
337
338 /**
339 * redraw to (possibly) get rid of helper line if selection changes.
340 */
341 @Override
342 public void selectionChanged(SelectionChangeEvent event) {
343 if (!Main.map.mapView.isActiveLayerDrawable())
344 return;
345 computeHelperLine();
346 addHighlighting();
347 }
348
349 private void tryAgain(MouseEvent e) {
350 getLayerManager().getEditDataSet().setSelected();
351 mouseReleased(e);
352 }
353
354 /**
355 * This function should be called when the user wishes to finish his current draw action.
356 * If Potlatch Style is enabled, it will switch to select tool, otherwise simply disable
357 * the helper line until the user chooses to draw something else.
358 */
359 private void finishDrawing() {
360 lastUsedNode = null;
361 wayIsFinished = true;
362 Main.map.selectSelectTool(true);
363 snapHelper.noSnapNow();
364
365 // Redraw to remove the helper line stub
366 computeHelperLine();
367 removeHighlighting();
368 }
369
370 @Override
371 public void mousePressed(MouseEvent e) {
372 if (e.getButton() == MouseEvent.BUTTON3) {
373 rightClickPressPos = e.getPoint();
374 }
375 }
376
377 /**
378 * If user clicked with the left button, add a node at the current mouse
379 * position.
380 *
381 * If in nodeway mode, insert the node into the way.
382 */
383 @Override
384 public void mouseReleased(MouseEvent e) {
385 if (e.getButton() == MouseEvent.BUTTON3) {
386 Point curMousePos = e.getPoint();
387 if (curMousePos.equals(rightClickPressPos)) {
388 tryToSetBaseSegmentForAngleSnap();
389 }
390 return;
391 }
392 if (e.getButton() != MouseEvent.BUTTON1)
393 return;
394 if (!Main.map.mapView.isActiveLayerDrawable())
395 return;
396 // request focus in order to enable the expected keyboard shortcuts
397 //
398 Main.map.mapView.requestFocus();
399
400 if (e.getClickCount() > 1 && mousePos != null && mousePos.equals(oldMousePos)) {
401 // A double click equals "user clicked last node again, finish way"
402 // Change draw tool only if mouse position is nearly the same, as
403 // otherwise fast clicks will count as a double click
404 finishDrawing();
405 return;
406 }
407 oldMousePos = mousePos;
408
409 // we copy ctrl/alt/shift from the event just in case our global
410 // keyDetector didn't make it through the security manager. Unclear
411 // if that can ever happen but better be safe.
412 updateKeyModifiers(e);
413 mousePos = e.getPoint();
414
415 DataSet ds = getLayerManager().getEditDataSet();
416 Collection<OsmPrimitive> selection = new ArrayList<>(ds.getSelected());
417
418 boolean newNode = false;
419 Node n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive::isSelectable);
420 if (ctrl) {
421 Iterator<Way> it = ds.getSelectedWays().iterator();
422 if (it.hasNext()) {
423 // ctrl-click on node of selected way = reuse node despite of ctrl
424 if (!it.next().containsNode(n)) n = null;
425 } else {
426 n = null; // ctrl-click + no selected way = new node
427 }
428 }
429
430 if (n != null && !snapHelper.isActive()) {
431 // user clicked on node
432 if (selection.isEmpty() || wayIsFinished) {
433 // select the clicked node and do nothing else
434 // (this is just a convenience option so that people don't
435 // have to switch modes)
436
437 ds.setSelected(n);
438 // If we extend/continue an existing way, select it already now to make it obvious
439 Way continueFrom = getWayForNode(n);
440 if (continueFrom != null) {
441 ds.addSelected(continueFrom);
442 }
443
444 // The user explicitly selected a node, so let him continue drawing
445 wayIsFinished = false;
446 return;
447 }
448 } else {
449 EastNorth newEN;
450 if (n != null) {
451 EastNorth foundPoint = n.getEastNorth();
452 // project found node to snapping line
453 newEN = snapHelper.getSnapPoint(foundPoint);
454 // do not add new node if there is some node within snapping distance
455 double tolerance = Main.map.mapView.getDist100Pixel() * toleranceMultiplier;
456 if (foundPoint.distance(newEN) > tolerance) {
457 n = new Node(newEN); // point != projected, so we create new node
458 newNode = true;
459 }
460 } else { // n==null, no node found in clicked area
461 EastNorth mouseEN = Main.map.mapView.getEastNorth(e.getX(), e.getY());
462 newEN = snapHelper.isSnapOn() ? snapHelper.getSnapPoint(mouseEN) : mouseEN;
463 n = new Node(newEN); //create node at clicked point
464 newNode = true;
465 }
466 snapHelper.unsetFixedMode();
467 }
468
469 Collection<Command> cmds = new LinkedList<>();
470 Collection<OsmPrimitive> newSelection = new LinkedList<>(ds.getSelected());
471 List<Way> reuseWays = new ArrayList<>();
472 List<Way> replacedWays = new ArrayList<>();
473
474 if (newNode) {
475 if (n.getCoor().isOutSideWorld()) {
476 JOptionPane.showMessageDialog(
477 Main.parent,
478 tr("Cannot add a node outside of the world."),
479 tr("Warning"),
480 JOptionPane.WARNING_MESSAGE
481 );
482 return;
483 }
484 cmds.add(new AddCommand(n));
485
486 if (!ctrl) {
487 // Insert the node into all the nearby way segments
488 List<WaySegment> wss = Main.map.mapView.getNearestWaySegments(
489 Main.map.mapView.getPoint(n), OsmPrimitive::isSelectable);
490 if (snapHelper.isActive()) {
491 tryToMoveNodeOnIntersection(wss, n);
492 }
493 insertNodeIntoAllNearbySegments(wss, n, newSelection, cmds, replacedWays, reuseWays);
494 }
495 }
496 // now "n" is newly created or reused node that shoud be added to some way
497
498 // This part decides whether or not a "segment" (i.e. a connection) is made to an existing node.
499
500 // For a connection to be made, the user must either have a node selected (connection
501 // is made to that node), or he must have a way selected *and* one of the endpoints
502 // of that way must be the last used node (connection is made to last used node), or
503 // he must have a way and a node selected (connection is made to the selected node).
504
505 // If the above does not apply, the selection is cleared and a new try is started
506
507 boolean extendedWay = false;
508 boolean wayIsFinishedTemp = wayIsFinished;
509 wayIsFinished = false;
510
511 // don't draw lines if shift is held
512 if (!selection.isEmpty() && !shift) {
513 Node selectedNode = null;
514 Way selectedWay = null;
515
516 for (OsmPrimitive p : selection) {
517 if (p instanceof Node) {
518 if (selectedNode != null) {
519 // Too many nodes selected to do something useful
520 tryAgain(e);
521 return;
522 }
523 selectedNode = (Node) p;
524 } else if (p instanceof Way) {
525 if (selectedWay != null) {
526 // Too many ways selected to do something useful
527 tryAgain(e);
528 return;
529 }
530 selectedWay = (Way) p;
531 }
532 }
533
534 // the node from which we make a connection
535 Node n0 = findNodeToContinueFrom(selectedNode, selectedWay);
536 // We have a selection but it isn't suitable. Try again.
537 if (n0 == null) {
538 tryAgain(e);
539 return;
540 }
541 if (!wayIsFinishedTemp) {
542 if (isSelfContainedWay(selectedWay, n0, n))
543 return;
544
545 // User clicked last node again, finish way
546 if (n0 == n) {
547 finishDrawing();
548 return;
549 }
550
551 // Ok we know now that we'll insert a line segment, but will it connect to an
552 // existing way or make a new way of its own? The "alt" modifier means that the
553 // user wants a new way.
554 Way way = alt ? null : (selectedWay != null ? selectedWay : getWayForNode(n0));
555 Way wayToSelect;
556
557 // Don't allow creation of self-overlapping ways
558 if (way != null) {
559 int nodeCount = 0;
560 for (Node p : way.getNodes()) {
561 if (p.equals(n0)) {
562 nodeCount++;
563 }
564 }
565 if (nodeCount > 1) {
566 way = null;
567 }
568 }
569
570 if (way == null) {
571 way = new Way();
572 way.addNode(n0);
573 cmds.add(new AddCommand(way));
574 wayToSelect = way;
575 } else {
576 int i;
577 if ((i = replacedWays.indexOf(way)) != -1) {
578 way = reuseWays.get(i);
579 wayToSelect = way;
580 } else {
581 wayToSelect = way;
582 Way wnew = new Way(way);
583 cmds.add(new ChangeCommand(way, wnew));
584 way = wnew;
585 }
586 }
587
588 // Connected to a node that's already in the way
589 if (way.containsNode(n)) {
590 wayIsFinished = true;
591 selection.clear();
592 }
593
594 // Add new node to way
595 if (way.getNode(way.getNodesCount() - 1) == n0) {
596 way.addNode(n);
597 } else {
598 way.addNode(0, n);
599 }
600
601 extendedWay = true;
602 newSelection.clear();
603 newSelection.add(wayToSelect);
604 }
605 }
606 if (!extendedWay && !newNode) {
607 return; // We didn't do anything.
608 }
609
610 String title = getTitle(newNode, n, newSelection, reuseWays, extendedWay);
611
612 Command c = new SequenceCommand(title, cmds);
613
614 Main.main.undoRedo.add(c);
615 if (!wayIsFinished) {
616 lastUsedNode = n;
617 }
618
619 ds.setSelected(newSelection);
620
621 // "viewport following" mode for tracing long features
622 // from aerial imagery or GPS tracks.
623 if (VIEWPORT_FOLLOWING.get()) {
624 Main.map.mapView.smoothScrollTo(n.getEastNorth());
625 }
626 computeHelperLine();
627 removeHighlighting();
628 }
629
630 private static String getTitle(boolean newNode, Node n, Collection<OsmPrimitive> newSelection, List<Way> reuseWays,
631 boolean extendedWay) {
632 String title;
633 if (!extendedWay) {
634 if (reuseWays.isEmpty()) {
635 title = tr("Add node");
636 } else {
637 title = tr("Add node into way");
638 for (Way w : reuseWays) {
639 newSelection.remove(w);
640 }
641 }
642 newSelection.clear();
643 newSelection.add(n);
644 } else if (!newNode) {
645 title = tr("Connect existing way to node");
646 } else if (reuseWays.isEmpty()) {
647 title = tr("Add a new node to an existing way");
648 } else {
649 title = tr("Add node into way and connect");
650 }
651 return title;
652 }
653
654 private void insertNodeIntoAllNearbySegments(List<WaySegment> wss, Node n, Collection<OsmPrimitive> newSelection,
655 Collection<Command> cmds, List<Way> replacedWays, List<Way> reuseWays) {
656 Map<Way, List<Integer>> insertPoints = new HashMap<>();
657 for (WaySegment ws : wss) {
658 List<Integer> is;
659 if (insertPoints.containsKey(ws.way)) {
660 is = insertPoints.get(ws.way);
661 } else {
662 is = new ArrayList<>();
663 insertPoints.put(ws.way, is);
664 }
665
666 is.add(ws.lowerIndex);
667 }
668
669 Set<Pair<Node, Node>> segSet = new HashSet<>();
670
671 for (Map.Entry<Way, List<Integer>> insertPoint : insertPoints.entrySet()) {
672 Way w = insertPoint.getKey();
673 List<Integer> is = insertPoint.getValue();
674
675 Way wnew = new Way(w);
676
677 pruneSuccsAndReverse(is);
678 for (int i : is) {
679 segSet.add(Pair.sort(new Pair<>(w.getNode(i), w.getNode(i+1))));
680 wnew.addNode(i + 1, n);
681 }
682
683 // If ALT is pressed, a new way should be created and that new way should get
684 // selected. This works everytime unless the ways the nodes get inserted into
685 // are already selected. This is the case when creating a self-overlapping way
686 // but pressing ALT prevents this. Therefore we must de-select the way manually
687 // here so /only/ the new way will be selected after this method finishes.
688 if (alt) {
689 newSelection.add(insertPoint.getKey());
690 }
691
692 cmds.add(new ChangeCommand(insertPoint.getKey(), wnew));
693 replacedWays.add(insertPoint.getKey());
694 reuseWays.add(wnew);
695 }
696
697 adjustNode(segSet, n);
698 }
699
700 /**
701 * Prevent creation of ways that look like this: &lt;----&gt;
702 * This happens if users want to draw a no-exit-sideway from the main way like this:
703 * ^
704 * |&lt;----&gt;
705 * |
706 * The solution isn't ideal because the main way will end in the side way, which is bad for
707 * navigation software ("drive straight on") but at least easier to fix. Maybe users will fix
708 * it on their own, too. At least it's better than producing an error.
709 *
710 * @param selectedWay the way to check
711 * @param currentNode the current node (i.e. the one the connection will be made from)
712 * @param targetNode the target node (i.e. the one the connection will be made to)
713 * @return {@code true} if this would create a selfcontaining way, {@code false} otherwise.
714 */
715 private boolean isSelfContainedWay(Way selectedWay, Node currentNode, Node targetNode) {
716 if (selectedWay != null) {
717 int posn0 = selectedWay.getNodes().indexOf(currentNode);
718 // CHECKSTYLE.OFF: SingleSpaceSeparator
719 if ((posn0 != -1 && // n0 is part of way
720 (posn0 >= 1 && targetNode.equals(selectedWay.getNode(posn0-1)))) || // previous node
721 (posn0 < selectedWay.getNodesCount()-1 && targetNode.equals(selectedWay.getNode(posn0+1)))) { // next node
722 getLayerManager().getEditDataSet().setSelected(targetNode);
723 lastUsedNode = targetNode;
724 return true;
725 }
726 // CHECKSTYLE.ON: SingleSpaceSeparator
727 }
728
729 return false;
730 }
731
732 /**
733 * Finds a node to continue drawing from. Decision is based upon given node and way.
734 * @param selectedNode Currently selected node, may be null
735 * @param selectedWay Currently selected way, may be null
736 * @return Node if a suitable node is found, null otherwise
737 */
738 private Node findNodeToContinueFrom(Node selectedNode, Way selectedWay) {
739 // No nodes or ways have been selected, this occurs when a relation
740 // has been selected or the selection is empty
741 if (selectedNode == null && selectedWay == null)
742 return null;
743
744 if (selectedNode == null) {
745 if (selectedWay.isFirstLastNode(lastUsedNode))
746 return lastUsedNode;
747
748 // We have a way selected, but no suitable node to continue from. Start anew.
749 return null;
750 }
751
752 if (selectedWay == null)
753 return selectedNode;
754
755 if (selectedWay.isFirstLastNode(selectedNode))
756 return selectedNode;
757
758 // We have a way and node selected, but it's not at the start/end of the way. Start anew.
759 return null;
760 }
761
762 @Override
763 public void mouseDragged(MouseEvent e) {
764 mouseMoved(e);
765 }
766
767 @Override
768 public void mouseMoved(MouseEvent e) {
769 if (!Main.map.mapView.isActiveLayerDrawable())
770 return;
771
772 // we copy ctrl/alt/shift from the event just in case our global
773 // keyDetector didn't make it through the security manager. Unclear
774 // if that can ever happen but better be safe.
775 updateKeyModifiers(e);
776 mousePos = e.getPoint();
777 if (snapHelper.isSnapOn() && ctrl)
778 tryToSetBaseSegmentForAngleSnap();
779
780 computeHelperLine();
781 addHighlighting();
782 }
783
784 /**
785 * This method is used to detect segment under mouse and use it as reference for angle snapping
786 */
787 private void tryToSetBaseSegmentForAngleSnap() {
788 WaySegment seg = Main.map.mapView.getNearestWaySegment(mousePos, OsmPrimitive::isSelectable);
789 if (seg != null) {
790 snapHelper.setBaseSegment(seg);
791 }
792 }
793
794 /**
795 * This method prepares data required for painting the "helper line" from
796 * the last used position to the mouse cursor. It duplicates some code from
797 * mouseReleased() (FIXME).
798 */
799 private void computeHelperLine() {
800 if (mousePos == null) {
801 // Don't draw the line.
802 currentMouseEastNorth = null;
803 currentBaseNode = null;
804 return;
805 }
806
807 Collection<OsmPrimitive> selection = getLayerManager().getEditDataSet().getSelected();
808
809 MapView mv = Main.map.mapView;
810 Node currentMouseNode = null;
811 mouseOnExistingNode = null;
812 mouseOnExistingWays = new HashSet<>();
813
814 showStatusInfo(-1, -1, -1, snapHelper.isSnapOn());
815
816 if (!ctrl && mousePos != null) {
817 currentMouseNode = mv.getNearestNode(mousePos, OsmPrimitive::isSelectable);
818 }
819
820 // We need this for highlighting and we'll only do so if we actually want to re-use
821 // *and* there is no node nearby (because nodes beat ways when re-using)
822 if (!ctrl && currentMouseNode == null) {
823 List<WaySegment> wss = mv.getNearestWaySegments(mousePos, OsmPrimitive::isSelectable);
824 for (WaySegment ws : wss) {
825 mouseOnExistingWays.add(ws.way);
826 }
827 }
828
829 if (currentMouseNode != null) {
830 // user clicked on node
831 if (selection.isEmpty()) return;
832 currentMouseEastNorth = currentMouseNode.getEastNorth();
833 mouseOnExistingNode = currentMouseNode;
834 } else {
835 // no node found in clicked area
836 currentMouseEastNorth = mv.getEastNorth(mousePos.x, mousePos.y);
837 }
838
839 determineCurrentBaseNodeAndPreviousNode(selection);
840 if (previousNode == null) {
841 snapHelper.noSnapNow();
842 }
843
844 if (getCurrentBaseNode() == null || getCurrentBaseNode() == currentMouseNode)
845 return; // Don't create zero length way segments.
846
847
848 double curHdg = Utils.toDegrees(getCurrentBaseNode().getEastNorth()
849 .heading(currentMouseEastNorth));
850 double baseHdg = -1;
851 if (previousNode != null) {
852 EastNorth en = previousNode.getEastNorth();
853 if (en != null) {
854 baseHdg = Utils.toDegrees(en.heading(getCurrentBaseNode().getEastNorth()));
855 }
856 }
857
858 snapHelper.checkAngleSnapping(currentMouseEastNorth, baseHdg, curHdg);
859
860 // status bar was filled by snapHelper
861 }
862
863 static void showStatusInfo(double angle, double hdg, double distance, boolean activeFlag) {
864 Main.map.statusLine.setAngle(angle);
865 Main.map.statusLine.activateAnglePanel(activeFlag);
866 Main.map.statusLine.setHeading(hdg);
867 Main.map.statusLine.setDist(distance);
868 }
869
870 /**
871 * Helper function that sets fields currentBaseNode and previousNode
872 * @param selection
873 * uses also lastUsedNode field
874 */
875 private void determineCurrentBaseNodeAndPreviousNode(Collection<OsmPrimitive> selection) {
876 Node selectedNode = null;
877 Way selectedWay = null;
878 for (OsmPrimitive p : selection) {
879 if (p instanceof Node) {
880 if (selectedNode != null)
881 return;
882 selectedNode = (Node) p;
883 } else if (p instanceof Way) {
884 if (selectedWay != null)
885 return;
886 selectedWay = (Way) p;
887 }
888 }
889 // we are here, if not more than 1 way or node is selected,
890
891 // the node from which we make a connection
892 currentBaseNode = null;
893 previousNode = null;
894
895 // Try to find an open way to measure angle from it. The way is not to be continued!
896 // warning: may result in changes of currentBaseNode and previousNode
897 // please remove if bugs arise
898 if (selectedWay == null && selectedNode != null) {
899 for (OsmPrimitive p: selectedNode.getReferrers()) {
900 if (p.isUsable() && p instanceof Way && ((Way) p).isFirstLastNode(selectedNode)) {
901 if (selectedWay != null) { // two uncontinued ways, nothing to take as reference
902 selectedWay = null;
903 break;
904 } else {
905 // set us ~continue this way (measure angle from it)
906 selectedWay = (Way) p;
907 }
908 }
909 }
910 }
911
912 if (selectedNode == null) {
913 if (selectedWay == null)
914 return;
915 continueWayFromNode(selectedWay, lastUsedNode);
916 } else if (selectedWay == null) {
917 currentBaseNode = selectedNode;
918 } else if (!selectedWay.isDeleted()) { // fix #7118
919 continueWayFromNode(selectedWay, selectedNode);
920 }
921 }
922
923 /**
924 * if one of the ends of {@code way} is given {@code node},
925 * then set currentBaseNode = node and previousNode = adjacent node of way
926 * @param way way to continue
927 * @param node starting node
928 */
929 private void continueWayFromNode(Way way, Node node) {
930 int n = way.getNodesCount();
931 if (node == way.firstNode()) {
932 currentBaseNode = node;
933 if (n > 1) previousNode = way.getNode(1);
934 } else if (node == way.lastNode()) {
935 currentBaseNode = node;
936 if (n > 1) previousNode = way.getNode(n-2);
937 }
938 }
939
940 /**
941 * Repaint on mouse exit so that the helper line goes away.
942 */
943 @Override
944 public void mouseExited(MouseEvent e) {
945 OsmDataLayer editLayer = Main.getLayerManager().getEditLayer();
946 if (editLayer == null)
947 return;
948 mousePos = e.getPoint();
949 snapHelper.noSnapNow();
950 boolean repaintIssued = removeHighlighting();
951 // force repaint in case snapHelper needs one. If removeHighlighting
952 // caused one already, don't do it again.
953 if (!repaintIssued) {
954 editLayer.invalidate();
955 }
956 }
957
958 /**
959 * @param n node
960 * @return If the node is the end of exactly one way, return this.
961 * <code>null</code> otherwise.
962 */
963 public static Way getWayForNode(Node n) {
964 Way way = null;
965 for (Way w : Utils.filteredCollection(n.getReferrers(), Way.class)) {
966 if (!w.isUsable() || w.getNodesCount() < 1) {
967 continue;
968 }
969 Node firstNode = w.getNode(0);
970 Node lastNode = w.getNode(w.getNodesCount() - 1);
971 if ((firstNode == n || lastNode == n) && (firstNode != lastNode)) {
972 if (way != null)
973 return null;
974 way = w;
975 }
976 }
977 return way;
978 }
979
980 /**
981 * Replies the current base node, after having checked it is still usable (see #11105).
982 * @return the current base node (can be null). If not-null, it's guaranteed the node is usable
983 */
984 public Node getCurrentBaseNode() {
985 if (currentBaseNode != null && (currentBaseNode.getDataSet() == null || !currentBaseNode.isUsable())) {
986 currentBaseNode = null;
987 }
988 return currentBaseNode;
989 }
990
991 private static void pruneSuccsAndReverse(List<Integer> is) {
992 Set<Integer> is2 = new HashSet<>();
993 for (int i : is) {
994 if (!is2.contains(i - 1) && !is2.contains(i + 1)) {
995 is2.add(i);
996 }
997 }
998 is.clear();
999 is.addAll(is2);
1000 Collections.sort(is);
1001 Collections.reverse(is);
1002 }
1003
1004 /**
1005 * Adjusts the position of a node to lie on a segment (or a segment intersection).
1006 *
1007 * If one or more than two segments are passed, the node is adjusted
1008 * to lie on the first segment that is passed.
1009 *
1010 * If two segments are passed, the node is adjusted to be at their intersection.
1011 *
1012 * No action is taken if no segments are passed.
1013 *
1014 * @param segs the segments to use as a reference when adjusting
1015 * @param n the node to adjust
1016 */
1017 private static void adjustNode(Collection<Pair<Node, Node>> segs, Node n) {
1018 switch (segs.size()) {
1019 case 0:
1020 return;
1021 case 2:
1022 adjustNodeTwoSegments(segs, n);
1023 break;
1024 default:
1025 adjustNodeDefault(segs, n);
1026 }
1027 }
1028
1029 private static void adjustNodeTwoSegments(Collection<Pair<Node, Node>> segs, Node n) {
1030 // This computes the intersection between the two segments and adjusts the node position.
1031 Iterator<Pair<Node, Node>> i = segs.iterator();
1032 Pair<Node, Node> seg = i.next();
1033 EastNorth pA = seg.a.getEastNorth();
1034 EastNorth pB = seg.b.getEastNorth();
1035 seg = i.next();
1036 EastNorth pC = seg.a.getEastNorth();
1037 EastNorth pD = seg.b.getEastNorth();
1038
1039 double u = det(pB.east() - pA.east(), pB.north() - pA.north(), pC.east() - pD.east(), pC.north() - pD.north());
1040
1041 // Check for parallel segments and do nothing if they are
1042 // In practice this will probably only happen when a way has been duplicated
1043
1044 if (u == 0)
1045 return;
1046
1047 // q is a number between 0 and 1
1048 // It is the point in the segment where the intersection occurs
1049 // if the segment is scaled to length 1
1050
1051 double q = det(pB.north() - pC.north(), pB.east() - pC.east(), pD.north() - pC.north(), pD.east() - pC.east()) / u;
1052 EastNorth intersection = new EastNorth(
1053 pB.east() + q * (pA.east() - pB.east()),
1054 pB.north() + q * (pA.north() - pB.north()));
1055
1056
1057 // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise
1058 // fall through to default action.
1059 // (for semi-parallel lines, intersection might be miles away!)
1060 if (Main.map.mapView.getPoint2D(n).distance(Main.map.mapView.getPoint2D(intersection)) < SNAP_TO_INTERSECTION_THRESHOLD.get()) {
1061 n.setEastNorth(intersection);
1062 return;
1063 }
1064
1065 adjustNodeDefault(segs, n);
1066 }
1067
1068 private static void adjustNodeDefault(Collection<Pair<Node, Node>> segs, Node n) {
1069 EastNorth p = n.getEastNorth();
1070 Pair<Node, Node> seg = segs.iterator().next();
1071 EastNorth pA = seg.a.getEastNorth();
1072 EastNorth pB = seg.b.getEastNorth();
1073 double a = p.distanceSq(pB);
1074 double b = p.distanceSq(pA);
1075 double c = pA.distanceSq(pB);
1076 double q = (a - b + c) / (2*c);
1077 n.setEastNorth(new EastNorth(pB.east() + q * (pA.east() - pB.east()), pB.north() + q * (pA.north() - pB.north())));
1078 }
1079
1080 // helper for adjustNode
1081 static double det(double a, double b, double c, double d) {
1082 return a * d - b * c;
1083 }
1084
1085 private void tryToMoveNodeOnIntersection(List<WaySegment> wss, Node n) {
1086 if (wss.isEmpty())
1087 return;
1088 WaySegment ws = wss.get(0);
1089 EastNorth p1 = ws.getFirstNode().getEastNorth();
1090 EastNorth p2 = ws.getSecondNode().getEastNorth();
1091 if (snapHelper.dir2 != null && getCurrentBaseNode() != null) {
1092 EastNorth xPoint = Geometry.getSegmentSegmentIntersection(p1, p2, snapHelper.dir2,
1093 getCurrentBaseNode().getEastNorth());
1094 if (xPoint != null) {
1095 n.setEastNorth(xPoint);
1096 }
1097 }
1098 }
1099
1100 /**
1101 * Takes the data from computeHelperLine to determine which ways/nodes should be highlighted
1102 * (if feature enabled). Also sets the target cursor if appropriate. It adds the to-be-
1103 * highlighted primitives to newHighlights but does not actually highlight them. This work is
1104 * done in redrawIfRequired. This means, calling addHighlighting() without redrawIfRequired()
1105 * will leave the data in an inconsistent state.
1106 *
1107 * The status bar derives its information from oldHighlights, so in order to update the status
1108 * bar both addHighlighting() and repaintIfRequired() are needed, since former fills newHighlights
1109 * and latter processes them into oldHighlights.
1110 */
1111 private void addHighlighting() {
1112 newHighlights = new HashSet<>();
1113
1114 // if ctrl key is held ("no join"), don't highlight anything
1115 if (ctrl) {
1116 Main.map.mapView.setNewCursor(cursor, this);
1117 redrawIfRequired();
1118 return;
1119 }
1120
1121 // This happens when nothing is selected, but we still want to highlight the "target node"
1122 if (mouseOnExistingNode == null && mousePos != null && getLayerManager().getEditDataSet().selectionEmpty()) {
1123 mouseOnExistingNode = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive::isSelectable);
1124 }
1125
1126 if (mouseOnExistingNode != null) {
1127 Main.map.mapView.setNewCursor(cursorJoinNode, this);
1128 newHighlights.add(mouseOnExistingNode);
1129 redrawIfRequired();
1130 return;
1131 }
1132
1133 // Insert the node into all the nearby way segments
1134 if (mouseOnExistingWays.isEmpty()) {
1135 Main.map.mapView.setNewCursor(cursor, this);
1136 redrawIfRequired();
1137 return;
1138 }
1139
1140 Main.map.mapView.setNewCursor(cursorJoinWay, this);
1141 newHighlights.addAll(mouseOnExistingWays);
1142 redrawIfRequired();
1143 }
1144
1145 /**
1146 * Removes target highlighting from primitives. Issues repaint if required.
1147 * @return true if a repaint has been issued.
1148 */
1149 private boolean removeHighlighting() {
1150 newHighlights = new HashSet<>();
1151 return redrawIfRequired();
1152 }
1153
1154 @Override
1155 public void paint(Graphics2D g, MapView mv, Bounds box) {
1156 // sanity checks
1157 if (Main.map.mapView == null || mousePos == null
1158 // don't draw line if we don't know where from or where to
1159 || currentMouseEastNorth == null || getCurrentBaseNode() == null
1160 // don't draw line if mouse is outside window
1161 || !Main.map.mapView.getState().getForView(mousePos.getX(), mousePos.getY()).isInView())
1162 return;
1163
1164 Graphics2D g2 = g;
1165 snapHelper.drawIfNeeded(g2, mv.getState());
1166 if (!DRAW_HELPER_LINE.get() || wayIsFinished || shift)
1167 return;
1168
1169 if (!snapHelper.isActive()) {
1170 g2.setColor(RUBBER_LINE_COLOR.get());
1171 g2.setStroke(RUBBER_LINE_STROKE.get());
1172 paintConstructionGeometry(mv, g2);
1173 } else if (DRAW_CONSTRUCTION_GEOMETRY.get()) {
1174 // else use color and stoke from snapHelper.draw
1175 paintConstructionGeometry(mv, g2);
1176 }
1177 }
1178
1179 private void paintConstructionGeometry(MapView mv, Graphics2D g2) {
1180 MapPath2D b = new MapPath2D();
1181 MapViewPoint p1 = mv.getState().getPointFor(getCurrentBaseNode());
1182 MapViewPoint p2 = mv.getState().getPointFor(currentMouseEastNorth);
1183
1184 b.moveTo(p1);
1185 b.lineTo(p2);
1186
1187 // if alt key is held ("start new way"), draw a little perpendicular line
1188 if (alt) {
1189 START_WAY_INDICATOR.paintArrowAt(b, p1, p2);
1190 }
1191
1192 g2.draw(b);
1193 g2.setStroke(BASIC_STROKE);
1194 }
1195
1196 @Override
1197 public String getModeHelpText() {
1198 StringBuilder rv;
1199 /*
1200 * No modifiers: all (Connect, Node Re-Use, Auto-Weld)
1201 * CTRL: disables node re-use, auto-weld
1202 * Shift: do not make connection
1203 * ALT: make connection but start new way in doing so
1204 */
1205
1206 /*
1207 * Status line text generation is split into two parts to keep it maintainable.
1208 * First part looks at what will happen to the new node inserted on click and
1209 * the second part will look if a connection is made or not.
1210 *
1211 * Note that this help text is not absolutely accurate as it doesn't catch any special
1212 * cases (e.g. when preventing <---> ways). The only special that it catches is when
1213 * a way is about to be finished.
1214 *
1215 * First check what happens to the new node.
1216 */
1217
1218 // oldHighlights stores the current highlights. If this
1219 // list is empty we can assume that we won't do any joins
1220 if (ctrl || oldHighlights.isEmpty()) {
1221 rv = new StringBuilder(tr("Create new node."));
1222 } else {
1223 // oldHighlights may store a node or way, check if it's a node
1224 OsmPrimitive x = oldHighlights.iterator().next();
1225 if (x instanceof Node) {
1226 rv = new StringBuilder(tr("Select node under cursor."));
1227 } else {
1228 rv = new StringBuilder(trn("Insert new node into way.", "Insert new node into {0} ways.",
1229 oldHighlights.size(), oldHighlights.size()));
1230 }
1231 }
1232
1233 /*
1234 * Check whether a connection will be made
1235 */
1236 if (!wayIsFinished && getCurrentBaseNode() != null) {
1237 if (alt) {
1238 rv.append(' ').append(tr("Start new way from last node."));
1239 } else {
1240 rv.append(' ').append(tr("Continue way from last node."));
1241 }
1242 if (snapHelper.isSnapOn()) {
1243 rv.append(' ').append(tr("Angle snapping active."));
1244 }
1245 }
1246
1247 Node n = mouseOnExistingNode;
1248 DataSet ds = getLayerManager().getEditDataSet();
1249 /*
1250 * Handle special case: Highlighted node == selected node => finish drawing
1251 */
1252 if (n != null && ds != null && ds.getSelectedNodes().contains(n)) {
1253 if (wayIsFinished) {
1254 rv = new StringBuilder(tr("Select node under cursor."));
1255 } else {
1256 rv = new StringBuilder(tr("Finish drawing."));
1257 }
1258 }
1259
1260 /*
1261 * Handle special case: Self-Overlapping or closing way
1262 */
1263 if (ds != null && !ds.getSelectedWays().isEmpty() && !wayIsFinished && !alt) {
1264 Way w = ds.getSelectedWays().iterator().next();
1265 for (Node m : w.getNodes()) {
1266 if (m.equals(mouseOnExistingNode) || mouseOnExistingWays.contains(w)) {
1267 rv.append(' ').append(tr("Finish drawing."));
1268 break;
1269 }
1270 }
1271 }
1272 return rv.toString();
1273 }
1274
1275 /**
1276 * Get selected primitives, while draw action is in progress.
1277 *
1278 * While drawing a way, technically the last node is selected.
1279 * This is inconvenient when the user tries to add/edit tags to the way.
1280 * For this case, this method returns the current way as selection,
1281 * to work around this issue.
1282 * Otherwise the normal selection of the current data layer is returned.
1283 * @return selected primitives, while draw action is in progress
1284 */
1285 public Collection<OsmPrimitive> getInProgressSelection() {
1286 DataSet ds = getLayerManager().getEditDataSet();
1287 if (ds == null) return null;
1288 if (getCurrentBaseNode() != null && !ds.selectionEmpty()) {
1289 Way continueFrom = getWayForNode(getCurrentBaseNode());
1290 if (continueFrom != null)
1291 return Collections.<OsmPrimitive>singleton(continueFrom);
1292 }
1293 return ds.getSelected();
1294 }
1295
1296 @Override
1297 public Collection<? extends OsmPrimitive> getPreservedPrimitives() {
1298 DataSet ds = getLayerManager().getEditDataSet();
1299 return ds != null ? ds.getSelected() : Collections.emptySet();
1300 }
1301
1302 @Override
1303 public boolean layerIsSupported(Layer l) {
1304 return l instanceof OsmDataLayer;
1305 }
1306
1307 @Override
1308 protected void updateEnabledState() {
1309 setEnabled(getLayerManager().getEditLayer() != null);
1310 }
1311
1312 @Override
1313 public void destroy() {
1314 super.destroy();
1315 snapChangeAction.destroy();
1316 }
1317
1318 /**
1319 * Undo the last command. Binded by default to backspace key.
1320 */
1321 public class BackSpaceAction extends AbstractAction {
1322
1323 @Override
1324 public void actionPerformed(ActionEvent e) {
1325 Main.main.undoRedo.undo();
1326 Command lastCmd = Main.main.undoRedo.getLastCommand();
1327 if (lastCmd == null) return;
1328 Node n = null;
1329 for (OsmPrimitive p: lastCmd.getParticipatingPrimitives()) {
1330 if (p instanceof Node) {
1331 if (n == null) {
1332 n = (Node) p; // found one node
1333 wayIsFinished = false;
1334 } else {
1335 // if more than 1 node were affected by previous command,
1336 // we have no way to continue, so we forget about found node
1337 n = null;
1338 break;
1339 }
1340 }
1341 }
1342 // select last added node - maybe we will continue drawing from it
1343 if (n != null) {
1344 getLayerManager().getEditDataSet().addSelected(n);
1345 }
1346 }
1347 }
1348
1349 private class SnapChangeAction extends JosmAction {
1350 /**
1351 * Constructs a new {@code SnapChangeAction}.
1352 */
1353 SnapChangeAction() {
1354 super(tr("Angle snapping"), /* ICON() */ "anglesnap",
1355 tr("Switch angle snapping mode while drawing"), null, false);
1356 putValue("help", ht("/Action/Draw/AngleSnap"));
1357 }
1358
1359 @Override
1360 public void actionPerformed(ActionEvent e) {
1361 if (snapHelper != null) {
1362 snapHelper.toggleSnapping();
1363 }
1364 }
1365
1366 @Override
1367 protected void updateEnabledState() {
1368 setEnabled(Main.map != null && Main.map.mapMode instanceof DrawAction);
1369 }
1370 }
1371}
Note: See TracBrowser for help on using the repository browser.