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

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

see #11889, see #11924, see #13387 - use backported versions of Math.toDegrees/toRadians (more accurate and faster) - to revert when migrating to Java 9

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