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

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

Sonar - fix various issues

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