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

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

pmd - Ternary operator with a boolean literal can be simplified with a boolean expression

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