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

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

see #12943 - gsoc-core - fix most of deprecation warnings (static accesses must be fixed)

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