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

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

fix Checkstyle issues

  • Property svn:eol-style set to native
File size: 67.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions.mapmode;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.marktr;
6import static org.openstreetmap.josm.tools.I18n.tr;
7import static org.openstreetmap.josm.tools.I18n.trn;
8
9import java.awt.BasicStroke;
10import java.awt.Color;
11import java.awt.Cursor;
12import java.awt.Graphics2D;
13import java.awt.Point;
14import java.awt.Stroke;
15import java.awt.event.ActionEvent;
16import java.awt.event.KeyEvent;
17import java.awt.event.MouseEvent;
18import java.awt.event.MouseListener;
19import java.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 = null;
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 = false;
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 // would like to but haven't got mouse position yet:
239 // computeHelperLine(false, false, false);
240 }
241
242 private void readPreferences() {
243 rubberLineColor = Main.pref.getColor(marktr("helper line"), null);
244 if (rubberLineColor == null) rubberLineColor = PaintColors.SELECTED.get();
245
246 rubberLineStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.stroke.helper-line", "3"));
247 drawHelperLine = Main.pref.getBoolean("draw.helper-line", true);
248 drawTargetHighlight = Main.pref.getBoolean("draw.target-highlight", true);
249 snapToIntersectionThreshold = Main.pref.getInteger("edit.snap-intersection-threshold", 10);
250 }
251
252 @Override
253 public void exitMode() {
254 super.exitMode();
255 Main.map.mapView.removeMouseListener(this);
256 Main.map.mapView.removeMouseMotionListener(this);
257 Main.map.mapView.removeTemporaryLayer(this);
258 DataSet.removeSelectionListener(this);
259 Main.unregisterActionShortcut(backspaceAction, backspaceShortcut);
260 snapHelper.unsetFixedMode();
261 snapCheckboxMenuItem.getAction().setEnabled(false);
262
263 Main.map.statusLine.getAnglePanel().removeMouseListener(snapHelper.anglePopupListener);
264 Main.map.statusLine.activateAnglePanel(false);
265
266 removeHighlighting();
267 Main.map.keyDetector.removeKeyListener(this);
268 Main.map.keyDetector.removeModifierListener(this);
269
270 // when exiting we let everybody know about the currently selected
271 // primitives
272 //
273 DataSet ds = getCurrentDataSet();
274 if (ds != null) {
275 ds.fireSelectionChanged();
276 }
277 }
278
279 /**
280 * redraw to (possibly) get rid of helper line if selection changes.
281 */
282 @Override
283 public void modifiersChanged(int modifiers) {
284 if (!Main.isDisplayingMapView() || !Main.map.mapView.isActiveLayerDrawable())
285 return;
286 updateKeyModifiers(modifiers);
287 computeHelperLine();
288 addHighlighting();
289 }
290
291 @Override
292 public void doKeyPressed(KeyEvent e) {
293 if (!snappingShortcut.isEvent(e) && !(useRepeatedShortcut && getShortcut().isEvent(e)))
294 return;
295 snapHelper.setFixedMode();
296 computeHelperLine();
297 redrawIfRequired();
298 }
299
300 @Override
301 public void doKeyReleased(KeyEvent e) {
302 if (!snappingShortcut.isEvent(e) && !(useRepeatedShortcut && getShortcut().isEvent(e)))
303 return;
304 if (ignoreNextKeyRelease) {
305 ignoreNextKeyRelease = false;
306 return;
307 }
308 snapHelper.unFixOrTurnOff();
309 computeHelperLine();
310 redrawIfRequired();
311 }
312
313 /**
314 * redraw to (possibly) get rid of helper line if selection changes.
315 */
316 @Override
317 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
318 if (!Main.map.mapView.isActiveLayerDrawable())
319 return;
320 computeHelperLine();
321 addHighlighting();
322 }
323
324 private void tryAgain(MouseEvent e) {
325 getCurrentDataSet().setSelected();
326 mouseReleased(e);
327 }
328
329 /**
330 * This function should be called when the user wishes to finish his current draw action.
331 * If Potlatch Style is enabled, it will switch to select tool, otherwise simply disable
332 * the helper line until the user chooses to draw something else.
333 */
334 private void finishDrawing() {
335 // let everybody else know about the current selection
336 //
337 Main.main.getCurrentDataSet().fireSelectionChanged();
338 lastUsedNode = null;
339 wayIsFinished = true;
340 Main.map.selectSelectTool(true);
341 snapHelper.noSnapNow();
342
343 // Redraw to remove the helper line stub
344 computeHelperLine();
345 removeHighlighting();
346 }
347
348 private Point rightClickPressPos;
349
350 @Override
351 public void mousePressed(MouseEvent e) {
352 if (e.getButton() == MouseEvent.BUTTON3) {
353 rightClickPressPos = e.getPoint();
354 }
355 }
356
357 /**
358 * If user clicked with the left button, add a node at the current mouse
359 * position.
360 *
361 * If in nodeway mode, insert the node into the way.
362 */
363 @Override
364 public void mouseReleased(MouseEvent e) {
365 if (e.getButton() == MouseEvent.BUTTON3) {
366 Point curMousePos = e.getPoint();
367 if (curMousePos.equals(rightClickPressPos)) {
368 tryToSetBaseSegmentForAngleSnap();
369 }
370 return;
371 }
372 if (e.getButton() != MouseEvent.BUTTON1)
373 return;
374 if (!Main.map.mapView.isActiveLayerDrawable())
375 return;
376 // request focus in order to enable the expected keyboard shortcuts
377 //
378 Main.map.mapView.requestFocus();
379
380 if (e.getClickCount() > 1 && mousePos != null && mousePos.equals(oldMousePos)) {
381 // A double click equals "user clicked last node again, finish way"
382 // Change draw tool only if mouse position is nearly the same, as
383 // otherwise fast clicks will count as a double click
384 finishDrawing();
385 return;
386 }
387 oldMousePos = mousePos;
388
389 // we copy ctrl/alt/shift from the event just in case our global
390 // keyDetector didn't make it through the security manager. Unclear
391 // if that can ever happen but better be safe.
392 updateKeyModifiers(e);
393 mousePos = e.getPoint();
394
395 DataSet ds = getCurrentDataSet();
396 Collection<OsmPrimitive> selection = new ArrayList<>(ds.getSelected());
397 Collection<Command> cmds = new LinkedList<>();
398 Collection<OsmPrimitive> newSelection = new LinkedList<>(ds.getSelected());
399
400 List<Way> reuseWays = new ArrayList<>(),
401 replacedWays = new ArrayList<>();
402 boolean newNode = false;
403 Node n = null;
404
405 n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
406 if (ctrl) {
407 Iterator<Way> it = getCurrentDataSet().getSelectedWays().iterator();
408 if (it.hasNext()) {
409 // ctrl-click on node of selected way = reuse node despite of ctrl
410 if (!it.next().containsNode(n)) n = null;
411 } else {
412 n = null; // ctrl-click + no selected way = new node
413 }
414 }
415
416 if (n != null && !snapHelper.isActive()) {
417 // user clicked on node
418 if (selection.isEmpty() || wayIsFinished) {
419 // select the clicked node and do nothing else
420 // (this is just a convenience option so that people don't
421 // have to switch modes)
422
423 getCurrentDataSet().setSelected(n);
424 // If we extend/continue an existing way, select it already now to make it obvious
425 Way continueFrom = getWayForNode(n);
426 if (continueFrom != null) {
427 getCurrentDataSet().addSelected(continueFrom);
428 }
429
430 // The user explicitly selected a node, so let him continue drawing
431 wayIsFinished = false;
432 return;
433 }
434 } else {
435 EastNorth newEN;
436 if (n != null) {
437 EastNorth foundPoint = n.getEastNorth();
438 // project found node to snapping line
439 newEN = snapHelper.getSnapPoint(foundPoint);
440 // do not add new node if there is some node within snapping distance
441 double tolerance = Main.map.mapView.getDist100Pixel() * toleranceMultiplier;
442 if (foundPoint.distance(newEN) > tolerance) {
443 n = new Node(newEN); // point != projected, so we create new node
444 newNode = true;
445 }
446 } else { // n==null, no node found in clicked area
447 EastNorth mouseEN = Main.map.mapView.getEastNorth(e.getX(), e.getY());
448 newEN = snapHelper.isSnapOn() ? snapHelper.getSnapPoint(mouseEN) : mouseEN;
449 n = new Node(newEN); //create node at clicked point
450 newNode = true;
451 }
452 snapHelper.unsetFixedMode();
453 }
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 }
655 for (int i : is) {
656 wnew.addNode(i + 1, n);
657 }
658
659 // If ALT is pressed, a new way should be created and that new way should get
660 // selected. This works everytime unless the ways the nodes get inserted into
661 // are already selected. This is the case when creating a self-overlapping way
662 // but pressing ALT prevents this. Therefore we must de-select the way manually
663 // here so /only/ the new way will be selected after this method finishes.
664 if (alt) {
665 newSelection.add(insertPoint.getKey());
666 }
667
668 cmds.add(new ChangeCommand(insertPoint.getKey(), wnew));
669 replacedWays.add(insertPoint.getKey());
670 reuseWays.add(wnew);
671 }
672
673 adjustNode(segSet, n);
674 }
675
676 /**
677 * Prevent creation of ways that look like this: &lt;----&gt;
678 * This happens if users want to draw a no-exit-sideway from the main way like this:
679 * ^
680 * |&lt;----&gt;
681 * |
682 * The solution isn't ideal because the main way will end in the side way, which is bad for
683 * navigation software ("drive straight on") but at least easier to fix. Maybe users will fix
684 * it on their own, too. At least it's better than producing an error.
685 *
686 * @param selectedWay the way to check
687 * @param currentNode the current node (i.e. the one the connection will be made from)
688 * @param targetNode the target node (i.e. the one the connection will be made to)
689 * @return {@code true} if this would create a selfcontaining way, {@code false} otherwise.
690 */
691 private boolean isSelfContainedWay(Way selectedWay, Node currentNode, Node targetNode) {
692 if (selectedWay != null) {
693 int posn0 = selectedWay.getNodes().indexOf(currentNode);
694 if (posn0 != -1 && // n0 is part of way
695 (posn0 >= 1 && targetNode.equals(selectedWay.getNode(posn0-1))) || // previous node
696 (posn0 < selectedWay.getNodesCount()-1) && targetNode.equals(selectedWay.getNode(posn0+1))) { // next node
697 getCurrentDataSet().setSelected(targetNode);
698 lastUsedNode = targetNode;
699 return true;
700 }
701 }
702
703 return false;
704 }
705
706 /**
707 * Finds a node to continue drawing from. Decision is based upon given node and way.
708 * @param selectedNode Currently selected node, may be null
709 * @param selectedWay Currently selected way, may be null
710 * @return Node if a suitable node is found, null otherwise
711 */
712 private Node findNodeToContinueFrom(Node selectedNode, Way selectedWay) {
713 // No nodes or ways have been selected, this occurs when a relation
714 // has been selected or the selection is empty
715 if (selectedNode == null && selectedWay == null)
716 return null;
717
718 if (selectedNode == null) {
719 if (selectedWay.isFirstLastNode(lastUsedNode))
720 return lastUsedNode;
721
722 // We have a way selected, but no suitable node to continue from. Start anew.
723 return null;
724 }
725
726 if (selectedWay == null)
727 return selectedNode;
728
729 if (selectedWay.isFirstLastNode(selectedNode))
730 return selectedNode;
731
732 // We have a way and node selected, but it's not at the start/end of the way. Start anew.
733 return null;
734 }
735
736 @Override
737 public void mouseDragged(MouseEvent e) {
738 mouseMoved(e);
739 }
740
741 @Override
742 public void mouseMoved(MouseEvent e) {
743 if (!Main.map.mapView.isActiveLayerDrawable())
744 return;
745
746 // we copy ctrl/alt/shift from the event just in case our global
747 // keyDetector didn't make it through the security manager. Unclear
748 // if that can ever happen but better be safe.
749 updateKeyModifiers(e);
750 mousePos = e.getPoint();
751 if (snapHelper.isSnapOn() && ctrl)
752 tryToSetBaseSegmentForAngleSnap();
753
754 computeHelperLine();
755 addHighlighting();
756 }
757
758 /**
759 * This method is used to detect segment under mouse and use it as reference for angle snapping
760 */
761 private void tryToSetBaseSegmentForAngleSnap() {
762 WaySegment seg = Main.map.mapView.getNearestWaySegment(mousePos, OsmPrimitive.isSelectablePredicate);
763 if (seg != null) {
764 snapHelper.setBaseSegment(seg);
765 }
766 }
767
768 /**
769 * This method prepares data required for painting the "helper line" from
770 * the last used position to the mouse cursor. It duplicates some code from
771 * mouseReleased() (FIXME).
772 */
773 private void computeHelperLine() {
774 MapView mv = Main.map.mapView;
775 if (mousePos == null) {
776 // Don't draw the line.
777 currentMouseEastNorth = null;
778 currentBaseNode = null;
779 return;
780 }
781
782 Collection<OsmPrimitive> selection = getCurrentDataSet().getSelected();
783
784 Node currentMouseNode = null;
785 mouseOnExistingNode = null;
786 mouseOnExistingWays = new HashSet<>();
787
788 showStatusInfo(-1, -1, -1, snapHelper.isSnapOn());
789
790 if (!ctrl && mousePos != null) {
791 currentMouseNode = mv.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
792 }
793
794 // We need this for highlighting and we'll only do so if we actually want to re-use
795 // *and* there is no node nearby (because nodes beat ways when re-using)
796 if (!ctrl && currentMouseNode == null) {
797 List<WaySegment> wss = mv.getNearestWaySegments(mousePos, OsmPrimitive.isSelectablePredicate);
798 for (WaySegment ws : wss) {
799 mouseOnExistingWays.add(ws.way);
800 }
801 }
802
803 if (currentMouseNode != null) {
804 // user clicked on node
805 if (selection.isEmpty()) return;
806 currentMouseEastNorth = currentMouseNode.getEastNorth();
807 mouseOnExistingNode = currentMouseNode;
808 } else {
809 // no node found in clicked area
810 currentMouseEastNorth = mv.getEastNorth(mousePos.x, mousePos.y);
811 }
812
813 determineCurrentBaseNodeAndPreviousNode(selection);
814 if (previousNode == null) {
815 snapHelper.noSnapNow();
816 }
817
818 if (getCurrentBaseNode() == null || getCurrentBaseNode() == currentMouseNode)
819 return; // Don't create zero length way segments.
820
821
822 double curHdg = Math.toDegrees(getCurrentBaseNode().getEastNorth()
823 .heading(currentMouseEastNorth));
824 double baseHdg = -1;
825 if (previousNode != null) {
826 EastNorth en = previousNode.getEastNorth();
827 if (en != null) {
828 baseHdg = Math.toDegrees(en.heading(getCurrentBaseNode().getEastNorth()));
829 }
830 }
831
832 snapHelper.checkAngleSnapping(currentMouseEastNorth, baseHdg, curHdg);
833
834 // status bar was filled by snapHelper
835 }
836
837 private void showStatusInfo(double angle, double hdg, double distance, boolean activeFlag) {
838 Main.map.statusLine.setAngle(angle);
839 Main.map.statusLine.activateAnglePanel(activeFlag);
840 Main.map.statusLine.setHeading(hdg);
841 Main.map.statusLine.setDist(distance);
842 }
843
844 /**
845 * Helper function that sets fields currentBaseNode and previousNode
846 * @param selection
847 * uses also lastUsedNode field
848 */
849 private void determineCurrentBaseNodeAndPreviousNode(Collection<OsmPrimitive> selection) {
850 Node selectedNode = null;
851 Way selectedWay = null;
852 for (OsmPrimitive p : selection) {
853 if (p instanceof Node) {
854 if (selectedNode != null)
855 return;
856 selectedNode = (Node) p;
857 } else if (p instanceof Way) {
858 if (selectedWay != null)
859 return;
860 selectedWay = (Way) p;
861 }
862 }
863 // we are here, if not more than 1 way or node is selected,
864
865 // the node from which we make a connection
866 currentBaseNode = null;
867 previousNode = null;
868
869 // Try to find an open way to measure angle from it. The way is not to be continued!
870 // warning: may result in changes of currentBaseNode and previousNode
871 // please remove if bugs arise
872 if (selectedWay == null && selectedNode != null) {
873 for (OsmPrimitive p: selectedNode.getReferrers()) {
874 if (p.isUsable() && p instanceof Way && ((Way) p).isFirstLastNode(selectedNode)) {
875 if (selectedWay != null) { // two uncontinued ways, nothing to take as reference
876 selectedWay = null;
877 break;
878 } else {
879 // set us ~continue this way (measure angle from it)
880 selectedWay = (Way) p;
881 }
882 }
883 }
884 }
885
886 if (selectedNode == null) {
887 if (selectedWay == null)
888 return;
889 continueWayFromNode(selectedWay, lastUsedNode);
890 } else if (selectedWay == null) {
891 currentBaseNode = selectedNode;
892 } else if (!selectedWay.isDeleted()) { // fix #7118
893 continueWayFromNode(selectedWay, selectedNode);
894 }
895 }
896
897 /**
898 * if one of the ends of @param way is given @param node ,
899 * then set currentBaseNode = node and previousNode = adjacent node of way
900 */
901 private void continueWayFromNode(Way way, Node node) {
902 int n = way.getNodesCount();
903 if (node == way.firstNode()) {
904 currentBaseNode = node;
905 if (n > 1) previousNode = way.getNode(1);
906 } else if (node == way.lastNode()) {
907 currentBaseNode = node;
908 if (n > 1) previousNode = way.getNode(n-2);
909 }
910 }
911
912 /**
913 * Repaint on mouse exit so that the helper line goes away.
914 */
915 @Override
916 public void mouseExited(MouseEvent e) {
917 if (!Main.map.mapView.isActiveLayerDrawable())
918 return;
919 mousePos = e.getPoint();
920 snapHelper.noSnapNow();
921 boolean repaintIssued = removeHighlighting();
922 // force repaint in case snapHelper needs one. If removeHighlighting
923 // caused one already, don’t do it again.
924 if (!repaintIssued) {
925 Main.map.mapView.repaint();
926 }
927 }
928
929 /**
930 * @return If the node is the end of exactly one way, return this.
931 * <code>null</code> otherwise.
932 */
933 public static Way getWayForNode(Node n) {
934 Way way = null;
935 for (Way w : Utils.filteredCollection(n.getReferrers(), Way.class)) {
936 if (!w.isUsable() || w.getNodesCount() < 1) {
937 continue;
938 }
939 Node firstNode = w.getNode(0);
940 Node lastNode = w.getNode(w.getNodesCount() - 1);
941 if ((firstNode == n || lastNode == n) && (firstNode != lastNode)) {
942 if (way != null)
943 return null;
944 way = w;
945 }
946 }
947 return way;
948 }
949
950 /**
951 * Replies the current base node, after having checked it is still usable (see #11105).
952 * @return the current base node (can be null). If not-null, it's guaranteed the node is usable
953 */
954 public Node getCurrentBaseNode() {
955 if (currentBaseNode != null && (currentBaseNode.getDataSet() == null || !currentBaseNode.isUsable())) {
956 currentBaseNode = null;
957 }
958 return currentBaseNode;
959 }
960
961 private static void pruneSuccsAndReverse(List<Integer> is) {
962 Set<Integer> is2 = new HashSet<>();
963 for (int i : is) {
964 if (!is2.contains(i - 1) && !is2.contains(i + 1)) {
965 is2.add(i);
966 }
967 }
968 is.clear();
969 is.addAll(is2);
970 Collections.sort(is);
971 Collections.reverse(is);
972 }
973
974 /**
975 * Adjusts the position of a node to lie on a segment (or a segment
976 * intersection).
977 *
978 * If one or more than two segments are passed, the node is adjusted
979 * to lie on the first segment that is passed.
980 *
981 * If two segments are passed, the node is adjusted to be at their
982 * intersection.
983 *
984 * No action is taken if no segments are passed.
985 *
986 * @param segs the segments to use as a reference when adjusting
987 * @param n the node to adjust
988 */
989 private static void adjustNode(Collection<Pair<Node, Node>> segs, Node n) {
990
991 switch (segs.size()) {
992 case 0:
993 return;
994 case 2:
995 // This computes the intersection between the two segments and adjusts the node position.
996 Iterator<Pair<Node, Node>> i = segs.iterator();
997 Pair<Node, Node> seg = i.next();
998 EastNorth A = seg.a.getEastNorth();
999 EastNorth B = seg.b.getEastNorth();
1000 seg = i.next();
1001 EastNorth C = seg.a.getEastNorth();
1002 EastNorth D = seg.b.getEastNorth();
1003
1004 double u = det(B.east() - A.east(), B.north() - A.north(), C.east() - D.east(), C.north() - D.north());
1005
1006 // Check for parallel segments and do nothing if they are
1007 // In practice this will probably only happen when a way has been duplicated
1008
1009 if (u == 0)
1010 return;
1011
1012 // q is a number between 0 and 1
1013 // It is the point in the segment where the intersection occurs
1014 // if the segment is scaled to lenght 1
1015
1016 double q = det(B.north() - C.north(), B.east() - C.east(), D.north() - C.north(), D.east() - C.east()) / u;
1017 EastNorth intersection = new EastNorth(
1018 B.east() + q * (A.east() - B.east()),
1019 B.north() + q * (A.north() - B.north()));
1020
1021
1022 // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise
1023 // fall through to default action.
1024 // (for semi-parallel lines, intersection might be miles away!)
1025 if (Main.map.mapView.getPoint2D(n).distance(Main.map.mapView.getPoint2D(intersection)) < snapToIntersectionThreshold) {
1026 n.setEastNorth(intersection);
1027 return;
1028 }
1029 default:
1030 EastNorth P = n.getEastNorth();
1031 seg = segs.iterator().next();
1032 A = seg.a.getEastNorth();
1033 B = seg.b.getEastNorth();
1034 double a = P.distanceSq(B);
1035 double b = P.distanceSq(A);
1036 double c = A.distanceSq(B);
1037 q = (a - b + c) / (2*c);
1038 n.setEastNorth(new EastNorth(B.east() + q * (A.east() - B.east()), B.north() + q * (A.north() - B.north())));
1039 }
1040 }
1041
1042 // helper for adjustNode
1043 static double det(double a, double b, double c, double d) {
1044 return a * d - b * c;
1045 }
1046
1047 private void tryToMoveNodeOnIntersection(List<WaySegment> wss, Node n) {
1048 if (wss.isEmpty())
1049 return;
1050 WaySegment ws = wss.get(0);
1051 EastNorth p1 = ws.getFirstNode().getEastNorth();
1052 EastNorth p2 = ws.getSecondNode().getEastNorth();
1053 if (snapHelper.dir2 != null && getCurrentBaseNode() != null) {
1054 EastNorth xPoint = Geometry.getSegmentSegmentIntersection(p1, p2, snapHelper.dir2,
1055 getCurrentBaseNode().getEastNorth());
1056 if (xPoint != null) {
1057 n.setEastNorth(xPoint);
1058 }
1059 }
1060 }
1061 /**
1062 * Takes the data from computeHelperLine to determine which ways/nodes should be highlighted
1063 * (if feature enabled). Also sets the target cursor if appropriate. It adds the to-be-
1064 * highlighted primitives to newHighlights but does not actually highlight them. This work is
1065 * done in redrawIfRequired. This means, calling addHighlighting() without redrawIfRequired()
1066 * will leave the data in an inconsistent state.
1067 *
1068 * The status bar derives its information from oldHighlights, so in order to update the status
1069 * bar both addHighlighting() and repaintIfRequired() are needed, since former fills newHighlights
1070 * and latter processes them into oldHighlights.
1071 */
1072 private void addHighlighting() {
1073 newHighlights = new HashSet<>();
1074
1075 // if ctrl key is held ("no join"), don't highlight anything
1076 if (ctrl) {
1077 Main.map.mapView.setNewCursor(cursor, this);
1078 redrawIfRequired();
1079 return;
1080 }
1081
1082 // This happens when nothing is selected, but we still want to highlight the "target node"
1083 if (mouseOnExistingNode == null && getCurrentDataSet().getSelected().isEmpty()
1084 && mousePos != null) {
1085 mouseOnExistingNode = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
1086 }
1087
1088 if (mouseOnExistingNode != null) {
1089 Main.map.mapView.setNewCursor(cursorJoinNode, this);
1090 newHighlights.add(mouseOnExistingNode);
1091 redrawIfRequired();
1092 return;
1093 }
1094
1095 // Insert the node into all the nearby way segments
1096 if (mouseOnExistingWays.isEmpty()) {
1097 Main.map.mapView.setNewCursor(cursor, this);
1098 redrawIfRequired();
1099 return;
1100 }
1101
1102 Main.map.mapView.setNewCursor(cursorJoinWay, this);
1103 newHighlights.addAll(mouseOnExistingWays);
1104 redrawIfRequired();
1105 }
1106
1107 /**
1108 * Removes target highlighting from primitives. Issues repaint if required.
1109 * Returns true if a repaint has been issued.
1110 */
1111 private boolean removeHighlighting() {
1112 newHighlights = new HashSet<>();
1113 return redrawIfRequired();
1114 }
1115
1116 @Override
1117 public void paint(Graphics2D g, MapView mv, Bounds box) {
1118 // sanity checks
1119 if (Main.map.mapView == null || mousePos == null
1120 // don't draw line if we don't know where from or where to
1121 || getCurrentBaseNode() == null || currentMouseEastNorth == null
1122 // don't draw line if mouse is outside window
1123 || !Main.map.mapView.getBounds().contains(mousePos))
1124 return;
1125
1126 Graphics2D g2 = g;
1127 snapHelper.drawIfNeeded(g2, mv);
1128 if (!drawHelperLine || wayIsFinished || shift)
1129 return;
1130
1131 if (!snapHelper.isActive()) { // else use color and stoke from snapHelper.draw
1132 g2.setColor(rubberLineColor);
1133 g2.setStroke(rubberLineStroke);
1134 } else if (!snapHelper.drawConstructionGeometry)
1135 return;
1136 GeneralPath b = new GeneralPath();
1137 Point p1 = mv.getPoint(getCurrentBaseNode());
1138 Point p2 = mv.getPoint(currentMouseEastNorth);
1139
1140 double t = Math.atan2(p2.y-p1.y, p2.x-p1.x) + Math.PI;
1141
1142 b.moveTo(p1.x, p1.y);
1143 b.lineTo(p2.x, p2.y);
1144
1145 // if alt key is held ("start new way"), draw a little perpendicular line
1146 if (alt) {
1147 b.moveTo((int) (p1.x + 8*Math.cos(t+PHI)), (int) (p1.y + 8*Math.sin(t+PHI)));
1148 b.lineTo((int) (p1.x + 8*Math.cos(t-PHI)), (int) (p1.y + 8*Math.sin(t-PHI)));
1149 }
1150
1151 g2.draw(b);
1152 g2.setStroke(BASIC_STROKE);
1153 }
1154
1155 @Override
1156 public String getModeHelpText() {
1157 StringBuilder rv;
1158 /*
1159 * No modifiers: all (Connect, Node Re-Use, Auto-Weld)
1160 * CTRL: disables node re-use, auto-weld
1161 * Shift: do not make connection
1162 * ALT: make connection but start new way in doing so
1163 */
1164
1165 /*
1166 * Status line text generation is split into two parts to keep it maintainable.
1167 * First part looks at what will happen to the new node inserted on click and
1168 * the second part will look if a connection is made or not.
1169 *
1170 * Note that this help text is not absolutely accurate as it doesn't catch any special
1171 * cases (e.g. when preventing <---> ways). The only special that it catches is when
1172 * a way is about to be finished.
1173 *
1174 * First check what happens to the new node.
1175 */
1176
1177 // oldHighlights stores the current highlights. If this
1178 // list is empty we can assume that we won't do any joins
1179 if (ctrl || oldHighlights.isEmpty()) {
1180 rv = new StringBuilder(tr("Create new node."));
1181 } else {
1182 // oldHighlights may store a node or way, check if it's a node
1183 OsmPrimitive x = oldHighlights.iterator().next();
1184 if (x instanceof Node) {
1185 rv = new StringBuilder(tr("Select node under cursor."));
1186 } else {
1187 rv = new StringBuilder(trn("Insert new node into way.", "Insert new node into {0} ways.",
1188 oldHighlights.size(), oldHighlights.size()));
1189 }
1190 }
1191
1192 /*
1193 * Check whether a connection will be made
1194 */
1195 if (getCurrentBaseNode() != null && !wayIsFinished) {
1196 if (alt) {
1197 rv.append(' ').append(tr("Start new way from last node."));
1198 } else {
1199 rv.append(' ').append(tr("Continue way from last node."));
1200 }
1201 if (snapHelper.isSnapOn()) {
1202 rv.append(' ').append(tr("Angle snapping active."));
1203 }
1204 }
1205
1206 Node n = mouseOnExistingNode;
1207 /*
1208 * Handle special case: Highlighted node == selected node => finish drawing
1209 */
1210 if (n != null && getCurrentDataSet() != null && getCurrentDataSet().getSelectedNodes().contains(n)) {
1211 if (wayIsFinished) {
1212 rv = new StringBuilder(tr("Select node under cursor."));
1213 } else {
1214 rv = new StringBuilder(tr("Finish drawing."));
1215 }
1216 }
1217
1218 /*
1219 * Handle special case: Self-Overlapping or closing way
1220 */
1221 if (getCurrentDataSet() != null && !getCurrentDataSet().getSelectedWays().isEmpty() && !wayIsFinished && !alt) {
1222 Way w = getCurrentDataSet().getSelectedWays().iterator().next();
1223 for (Node m : w.getNodes()) {
1224 if (m.equals(mouseOnExistingNode) || mouseOnExistingWays.contains(w)) {
1225 rv.append(' ').append(tr("Finish drawing."));
1226 break;
1227 }
1228 }
1229 }
1230 return rv.toString();
1231 }
1232
1233 /**
1234 * Get selected primitives, while draw action is in progress.
1235 *
1236 * While drawing a way, technically the last node is selected.
1237 * This is inconvenient when the user tries to add/edit tags to the way.
1238 * For this case, this method returns the current way as selection,
1239 * to work around this issue.
1240 * Otherwise the normal selection of the current data layer is returned.
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 Node n = null;
1275 Command lastCmd = Main.main.undoRedo.commands.peekLast();
1276 if (lastCmd == null) return;
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 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) ? true : 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.