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

Last change on this file since 13293 was 13293, checked in by Don-vip, 6 years ago

fix NPE seen in unit tests

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