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

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

remove extra whitespaces

  • Property svn:eol-style set to native
File size: 66.8 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
480 // existing node.
481
482 // For a connection to be made, the user must either have a node selected (connection
483 // is made to that node), or he must have a way selected *and* one of the endpoints
484 // of that way must be the last used node (connection is made to last used node), or
485 // he must have a way and a node selected (connection is made to the selected node).
486
487 // If the above does not apply, the selection is cleared and a new try is started
488
489 boolean extendedWay = false;
490 boolean wayIsFinishedTemp = wayIsFinished;
491 wayIsFinished = false;
492
493 // don't draw lines if shift is held
494 if (!selection.isEmpty() && !shift) {
495 Node selectedNode = null;
496 Way selectedWay = null;
497
498 for (OsmPrimitive p : selection) {
499 if (p instanceof Node) {
500 if (selectedNode != null) {
501 // Too many nodes selected to do something useful
502 tryAgain(e);
503 return;
504 }
505 selectedNode = (Node) p;
506 } else if (p instanceof Way) {
507 if (selectedWay != null) {
508 // Too many ways selected to do something useful
509 tryAgain(e);
510 return;
511 }
512 selectedWay = (Way) p;
513 }
514 }
515
516 // the node from which we make a connection
517 Node n0 = findNodeToContinueFrom(selectedNode, selectedWay);
518 // We have a selection but it isn't suitable. Try again.
519 if(n0 == null) {
520 tryAgain(e);
521 return;
522 }
523 if(!wayIsFinishedTemp){
524 if(isSelfContainedWay(selectedWay, n0, n))
525 return;
526
527 // User clicked last node again, finish way
528 if(n0 == n) {
529 finishDrawing();
530 return;
531 }
532
533 // Ok we know now that we'll insert a line segment, but will it connect to an
534 // existing way or make a new way of its own? The "alt" modifier means that the
535 // user wants a new way.
536 Way way = alt ? null : (selectedWay != null) ? selectedWay : getWayForNode(n0);
537 Way wayToSelect;
538
539 // Don't allow creation of self-overlapping ways
540 if(way != null) {
541 int nodeCount=0;
542 for (Node p : way.getNodes())
543 if(p.equals(n0)) {
544 nodeCount++;
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, Collection<Command> cmds, List<Way> replacedWays, List<Way> reuseWays) {
629 Map<Way, List<Integer>> insertPoints = new HashMap<>();
630 for (WaySegment ws : wss) {
631 List<Integer> is;
632 if (insertPoints.containsKey(ws.way)) {
633 is = insertPoints.get(ws.way);
634 } else {
635 is = new ArrayList<>();
636 insertPoints.put(ws.way, is);
637 }
638
639 is.add(ws.lowerIndex);
640 }
641
642 Set<Pair<Node,Node>> segSet = new HashSet<>();
643
644 for (Map.Entry<Way, List<Integer>> insertPoint : insertPoints.entrySet()) {
645 Way w = insertPoint.getKey();
646 List<Integer> is = insertPoint.getValue();
647
648 Way wnew = new Way(w);
649
650 pruneSuccsAndReverse(is);
651 for (int i : is) {
652 segSet.add(Pair.sort(new Pair<>(w.getNode(i), w.getNode(i+1))));
653 }
654 for (int i : is) {
655 wnew.addNode(i + 1, n);
656 }
657
658 // If ALT is pressed, a new way should be created and that new way should get
659 // selected. This works everytime unless the ways the nodes get inserted into
660 // are already selected. This is the case when creating a self-overlapping way
661 // but pressing ALT prevents this. Therefore we must de-select the way manually
662 // here so /only/ the new way will be selected after this method finishes.
663 if(alt) {
664 newSelection.add(insertPoint.getKey());
665 }
666
667 cmds.add(new ChangeCommand(insertPoint.getKey(), wnew));
668 replacedWays.add(insertPoint.getKey());
669 reuseWays.add(wnew);
670 }
671
672 adjustNode(segSet, n);
673 }
674
675 /**
676 * Prevent creation of ways that look like this: &lt;----&gt;
677 * This happens if users want to draw a no-exit-sideway from the main way like this:
678 * ^
679 * |&lt;----&gt;
680 * |
681 * The solution isn't ideal because the main way will end in the side way, which is bad for
682 * navigation software ("drive straight on") but at least easier to fix. Maybe users will fix
683 * it on their own, too. At least it's better than producing an error.
684 *
685 * @param selectedWay the way to check
686 * @param currentNode the current node (i.e. the one the connection will be made from)
687 * @param targetNode the target node (i.e. the one the connection will be made to)
688 * @return {@code true} if this would create a selfcontaining way, {@code false} otherwise.
689 */
690 private boolean isSelfContainedWay(Way selectedWay, Node currentNode, Node targetNode) {
691 if(selectedWay != null) {
692 int posn0 = selectedWay.getNodes().indexOf(currentNode);
693 if (posn0 != -1 && // n0 is part of way
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 getCurrentDataSet().setSelected(targetNode);
697 lastUsedNode = targetNode;
698 return true;
699 }
700 }
701
702 return false;
703 }
704
705 /**
706 * Finds a node to continue drawing from. Decision is based upon given node and way.
707 * @param selectedNode Currently selected node, may be null
708 * @param selectedWay Currently selected way, may be null
709 * @return Node if a suitable node is found, null otherwise
710 */
711 private Node findNodeToContinueFrom(Node selectedNode, Way selectedWay) {
712 // No nodes or ways have been selected, this occurs when a relation
713 // has been selected or the selection is empty
714 if(selectedNode == null && selectedWay == null)
715 return null;
716
717 if (selectedNode == null) {
718 if (selectedWay.isFirstLastNode(lastUsedNode))
719 return lastUsedNode;
720
721 // We have a way selected, but no suitable node to continue from. Start anew.
722 return null;
723 }
724
725 if (selectedWay == null)
726 return selectedNode;
727
728 if (selectedWay.isFirstLastNode(selectedNode))
729 return selectedNode;
730
731 // We have a way and node selected, but it's not at the start/end of the way. Start anew.
732 return null;
733 }
734
735 @Override
736 public void mouseDragged(MouseEvent e) {
737 mouseMoved(e);
738 }
739
740 @Override
741 public void mouseMoved(MouseEvent e) {
742 if(!Main.map.mapView.isActiveLayerDrawable())
743 return;
744
745 // we copy ctrl/alt/shift from the event just in case our global
746 // keyDetector didn't make it through the security manager. Unclear
747 // if that can ever happen but better be safe.
748 updateKeyModifiers(e);
749 mousePos = e.getPoint();
750 if (snapHelper.isSnapOn() && ctrl)
751 tryToSetBaseSegmentForAngleSnap();
752
753 computeHelperLine();
754 addHighlighting();
755 }
756
757 /**
758 * This method is used to detect segment under mouse and use it as reference for angle snapping
759 */
760 private void tryToSetBaseSegmentForAngleSnap() {
761 WaySegment seg = Main.map.mapView.getNearestWaySegment(mousePos, OsmPrimitive.isSelectablePredicate);
762 if (seg!=null) {
763 snapHelper.setBaseSegment(seg);
764 }
765 }
766
767 /**
768 * This method prepares data required for painting the "helper line" from
769 * the last used position to the mouse cursor. It duplicates some code from
770 * mouseReleased() (FIXME).
771 */
772 private void computeHelperLine() {
773 MapView mv = Main.map.mapView;
774 if (mousePos == null) {
775 // Don't draw the line.
776 currentMouseEastNorth = null;
777 currentBaseNode = null;
778 return;
779 }
780
781 Collection<OsmPrimitive> selection = getCurrentDataSet().getSelected();
782
783 Node currentMouseNode = null;
784 mouseOnExistingNode = null;
785 mouseOnExistingWays = new HashSet<>();
786
787 showStatusInfo(-1, -1, -1, snapHelper.isSnapOn());
788
789 if (!ctrl && mousePos != null) {
790 currentMouseNode = mv.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
791 }
792
793 // We need this for highlighting and we'll only do so if we actually want to re-use
794 // *and* there is no node nearby (because nodes beat ways when re-using)
795 if(!ctrl && currentMouseNode == null) {
796 List<WaySegment> wss = mv.getNearestWaySegments(mousePos, OsmPrimitive.isSelectablePredicate);
797 for(WaySegment ws : wss) {
798 mouseOnExistingWays.add(ws.way);
799 }
800 }
801
802 if (currentMouseNode != null) {
803 // user clicked on node
804 if (selection.isEmpty()) return;
805 currentMouseEastNorth = currentMouseNode.getEastNorth();
806 mouseOnExistingNode = currentMouseNode;
807 } else {
808 // no node found in clicked area
809 currentMouseEastNorth = mv.getEastNorth(mousePos.x, mousePos.y);
810 }
811
812 determineCurrentBaseNodeAndPreviousNode(selection);
813 if (previousNode == null) {
814 snapHelper.noSnapNow();
815 }
816
817 if (getCurrentBaseNode() == null || getCurrentBaseNode() == currentMouseNode)
818 return; // Don't create zero length way segments.
819
820
821 double curHdg = Math.toDegrees(getCurrentBaseNode().getEastNorth()
822 .heading(currentMouseEastNorth));
823 double baseHdg=-1;
824 if (previousNode != null) {
825 baseHdg = Math.toDegrees(previousNode.getEastNorth()
826 .heading(getCurrentBaseNode().getEastNorth()));
827 }
828
829 snapHelper.checkAngleSnapping(currentMouseEastNorth,baseHdg, curHdg);
830
831 // status bar was filled by snapHelper
832 }
833
834 private void showStatusInfo(double angle, double hdg, double distance, boolean activeFlag) {
835 Main.map.statusLine.setAngle(angle);
836 Main.map.statusLine.activateAnglePanel(activeFlag);
837 Main.map.statusLine.setHeading(hdg);
838 Main.map.statusLine.setDist(distance);
839 }
840
841 /**
842 * Helper function that sets fields currentBaseNode and previousNode
843 * @param selection
844 * uses also lastUsedNode field
845 */
846 private void determineCurrentBaseNodeAndPreviousNode(Collection<OsmPrimitive> selection) {
847 Node selectedNode = null;
848 Way selectedWay = null;
849 for (OsmPrimitive p : selection) {
850 if (p instanceof Node) {
851 if (selectedNode != null)
852 return;
853 selectedNode = (Node) p;
854 } else if (p instanceof Way) {
855 if (selectedWay != null)
856 return;
857 selectedWay = (Way) p;
858 }
859 }
860 // we are here, if not more than 1 way or node is selected,
861
862 // the node from which we make a connection
863 currentBaseNode = null;
864 previousNode = null;
865
866 // Try to find an open way to measure angle from it. The way is not to be continued!
867 // warning: may result in changes of currentBaseNode and previousNode
868 // please remove if bugs arise
869 if (selectedWay == null && selectedNode != null) {
870 for (OsmPrimitive p: selectedNode.getReferrers()) {
871 if (p.isUsable() && p instanceof Way && ((Way) p).isFirstLastNode(selectedNode)) {
872 if (selectedWay!=null) { // two uncontinued ways, nothing to take as reference
873 selectedWay=null;
874 break;
875 } else {
876 // set us ~continue this way (measure angle from it)
877 selectedWay = (Way) p;
878 }
879 }
880 }
881 }
882
883 if (selectedNode == null) {
884 if (selectedWay == null)
885 return;
886 continueWayFromNode(selectedWay, lastUsedNode);
887 } else if (selectedWay == null) {
888 currentBaseNode = selectedNode;
889 } else if (!selectedWay.isDeleted()) { // fix #7118
890 continueWayFromNode(selectedWay, selectedNode);
891 }
892 }
893
894 /**
895 * if one of the ends of @param way is given @param node ,
896 * then set currentBaseNode = node and previousNode = adjacent node of way
897 */
898 private void continueWayFromNode(Way way, Node node) {
899 int n = way.getNodesCount();
900 if (node == way.firstNode()){
901 currentBaseNode = node;
902 if (n>1) previousNode = way.getNode(1);
903 } else if (node == way.lastNode()) {
904 currentBaseNode = node;
905 if (n>1) previousNode = way.getNode(n-2);
906 }
907 }
908
909 /**
910 * Repaint on mouse exit so that the helper line goes away.
911 */
912 @Override
913 public void mouseExited(MouseEvent e) {
914 if(!Main.map.mapView.isActiveLayerDrawable())
915 return;
916 mousePos = e.getPoint();
917 snapHelper.noSnapNow();
918 boolean repaintIssued = removeHighlighting();
919 // force repaint in case snapHelper needs one. If removeHighlighting
920 // caused one already, don’t do it again.
921 if(!repaintIssued) {
922 Main.map.mapView.repaint();
923 }
924 }
925
926 /**
927 * @return If the node is the end of exactly one way, return this.
928 * <code>null</code> otherwise.
929 */
930 public static Way getWayForNode(Node n) {
931 Way way = null;
932 for (Way w : Utils.filteredCollection(n.getReferrers(), Way.class)) {
933 if (!w.isUsable() || w.getNodesCount() < 1) {
934 continue;
935 }
936 Node firstNode = w.getNode(0);
937 Node lastNode = w.getNode(w.getNodesCount() - 1);
938 if ((firstNode == n || lastNode == n) && (firstNode != lastNode)) {
939 if (way != null)
940 return null;
941 way = w;
942 }
943 }
944 return way;
945 }
946
947 /**
948 * Replies the current base node, after having checked it is still usable (see #11105).
949 * @return the current base node (can be null). If not-null, it's guaranteed the node is usable
950 */
951 public Node getCurrentBaseNode() {
952 if (currentBaseNode != null && (currentBaseNode.getDataSet() == null || !currentBaseNode.isUsable())) {
953 currentBaseNode = null;
954 }
955 return currentBaseNode;
956 }
957
958 private static void pruneSuccsAndReverse(List<Integer> is) {
959 Set<Integer> is2 = new HashSet<>();
960 for (int i : is) {
961 if (!is2.contains(i - 1) && !is2.contains(i + 1)) {
962 is2.add(i);
963 }
964 }
965 is.clear();
966 is.addAll(is2);
967 Collections.sort(is);
968 Collections.reverse(is);
969 }
970
971 /**
972 * Adjusts the position of a node to lie on a segment (or a segment
973 * intersection).
974 *
975 * If one or more than two segments are passed, the node is adjusted
976 * to lie on the first segment that is passed.
977 *
978 * If two segments are passed, the node is adjusted to be at their
979 * intersection.
980 *
981 * No action is taken if no segments are passed.
982 *
983 * @param segs the segments to use as a reference when adjusting
984 * @param n the node to adjust
985 */
986 private static void adjustNode(Collection<Pair<Node,Node>> segs, Node n) {
987
988 switch (segs.size()) {
989 case 0:
990 return;
991 case 2:
992 // This computes the intersection between
993 // the two segments and adjusts the node position.
994 Iterator<Pair<Node,Node>> i = segs.iterator();
995 Pair<Node,Node> seg = i.next();
996 EastNorth A = seg.a.getEastNorth();
997 EastNorth B = seg.b.getEastNorth();
998 seg = i.next();
999 EastNorth C = seg.a.getEastNorth();
1000 EastNorth D = seg.b.getEastNorth();
1001
1002 double u=det(B.east() - A.east(), B.north() - A.north(), C.east() - D.east(), C.north() - D.north());
1003
1004 // Check for parallel segments and do nothing if they are
1005 // In practice this will probably only happen when a way has been duplicated
1006
1007 if (u == 0)
1008 return;
1009
1010 // q is a number between 0 and 1
1011 // It is the point in the segment where the intersection occurs
1012 // if the segment is scaled to lenght 1
1013
1014 double q = det(B.north() - C.north(), B.east() - C.east(), D.north() - C.north(), D.east() - C.east()) / u;
1015 EastNorth intersection = new EastNorth(
1016 B.east() + q * (A.east() - B.east()),
1017 B.north() + q * (A.north() - B.north()));
1018
1019
1020 // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise
1021 // fall through to default action.
1022 // (for semi-parallel lines, intersection might be miles away!)
1023 if (Main.map.mapView.getPoint2D(n).distance(Main.map.mapView.getPoint2D(intersection)) < snapToIntersectionThreshold) {
1024 n.setEastNorth(intersection);
1025 return;
1026 }
1027 default:
1028 EastNorth P = n.getEastNorth();
1029 seg = segs.iterator().next();
1030 A = seg.a.getEastNorth();
1031 B = seg.b.getEastNorth();
1032 double a = P.distanceSq(B);
1033 double b = P.distanceSq(A);
1034 double c = A.distanceSq(B);
1035 q = (a - b + c) / (2*c);
1036 n.setEastNorth(new EastNorth(B.east() + q * (A.east() - B.east()), B.north() + q * (A.north() - B.north())));
1037 }
1038 }
1039
1040 // helper for adjustNode
1041 static double det(double a, double b, double c, double d) {
1042 return a * d - b * c;
1043 }
1044
1045 private void tryToMoveNodeOnIntersection(List<WaySegment> wss, Node n) {
1046 if (wss.isEmpty())
1047 return;
1048 WaySegment ws = wss.get(0);
1049 EastNorth p1=ws.getFirstNode().getEastNorth();
1050 EastNorth p2=ws.getSecondNode().getEastNorth();
1051 if (snapHelper.dir2 != null && getCurrentBaseNode() != null) {
1052 EastNorth xPoint = Geometry.getSegmentSegmentIntersection(p1, p2, snapHelper.dir2,
1053 getCurrentBaseNode().getEastNorth());
1054 if (xPoint!=null) {
1055 n.setEastNorth(xPoint);
1056 }
1057 }
1058 }
1059 /**
1060 * Takes the data from computeHelperLine to determine which ways/nodes should be highlighted
1061 * (if feature enabled). Also sets the target cursor if appropriate. It adds the to-be-
1062 * highlighted primitives to newHighlights but does not actually highlight them. This work is
1063 * done in redrawIfRequired. This means, calling addHighlighting() without redrawIfRequired()
1064 * will leave the data in an inconsistent state.
1065 *
1066 * The status bar derives its information from oldHighlights, so in order to update the status
1067 * bar both addHighlighting() and repaintIfRequired() are needed, since former fills newHighlights
1068 * and latter processes them into oldHighlights.
1069 */
1070 private void addHighlighting() {
1071 newHighlights = new HashSet<>();
1072
1073 // if ctrl key is held ("no join"), don't highlight anything
1074 if (ctrl) {
1075 Main.map.mapView.setNewCursor(cursor, this);
1076 redrawIfRequired();
1077 return;
1078 }
1079
1080 // This happens when nothing is selected, but we still want to highlight the "target node"
1081 if (mouseOnExistingNode == null && getCurrentDataSet().getSelected().isEmpty()
1082 && mousePos != null) {
1083 mouseOnExistingNode = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
1084 }
1085
1086 if (mouseOnExistingNode != null) {
1087 Main.map.mapView.setNewCursor(cursorJoinNode, this);
1088 newHighlights.add(mouseOnExistingNode);
1089 redrawIfRequired();
1090 return;
1091 }
1092
1093 // Insert the node into all the nearby way segments
1094 if (mouseOnExistingWays.isEmpty()) {
1095 Main.map.mapView.setNewCursor(cursor, this);
1096 redrawIfRequired();
1097 return;
1098 }
1099
1100 Main.map.mapView.setNewCursor(cursorJoinWay, this);
1101 newHighlights.addAll(mouseOnExistingWays);
1102 redrawIfRequired();
1103 }
1104
1105 /**
1106 * Removes target highlighting from primitives. Issues repaint if required.
1107 * Returns true if a repaint has been issued.
1108 */
1109 private boolean removeHighlighting() {
1110 newHighlights = new HashSet<>();
1111 return redrawIfRequired();
1112 }
1113
1114 @Override
1115 public void paint(Graphics2D g, MapView mv, Bounds box) {
1116 // sanity checks
1117 if (Main.map.mapView == null || mousePos == null
1118 // don't draw line if we don't know where from or where to
1119 || getCurrentBaseNode() == null || currentMouseEastNorth == null
1120 // don't draw line if mouse is outside window
1121 || !Main.map.mapView.getBounds().contains(mousePos))
1122 return;
1123
1124 Graphics2D g2 = g;
1125 snapHelper.drawIfNeeded(g2,mv);
1126 if (!drawHelperLine || wayIsFinished || shift)
1127 return;
1128
1129 if (!snapHelper.isActive()) { // else use color and stoke from snapHelper.draw
1130 g2.setColor(rubberLineColor);
1131 g2.setStroke(rubberLineStroke);
1132 } else if (!snapHelper.drawConstructionGeometry)
1133 return;
1134 GeneralPath b = new GeneralPath();
1135 Point p1=mv.getPoint(getCurrentBaseNode());
1136 Point p2=mv.getPoint(currentMouseEastNorth);
1137
1138 double t = Math.atan2(p2.y-p1.y, p2.x-p1.x) + Math.PI;
1139
1140 b.moveTo(p1.x,p1.y); b.lineTo(p2.x, p2.y);
1141
1142 // if alt key is held ("start new way"), draw a little perpendicular line
1143 if (alt) {
1144 b.moveTo((int)(p1.x + 8*Math.cos(t+PHI)), (int)(p1.y + 8*Math.sin(t+PHI)));
1145 b.lineTo((int)(p1.x + 8*Math.cos(t-PHI)), (int)(p1.y + 8*Math.sin(t-PHI)));
1146 }
1147
1148 g2.draw(b);
1149 g2.setStroke(BASIC_STROKE);
1150 }
1151
1152 @Override
1153 public String getModeHelpText() {
1154 StringBuilder rv;
1155 /*
1156 * No modifiers: all (Connect, Node Re-Use, Auto-Weld)
1157 * CTRL: disables node re-use, auto-weld
1158 * Shift: do not make connection
1159 * ALT: make connection but start new way in doing so
1160 */
1161
1162 /*
1163 * Status line text generation is split into two parts to keep it maintainable.
1164 * First part looks at what will happen to the new node inserted on click and
1165 * the second part will look if a connection is made or not.
1166 *
1167 * Note that this help text is not absolutely accurate as it doesn't catch any special
1168 * cases (e.g. when preventing <---> ways). The only special that it catches is when
1169 * a way is about to be finished.
1170 *
1171 * First check what happens to the new node.
1172 */
1173
1174 // oldHighlights stores the current highlights. If this
1175 // list is empty we can assume that we won't do any joins
1176 if (ctrl || oldHighlights.isEmpty()) {
1177 rv = new StringBuilder(tr("Create new node."));
1178 } else {
1179 // oldHighlights may store a node or way, check if it's a node
1180 OsmPrimitive x = oldHighlights.iterator().next();
1181 if (x instanceof Node) {
1182 rv = new StringBuilder(tr("Select node under cursor."));
1183 } else {
1184 rv = new StringBuilder(trn("Insert new node into way.", "Insert new node into {0} ways.",
1185 oldHighlights.size(), oldHighlights.size()));
1186 }
1187 }
1188
1189 /*
1190 * Check whether a connection will be made
1191 */
1192 if (getCurrentBaseNode() != null && !wayIsFinished) {
1193 if (alt) {
1194 rv.append(' ').append(tr("Start new way from last node."));
1195 } else {
1196 rv.append(' ').append(tr("Continue way from last node."));
1197 }
1198 if (snapHelper.isSnapOn()) {
1199 rv.append(' ').append(tr("Angle snapping active."));
1200 }
1201 }
1202
1203 Node n = mouseOnExistingNode;
1204 /*
1205 * Handle special case: Highlighted node == selected node => finish drawing
1206 */
1207 if (n != null && getCurrentDataSet() != null && getCurrentDataSet().getSelectedNodes().contains(n)) {
1208 if (wayIsFinished) {
1209 rv = new StringBuilder(tr("Select node under cursor."));
1210 } else {
1211 rv = new StringBuilder(tr("Finish drawing."));
1212 }
1213 }
1214
1215 /*
1216 * Handle special case: Self-Overlapping or closing way
1217 */
1218 if (getCurrentDataSet() != null && !getCurrentDataSet().getSelectedWays().isEmpty() && !wayIsFinished && !alt) {
1219 Way w = getCurrentDataSet().getSelectedWays().iterator().next();
1220 for (Node m : w.getNodes()) {
1221 if (m.equals(mouseOnExistingNode) || mouseOnExistingWays.contains(w)) {
1222 rv.append(' ').append(tr("Finish drawing."));
1223 break;
1224 }
1225 }
1226 }
1227 return rv.toString();
1228 }
1229
1230 /**
1231 * Get selected primitives, while draw action is in progress.
1232 *
1233 * While drawing a way, technically the last node is selected.
1234 * This is inconvenient when the user tries to add/edit tags to the way.
1235 * For this case, this method returns the current way as selection,
1236 * to work around this issue.
1237 * Otherwise the normal selection of the current data layer is returned.
1238 */
1239 public Collection<OsmPrimitive> getInProgressSelection() {
1240 DataSet ds = getCurrentDataSet();
1241 if (ds == null) return null;
1242 if (getCurrentBaseNode() != null && !ds.getSelected().isEmpty()) {
1243 Way continueFrom = getWayForNode(getCurrentBaseNode());
1244 if (continueFrom != null)
1245 return Collections.<OsmPrimitive>singleton(continueFrom);
1246 }
1247 return ds.getSelected();
1248 }
1249
1250 @Override
1251 public boolean layerIsSupported(Layer l) {
1252 return l instanceof OsmDataLayer;
1253 }
1254
1255 @Override
1256 protected void updateEnabledState() {
1257 setEnabled(getEditLayer() != null);
1258 }
1259
1260 @Override
1261 public void destroy() {
1262 super.destroy();
1263 snapChangeAction.destroy();
1264 }
1265
1266 public class BackSpaceAction extends AbstractAction {
1267
1268 @Override
1269 public void actionPerformed(ActionEvent e) {
1270 Main.main.undoRedo.undo();
1271 Node n=null;
1272 Command lastCmd=Main.main.undoRedo.commands.peekLast();
1273 if (lastCmd==null) return;
1274 for (OsmPrimitive p: lastCmd.getParticipatingPrimitives()) {
1275 if (p instanceof Node) {
1276 if (n==null) {
1277 n=(Node) p; // found one node
1278 wayIsFinished=false;
1279 } else {
1280 // if more than 1 node were affected by previous command,
1281 // we have no way to continue, so we forget about found node
1282 n=null;
1283 break;
1284 }
1285 }
1286 }
1287 // select last added node - maybe we will continue drawing from it
1288 if (n!=null) {
1289 getCurrentDataSet().addSelected(n);
1290 }
1291 }
1292 }
1293
1294 private class SnapHelper {
1295 private boolean snapOn; // snapping is turned on
1296
1297 private boolean active; // snapping is active for current mouse position
1298 private boolean fixed; // snap angle is fixed
1299 private boolean absoluteFix; // snap angle is absolute
1300
1301 private boolean drawConstructionGeometry;
1302 private boolean showProjectedPoint;
1303 private boolean showAngle;
1304
1305 private boolean snapToProjections;
1306
1307 private EastNorth dir2;
1308 private EastNorth projected;
1309 private String labelText;
1310 private double lastAngle;
1311
1312 private double customBaseHeading=-1; // angle of base line, if not last segment)
1313 private EastNorth segmentPoint1; // remembered first point of base segment
1314 private EastNorth segmentPoint2; // remembered second point of base segment
1315 private EastNorth projectionSource; // point that we are projecting to the line
1316
1317 private double[] snapAngles;
1318 private double snapAngleTolerance;
1319
1320 private double pe,pn; // (pe,pn) - direction of snapping line
1321 private double e0,n0; // (e0,n0) - origin of snapping line
1322
1323 private final String fixFmt="%d "+tr("FIX");
1324 private Color snapHelperColor;
1325 private Color highlightColor;
1326
1327 private Stroke normalStroke;
1328 private Stroke helperStroke;
1329 private Stroke highlightStroke;
1330
1331 private JCheckBoxMenuItem checkBox;
1332
1333 public void init() {
1334 snapOn=false;
1335 checkBox.setState(snapOn);
1336 fixed=false; absoluteFix=false;
1337
1338 Collection<String> angles = Main.pref.getCollection("draw.anglesnap.angles",
1339 Arrays.asList("0","30","45","60","90","120","135","150","180"));
1340
1341 snapAngles = new double[2*angles.size()];
1342 int i=0;
1343 for (String s: angles) {
1344 try {
1345 snapAngles[i] = Double.parseDouble(s); i++;
1346 snapAngles[i] = 360-Double.parseDouble(s); i++;
1347 } catch (NumberFormatException e) {
1348 Main.warn("Incorrect number in draw.anglesnap.angles preferences: "+s);
1349 snapAngles[i]=0;i++;
1350 snapAngles[i]=0;i++;
1351 }
1352 }
1353 snapAngleTolerance = Main.pref.getDouble("draw.anglesnap.tolerance", 5.0);
1354 drawConstructionGeometry = Main.pref.getBoolean("draw.anglesnap.drawConstructionGeometry", true);
1355 showProjectedPoint = Main.pref.getBoolean("draw.anglesnap.drawProjectedPoint", true);
1356 snapToProjections = Main.pref.getBoolean("draw.anglesnap.projectionsnap", true);
1357
1358 showAngle = Main.pref.getBoolean("draw.anglesnap.showAngle", true);
1359 useRepeatedShortcut = Main.pref.getBoolean("draw.anglesnap.toggleOnRepeatedA", true);
1360
1361 normalStroke = rubberLineStroke;
1362 snapHelperColor = Main.pref.getColor(marktr("draw angle snap"), Color.ORANGE);
1363
1364 highlightColor = Main.pref.getColor(marktr("draw angle snap highlight"), ORANGE_TRANSPARENT);
1365 highlightStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.anglesnap.stroke.highlight","10"));
1366 helperStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.anglesnap.stroke.helper","1 4"));
1367 }
1368
1369 public void saveAngles(String ... angles) {
1370 Main.pref.putCollection("draw.anglesnap.angles", Arrays.asList(angles));
1371 }
1372
1373 public void setMenuCheckBox(JCheckBoxMenuItem checkBox) {
1374 this.checkBox = checkBox;
1375 }
1376
1377 public void drawIfNeeded(Graphics2D g2, MapView mv) {
1378 if (!snapOn || !active)
1379 return;
1380 Point p1=mv.getPoint(getCurrentBaseNode());
1381 Point p2=mv.getPoint(dir2);
1382 Point p3=mv.getPoint(projected);
1383 GeneralPath b;
1384 if (drawConstructionGeometry) {
1385 g2.setColor(snapHelperColor);
1386 g2.setStroke(helperStroke);
1387
1388 b = new GeneralPath();
1389 if (absoluteFix) {
1390 b.moveTo(p2.x,p2.y);
1391 b.lineTo(2*p1.x-p2.x,2*p1.y-p2.y); // bi-directional line
1392 } else {
1393 b.moveTo(p2.x,p2.y);
1394 b.lineTo(p3.x,p3.y);
1395 }
1396 g2.draw(b);
1397 }
1398 if (projectionSource != null) {
1399 g2.setColor(snapHelperColor);
1400 g2.setStroke(helperStroke);
1401 b = new GeneralPath();
1402 b.moveTo(p3.x,p3.y);
1403 Point pp=mv.getPoint(projectionSource);
1404 b.lineTo(pp.x,pp.y);
1405 g2.draw(b);
1406 }
1407
1408 if (customBaseHeading >= 0) {
1409 g2.setColor(highlightColor);
1410 g2.setStroke(highlightStroke);
1411 b = new GeneralPath();
1412 Point pp1=mv.getPoint(segmentPoint1);
1413 Point pp2=mv.getPoint(segmentPoint2);
1414 b.moveTo(pp1.x,pp1.y);
1415 b.lineTo(pp2.x,pp2.y);
1416 g2.draw(b);
1417 }
1418
1419 g2.setColor(rubberLineColor);
1420 g2.setStroke(normalStroke);
1421 b = new GeneralPath();
1422 b.moveTo(p1.x,p1.y);
1423 b.lineTo(p3.x,p3.y);
1424 g2.draw(b);
1425
1426 g2.drawString(labelText, p3.x-5, p3.y+20);
1427 if (showProjectedPoint) {
1428 g2.setStroke(normalStroke);
1429 g2.drawOval(p3.x-5, p3.y-5, 10, 10); // projected point
1430 }
1431
1432 g2.setColor(snapHelperColor);
1433 g2.setStroke(helperStroke);
1434 }
1435
1436 /* If mouse position is close to line at 15-30-45-... angle, remembers this direction
1437 */
1438 public void checkAngleSnapping(EastNorth currentEN, double baseHeading, double curHeading) {
1439 EastNorth p0 = getCurrentBaseNode().getEastNorth();
1440 EastNorth snapPoint = currentEN;
1441 double angle = -1;
1442
1443 double activeBaseHeading = (customBaseHeading>=0)? customBaseHeading : baseHeading;
1444
1445 if (snapOn && (activeBaseHeading>=0)) {
1446 angle = curHeading - activeBaseHeading;
1447 if (angle < 0) {
1448 angle+=360;
1449 }
1450 if (angle > 360) {
1451 angle=0;
1452 }
1453
1454 double nearestAngle;
1455 if (fixed) {
1456 nearestAngle = lastAngle; // if direction is fixed use previous angle
1457 active = true;
1458 } else {
1459 nearestAngle = getNearestAngle(angle);
1460 if (getAngleDelta(nearestAngle, angle) < snapAngleTolerance) {
1461 active = (customBaseHeading>=0)? true : Math.abs(nearestAngle - 180) > 1e-3;
1462 // if angle is to previous segment, exclude 180 degrees
1463 lastAngle = nearestAngle;
1464 } else {
1465 active=false;
1466 }
1467 }
1468
1469 if (active) {
1470 double phi;
1471 e0 = p0.east();
1472 n0 = p0.north();
1473 buildLabelText((nearestAngle<=180) ? nearestAngle : nearestAngle-360);
1474
1475 phi = (nearestAngle + activeBaseHeading) * Math.PI / 180;
1476 // (pe,pn) - direction of snapping line
1477 pe = Math.sin(phi);
1478 pn = Math.cos(phi);
1479 double scale = 20 * Main.map.mapView.getDist100Pixel();
1480 dir2 = new EastNorth(e0 + scale * pe, n0 + scale * pn);
1481 snapPoint = getSnapPoint(currentEN);
1482 } else {
1483 noSnapNow();
1484 }
1485 }
1486
1487 // find out the distance, in metres, between the base point and projected point
1488 LatLon mouseLatLon = Main.map.mapView.getProjection().eastNorth2latlon(snapPoint);
1489 double distance = getCurrentBaseNode().getCoor().greatCircleDistance(mouseLatLon);
1490 double hdg = Math.toDegrees(p0.heading(snapPoint));
1491 // heading of segment from current to calculated point, not to mouse position
1492
1493 if (baseHeading >= 0) { // there is previous line segment with some heading
1494 angle = hdg - baseHeading;
1495 if (angle < 0) {
1496 angle+=360;
1497 }
1498 if (angle > 360) {
1499 angle=0;
1500 }
1501 }
1502 showStatusInfo(angle, hdg, distance, isSnapOn());
1503 }
1504
1505 private void buildLabelText(double nearestAngle) {
1506 if (showAngle) {
1507 if (fixed) {
1508 if (absoluteFix) {
1509 labelText = "=";
1510 } else {
1511 labelText = String.format(fixFmt, (int) nearestAngle);
1512 }
1513 } else {
1514 labelText = String.format("%d", (int) nearestAngle);
1515 }
1516 } else {
1517 if (fixed) {
1518 if (absoluteFix) {
1519 labelText = "=";
1520 } else {
1521 labelText = String.format(tr("FIX"), 0);
1522 }
1523 } else {
1524 labelText = "";
1525 }
1526 }
1527 }
1528
1529 public EastNorth getSnapPoint(EastNorth p) {
1530 if (!active)
1531 return p;
1532 double de=p.east()-e0;
1533 double dn=p.north()-n0;
1534 double l = de*pe+dn*pn;
1535 double delta = Main.map.mapView.getDist100Pixel()/20;
1536 if (!absoluteFix && l<delta) {
1537 active=false;
1538 return p;
1539 } // do not go backward!
1540
1541 projectionSource=null;
1542 if (snapToProjections) {
1543 DataSet ds = getCurrentDataSet();
1544 Collection<Way> selectedWays = ds.getSelectedWays();
1545 if (selectedWays.size()==1) {
1546 Way w = selectedWays.iterator().next();
1547 Collection <EastNorth> pointsToProject = new ArrayList<>();
1548 if (w.getNodesCount()<1000) {
1549 for (Node n: w.getNodes()) {
1550 pointsToProject.add(n.getEastNorth());
1551 }
1552 }
1553 if (customBaseHeading >= 0) {
1554 pointsToProject.add(segmentPoint1);
1555 pointsToProject.add(segmentPoint2);
1556 }
1557 EastNorth enOpt=null;
1558 double dOpt=1e5;
1559 for (EastNorth en: pointsToProject) { // searching for besht projection
1560 double l1 = (en.east()-e0)*pe+(en.north()-n0)*pn;
1561 double d1 = Math.abs(l1-l);
1562 if (d1 < delta && d1 < dOpt) {
1563 l=l1;
1564 enOpt = en;
1565 dOpt = d1;
1566 }
1567 }
1568 if (enOpt!=null) {
1569 projectionSource = enOpt;
1570 }
1571 }
1572 }
1573 return projected = new EastNorth(e0+l*pe, n0+l*pn);
1574 }
1575
1576
1577 public void noSnapNow() {
1578 active=false;
1579 dir2=null; projected=null;
1580 labelText=null;
1581 }
1582
1583 public void setBaseSegment(WaySegment seg) {
1584 if (seg==null) return;
1585 segmentPoint1=seg.getFirstNode().getEastNorth();
1586 segmentPoint2=seg.getSecondNode().getEastNorth();
1587
1588 double hdg = segmentPoint1.heading(segmentPoint2);
1589 hdg=Math.toDegrees(hdg);
1590 if (hdg<0) {
1591 hdg+=360;
1592 }
1593 if (hdg>360) {
1594 hdg-=360;
1595 }
1596 customBaseHeading=hdg;
1597 }
1598
1599 private void nextSnapMode() {
1600 if (snapOn) {
1601 // turn off snapping if we are in fixed mode or no actile snapping line exist
1602 if (fixed || !active) {
1603 snapOn = false;
1604 unsetFixedMode();
1605 } else {
1606 setFixedMode();
1607 }
1608 } else {
1609 snapOn=true;
1610 unsetFixedMode();
1611 }
1612 checkBox.setState(snapOn);
1613 customBaseHeading=-1;
1614 }
1615
1616 private void enableSnapping() {
1617 snapOn = true;
1618 checkBox.setState(snapOn);
1619 customBaseHeading=-1;
1620 unsetFixedMode();
1621 }
1622
1623 private void toggleSnapping() {
1624 snapOn = !snapOn;
1625 checkBox.setState(snapOn);
1626 customBaseHeading=-1;
1627 unsetFixedMode();
1628 }
1629
1630 public void setFixedMode() {
1631 if (active) {
1632 fixed=true;
1633 }
1634 }
1635
1636
1637 public void unsetFixedMode() {
1638 fixed=false;
1639 absoluteFix=false;
1640 lastAngle=0;
1641 active=false;
1642 }
1643
1644 public boolean isActive() {
1645 return active;
1646 }
1647
1648 public boolean isSnapOn() {
1649 return snapOn;
1650 }
1651
1652 private double getNearestAngle(double angle) {
1653 double delta,minDelta=1e5, bestAngle=0.0;
1654 for (double snapAngle : snapAngles) {
1655 delta = getAngleDelta(angle, snapAngle);
1656 if (delta < minDelta) {
1657 minDelta = delta;
1658 bestAngle = snapAngle;
1659 }
1660 }
1661 if (Math.abs(bestAngle-360) < 1e-3) {
1662 bestAngle=0;
1663 }
1664 return bestAngle;
1665 }
1666
1667 private double getAngleDelta(double a, double b) {
1668 double delta = Math.abs(a-b);
1669 if (delta>180)
1670 return 360-delta;
1671 else
1672 return delta;
1673 }
1674
1675 private void unFixOrTurnOff() {
1676 if (absoluteFix) {
1677 unsetFixedMode();
1678 } else {
1679 toggleSnapping();
1680 }
1681 }
1682
1683 private MouseListener anglePopupListener = new PopupMenuLauncher(new JPopupMenu() {
1684 private JCheckBoxMenuItem repeatedCb = new JCheckBoxMenuItem(
1685 new AbstractAction(tr("Toggle snapping by {0}", getShortcut().getKeyText())) {
1686 @Override public void actionPerformed(ActionEvent e) {
1687 boolean sel=((JCheckBoxMenuItem) e.getSource()).getState();
1688 Main.pref.put("draw.anglesnap.toggleOnRepeatedA", sel);
1689 init();
1690 }
1691 });
1692 private JCheckBoxMenuItem helperCb = new JCheckBoxMenuItem(
1693 new AbstractAction(tr("Show helper geometry")) {
1694 @Override public void actionPerformed(ActionEvent e) {
1695 boolean sel=((JCheckBoxMenuItem) e.getSource()).getState();
1696 Main.pref.put("draw.anglesnap.drawConstructionGeometry", sel);
1697 Main.pref.put("draw.anglesnap.drawProjectedPoint", sel);
1698 Main.pref.put("draw.anglesnap.showAngle", sel);
1699 init();
1700 enableSnapping();
1701 }
1702 });
1703 private JCheckBoxMenuItem projectionCb = new JCheckBoxMenuItem(
1704 new AbstractAction(tr("Snap to node projections")) {
1705 @Override public void actionPerformed(ActionEvent e) {
1706 boolean sel=((JCheckBoxMenuItem) e.getSource()).getState();
1707 Main.pref.put("draw.anglesnap.projectionsnap", sel);
1708 init();
1709 enableSnapping();
1710 }
1711 });
1712 {
1713 helperCb.setState(Main.pref.getBoolean("draw.anglesnap.drawConstructionGeometry",true));
1714 projectionCb.setState(Main.pref.getBoolean("draw.anglesnap.projectionsnapgvff",true));
1715 repeatedCb.setState(Main.pref.getBoolean("draw.anglesnap.toggleOnRepeatedA",true));
1716 add(repeatedCb);
1717 add(helperCb);
1718 add(projectionCb);
1719 add(new AbstractAction(tr("Disable")) {
1720 @Override public void actionPerformed(ActionEvent e) {
1721 saveAngles("180");
1722 init();
1723 enableSnapping();
1724 }
1725 });
1726 add(new AbstractAction(tr("0,90,...")) {
1727 @Override public void actionPerformed(ActionEvent e) {
1728 saveAngles("0","90","180");
1729 init();
1730 enableSnapping();
1731 }
1732 });
1733 add(new AbstractAction(tr("0,45,90,...")) {
1734 @Override public void actionPerformed(ActionEvent e) {
1735 saveAngles("0","45","90","135","180");
1736 init();
1737 enableSnapping();
1738 }
1739 });
1740 add(new AbstractAction(tr("0,30,45,60,90,...")) {
1741 @Override public void actionPerformed(ActionEvent e) {
1742 saveAngles("0","30","45","60","90","120","135","150","180");
1743 init();
1744 enableSnapping();
1745 }
1746 });
1747 }
1748 }) {
1749 @Override
1750 public void mouseClicked(MouseEvent e) {
1751 super.mouseClicked(e);
1752 if (e.getButton() == MouseEvent.BUTTON1) {
1753 toggleSnapping();
1754 updateStatusLine();
1755 }
1756 }
1757 };
1758 }
1759
1760 private class SnapChangeAction extends JosmAction {
1761 public SnapChangeAction() {
1762 super(tr("Angle snapping"), /* ICON() */ "anglesnap",
1763 tr("Switch angle snapping mode while drawing"), null, false);
1764 putValue("help", ht("/Action/Draw/AngleSnap"));
1765 }
1766
1767 @Override
1768 public void actionPerformed(ActionEvent e) {
1769 if (snapHelper!=null) {
1770 snapHelper.toggleSnapping();
1771 }
1772 }
1773 }
1774}
Note: See TracBrowser for help on using the repository browser.