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

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

extract DrawAction.SnapHelper to a new class

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