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

Last change on this file since 17414 was 17295, checked in by GerdP, 4 years ago

see #19906: Scale, rotate & create areas tool: bottom toolbar unusable to view angle/scale factor/offset measurement
update statusline when exiting DrawAction

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