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

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

fix #9482, see #9423, see #6853 - fix regression from r6542: irregular behaviour drawing ways

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