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

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

fix #15688 - do not filter selected way nodes in draw mode

  • 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 Collection<OsmPrimitive> selection = getLayerManager().getEditDataSet().getSelected();
820
821 MapView mv = MainApplication.getMap().mapView;
822 Node currentMouseNode = null;
823 mouseOnExistingNode = null;
824 mouseOnExistingWays = new HashSet<>();
825
826 if (!ctrl && mousePos != null) {
827 currentMouseNode = mv.getNearestNode(mousePos, OsmPrimitive::isSelectable);
828 }
829
830 // We need this for highlighting and we'll only do so if we actually want to re-use
831 // *and* there is no node nearby (because nodes beat ways when re-using)
832 if (!ctrl && currentMouseNode == null) {
833 List<WaySegment> wss = mv.getNearestWaySegments(mousePos, OsmPrimitive::isSelectable);
834 for (WaySegment ws : wss) {
835 mouseOnExistingWays.add(ws.way);
836 }
837 }
838
839 if (currentMouseNode != null) {
840 // user clicked on node
841 if (selection.isEmpty()) return;
842 currentMouseEastNorth = currentMouseNode.getEastNorth();
843 mouseOnExistingNode = currentMouseNode;
844 } else {
845 // no node found in clicked area
846 currentMouseEastNorth = mv.getEastNorth(mousePos.x, mousePos.y);
847 }
848
849 determineCurrentBaseNodeAndPreviousNode(selection);
850 if (previousNode == null) {
851 snapHelper.noSnapNow();
852 }
853
854 if (getCurrentBaseNode() == null || getCurrentBaseNode() == currentMouseNode)
855 return; // Don't create zero length way segments.
856
857 showStatusInfo(-1, -1, -1, snapHelper.isSnapOn());
858
859 double curHdg = Utils.toDegrees(getCurrentBaseNode().getEastNorth()
860 .heading(currentMouseEastNorth));
861 double baseHdg = -1;
862 if (previousNode != null) {
863 EastNorth en = previousNode.getEastNorth();
864 if (en != null) {
865 baseHdg = Utils.toDegrees(en.heading(getCurrentBaseNode().getEastNorth()));
866 }
867 }
868
869 snapHelper.checkAngleSnapping(currentMouseEastNorth, baseHdg, curHdg);
870
871 // status bar was filled by snapHelper
872 }
873
874 static void showStatusInfo(double angle, double hdg, double distance, boolean activeFlag) {
875 MapFrame map = MainApplication.getMap();
876 map.statusLine.setAngle(angle);
877 map.statusLine.activateAnglePanel(activeFlag);
878 map.statusLine.setHeading(hdg);
879 map.statusLine.setDist(distance);
880 }
881
882 /**
883 * Helper function that sets fields currentBaseNode and previousNode
884 * @param selection
885 * uses also lastUsedNode field
886 */
887 private void determineCurrentBaseNodeAndPreviousNode(Collection<OsmPrimitive> selection) {
888 Node selectedNode = null;
889 Way selectedWay = null;
890 for (OsmPrimitive p : selection) {
891 if (p instanceof Node) {
892 if (selectedNode != null)
893 return;
894 selectedNode = (Node) p;
895 } else if (p instanceof Way) {
896 if (selectedWay != null)
897 return;
898 selectedWay = (Way) p;
899 }
900 }
901 // we are here, if not more than 1 way or node is selected,
902
903 // the node from which we make a connection
904 currentBaseNode = null;
905 previousNode = null;
906
907 // Try to find an open way to measure angle from it. The way is not to be continued!
908 // warning: may result in changes of currentBaseNode and previousNode
909 // please remove if bugs arise
910 if (selectedWay == null && selectedNode != null) {
911 for (OsmPrimitive p: selectedNode.getReferrers()) {
912 if (p.isUsable() && p instanceof Way && ((Way) p).isFirstLastNode(selectedNode)) {
913 if (selectedWay != null) { // two uncontinued ways, nothing to take as reference
914 selectedWay = null;
915 break;
916 } else {
917 // set us ~continue this way (measure angle from it)
918 selectedWay = (Way) p;
919 }
920 }
921 }
922 }
923
924 if (selectedNode == null) {
925 if (selectedWay == null)
926 return;
927 continueWayFromNode(selectedWay, lastUsedNode);
928 } else if (selectedWay == null) {
929 currentBaseNode = selectedNode;
930 } else if (!selectedWay.isDeleted()) { // fix #7118
931 continueWayFromNode(selectedWay, selectedNode);
932 }
933 }
934
935 /**
936 * if one of the ends of {@code way} is given {@code node},
937 * then set currentBaseNode = node and previousNode = adjacent node of way
938 * @param way way to continue
939 * @param node starting node
940 */
941 private void continueWayFromNode(Way way, Node node) {
942 int n = way.getNodesCount();
943 if (node == way.firstNode()) {
944 currentBaseNode = node;
945 if (n > 1) previousNode = way.getNode(1);
946 } else if (node == way.lastNode()) {
947 currentBaseNode = node;
948 if (n > 1) previousNode = way.getNode(n-2);
949 }
950 }
951
952 /**
953 * Repaint on mouse exit so that the helper line goes away.
954 */
955 @Override
956 public void mouseExited(MouseEvent e) {
957 OsmDataLayer editLayer = MainApplication.getLayerManager().getEditLayer();
958 if (editLayer == null)
959 return;
960 mousePos = e.getPoint();
961 snapHelper.noSnapNow();
962 boolean repaintIssued = removeHighlighting();
963 // force repaint in case snapHelper needs one. If removeHighlighting
964 // caused one already, don't do it again.
965 if (!repaintIssued) {
966 editLayer.invalidate();
967 }
968 }
969
970 /**
971 * Replies the parent way of a node, if it is the end of exactly one usable way.
972 * @param n node
973 * @return If the node is the end of exactly one way, return this.
974 * <code>null</code> otherwise.
975 */
976 public static Way getWayForNode(Node n) {
977 Way way = null;
978 for (Way w : Utils.filteredCollection(n.getReferrers(), Way.class)) {
979 if (!w.isUsable() || w.getNodesCount() < 1) {
980 continue;
981 }
982 Node firstNode = w.getNode(0);
983 Node lastNode = w.getNode(w.getNodesCount() - 1);
984 if ((firstNode == n || lastNode == n) && (firstNode != lastNode)) {
985 if (way != null)
986 return null;
987 way = w;
988 }
989 }
990 return way;
991 }
992
993 /**
994 * Replies the current base node, after having checked it is still usable (see #11105).
995 * @return the current base node (can be null). If not-null, it's guaranteed the node is usable
996 */
997 public Node getCurrentBaseNode() {
998 if (currentBaseNode != null && (currentBaseNode.getDataSet() == null || !currentBaseNode.isUsable())) {
999 currentBaseNode = null;
1000 }
1001 return currentBaseNode;
1002 }
1003
1004 private static void pruneSuccsAndReverse(List<Integer> is) {
1005 Set<Integer> is2 = new HashSet<>();
1006 for (int i : is) {
1007 if (!is2.contains(i - 1) && !is2.contains(i + 1)) {
1008 is2.add(i);
1009 }
1010 }
1011 is.clear();
1012 is.addAll(is2);
1013 Collections.sort(is);
1014 Collections.reverse(is);
1015 }
1016
1017 /**
1018 * Adjusts the position of a node to lie on a segment (or a segment intersection).
1019 *
1020 * If one or more than two segments are passed, the node is adjusted
1021 * to lie on the first segment that is passed.
1022 *
1023 * If two segments are passed, the node is adjusted to be at their intersection.
1024 *
1025 * No action is taken if no segments are passed.
1026 *
1027 * @param segs the segments to use as a reference when adjusting
1028 * @param n the node to adjust
1029 */
1030 private static void adjustNode(Collection<Pair<Node, Node>> segs, Node n) {
1031 switch (segs.size()) {
1032 case 0:
1033 return;
1034 case 2:
1035 adjustNodeTwoSegments(segs, n);
1036 break;
1037 default:
1038 adjustNodeDefault(segs, n);
1039 }
1040 }
1041
1042 private static void adjustNodeTwoSegments(Collection<Pair<Node, Node>> segs, Node n) {
1043 // This computes the intersection between the two segments and adjusts the node position.
1044 Iterator<Pair<Node, Node>> i = segs.iterator();
1045 Pair<Node, Node> seg = i.next();
1046 EastNorth pA = seg.a.getEastNorth();
1047 EastNorth pB = seg.b.getEastNorth();
1048 seg = i.next();
1049 EastNorth pC = seg.a.getEastNorth();
1050 EastNorth pD = seg.b.getEastNorth();
1051
1052 double u = det(pB.east() - pA.east(), pB.north() - pA.north(), pC.east() - pD.east(), pC.north() - pD.north());
1053
1054 // Check for parallel segments and do nothing if they are
1055 // In practice this will probably only happen when a way has been duplicated
1056
1057 if (u == 0)
1058 return;
1059
1060 // q is a number between 0 and 1
1061 // It is the point in the segment where the intersection occurs
1062 // if the segment is scaled to length 1
1063
1064 double q = det(pB.north() - pC.north(), pB.east() - pC.east(), pD.north() - pC.north(), pD.east() - pC.east()) / u;
1065 EastNorth intersection = new EastNorth(
1066 pB.east() + q * (pA.east() - pB.east()),
1067 pB.north() + q * (pA.north() - pB.north()));
1068
1069
1070 // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise
1071 // fall through to default action.
1072 // (for semi-parallel lines, intersection might be miles away!)
1073 MapFrame map = MainApplication.getMap();
1074 if (map.mapView.getPoint2D(n).distance(map.mapView.getPoint2D(intersection)) < SNAP_TO_INTERSECTION_THRESHOLD.get()) {
1075 n.setEastNorth(intersection);
1076 return;
1077 }
1078
1079 adjustNodeDefault(segs, n);
1080 }
1081
1082 private static void adjustNodeDefault(Collection<Pair<Node, Node>> segs, Node n) {
1083 EastNorth p = n.getEastNorth();
1084 Pair<Node, Node> seg = segs.iterator().next();
1085 EastNorth pA = seg.a.getEastNorth();
1086 EastNorth pB = seg.b.getEastNorth();
1087 double a = p.distanceSq(pB);
1088 double b = p.distanceSq(pA);
1089 double c = pA.distanceSq(pB);
1090 double q = (a - b + c) / (2*c);
1091 n.setEastNorth(new EastNorth(pB.east() + q * (pA.east() - pB.east()), pB.north() + q * (pA.north() - pB.north())));
1092 }
1093
1094 // helper for adjustNode
1095 static double det(double a, double b, double c, double d) {
1096 return a * d - b * c;
1097 }
1098
1099 private void tryToMoveNodeOnIntersection(List<WaySegment> wss, Node n) {
1100 if (wss.isEmpty())
1101 return;
1102 WaySegment ws = wss.get(0);
1103 EastNorth p1 = ws.getFirstNode().getEastNorth();
1104 EastNorth p2 = ws.getSecondNode().getEastNorth();
1105 if (snapHelper.dir2 != null && getCurrentBaseNode() != null) {
1106 EastNorth xPoint = Geometry.getSegmentSegmentIntersection(p1, p2, snapHelper.dir2,
1107 getCurrentBaseNode().getEastNorth());
1108 if (xPoint != null) {
1109 n.setEastNorth(xPoint);
1110 }
1111 }
1112 }
1113
1114 /**
1115 * Takes the data from computeHelperLine to determine which ways/nodes should be highlighted
1116 * (if feature enabled). Also sets the target cursor if appropriate. It adds the to-be-
1117 * highlighted primitives to newHighlights but does not actually highlight them. This work is
1118 * done in redrawIfRequired. This means, calling addHighlighting() without redrawIfRequired()
1119 * will leave the data in an inconsistent state.
1120 *
1121 * The status bar derives its information from oldHighlights, so in order to update the status
1122 * bar both addHighlighting() and repaintIfRequired() are needed, since former fills newHighlights
1123 * and latter processes them into oldHighlights.
1124 */
1125 private void addHighlighting() {
1126 newHighlights = new HashSet<>();
1127 MapView mapView = MainApplication.getMap().mapView;
1128
1129 // if ctrl key is held ("no join"), don't highlight anything
1130 if (ctrl) {
1131 mapView.setNewCursor(cursor, this);
1132 redrawIfRequired();
1133 return;
1134 }
1135
1136 // This happens when nothing is selected, but we still want to highlight the "target node"
1137 if (mouseOnExistingNode == null && mousePos != null && getLayerManager().getEditDataSet().selectionEmpty()) {
1138 mouseOnExistingNode = mapView.getNearestNode(mousePos, OsmPrimitive::isSelectable);
1139 }
1140
1141 if (mouseOnExistingNode != null) {
1142 mapView.setNewCursor(cursorJoinNode, this);
1143 newHighlights.add(mouseOnExistingNode);
1144 redrawIfRequired();
1145 return;
1146 }
1147
1148 // Insert the node into all the nearby way segments
1149 if (mouseOnExistingWays.isEmpty()) {
1150 mapView.setNewCursor(cursor, this);
1151 redrawIfRequired();
1152 return;
1153 }
1154
1155 mapView.setNewCursor(cursorJoinWay, this);
1156 newHighlights.addAll(mouseOnExistingWays);
1157 redrawIfRequired();
1158 }
1159
1160 /**
1161 * Removes target highlighting from primitives. Issues repaint if required.
1162 * @return true if a repaint has been issued.
1163 */
1164 private boolean removeHighlighting() {
1165 newHighlights = new HashSet<>();
1166 return redrawIfRequired();
1167 }
1168
1169 @Override
1170 public void paint(Graphics2D g, MapView mv, Bounds box) {
1171 // sanity checks
1172 MapView mapView = MainApplication.getMap().mapView;
1173 if (mapView == null || mousePos == null
1174 // don't draw line if we don't know where from or where to
1175 || currentMouseEastNorth == null || getCurrentBaseNode() == null
1176 // don't draw line if mouse is outside window
1177 || !mapView.getState().getForView(mousePos.getX(), mousePos.getY()).isInView())
1178 return;
1179
1180 Graphics2D g2 = g;
1181 snapHelper.drawIfNeeded(g2, mv.getState());
1182 if (!DRAW_HELPER_LINE.get() || wayIsFinished || shift)
1183 return;
1184
1185 if (!snapHelper.isActive()) {
1186 g2.setColor(RUBBER_LINE_COLOR.get());
1187 g2.setStroke(RUBBER_LINE_STROKE.get());
1188 paintConstructionGeometry(mv, g2);
1189 } else if (DRAW_CONSTRUCTION_GEOMETRY.get()) {
1190 // else use color and stoke from snapHelper.draw
1191 paintConstructionGeometry(mv, g2);
1192 }
1193 }
1194
1195 private void paintConstructionGeometry(MapView mv, Graphics2D g2) {
1196 MapPath2D b = new MapPath2D();
1197 MapViewPoint p1 = mv.getState().getPointFor(getCurrentBaseNode());
1198 MapViewPoint p2 = mv.getState().getPointFor(currentMouseEastNorth);
1199
1200 b.moveTo(p1);
1201 b.lineTo(p2);
1202
1203 // if alt key is held ("start new way"), draw a little perpendicular line
1204 if (alt) {
1205 START_WAY_INDICATOR.paintArrowAt(b, p1, p2);
1206 }
1207
1208 g2.draw(b);
1209 g2.setStroke(BASIC_STROKE);
1210 }
1211
1212 @Override
1213 public String getModeHelpText() {
1214 StringBuilder rv;
1215 /*
1216 * No modifiers: all (Connect, Node Re-Use, Auto-Weld)
1217 * CTRL: disables node re-use, auto-weld
1218 * Shift: do not make connection
1219 * ALT: make connection but start new way in doing so
1220 */
1221
1222 /*
1223 * Status line text generation is split into two parts to keep it maintainable.
1224 * First part looks at what will happen to the new node inserted on click and
1225 * the second part will look if a connection is made or not.
1226 *
1227 * Note that this help text is not absolutely accurate as it doesn't catch any special
1228 * cases (e.g. when preventing <---> ways). The only special that it catches is when
1229 * a way is about to be finished.
1230 *
1231 * First check what happens to the new node.
1232 */
1233
1234 // oldHighlights stores the current highlights. If this
1235 // list is empty we can assume that we won't do any joins
1236 if (ctrl || oldHighlights.isEmpty()) {
1237 rv = new StringBuilder(tr("Create new node."));
1238 } else {
1239 // oldHighlights may store a node or way, check if it's a node
1240 OsmPrimitive x = oldHighlights.iterator().next();
1241 if (x instanceof Node) {
1242 rv = new StringBuilder(tr("Select node under cursor."));
1243 } else {
1244 rv = new StringBuilder(trn("Insert new node into way.", "Insert new node into {0} ways.",
1245 oldHighlights.size(), oldHighlights.size()));
1246 }
1247 }
1248
1249 /*
1250 * Check whether a connection will be made
1251 */
1252 if (!wayIsFinished && getCurrentBaseNode() != null) {
1253 if (alt) {
1254 rv.append(' ').append(tr("Start new way from last node."));
1255 } else {
1256 rv.append(' ').append(tr("Continue way from last node."));
1257 }
1258 if (snapHelper.isSnapOn()) {
1259 rv.append(' ').append(tr("Angle snapping active."));
1260 }
1261 }
1262
1263 Node n = mouseOnExistingNode;
1264 DataSet ds = getLayerManager().getEditDataSet();
1265 /*
1266 * Handle special case: Highlighted node == selected node => finish drawing
1267 */
1268 if (n != null && ds != null && ds.getSelectedNodes().contains(n)) {
1269 if (wayIsFinished) {
1270 rv = new StringBuilder(tr("Select node under cursor."));
1271 } else {
1272 rv = new StringBuilder(tr("Finish drawing."));
1273 }
1274 }
1275
1276 /*
1277 * Handle special case: Self-Overlapping or closing way
1278 */
1279 if (ds != null && !ds.getSelectedWays().isEmpty() && !wayIsFinished && !alt) {
1280 Way w = ds.getSelectedWays().iterator().next();
1281 for (Node m : w.getNodes()) {
1282 if (m.equals(mouseOnExistingNode) || mouseOnExistingWays.contains(w)) {
1283 rv.append(' ').append(tr("Finish drawing."));
1284 break;
1285 }
1286 }
1287 }
1288 return rv.toString();
1289 }
1290
1291 /**
1292 * Get selected primitives, while draw action is in progress.
1293 *
1294 * While drawing a way, technically the last node is selected.
1295 * This is inconvenient when the user tries to add/edit tags to the way.
1296 * For this case, this method returns the current way as selection,
1297 * to work around this issue.
1298 * Otherwise the normal selection of the current data layer is returned.
1299 * @return selected primitives, while draw action is in progress
1300 */
1301 public Collection<OsmPrimitive> getInProgressSelection() {
1302 DataSet ds = getLayerManager().getEditDataSet();
1303 if (ds == null) return null;
1304 if (getCurrentBaseNode() != null && !ds.selectionEmpty()) {
1305 Way continueFrom = getWayForNode(getCurrentBaseNode());
1306 if (continueFrom != null)
1307 return Collections.<OsmPrimitive>singleton(continueFrom);
1308 }
1309 return ds.getSelected();
1310 }
1311
1312 @Override
1313 public Collection<? extends OsmPrimitive> getPreservedPrimitives() {
1314 DataSet ds = getLayerManager().getEditDataSet();
1315 if (ds != null) {
1316 // Preserves selected primitives and selected way nodes
1317 Set<OsmPrimitive> result = new HashSet<>();
1318 for (Way w : ds.getSelectedWays()) {
1319 result.addAll(w.getNodes());
1320 }
1321 result.addAll(ds.getSelected());
1322 return result;
1323 }
1324 return Collections.emptySet();
1325 }
1326
1327 @Override
1328 public boolean layerIsSupported(Layer l) {
1329 return l instanceof OsmDataLayer;
1330 }
1331
1332 @Override
1333 protected void updateEnabledState() {
1334 setEnabled(getLayerManager().getEditLayer() != null);
1335 }
1336
1337 @Override
1338 public void destroy() {
1339 super.destroy();
1340 snapChangeAction.destroy();
1341 }
1342
1343 /**
1344 * Undo the last command. Binded by default to backspace key.
1345 */
1346 public class BackSpaceAction extends AbstractAction {
1347
1348 @Override
1349 public void actionPerformed(ActionEvent e) {
1350 MainApplication.undoRedo.undo();
1351 Command lastCmd = MainApplication.undoRedo.getLastCommand();
1352 if (lastCmd == null) return;
1353 Node n = null;
1354 for (OsmPrimitive p: lastCmd.getParticipatingPrimitives()) {
1355 if (p instanceof Node) {
1356 if (n == null) {
1357 n = (Node) p; // found one node
1358 wayIsFinished = false;
1359 } else {
1360 // if more than 1 node were affected by previous command,
1361 // we have no way to continue, so we forget about found node
1362 n = null;
1363 break;
1364 }
1365 }
1366 }
1367 // select last added node - maybe we will continue drawing from it
1368 if (n != null) {
1369 getLayerManager().getEditDataSet().addSelected(n);
1370 }
1371 }
1372 }
1373
1374 private class SnapChangeAction extends JosmAction {
1375 /**
1376 * Constructs a new {@code SnapChangeAction}.
1377 */
1378 SnapChangeAction() {
1379 super(tr("Angle snapping"), /* ICON() */ "anglesnap",
1380 tr("Switch angle snapping mode while drawing"), null, false);
1381 putValue("help", ht("/Action/Draw/AngleSnap"));
1382 }
1383
1384 @Override
1385 public void actionPerformed(ActionEvent e) {
1386 if (snapHelper != null) {
1387 snapHelper.toggleSnapping();
1388 }
1389 }
1390
1391 @Override
1392 protected void updateEnabledState() {
1393 MapFrame map = MainApplication.getMap();
1394 setEnabled(map != null && map.mapMode instanceof DrawAction);
1395 }
1396 }
1397}
Note: See TracBrowser for help on using the repository browser.