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

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

fix #18962 - introduce DataSet.update to avoid repetitive begin/endUpdate statements

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