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

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

fix #13306 - Make map paint code use double coordinates (patch by michael2402) - gsoc-core

  • Property svn:eol-style set to native
File size: 67.4 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.Stroke;
15import java.awt.event.ActionEvent;
16import java.awt.event.KeyEvent;
17import java.awt.event.MouseEvent;
18import java.awt.event.MouseListener;
19import java.util.ArrayList;
20import java.util.Arrays;
21import java.util.Collection;
22import java.util.Collections;
23import java.util.HashMap;
24import java.util.HashSet;
25import java.util.Iterator;
26import java.util.LinkedList;
27import java.util.List;
28import java.util.Map;
29import java.util.Set;
30
31import javax.swing.AbstractAction;
32import javax.swing.JCheckBoxMenuItem;
33import javax.swing.JMenuItem;
34import javax.swing.JOptionPane;
35import javax.swing.JPopupMenu;
36
37import org.openstreetmap.josm.Main;
38import org.openstreetmap.josm.actions.JosmAction;
39import org.openstreetmap.josm.command.AddCommand;
40import org.openstreetmap.josm.command.ChangeCommand;
41import org.openstreetmap.josm.command.Command;
42import org.openstreetmap.josm.command.SequenceCommand;
43import org.openstreetmap.josm.data.Bounds;
44import org.openstreetmap.josm.data.SelectionChangedListener;
45import org.openstreetmap.josm.data.coor.EastNorth;
46import org.openstreetmap.josm.data.coor.LatLon;
47import org.openstreetmap.josm.data.osm.DataSet;
48import org.openstreetmap.josm.data.osm.Node;
49import org.openstreetmap.josm.data.osm.OsmPrimitive;
50import org.openstreetmap.josm.data.osm.Way;
51import org.openstreetmap.josm.data.osm.WaySegment;
52import org.openstreetmap.josm.data.osm.visitor.paint.ArrowPaintHelper;
53import org.openstreetmap.josm.data.osm.visitor.paint.MapPath2D;
54import org.openstreetmap.josm.data.osm.visitor.paint.PaintColors;
55import org.openstreetmap.josm.gui.MainMenu;
56import org.openstreetmap.josm.gui.MapFrame;
57import org.openstreetmap.josm.gui.MapView;
58import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
59import org.openstreetmap.josm.gui.NavigatableComponent;
60import org.openstreetmap.josm.gui.layer.Layer;
61import org.openstreetmap.josm.gui.layer.MapViewPaintable;
62import org.openstreetmap.josm.gui.layer.OsmDataLayer;
63import org.openstreetmap.josm.gui.util.GuiHelper;
64import org.openstreetmap.josm.gui.util.KeyPressReleaseListener;
65import org.openstreetmap.josm.gui.util.ModifierListener;
66import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
67import org.openstreetmap.josm.tools.Geometry;
68import org.openstreetmap.josm.tools.ImageProvider;
69import org.openstreetmap.josm.tools.Pair;
70import org.openstreetmap.josm.tools.Shortcut;
71import org.openstreetmap.josm.tools.Utils;
72
73/**
74 * Mapmode to add nodes, create and extend ways.
75 */
76public class DrawAction extends MapMode implements MapViewPaintable, SelectionChangedListener, KeyPressReleaseListener, ModifierListener {
77
78 private static final Color ORANGE_TRANSPARENT = new Color(Color.ORANGE.getRed(), Color.ORANGE.getGreen(), Color.ORANGE.getBlue(), 128);
79
80 private static final ArrowPaintHelper START_WAY_INDICATOR = new ArrowPaintHelper(Math.toRadians(90), 8);
81
82 private final Cursor cursorJoinNode;
83 private final Cursor cursorJoinWay;
84
85 private transient Node lastUsedNode;
86 private double toleranceMultiplier;
87
88 private transient Node mouseOnExistingNode;
89 private transient Set<Way> mouseOnExistingWays = new HashSet<>();
90 // old highlights store which primitives are currently highlighted. This
91 // is true, even if target highlighting is disabled since the status bar
92 // derives its information from this list as well.
93 private transient Set<OsmPrimitive> oldHighlights = new HashSet<>();
94 // new highlights contains a list of primitives that should be highlighted
95 // but haven’t been so far. The idea is to compare old and new and only
96 // repaint if there are changes.
97 private transient Set<OsmPrimitive> newHighlights = new HashSet<>();
98 private boolean drawHelperLine;
99 private boolean wayIsFinished;
100 private boolean drawTargetHighlight;
101 private Point mousePos;
102 private Point oldMousePos;
103 private Color rubberLineColor;
104
105 private transient Node currentBaseNode;
106 private transient Node previousNode;
107 private EastNorth currentMouseEastNorth;
108
109 private final transient SnapHelper snapHelper = new SnapHelper();
110
111 private final transient Shortcut backspaceShortcut;
112 private final BackSpaceAction backspaceAction;
113 private final transient Shortcut snappingShortcut;
114 private boolean ignoreNextKeyRelease;
115
116 private final SnapChangeAction snapChangeAction;
117 private final JCheckBoxMenuItem snapCheckboxMenuItem;
118 private boolean useRepeatedShortcut;
119 private transient Stroke rubberLineStroke;
120 private static final BasicStroke BASIC_STROKE = new BasicStroke(1);
121
122 private static int snapToIntersectionThreshold;
123
124 /**
125 * Constructs a new {@code DrawAction}.
126 * @param mapFrame Map frame
127 */
128 public DrawAction(MapFrame mapFrame) {
129 super(tr("Draw"), "node/autonode", tr("Draw nodes"),
130 Shortcut.registerShortcut("mapmode:draw", tr("Mode: {0}", tr("Draw")), KeyEvent.VK_A, Shortcut.DIRECT),
131 mapFrame, ImageProvider.getCursor("crosshair", null));
132
133 snappingShortcut = Shortcut.registerShortcut("mapmode:drawanglesnapping",
134 tr("Mode: Draw Angle snapping"), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE);
135 snapChangeAction = new SnapChangeAction();
136 snapCheckboxMenuItem = addMenuItem();
137 snapHelper.setMenuCheckBox(snapCheckboxMenuItem);
138 backspaceShortcut = Shortcut.registerShortcut("mapmode:backspace",
139 tr("Backspace in Add mode"), KeyEvent.VK_BACK_SPACE, Shortcut.DIRECT);
140 backspaceAction = new BackSpaceAction();
141 cursorJoinNode = ImageProvider.getCursor("crosshair", "joinnode");
142 cursorJoinWay = ImageProvider.getCursor("crosshair", "joinway");
143
144 readPreferences();
145 snapHelper.init();
146 readPreferences();
147 }
148
149 private JCheckBoxMenuItem addMenuItem() {
150 int n = Main.main.menu.editMenu.getItemCount();
151 for (int i = n-1; i > 0; i--) {
152 JMenuItem item = Main.main.menu.editMenu.getItem(i);
153 if (item != null && item.getAction() != null && item.getAction() instanceof SnapChangeAction) {
154 Main.main.menu.editMenu.remove(i);
155 }
156 }
157 return MainMenu.addWithCheckbox(Main.main.menu.editMenu, snapChangeAction, MainMenu.WINDOW_MENU_GROUP.VOLATILE);
158 }
159
160 /**
161 * Checks if a map redraw is required and does so if needed. Also updates the status bar.
162 * @return true if a repaint is needed
163 */
164 private boolean redrawIfRequired() {
165 updateStatusLine();
166 // repaint required if the helper line is active.
167 boolean needsRepaint = drawHelperLine && !wayIsFinished;
168 if (drawTargetHighlight) {
169 // move newHighlights to oldHighlights; only update changed primitives
170 for (OsmPrimitive x : newHighlights) {
171 if (oldHighlights.contains(x)) {
172 continue;
173 }
174 x.setHighlighted(true);
175 needsRepaint = true;
176 }
177 oldHighlights.removeAll(newHighlights);
178 for (OsmPrimitive x : oldHighlights) {
179 x.setHighlighted(false);
180 needsRepaint = true;
181 }
182 }
183 // required in order to print correct help text
184 oldHighlights = newHighlights;
185
186 if (!needsRepaint && !drawTargetHighlight)
187 return false;
188
189 // update selection to reflect which way being modified
190 OsmDataLayer editLayer = getLayerManager().getEditLayer();
191 if (getCurrentBaseNode() != null && editLayer != null && !editLayer.data.selectionEmpty()) {
192 DataSet currentDataSet = editLayer.data;
193 Way continueFrom = getWayForNode(getCurrentBaseNode());
194 if (alt && continueFrom != null && (!getCurrentBaseNode().isSelected() || continueFrom.isSelected())) {
195 addRemoveSelection(currentDataSet, getCurrentBaseNode(), continueFrom);
196 needsRepaint = true;
197 } else if (!alt && continueFrom != null && !continueFrom.isSelected()) {
198 currentDataSet.addSelected(continueFrom);
199 needsRepaint = true;
200 }
201 }
202
203 if (needsRepaint && editLayer != null) {
204 editLayer.invalidate();
205 }
206 return needsRepaint;
207 }
208
209 private static void addRemoveSelection(DataSet ds, OsmPrimitive toAdd, OsmPrimitive toRemove) {
210 ds.beginUpdate(); // to prevent the selection listener to screw around with the state
211 ds.addSelected(toAdd);
212 ds.clearSelection(toRemove);
213 ds.endUpdate();
214 }
215
216 @Override
217 public void enterMode() {
218 if (!isEnabled())
219 return;
220 super.enterMode();
221 readPreferences();
222
223 // determine if selection is suitable to continue drawing. If it
224 // isn't, set wayIsFinished to true to avoid superfluous repaints.
225 determineCurrentBaseNodeAndPreviousNode(getLayerManager().getEditDataSet().getSelected());
226 wayIsFinished = getCurrentBaseNode() == null;
227
228 toleranceMultiplier = 0.01 * NavigatableComponent.PROP_SNAP_DISTANCE.get();
229
230 snapHelper.init();
231 snapCheckboxMenuItem.getAction().setEnabled(true);
232
233 Main.map.statusLine.getAnglePanel().addMouseListener(snapHelper.anglePopupListener);
234 Main.registerActionShortcut(backspaceAction, backspaceShortcut);
235
236 Main.map.mapView.addMouseListener(this);
237 Main.map.mapView.addMouseMotionListener(this);
238 Main.map.mapView.addTemporaryLayer(this);
239 DataSet.addSelectionListener(this);
240
241 Main.map.keyDetector.addKeyListener(this);
242 Main.map.keyDetector.addModifierListener(this);
243 ignoreNextKeyRelease = true;
244 }
245
246 @Override
247 protected void readPreferences() {
248 rubberLineColor = Main.pref.getColor(marktr("helper line"), null);
249 if (rubberLineColor == null) rubberLineColor = PaintColors.SELECTED.get();
250
251 rubberLineStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.stroke.helper-line", "3"));
252 drawHelperLine = Main.pref.getBoolean("draw.helper-line", true);
253 drawTargetHighlight = Main.pref.getBoolean("draw.target-highlight", true);
254 snapToIntersectionThreshold = Main.pref.getInteger("edit.snap-intersection-threshold", 10);
255 }
256
257 @Override
258 public void exitMode() {
259 super.exitMode();
260 Main.map.mapView.removeMouseListener(this);
261 Main.map.mapView.removeMouseMotionListener(this);
262 Main.map.mapView.removeTemporaryLayer(this);
263 DataSet.removeSelectionListener(this);
264 Main.unregisterActionShortcut(backspaceAction, backspaceShortcut);
265 snapHelper.unsetFixedMode();
266 snapCheckboxMenuItem.getAction().setEnabled(false);
267
268 Main.map.statusLine.getAnglePanel().removeMouseListener(snapHelper.anglePopupListener);
269 Main.map.statusLine.activateAnglePanel(false);
270
271 removeHighlighting();
272 Main.map.keyDetector.removeKeyListener(this);
273 Main.map.keyDetector.removeModifierListener(this);
274
275 // when exiting we let everybody know about the currently selected
276 // primitives
277 //
278 DataSet ds = getLayerManager().getEditDataSet();
279 if (ds != null) {
280 ds.fireSelectionChanged();
281 }
282 }
283
284 /**
285 * redraw to (possibly) get rid of helper line if selection changes.
286 */
287 @Override
288 public void modifiersChanged(int modifiers) {
289 if (!Main.isDisplayingMapView() || !Main.map.mapView.isActiveLayerDrawable())
290 return;
291 updateKeyModifiers(modifiers);
292 computeHelperLine();
293 addHighlighting();
294 }
295
296 @Override
297 public void doKeyPressed(KeyEvent e) {
298 if (!snappingShortcut.isEvent(e) && !(useRepeatedShortcut && getShortcut().isEvent(e)))
299 return;
300 snapHelper.setFixedMode();
301 computeHelperLine();
302 redrawIfRequired();
303 }
304
305 @Override
306 public void doKeyReleased(KeyEvent e) {
307 if (!snappingShortcut.isEvent(e) && !(useRepeatedShortcut && getShortcut().isEvent(e)))
308 return;
309 if (ignoreNextKeyRelease) {
310 ignoreNextKeyRelease = false;
311 return;
312 }
313 snapHelper.unFixOrTurnOff();
314 computeHelperLine();
315 redrawIfRequired();
316 }
317
318 /**
319 * redraw to (possibly) get rid of helper line if selection changes.
320 */
321 @Override
322 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
323 if (!Main.map.mapView.isActiveLayerDrawable())
324 return;
325 computeHelperLine();
326 addHighlighting();
327 }
328
329 private void tryAgain(MouseEvent e) {
330 getLayerManager().getEditDataSet().setSelected();
331 mouseReleased(e);
332 }
333
334 /**
335 * This function should be called when the user wishes to finish his current draw action.
336 * If Potlatch Style is enabled, it will switch to select tool, otherwise simply disable
337 * the helper line until the user chooses to draw something else.
338 */
339 private void finishDrawing() {
340 // let everybody else know about the current selection
341 //
342 Main.getLayerManager().getEditDataSet().fireSelectionChanged();
343 lastUsedNode = null;
344 wayIsFinished = true;
345 Main.map.selectSelectTool(true);
346 snapHelper.noSnapNow();
347
348 // Redraw to remove the helper line stub
349 computeHelperLine();
350 removeHighlighting();
351 }
352
353 private Point rightClickPressPos;
354
355 @Override
356 public void mousePressed(MouseEvent e) {
357 if (e.getButton() == MouseEvent.BUTTON3) {
358 rightClickPressPos = e.getPoint();
359 }
360 }
361
362 /**
363 * If user clicked with the left button, add a node at the current mouse
364 * position.
365 *
366 * If in nodeway mode, insert the node into the way.
367 */
368 @Override
369 public void mouseReleased(MouseEvent e) {
370 if (e.getButton() == MouseEvent.BUTTON3) {
371 Point curMousePos = e.getPoint();
372 if (curMousePos.equals(rightClickPressPos)) {
373 tryToSetBaseSegmentForAngleSnap();
374 }
375 return;
376 }
377 if (e.getButton() != MouseEvent.BUTTON1)
378 return;
379 if (!Main.map.mapView.isActiveLayerDrawable())
380 return;
381 // request focus in order to enable the expected keyboard shortcuts
382 //
383 Main.map.mapView.requestFocus();
384
385 if (e.getClickCount() > 1 && mousePos != null && mousePos.equals(oldMousePos)) {
386 // A double click equals "user clicked last node again, finish way"
387 // Change draw tool only if mouse position is nearly the same, as
388 // otherwise fast clicks will count as a double click
389 finishDrawing();
390 return;
391 }
392 oldMousePos = mousePos;
393
394 // we copy ctrl/alt/shift from the event just in case our global
395 // keyDetector didn't make it through the security manager. Unclear
396 // if that can ever happen but better be safe.
397 updateKeyModifiers(e);
398 mousePos = e.getPoint();
399
400 DataSet ds = getLayerManager().getEditDataSet();
401 Collection<OsmPrimitive> selection = new ArrayList<>(ds.getSelected());
402
403 boolean newNode = false;
404 Node n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive::isSelectable);
405 if (ctrl) {
406 Iterator<Way> it = ds.getSelectedWays().iterator();
407 if (it.hasNext()) {
408 // ctrl-click on node of selected way = reuse node despite of ctrl
409 if (!it.next().containsNode(n)) n = null;
410 } else {
411 n = null; // ctrl-click + no selected way = new node
412 }
413 }
414
415 if (n != null && !snapHelper.isActive()) {
416 // user clicked on node
417 if (selection.isEmpty() || wayIsFinished) {
418 // select the clicked node and do nothing else
419 // (this is just a convenience option so that people don't
420 // have to switch modes)
421
422 ds.setSelected(n);
423 // If we extend/continue an existing way, select it already now to make it obvious
424 Way continueFrom = getWayForNode(n);
425 if (continueFrom != null) {
426 ds.addSelected(continueFrom);
427 }
428
429 // The user explicitly selected a node, so let him continue drawing
430 wayIsFinished = false;
431 return;
432 }
433 } else {
434 EastNorth newEN;
435 if (n != null) {
436 EastNorth foundPoint = n.getEastNorth();
437 // project found node to snapping line
438 newEN = snapHelper.getSnapPoint(foundPoint);
439 // do not add new node if there is some node within snapping distance
440 double tolerance = Main.map.mapView.getDist100Pixel() * toleranceMultiplier;
441 if (foundPoint.distance(newEN) > tolerance) {
442 n = new Node(newEN); // point != projected, so we create new node
443 newNode = true;
444 }
445 } else { // n==null, no node found in clicked area
446 EastNorth mouseEN = Main.map.mapView.getEastNorth(e.getX(), e.getY());
447 newEN = snapHelper.isSnapOn() ? snapHelper.getSnapPoint(mouseEN) : mouseEN;
448 n = new Node(newEN); //create node at clicked point
449 newNode = true;
450 }
451 snapHelper.unsetFixedMode();
452 }
453
454 Collection<Command> cmds = new LinkedList<>();
455 Collection<OsmPrimitive> newSelection = new LinkedList<>(ds.getSelected());
456 List<Way> reuseWays = new ArrayList<>();
457 List<Way> replacedWays = new ArrayList<>();
458
459 if (newNode) {
460 if (n.getCoor().isOutSideWorld()) {
461 JOptionPane.showMessageDialog(
462 Main.parent,
463 tr("Cannot add a node outside of the world."),
464 tr("Warning"),
465 JOptionPane.WARNING_MESSAGE
466 );
467 return;
468 }
469 cmds.add(new AddCommand(n));
470
471 if (!ctrl) {
472 // Insert the node into all the nearby way segments
473 List<WaySegment> wss = Main.map.mapView.getNearestWaySegments(
474 Main.map.mapView.getPoint(n), OsmPrimitive::isSelectable);
475 if (snapHelper.isActive()) {
476 tryToMoveNodeOnIntersection(wss, n);
477 }
478 insertNodeIntoAllNearbySegments(wss, n, newSelection, cmds, replacedWays, reuseWays);
479 }
480 }
481 // now "n" is newly created or reused node that shoud be added to some way
482
483 // This part decides whether or not a "segment" (i.e. a connection) is made to an existing node.
484
485 // For a connection to be made, the user must either have a node selected (connection
486 // is made to that node), or he must have a way selected *and* one of the endpoints
487 // of that way must be the last used node (connection is made to last used node), or
488 // he must have a way and a node selected (connection is made to the selected node).
489
490 // If the above does not apply, the selection is cleared and a new try is started
491
492 boolean extendedWay = false;
493 boolean wayIsFinishedTemp = wayIsFinished;
494 wayIsFinished = false;
495
496 // don't draw lines if shift is held
497 if (!selection.isEmpty() && !shift) {
498 Node selectedNode = null;
499 Way selectedWay = null;
500
501 for (OsmPrimitive p : selection) {
502 if (p instanceof Node) {
503 if (selectedNode != null) {
504 // Too many nodes selected to do something useful
505 tryAgain(e);
506 return;
507 }
508 selectedNode = (Node) p;
509 } else if (p instanceof Way) {
510 if (selectedWay != null) {
511 // Too many ways selected to do something useful
512 tryAgain(e);
513 return;
514 }
515 selectedWay = (Way) p;
516 }
517 }
518
519 // the node from which we make a connection
520 Node n0 = findNodeToContinueFrom(selectedNode, selectedWay);
521 // We have a selection but it isn't suitable. Try again.
522 if (n0 == null) {
523 tryAgain(e);
524 return;
525 }
526 if (!wayIsFinishedTemp) {
527 if (isSelfContainedWay(selectedWay, n0, n))
528 return;
529
530 // User clicked last node again, finish way
531 if (n0 == n) {
532 finishDrawing();
533 return;
534 }
535
536 // Ok we know now that we'll insert a line segment, but will it connect to an
537 // existing way or make a new way of its own? The "alt" modifier means that the
538 // user wants a new way.
539 Way way = alt ? null : (selectedWay != null ? selectedWay : getWayForNode(n0));
540 Way wayToSelect;
541
542 // Don't allow creation of self-overlapping ways
543 if (way != null) {
544 int nodeCount = 0;
545 for (Node p : way.getNodes()) {
546 if (p.equals(n0)) {
547 nodeCount++;
548 }
549 }
550 if (nodeCount > 1) {
551 way = null;
552 }
553 }
554
555 if (way == null) {
556 way = new Way();
557 way.addNode(n0);
558 cmds.add(new AddCommand(way));
559 wayToSelect = way;
560 } else {
561 int i;
562 if ((i = replacedWays.indexOf(way)) != -1) {
563 way = reuseWays.get(i);
564 wayToSelect = way;
565 } else {
566 wayToSelect = way;
567 Way wnew = new Way(way);
568 cmds.add(new ChangeCommand(way, wnew));
569 way = wnew;
570 }
571 }
572
573 // Connected to a node that's already in the way
574 if (way.containsNode(n)) {
575 wayIsFinished = true;
576 selection.clear();
577 }
578
579 // Add new node to way
580 if (way.getNode(way.getNodesCount() - 1) == n0) {
581 way.addNode(n);
582 } else {
583 way.addNode(0, n);
584 }
585
586 extendedWay = true;
587 newSelection.clear();
588 newSelection.add(wayToSelect);
589 }
590 }
591
592 String title;
593 if (!extendedWay) {
594 if (!newNode)
595 return; // We didn't do anything.
596 else if (reuseWays.isEmpty()) {
597 title = tr("Add node");
598 } else {
599 title = tr("Add node into way");
600 for (Way w : reuseWays) {
601 newSelection.remove(w);
602 }
603 }
604 newSelection.clear();
605 newSelection.add(n);
606 } else if (!newNode) {
607 title = tr("Connect existing way to node");
608 } else if (reuseWays.isEmpty()) {
609 title = tr("Add a new node to an existing way");
610 } else {
611 title = tr("Add node into way and connect");
612 }
613
614 Command c = new SequenceCommand(title, cmds);
615
616 Main.main.undoRedo.add(c);
617 if (!wayIsFinished) {
618 lastUsedNode = n;
619 }
620
621 ds.setSelected(newSelection);
622
623 // "viewport following" mode for tracing long features
624 // from aerial imagery or GPS tracks.
625 if (n != null && Main.map.mapView.viewportFollowing) {
626 Main.map.mapView.smoothScrollTo(n.getEastNorth());
627 }
628 computeHelperLine();
629 removeHighlighting();
630 }
631
632 private void insertNodeIntoAllNearbySegments(List<WaySegment> wss, Node n, Collection<OsmPrimitive> newSelection,
633 Collection<Command> cmds, List<Way> replacedWays, List<Way> reuseWays) {
634 Map<Way, List<Integer>> insertPoints = new HashMap<>();
635 for (WaySegment ws : wss) {
636 List<Integer> is;
637 if (insertPoints.containsKey(ws.way)) {
638 is = insertPoints.get(ws.way);
639 } else {
640 is = new ArrayList<>();
641 insertPoints.put(ws.way, is);
642 }
643
644 is.add(ws.lowerIndex);
645 }
646
647 Set<Pair<Node, Node>> segSet = new HashSet<>();
648
649 for (Map.Entry<Way, List<Integer>> insertPoint : insertPoints.entrySet()) {
650 Way w = insertPoint.getKey();
651 List<Integer> is = insertPoint.getValue();
652
653 Way wnew = new Way(w);
654
655 pruneSuccsAndReverse(is);
656 for (int i : is) {
657 segSet.add(Pair.sort(new Pair<>(w.getNode(i), w.getNode(i+1))));
658 wnew.addNode(i + 1, n);
659 }
660
661 // If ALT is pressed, a new way should be created and that new way should get
662 // selected. This works everytime unless the ways the nodes get inserted into
663 // are already selected. This is the case when creating a self-overlapping way
664 // but pressing ALT prevents this. Therefore we must de-select the way manually
665 // here so /only/ the new way will be selected after this method finishes.
666 if (alt) {
667 newSelection.add(insertPoint.getKey());
668 }
669
670 cmds.add(new ChangeCommand(insertPoint.getKey(), wnew));
671 replacedWays.add(insertPoint.getKey());
672 reuseWays.add(wnew);
673 }
674
675 adjustNode(segSet, n);
676 }
677
678 /**
679 * Prevent creation of ways that look like this: &lt;----&gt;
680 * This happens if users want to draw a no-exit-sideway from the main way like this:
681 * ^
682 * |&lt;----&gt;
683 * |
684 * The solution isn't ideal because the main way will end in the side way, which is bad for
685 * navigation software ("drive straight on") but at least easier to fix. Maybe users will fix
686 * it on their own, too. At least it's better than producing an error.
687 *
688 * @param selectedWay the way to check
689 * @param currentNode the current node (i.e. the one the connection will be made from)
690 * @param targetNode the target node (i.e. the one the connection will be made to)
691 * @return {@code true} if this would create a selfcontaining way, {@code false} otherwise.
692 */
693 private boolean isSelfContainedWay(Way selectedWay, Node currentNode, Node targetNode) {
694 if (selectedWay != null) {
695 int posn0 = selectedWay.getNodes().indexOf(currentNode);
696 // CHECKSTYLE.OFF: SingleSpaceSeparator
697 if ((posn0 != -1 && // n0 is part of way
698 (posn0 >= 1 && targetNode.equals(selectedWay.getNode(posn0-1)))) || // previous node
699 (posn0 < selectedWay.getNodesCount()-1 && targetNode.equals(selectedWay.getNode(posn0+1)))) { // next node
700 getLayerManager().getEditDataSet().setSelected(targetNode);
701 lastUsedNode = targetNode;
702 return true;
703 }
704 // CHECKSTYLE.ON: SingleSpaceSeparator
705 }
706
707 return false;
708 }
709
710 /**
711 * Finds a node to continue drawing from. Decision is based upon given node and way.
712 * @param selectedNode Currently selected node, may be null
713 * @param selectedWay Currently selected way, may be null
714 * @return Node if a suitable node is found, null otherwise
715 */
716 private Node findNodeToContinueFrom(Node selectedNode, Way selectedWay) {
717 // No nodes or ways have been selected, this occurs when a relation
718 // has been selected or the selection is empty
719 if (selectedNode == null && selectedWay == null)
720 return null;
721
722 if (selectedNode == null) {
723 if (selectedWay.isFirstLastNode(lastUsedNode))
724 return lastUsedNode;
725
726 // We have a way selected, but no suitable node to continue from. Start anew.
727 return null;
728 }
729
730 if (selectedWay == null)
731 return selectedNode;
732
733 if (selectedWay.isFirstLastNode(selectedNode))
734 return selectedNode;
735
736 // We have a way and node selected, but it's not at the start/end of the way. Start anew.
737 return null;
738 }
739
740 @Override
741 public void mouseDragged(MouseEvent e) {
742 mouseMoved(e);
743 }
744
745 @Override
746 public void mouseMoved(MouseEvent e) {
747 if (!Main.map.mapView.isActiveLayerDrawable())
748 return;
749
750 // we copy ctrl/alt/shift from the event just in case our global
751 // keyDetector didn't make it through the security manager. Unclear
752 // if that can ever happen but better be safe.
753 updateKeyModifiers(e);
754 mousePos = e.getPoint();
755 if (snapHelper.isSnapOn() && ctrl)
756 tryToSetBaseSegmentForAngleSnap();
757
758 computeHelperLine();
759 addHighlighting();
760 }
761
762 /**
763 * This method is used to detect segment under mouse and use it as reference for angle snapping
764 */
765 private void tryToSetBaseSegmentForAngleSnap() {
766 WaySegment seg = Main.map.mapView.getNearestWaySegment(mousePos, OsmPrimitive::isSelectable);
767 if (seg != null) {
768 snapHelper.setBaseSegment(seg);
769 }
770 }
771
772 /**
773 * This method prepares data required for painting the "helper line" from
774 * the last used position to the mouse cursor. It duplicates some code from
775 * mouseReleased() (FIXME).
776 */
777 private void computeHelperLine() {
778 if (mousePos == null) {
779 // Don't draw the line.
780 currentMouseEastNorth = null;
781 currentBaseNode = null;
782 return;
783 }
784
785 Collection<OsmPrimitive> selection = getLayerManager().getEditDataSet().getSelected();
786
787 MapView mv = Main.map.mapView;
788 Node currentMouseNode = null;
789 mouseOnExistingNode = null;
790 mouseOnExistingWays = new HashSet<>();
791
792 showStatusInfo(-1, -1, -1, snapHelper.isSnapOn());
793
794 if (!ctrl && mousePos != null) {
795 currentMouseNode = mv.getNearestNode(mousePos, OsmPrimitive::isSelectable);
796 }
797
798 // We need this for highlighting and we'll only do so if we actually want to re-use
799 // *and* there is no node nearby (because nodes beat ways when re-using)
800 if (!ctrl && currentMouseNode == null) {
801 List<WaySegment> wss = mv.getNearestWaySegments(mousePos, OsmPrimitive::isSelectable);
802 for (WaySegment ws : wss) {
803 mouseOnExistingWays.add(ws.way);
804 }
805 }
806
807 if (currentMouseNode != null) {
808 // user clicked on node
809 if (selection.isEmpty()) return;
810 currentMouseEastNorth = currentMouseNode.getEastNorth();
811 mouseOnExistingNode = currentMouseNode;
812 } else {
813 // no node found in clicked area
814 currentMouseEastNorth = mv.getEastNorth(mousePos.x, mousePos.y);
815 }
816
817 determineCurrentBaseNodeAndPreviousNode(selection);
818 if (previousNode == null) {
819 snapHelper.noSnapNow();
820 }
821
822 if (getCurrentBaseNode() == null || getCurrentBaseNode() == currentMouseNode)
823 return; // Don't create zero length way segments.
824
825
826 double curHdg = Math.toDegrees(getCurrentBaseNode().getEastNorth()
827 .heading(currentMouseEastNorth));
828 double baseHdg = -1;
829 if (previousNode != null) {
830 EastNorth en = previousNode.getEastNorth();
831 if (en != null) {
832 baseHdg = Math.toDegrees(en.heading(getCurrentBaseNode().getEastNorth()));
833 }
834 }
835
836 snapHelper.checkAngleSnapping(currentMouseEastNorth, baseHdg, curHdg);
837
838 // status bar was filled by snapHelper
839 }
840
841 private static void showStatusInfo(double angle, double hdg, double distance, boolean activeFlag) {
842 Main.map.statusLine.setAngle(angle);
843 Main.map.statusLine.activateAnglePanel(activeFlag);
844 Main.map.statusLine.setHeading(hdg);
845 Main.map.statusLine.setDist(distance);
846 }
847
848 /**
849 * Helper function that sets fields currentBaseNode and previousNode
850 * @param selection
851 * uses also lastUsedNode field
852 */
853 private void determineCurrentBaseNodeAndPreviousNode(Collection<OsmPrimitive> selection) {
854 Node selectedNode = null;
855 Way selectedWay = null;
856 for (OsmPrimitive p : selection) {
857 if (p instanceof Node) {
858 if (selectedNode != null)
859 return;
860 selectedNode = (Node) p;
861 } else if (p instanceof Way) {
862 if (selectedWay != null)
863 return;
864 selectedWay = (Way) p;
865 }
866 }
867 // we are here, if not more than 1 way or node is selected,
868
869 // the node from which we make a connection
870 currentBaseNode = null;
871 previousNode = null;
872
873 // Try to find an open way to measure angle from it. The way is not to be continued!
874 // warning: may result in changes of currentBaseNode and previousNode
875 // please remove if bugs arise
876 if (selectedWay == null && selectedNode != null) {
877 for (OsmPrimitive p: selectedNode.getReferrers()) {
878 if (p.isUsable() && p instanceof Way && ((Way) p).isFirstLastNode(selectedNode)) {
879 if (selectedWay != null) { // two uncontinued ways, nothing to take as reference
880 selectedWay = null;
881 break;
882 } else {
883 // set us ~continue this way (measure angle from it)
884 selectedWay = (Way) p;
885 }
886 }
887 }
888 }
889
890 if (selectedNode == null) {
891 if (selectedWay == null)
892 return;
893 continueWayFromNode(selectedWay, lastUsedNode);
894 } else if (selectedWay == null) {
895 currentBaseNode = selectedNode;
896 } else if (!selectedWay.isDeleted()) { // fix #7118
897 continueWayFromNode(selectedWay, selectedNode);
898 }
899 }
900
901 /**
902 * if one of the ends of {@code way} is given {@code node},
903 * then set currentBaseNode = node and previousNode = adjacent node of way
904 * @param way way to continue
905 * @param node starting node
906 */
907 private void continueWayFromNode(Way way, Node node) {
908 int n = way.getNodesCount();
909 if (node == way.firstNode()) {
910 currentBaseNode = node;
911 if (n > 1) previousNode = way.getNode(1);
912 } else if (node == way.lastNode()) {
913 currentBaseNode = node;
914 if (n > 1) previousNode = way.getNode(n-2);
915 }
916 }
917
918 /**
919 * Repaint on mouse exit so that the helper line goes away.
920 */
921 @Override
922 public void mouseExited(MouseEvent e) {
923 OsmDataLayer editLayer = Main.getLayerManager().getEditLayer();
924 if (editLayer == null)
925 return;
926 mousePos = e.getPoint();
927 snapHelper.noSnapNow();
928 boolean repaintIssued = removeHighlighting();
929 // force repaint in case snapHelper needs one. If removeHighlighting
930 // caused one already, don’t do it again.
931 if (!repaintIssued) {
932 editLayer.invalidate();
933 }
934 }
935
936 /**
937 * @param n node
938 * @return If the node is the end of exactly one way, return this.
939 * <code>null</code> otherwise.
940 */
941 public static Way getWayForNode(Node n) {
942 Way way = null;
943 for (Way w : Utils.filteredCollection(n.getReferrers(), Way.class)) {
944 if (!w.isUsable() || w.getNodesCount() < 1) {
945 continue;
946 }
947 Node firstNode = w.getNode(0);
948 Node lastNode = w.getNode(w.getNodesCount() - 1);
949 if ((firstNode == n || lastNode == n) && (firstNode != lastNode)) {
950 if (way != null)
951 return null;
952 way = w;
953 }
954 }
955 return way;
956 }
957
958 /**
959 * Replies the current base node, after having checked it is still usable (see #11105).
960 * @return the current base node (can be null). If not-null, it's guaranteed the node is usable
961 */
962 public Node getCurrentBaseNode() {
963 if (currentBaseNode != null && (currentBaseNode.getDataSet() == null || !currentBaseNode.isUsable())) {
964 currentBaseNode = null;
965 }
966 return currentBaseNode;
967 }
968
969 private static void pruneSuccsAndReverse(List<Integer> is) {
970 Set<Integer> is2 = new HashSet<>();
971 for (int i : is) {
972 if (!is2.contains(i - 1) && !is2.contains(i + 1)) {
973 is2.add(i);
974 }
975 }
976 is.clear();
977 is.addAll(is2);
978 Collections.sort(is);
979 Collections.reverse(is);
980 }
981
982 /**
983 * Adjusts the position of a node to lie on a segment (or a segment
984 * intersection).
985 *
986 * If one or more than two segments are passed, the node is adjusted
987 * to lie on the first segment that is passed.
988 *
989 * If two segments are passed, the node is adjusted to be at their
990 * intersection.
991 *
992 * No action is taken if no segments are passed.
993 *
994 * @param segs the segments to use as a reference when adjusting
995 * @param n the node to adjust
996 */
997 private static void adjustNode(Collection<Pair<Node, Node>> segs, Node n) {
998
999 switch (segs.size()) {
1000 case 0:
1001 return;
1002 case 2:
1003 // This computes the intersection between the two segments and adjusts the node position.
1004 Iterator<Pair<Node, Node>> i = segs.iterator();
1005 Pair<Node, Node> seg = i.next();
1006 EastNorth pA = seg.a.getEastNorth();
1007 EastNorth pB = seg.b.getEastNorth();
1008 seg = i.next();
1009 EastNorth pC = seg.a.getEastNorth();
1010 EastNorth pD = seg.b.getEastNorth();
1011
1012 double u = det(pB.east() - pA.east(), pB.north() - pA.north(), pC.east() - pD.east(), pC.north() - pD.north());
1013
1014 // Check for parallel segments and do nothing if they are
1015 // In practice this will probably only happen when a way has been duplicated
1016
1017 if (u == 0)
1018 return;
1019
1020 // q is a number between 0 and 1
1021 // It is the point in the segment where the intersection occurs
1022 // if the segment is scaled to lenght 1
1023
1024 double q = det(pB.north() - pC.north(), pB.east() - pC.east(), pD.north() - pC.north(), pD.east() - pC.east()) / u;
1025 EastNorth intersection = new EastNorth(
1026 pB.east() + q * (pA.east() - pB.east()),
1027 pB.north() + q * (pA.north() - pB.north()));
1028
1029
1030 // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise
1031 // fall through to default action.
1032 // (for semi-parallel lines, intersection might be miles away!)
1033 if (Main.map.mapView.getPoint2D(n).distance(Main.map.mapView.getPoint2D(intersection)) < snapToIntersectionThreshold) {
1034 n.setEastNorth(intersection);
1035 return;
1036 }
1037 default:
1038 EastNorth p = n.getEastNorth();
1039 seg = segs.iterator().next();
1040 pA = seg.a.getEastNorth();
1041 pB = seg.b.getEastNorth();
1042 double a = p.distanceSq(pB);
1043 double b = p.distanceSq(pA);
1044 double c = pA.distanceSq(pB);
1045 q = (a - b + c) / (2*c);
1046 n.setEastNorth(new EastNorth(pB.east() + q * (pA.east() - pB.east()), pB.north() + q * (pA.north() - pB.north())));
1047 }
1048 }
1049
1050 // helper for adjustNode
1051 static double det(double a, double b, double c, double d) {
1052 return a * d - b * c;
1053 }
1054
1055 private void tryToMoveNodeOnIntersection(List<WaySegment> wss, Node n) {
1056 if (wss.isEmpty())
1057 return;
1058 WaySegment ws = wss.get(0);
1059 EastNorth p1 = ws.getFirstNode().getEastNorth();
1060 EastNorth p2 = ws.getSecondNode().getEastNorth();
1061 if (snapHelper.dir2 != null && getCurrentBaseNode() != null) {
1062 EastNorth xPoint = Geometry.getSegmentSegmentIntersection(p1, p2, snapHelper.dir2,
1063 getCurrentBaseNode().getEastNorth());
1064 if (xPoint != null) {
1065 n.setEastNorth(xPoint);
1066 }
1067 }
1068 }
1069
1070 /**
1071 * Takes the data from computeHelperLine to determine which ways/nodes should be highlighted
1072 * (if feature enabled). Also sets the target cursor if appropriate. It adds the to-be-
1073 * highlighted primitives to newHighlights but does not actually highlight them. This work is
1074 * done in redrawIfRequired. This means, calling addHighlighting() without redrawIfRequired()
1075 * will leave the data in an inconsistent state.
1076 *
1077 * The status bar derives its information from oldHighlights, so in order to update the status
1078 * bar both addHighlighting() and repaintIfRequired() are needed, since former fills newHighlights
1079 * and latter processes them into oldHighlights.
1080 */
1081 private void addHighlighting() {
1082 newHighlights = new HashSet<>();
1083
1084 // if ctrl key is held ("no join"), don't highlight anything
1085 if (ctrl) {
1086 Main.map.mapView.setNewCursor(cursor, this);
1087 redrawIfRequired();
1088 return;
1089 }
1090
1091 // This happens when nothing is selected, but we still want to highlight the "target node"
1092 if (mouseOnExistingNode == null && getLayerManager().getEditDataSet().selectionEmpty() && mousePos != null) {
1093 mouseOnExistingNode = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive::isSelectable);
1094 }
1095
1096 if (mouseOnExistingNode != null) {
1097 Main.map.mapView.setNewCursor(cursorJoinNode, this);
1098 newHighlights.add(mouseOnExistingNode);
1099 redrawIfRequired();
1100 return;
1101 }
1102
1103 // Insert the node into all the nearby way segments
1104 if (mouseOnExistingWays.isEmpty()) {
1105 Main.map.mapView.setNewCursor(cursor, this);
1106 redrawIfRequired();
1107 return;
1108 }
1109
1110 Main.map.mapView.setNewCursor(cursorJoinWay, this);
1111 newHighlights.addAll(mouseOnExistingWays);
1112 redrawIfRequired();
1113 }
1114
1115 /**
1116 * Removes target highlighting from primitives. Issues repaint if required.
1117 * @return true if a repaint has been issued.
1118 */
1119 private boolean removeHighlighting() {
1120 newHighlights = new HashSet<>();
1121 return redrawIfRequired();
1122 }
1123
1124 @Override
1125 public void paint(Graphics2D g, MapView mv, Bounds box) {
1126 // sanity checks
1127 if (Main.map.mapView == null || mousePos == null
1128 // don't draw line if we don't know where from or where to
1129 || getCurrentBaseNode() == null || currentMouseEastNorth == null
1130 // don't draw line if mouse is outside window
1131 || !Main.map.mapView.getBounds().contains(mousePos))
1132 return;
1133
1134 Graphics2D g2 = g;
1135 snapHelper.drawIfNeeded(g2, mv);
1136 if (!drawHelperLine || wayIsFinished || shift)
1137 return;
1138
1139 if (!snapHelper.isActive()) { // else use color and stoke from snapHelper.draw
1140 g2.setColor(rubberLineColor);
1141 g2.setStroke(rubberLineStroke);
1142 } else if (!snapHelper.drawConstructionGeometry)
1143 return;
1144 MapPath2D b = new MapPath2D();
1145 MapViewPoint p1 = mv.getState().getPointFor(getCurrentBaseNode());
1146 MapViewPoint p2 = mv.getState().getPointFor(currentMouseEastNorth);
1147
1148 b.moveTo(p1);
1149 b.lineTo(p2);
1150
1151 // if alt key is held ("start new way"), draw a little perpendicular line
1152 if (alt) {
1153 START_WAY_INDICATOR.paintArrowAt(b, p1, p2);
1154 }
1155
1156 g2.draw(b);
1157 g2.setStroke(BASIC_STROKE);
1158 }
1159
1160 @Override
1161 public String getModeHelpText() {
1162 StringBuilder rv;
1163 /*
1164 * No modifiers: all (Connect, Node Re-Use, Auto-Weld)
1165 * CTRL: disables node re-use, auto-weld
1166 * Shift: do not make connection
1167 * ALT: make connection but start new way in doing so
1168 */
1169
1170 /*
1171 * Status line text generation is split into two parts to keep it maintainable.
1172 * First part looks at what will happen to the new node inserted on click and
1173 * the second part will look if a connection is made or not.
1174 *
1175 * Note that this help text is not absolutely accurate as it doesn't catch any special
1176 * cases (e.g. when preventing <---> ways). The only special that it catches is when
1177 * a way is about to be finished.
1178 *
1179 * First check what happens to the new node.
1180 */
1181
1182 // oldHighlights stores the current highlights. If this
1183 // list is empty we can assume that we won't do any joins
1184 if (ctrl || oldHighlights.isEmpty()) {
1185 rv = new StringBuilder(tr("Create new node."));
1186 } else {
1187 // oldHighlights may store a node or way, check if it's a node
1188 OsmPrimitive x = oldHighlights.iterator().next();
1189 if (x instanceof Node) {
1190 rv = new StringBuilder(tr("Select node under cursor."));
1191 } else {
1192 rv = new StringBuilder(trn("Insert new node into way.", "Insert new node into {0} ways.",
1193 oldHighlights.size(), oldHighlights.size()));
1194 }
1195 }
1196
1197 /*
1198 * Check whether a connection will be made
1199 */
1200 if (getCurrentBaseNode() != null && !wayIsFinished) {
1201 if (alt) {
1202 rv.append(' ').append(tr("Start new way from last node."));
1203 } else {
1204 rv.append(' ').append(tr("Continue way from last node."));
1205 }
1206 if (snapHelper.isSnapOn()) {
1207 rv.append(' ').append(tr("Angle snapping active."));
1208 }
1209 }
1210
1211 Node n = mouseOnExistingNode;
1212 DataSet ds = getLayerManager().getEditDataSet();
1213 /*
1214 * Handle special case: Highlighted node == selected node => finish drawing
1215 */
1216 if (n != null && ds != null && ds.getSelectedNodes().contains(n)) {
1217 if (wayIsFinished) {
1218 rv = new StringBuilder(tr("Select node under cursor."));
1219 } else {
1220 rv = new StringBuilder(tr("Finish drawing."));
1221 }
1222 }
1223
1224 /*
1225 * Handle special case: Self-Overlapping or closing way
1226 */
1227 if (ds != null && !ds.getSelectedWays().isEmpty() && !wayIsFinished && !alt) {
1228 Way w = ds.getSelectedWays().iterator().next();
1229 for (Node m : w.getNodes()) {
1230 if (m.equals(mouseOnExistingNode) || mouseOnExistingWays.contains(w)) {
1231 rv.append(' ').append(tr("Finish drawing."));
1232 break;
1233 }
1234 }
1235 }
1236 return rv.toString();
1237 }
1238
1239 /**
1240 * Get selected primitives, while draw action is in progress.
1241 *
1242 * While drawing a way, technically the last node is selected.
1243 * This is inconvenient when the user tries to add/edit tags to the way.
1244 * For this case, this method returns the current way as selection,
1245 * to work around this issue.
1246 * Otherwise the normal selection of the current data layer is returned.
1247 * @return selected primitives, while draw action is in progress
1248 */
1249 public Collection<OsmPrimitive> getInProgressSelection() {
1250 DataSet ds = getLayerManager().getEditDataSet();
1251 if (ds == null) return null;
1252 if (getCurrentBaseNode() != null && !ds.selectionEmpty()) {
1253 Way continueFrom = getWayForNode(getCurrentBaseNode());
1254 if (continueFrom != null)
1255 return Collections.<OsmPrimitive>singleton(continueFrom);
1256 }
1257 return ds.getSelected();
1258 }
1259
1260 @Override
1261 public boolean layerIsSupported(Layer l) {
1262 return l instanceof OsmDataLayer;
1263 }
1264
1265 @Override
1266 protected void updateEnabledState() {
1267 setEnabled(getLayerManager().getEditLayer() != null);
1268 }
1269
1270 @Override
1271 public void destroy() {
1272 super.destroy();
1273 snapChangeAction.destroy();
1274 }
1275
1276 public class BackSpaceAction extends AbstractAction {
1277
1278 @Override
1279 public void actionPerformed(ActionEvent e) {
1280 Main.main.undoRedo.undo();
1281 Command lastCmd = Main.main.undoRedo.commands.peekLast();
1282 if (lastCmd == null) return;
1283 Node n = null;
1284 for (OsmPrimitive p: lastCmd.getParticipatingPrimitives()) {
1285 if (p instanceof Node) {
1286 if (n == null) {
1287 n = (Node) p; // found one node
1288 wayIsFinished = false;
1289 } else {
1290 // if more than 1 node were affected by previous command,
1291 // we have no way to continue, so we forget about found node
1292 n = null;
1293 break;
1294 }
1295 }
1296 }
1297 // select last added node - maybe we will continue drawing from it
1298 if (n != null) {
1299 getLayerManager().getEditDataSet().addSelected(n);
1300 }
1301 }
1302 }
1303
1304 private class SnapHelper {
1305 private final class AnglePopupMenu extends JPopupMenu {
1306
1307 private final JCheckBoxMenuItem repeatedCb = new JCheckBoxMenuItem(
1308 new AbstractAction(tr("Toggle snapping by {0}", getShortcut().getKeyText())) {
1309 @Override
1310 public void actionPerformed(ActionEvent e) {
1311 boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
1312 Main.pref.put("draw.anglesnap.toggleOnRepeatedA", sel);
1313 init();
1314 }
1315 });
1316
1317 private final JCheckBoxMenuItem helperCb = new JCheckBoxMenuItem(
1318 new AbstractAction(tr("Show helper geometry")) {
1319 @Override
1320 public void actionPerformed(ActionEvent e) {
1321 boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
1322 Main.pref.put("draw.anglesnap.drawConstructionGeometry", sel);
1323 Main.pref.put("draw.anglesnap.drawProjectedPoint", sel);
1324 Main.pref.put("draw.anglesnap.showAngle", sel);
1325 init();
1326 enableSnapping();
1327 }
1328 });
1329
1330 private final JCheckBoxMenuItem projectionCb = new JCheckBoxMenuItem(
1331 new AbstractAction(tr("Snap to node projections")) {
1332 @Override
1333 public void actionPerformed(ActionEvent e) {
1334 boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
1335 Main.pref.put("draw.anglesnap.projectionsnap", sel);
1336 init();
1337 enableSnapping();
1338 }
1339 });
1340
1341 private AnglePopupMenu() {
1342 helperCb.setState(Main.pref.getBoolean("draw.anglesnap.drawConstructionGeometry", true));
1343 projectionCb.setState(Main.pref.getBoolean("draw.anglesnap.projectionsnapgvff", true));
1344 repeatedCb.setState(Main.pref.getBoolean("draw.anglesnap.toggleOnRepeatedA", true));
1345 add(repeatedCb);
1346 add(helperCb);
1347 add(projectionCb);
1348 add(new AbstractAction(tr("Disable")) {
1349 @Override public void actionPerformed(ActionEvent e) {
1350 saveAngles("180");
1351 init();
1352 enableSnapping();
1353 }
1354 });
1355 add(new AbstractAction(tr("0,90,...")) {
1356 @Override public void actionPerformed(ActionEvent e) {
1357 saveAngles("0", "90", "180");
1358 init();
1359 enableSnapping();
1360 }
1361 });
1362 add(new AbstractAction(tr("0,45,90,...")) {
1363 @Override public void actionPerformed(ActionEvent e) {
1364 saveAngles("0", "45", "90", "135", "180");
1365 init();
1366 enableSnapping();
1367 }
1368 });
1369 add(new AbstractAction(tr("0,30,45,60,90,...")) {
1370 @Override public void actionPerformed(ActionEvent e) {
1371 saveAngles("0", "30", "45", "60", "90", "120", "135", "150", "180");
1372 init();
1373 enableSnapping();
1374 }
1375 });
1376 }
1377 }
1378
1379 private boolean snapOn; // snapping is turned on
1380
1381 private boolean active; // snapping is active for current mouse position
1382 private boolean fixed; // snap angle is fixed
1383 private boolean absoluteFix; // snap angle is absolute
1384
1385 private boolean drawConstructionGeometry;
1386 private boolean showProjectedPoint;
1387 private boolean showAngle;
1388
1389 private boolean snapToProjections;
1390
1391 private EastNorth dir2;
1392 private EastNorth projected;
1393 private String labelText;
1394 private double lastAngle;
1395
1396 private double customBaseHeading = -1; // angle of base line, if not last segment)
1397 private EastNorth segmentPoint1; // remembered first point of base segment
1398 private EastNorth segmentPoint2; // remembered second point of base segment
1399 private EastNorth projectionSource; // point that we are projecting to the line
1400
1401 private double[] snapAngles;
1402 private double snapAngleTolerance;
1403
1404 private double pe, pn; // (pe, pn) - direction of snapping line
1405 private double e0, n0; // (e0, n0) - origin of snapping line
1406
1407 private final String fixFmt = "%d "+tr("FIX");
1408 private Color snapHelperColor;
1409 private Color highlightColor;
1410
1411 private Stroke normalStroke;
1412 private Stroke helperStroke;
1413 private Stroke highlightStroke;
1414
1415 private JCheckBoxMenuItem checkBox;
1416
1417 private final MouseListener anglePopupListener = new PopupMenuLauncher(new AnglePopupMenu()) {
1418 @Override
1419 public void mouseClicked(MouseEvent e) {
1420 super.mouseClicked(e);
1421 if (e.getButton() == MouseEvent.BUTTON1) {
1422 toggleSnapping();
1423 updateStatusLine();
1424 }
1425 }
1426 };
1427
1428 public void init() {
1429 snapOn = false;
1430 checkBox.setState(snapOn);
1431 fixed = false;
1432 absoluteFix = false;
1433
1434 Collection<String> angles = Main.pref.getCollection("draw.anglesnap.angles",
1435 Arrays.asList("0", "30", "45", "60", "90", "120", "135", "150", "180"));
1436
1437 snapAngles = new double[2*angles.size()];
1438 int i = 0;
1439 for (String s: angles) {
1440 try {
1441 snapAngles[i] = Double.parseDouble(s); i++;
1442 snapAngles[i] = 360-Double.parseDouble(s); i++;
1443 } catch (NumberFormatException e) {
1444 Main.warn("Incorrect number in draw.anglesnap.angles preferences: "+s);
1445 snapAngles[i] = 0; i++;
1446 snapAngles[i] = 0; i++;
1447 }
1448 }
1449 snapAngleTolerance = Main.pref.getDouble("draw.anglesnap.tolerance", 5.0);
1450 drawConstructionGeometry = Main.pref.getBoolean("draw.anglesnap.drawConstructionGeometry", true);
1451 showProjectedPoint = Main.pref.getBoolean("draw.anglesnap.drawProjectedPoint", true);
1452 snapToProjections = Main.pref.getBoolean("draw.anglesnap.projectionsnap", true);
1453
1454 showAngle = Main.pref.getBoolean("draw.anglesnap.showAngle", true);
1455 useRepeatedShortcut = Main.pref.getBoolean("draw.anglesnap.toggleOnRepeatedA", true);
1456
1457 normalStroke = rubberLineStroke;
1458 snapHelperColor = Main.pref.getColor(marktr("draw angle snap"), Color.ORANGE);
1459
1460 highlightColor = Main.pref.getColor(marktr("draw angle snap highlight"), ORANGE_TRANSPARENT);
1461 highlightStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.anglesnap.stroke.highlight", "10"));
1462 helperStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.anglesnap.stroke.helper", "1 4"));
1463 }
1464
1465 public void saveAngles(String ... angles) {
1466 Main.pref.putCollection("draw.anglesnap.angles", Arrays.asList(angles));
1467 }
1468
1469 public void setMenuCheckBox(JCheckBoxMenuItem checkBox) {
1470 this.checkBox = checkBox;
1471 }
1472
1473 public void drawIfNeeded(Graphics2D g2, MapView mv) {
1474 if (!snapOn || !active)
1475 return;
1476 MapViewPoint p1 = mv.getState().getPointFor(getCurrentBaseNode());
1477 MapViewPoint p2 = mv.getState().getPointFor(dir2);
1478 MapViewPoint p3 = mv.getState().getPointFor(projected);
1479 if (drawConstructionGeometry) {
1480 g2.setColor(snapHelperColor);
1481 g2.setStroke(helperStroke);
1482
1483 MapPath2D b = new MapPath2D();
1484 b.moveTo(p2);
1485 if (absoluteFix) {
1486 b.lineTo(2d*p1.getInViewX()-p2.getInViewX(), 2d*p1.getInViewY()-p2.getInViewY()); // bi-directional line
1487 } else {
1488 b.lineTo(p3);
1489 }
1490 g2.draw(b);
1491 }
1492 if (projectionSource != null) {
1493 g2.setColor(snapHelperColor);
1494 g2.setStroke(helperStroke);
1495 MapPath2D b = new MapPath2D();
1496 b.moveTo(p3);
1497 b.lineTo(mv.getState().getPointFor(projectionSource));
1498 g2.draw(b);
1499 }
1500
1501 if (customBaseHeading >= 0) {
1502 g2.setColor(highlightColor);
1503 g2.setStroke(highlightStroke);
1504 MapPath2D b = new MapPath2D();
1505 b.moveTo(mv.getState().getPointFor(segmentPoint1));
1506 b.lineTo(mv.getState().getPointFor(segmentPoint2));
1507 g2.draw(b);
1508 }
1509
1510 g2.setColor(rubberLineColor);
1511 g2.setStroke(normalStroke);
1512 MapPath2D b = new MapPath2D();
1513 b.moveTo(p1);
1514 b.lineTo(p3);
1515 g2.draw(b);
1516
1517 g2.drawString(labelText, (int) p3.getInViewX()-5, (int) p3.getInViewY()+20);
1518 if (showProjectedPoint) {
1519 g2.setStroke(normalStroke);
1520 g2.drawOval((int) p3.getInViewX()-5, (int) p3.getInViewY()-5, 10, 10); // projected point
1521 }
1522
1523 g2.setColor(snapHelperColor);
1524 g2.setStroke(helperStroke);
1525 }
1526
1527 /* If mouse position is close to line at 15-30-45-... angle, remembers this direction
1528 */
1529 public void checkAngleSnapping(EastNorth currentEN, double baseHeading, double curHeading) {
1530 EastNorth p0 = getCurrentBaseNode().getEastNorth();
1531 EastNorth snapPoint = currentEN;
1532 double angle = -1;
1533
1534 double activeBaseHeading = (customBaseHeading >= 0) ? customBaseHeading : baseHeading;
1535
1536 if (snapOn && (activeBaseHeading >= 0)) {
1537 angle = curHeading - activeBaseHeading;
1538 if (angle < 0) {
1539 angle += 360;
1540 }
1541 if (angle > 360) {
1542 angle = 0;
1543 }
1544
1545 double nearestAngle;
1546 if (fixed) {
1547 nearestAngle = lastAngle; // if direction is fixed use previous angle
1548 active = true;
1549 } else {
1550 nearestAngle = getNearestAngle(angle);
1551 if (getAngleDelta(nearestAngle, angle) < snapAngleTolerance) {
1552 active = customBaseHeading >= 0 || Math.abs(nearestAngle - 180) > 1e-3;
1553 // if angle is to previous segment, exclude 180 degrees
1554 lastAngle = nearestAngle;
1555 } else {
1556 active = false;
1557 }
1558 }
1559
1560 if (active) {
1561 double phi;
1562 e0 = p0.east();
1563 n0 = p0.north();
1564 buildLabelText((nearestAngle <= 180) ? nearestAngle : (nearestAngle-360));
1565
1566 phi = (nearestAngle + activeBaseHeading) * Math.PI / 180;
1567 // (pe,pn) - direction of snapping line
1568 pe = Math.sin(phi);
1569 pn = Math.cos(phi);
1570 double scale = 20 * Main.map.mapView.getDist100Pixel();
1571 dir2 = new EastNorth(e0 + scale * pe, n0 + scale * pn);
1572 snapPoint = getSnapPoint(currentEN);
1573 } else {
1574 noSnapNow();
1575 }
1576 }
1577
1578 // find out the distance, in metres, between the base point and projected point
1579 LatLon mouseLatLon = Main.map.mapView.getProjection().eastNorth2latlon(snapPoint);
1580 double distance = getCurrentBaseNode().getCoor().greatCircleDistance(mouseLatLon);
1581 double hdg = Math.toDegrees(p0.heading(snapPoint));
1582 // heading of segment from current to calculated point, not to mouse position
1583
1584 if (baseHeading >= 0) { // there is previous line segment with some heading
1585 angle = hdg - baseHeading;
1586 if (angle < 0) {
1587 angle += 360;
1588 }
1589 if (angle > 360) {
1590 angle = 0;
1591 }
1592 }
1593 showStatusInfo(angle, hdg, distance, isSnapOn());
1594 }
1595
1596 private void buildLabelText(double nearestAngle) {
1597 if (showAngle) {
1598 if (fixed) {
1599 if (absoluteFix) {
1600 labelText = "=";
1601 } else {
1602 labelText = String.format(fixFmt, (int) nearestAngle);
1603 }
1604 } else {
1605 labelText = String.format("%d", (int) nearestAngle);
1606 }
1607 } else {
1608 if (fixed) {
1609 if (absoluteFix) {
1610 labelText = "=";
1611 } else {
1612 labelText = String.format(tr("FIX"), 0);
1613 }
1614 } else {
1615 labelText = "";
1616 }
1617 }
1618 }
1619
1620 public EastNorth getSnapPoint(EastNorth p) {
1621 if (!active)
1622 return p;
1623 double de = p.east()-e0;
1624 double dn = p.north()-n0;
1625 double l = de*pe+dn*pn;
1626 double delta = Main.map.mapView.getDist100Pixel()/20;
1627 if (!absoluteFix && l < delta) {
1628 active = false;
1629 return p;
1630 } // do not go backward!
1631
1632 projectionSource = null;
1633 if (snapToProjections) {
1634 DataSet ds = getLayerManager().getEditDataSet();
1635 Collection<Way> selectedWays = ds.getSelectedWays();
1636 if (selectedWays.size() == 1) {
1637 Way w = selectedWays.iterator().next();
1638 Collection<EastNorth> pointsToProject = new ArrayList<>();
1639 if (w.getNodesCount() < 1000) {
1640 for (Node n: w.getNodes()) {
1641 pointsToProject.add(n.getEastNorth());
1642 }
1643 }
1644 if (customBaseHeading >= 0) {
1645 pointsToProject.add(segmentPoint1);
1646 pointsToProject.add(segmentPoint2);
1647 }
1648 EastNorth enOpt = null;
1649 double dOpt = 1e5;
1650 for (EastNorth en: pointsToProject) { // searching for besht projection
1651 double l1 = (en.east()-e0)*pe+(en.north()-n0)*pn;
1652 double d1 = Math.abs(l1-l);
1653 if (d1 < delta && d1 < dOpt) {
1654 l = l1;
1655 enOpt = en;
1656 dOpt = d1;
1657 }
1658 }
1659 if (enOpt != null) {
1660 projectionSource = enOpt;
1661 }
1662 }
1663 }
1664 projected = new EastNorth(e0+l*pe, n0+l*pn);
1665 return projected;
1666 }
1667
1668 public void noSnapNow() {
1669 active = false;
1670 dir2 = null;
1671 projected = null;
1672 labelText = null;
1673 }
1674
1675 public void setBaseSegment(WaySegment seg) {
1676 if (seg == null) return;
1677 segmentPoint1 = seg.getFirstNode().getEastNorth();
1678 segmentPoint2 = seg.getSecondNode().getEastNorth();
1679
1680 double hdg = segmentPoint1.heading(segmentPoint2);
1681 hdg = Math.toDegrees(hdg);
1682 if (hdg < 0) {
1683 hdg += 360;
1684 }
1685 if (hdg > 360) {
1686 hdg -= 360;
1687 }
1688 customBaseHeading = hdg;
1689 }
1690
1691 private void enableSnapping() {
1692 snapOn = true;
1693 checkBox.setState(snapOn);
1694 customBaseHeading = -1;
1695 unsetFixedMode();
1696 }
1697
1698 private void toggleSnapping() {
1699 snapOn = !snapOn;
1700 checkBox.setState(snapOn);
1701 customBaseHeading = -1;
1702 unsetFixedMode();
1703 }
1704
1705 public void setFixedMode() {
1706 if (active) {
1707 fixed = true;
1708 }
1709 }
1710
1711 public void unsetFixedMode() {
1712 fixed = false;
1713 absoluteFix = false;
1714 lastAngle = 0;
1715 active = false;
1716 }
1717
1718 public boolean isActive() {
1719 return active;
1720 }
1721
1722 public boolean isSnapOn() {
1723 return snapOn;
1724 }
1725
1726 private double getNearestAngle(double angle) {
1727 double delta, minDelta = 1e5, bestAngle = 0.0;
1728 for (double snapAngle : snapAngles) {
1729 delta = getAngleDelta(angle, snapAngle);
1730 if (delta < minDelta) {
1731 minDelta = delta;
1732 bestAngle = snapAngle;
1733 }
1734 }
1735 if (Math.abs(bestAngle-360) < 1e-3) {
1736 bestAngle = 0;
1737 }
1738 return bestAngle;
1739 }
1740
1741 private double getAngleDelta(double a, double b) {
1742 double delta = Math.abs(a-b);
1743 if (delta > 180)
1744 return 360-delta;
1745 else
1746 return delta;
1747 }
1748
1749 private void unFixOrTurnOff() {
1750 if (absoluteFix) {
1751 unsetFixedMode();
1752 } else {
1753 toggleSnapping();
1754 }
1755 }
1756 }
1757
1758 private class SnapChangeAction extends JosmAction {
1759 /**
1760 * Constructs a new {@code SnapChangeAction}.
1761 */
1762 SnapChangeAction() {
1763 super(tr("Angle snapping"), /* ICON() */ "anglesnap",
1764 tr("Switch angle snapping mode while drawing"), null, false);
1765 putValue("help", ht("/Action/Draw/AngleSnap"));
1766 }
1767
1768 @Override
1769 public void actionPerformed(ActionEvent e) {
1770 if (snapHelper != null) {
1771 snapHelper.toggleSnapping();
1772 }
1773 }
1774
1775 @Override
1776 protected void updateEnabledState() {
1777 setEnabled(Main.map != null && Main.map.mapMode instanceof DrawAction);
1778 }
1779 }
1780}
Note: See TracBrowser for help on using the repository browser.