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

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

sonar - Unused private method should be removed
sonar - Unused protected methods should be removed
sonar - Sections of code should not be "commented out"
sonar - Empty statements should be removed
sonar - squid:S1172 - Unused method parameters should be removed
sonar - squid:S1481 - Unused local variables should be removed

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