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

Last change on this file since 4539 was 4539, checked in by bastiK, 12 years ago

applied #6853 - In draw mode, select the way to be extended immediately (patch by olejorgenb)

  • Property svn:eol-style set to native
File size: 35.7 KB
Line 
1// License: GPL. See LICENSE file for details.
2package org.openstreetmap.josm.actions.mapmode;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.awt.AWTEvent;
8import java.awt.BasicStroke;
9import java.awt.Color;
10import java.awt.Cursor;
11import java.awt.Graphics2D;
12import java.awt.Point;
13import java.awt.Toolkit;
14import java.awt.event.AWTEventListener;
15import java.awt.event.InputEvent;
16import java.awt.event.KeyEvent;
17import java.awt.event.MouseEvent;
18import java.awt.geom.GeneralPath;
19import java.util.ArrayList;
20import java.util.Collection;
21import java.util.Collections;
22import java.util.HashMap;
23import java.util.HashSet;
24import java.util.Iterator;
25import java.util.LinkedList;
26import java.util.List;
27import java.util.Map;
28import java.util.Set;
29
30import javax.swing.JOptionPane;
31
32import org.openstreetmap.josm.Main;
33import org.openstreetmap.josm.command.AddCommand;
34import org.openstreetmap.josm.command.ChangeCommand;
35import org.openstreetmap.josm.command.Command;
36import org.openstreetmap.josm.command.SequenceCommand;
37import org.openstreetmap.josm.data.Bounds;
38import org.openstreetmap.josm.data.SelectionChangedListener;
39import org.openstreetmap.josm.data.coor.EastNorth;
40import org.openstreetmap.josm.data.coor.LatLon;
41import org.openstreetmap.josm.data.osm.DataSet;
42import org.openstreetmap.josm.data.osm.Node;
43import org.openstreetmap.josm.data.osm.OsmPrimitive;
44import org.openstreetmap.josm.data.osm.Way;
45import org.openstreetmap.josm.data.osm.WaySegment;
46import org.openstreetmap.josm.data.osm.visitor.paint.PaintColors;
47import org.openstreetmap.josm.gui.MapFrame;
48import org.openstreetmap.josm.gui.MapView;
49import org.openstreetmap.josm.gui.layer.Layer;
50import org.openstreetmap.josm.gui.layer.MapViewPaintable;
51import org.openstreetmap.josm.gui.layer.OsmDataLayer;
52import org.openstreetmap.josm.tools.ImageProvider;
53import org.openstreetmap.josm.tools.Pair;
54import org.openstreetmap.josm.tools.Shortcut;
55import org.openstreetmap.josm.tools.Utils;
56
57/**
58 * Mapmode to add nodes, create and extend ways.
59 */
60public class DrawAction extends MapMode implements MapViewPaintable, SelectionChangedListener, AWTEventListener {
61 final private Cursor cursorJoinNode;
62 final private Cursor cursorJoinWay;
63
64 private Node lastUsedNode = null;
65 private double PHI=Math.toRadians(90);
66
67 private Node mouseOnExistingNode;
68 private Set<Way> mouseOnExistingWays = new HashSet<Way>();
69 private Set<OsmPrimitive> oldHighlights = new HashSet<OsmPrimitive>();
70 private boolean drawHelperLine;
71 private boolean wayIsFinished = false;
72 private boolean drawTargetHighlight;
73 private Point mousePos;
74 private Point oldMousePos;
75 private Color selectedColor;
76
77 private Node currentBaseNode;
78 private EastNorth currentMouseEastNorth;
79
80 private Shortcut extraShortcut;
81
82 public DrawAction(MapFrame mapFrame) {
83 super(tr("Draw"), "node/autonode", tr("Draw nodes"),
84 Shortcut.registerShortcut("mapmode:draw", tr("Mode: {0}", tr("Draw")), KeyEvent.VK_A, Shortcut.GROUP_EDIT),
85 mapFrame, ImageProvider.getCursor("crosshair", null));
86
87 // Add extra shortcut N
88 extraShortcut = Shortcut.registerShortcut("mapmode:drawfocus", tr("Mode: Draw Focus"), KeyEvent.VK_N, Shortcut.GROUP_EDIT);
89 Main.registerActionShortcut(this, extraShortcut);
90
91 cursorJoinNode = ImageProvider.getCursor("crosshair", "joinnode");
92 cursorJoinWay = ImageProvider.getCursor("crosshair", "joinway");
93 }
94
95 /**
96 * Checks if a map redraw is required and does so if needed. Also updates the status bar
97 */
98 private void redrawIfRequired() {
99 updateStatusLine();
100 if ((!drawHelperLine || wayIsFinished) && !drawTargetHighlight) return;
101 // update selection to reflect which way being modified
102 if (currentBaseNode != null && getCurrentDataSet().getSelected().isEmpty() == false) {
103 Way continueFrom = getWayForNode(currentBaseNode);
104 if (alt && continueFrom != null) {
105 getCurrentDataSet().beginUpdate(); // to prevent the selection listener to screw around with the state
106 getCurrentDataSet().addSelected(currentBaseNode);
107 getCurrentDataSet().clearSelection(continueFrom);
108 getCurrentDataSet().endUpdate();
109 } else if (!alt && continueFrom != null) {
110 getCurrentDataSet().addSelected(continueFrom);
111 }
112 }
113 Main.map.mapView.repaint();
114 }
115
116 /**
117 * Takes the data from computeHelperLine to determine which ways/nodes should be highlighted
118 * (if feature enabled). Also sets the target cursor if appropriate.
119 */
120 private void addHighlighting() {
121 removeHighlighting();
122 // if ctrl key is held ("no join"), don't highlight anything
123 if (ctrl) {
124 Main.map.mapView.setNewCursor(cursor, this);
125 return;
126 }
127
128 // This happens when nothing is selected, but we still want to highlight the "target node"
129 if (mouseOnExistingNode == null && getCurrentDataSet().getSelected().size() == 0
130 && mousePos != null) {
131 mouseOnExistingNode = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
132 }
133
134 if (mouseOnExistingNode != null) {
135 Main.map.mapView.setNewCursor(cursorJoinNode, this);
136 // We also need this list for the statusbar help text
137 oldHighlights.add(mouseOnExistingNode);
138 if(drawTargetHighlight) {
139 mouseOnExistingNode.setHighlighted(true);
140 }
141 return;
142 }
143
144 // Insert the node into all the nearby way segments
145 if (mouseOnExistingWays.size() == 0) {
146 Main.map.mapView.setNewCursor(cursor, this);
147 return;
148 }
149
150 Main.map.mapView.setNewCursor(cursorJoinWay, this);
151
152 // We also need this list for the statusbar help text
153 oldHighlights.addAll(mouseOnExistingWays);
154 if (!drawTargetHighlight) return;
155 for (Way w : mouseOnExistingWays) {
156 w.setHighlighted(true);
157 }
158 }
159
160 /**
161 * Removes target highlighting from primitives
162 */
163 private void removeHighlighting() {
164 for(OsmPrimitive prim : oldHighlights) {
165 prim.setHighlighted(false);
166 }
167 oldHighlights = new HashSet<OsmPrimitive>();
168 }
169
170 @Override public void enterMode() {
171 if (!isEnabled())
172 return;
173 super.enterMode();
174 selectedColor =PaintColors.SELECTED.get();
175 drawHelperLine = Main.pref.getBoolean("draw.helper-line", true);
176 drawTargetHighlight = Main.pref.getBoolean("draw.target-highlight", true);
177 wayIsFinished = false;
178
179 Main.map.mapView.addMouseListener(this);
180 Main.map.mapView.addMouseMotionListener(this);
181 Main.map.mapView.addTemporaryLayer(this);
182 DataSet.addSelectionListener(this);
183
184 try {
185 Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
186 } catch (SecurityException ex) {
187 }
188 // would like to but haven't got mouse position yet:
189 // computeHelperLine(false, false, false);
190 }
191
192 @Override public void exitMode() {
193 super.exitMode();
194 Main.map.mapView.removeMouseListener(this);
195 Main.map.mapView.removeMouseMotionListener(this);
196 Main.map.mapView.removeTemporaryLayer(this);
197 DataSet.removeSelectionListener(this);
198 removeHighlighting();
199 try {
200 Toolkit.getDefaultToolkit().removeAWTEventListener(this);
201 } catch (SecurityException ex) {
202 }
203
204 // when exiting we let everybody know about the currently selected
205 // primitives
206 //
207 DataSet ds = getCurrentDataSet();
208 if(ds != null) {
209 ds.fireSelectionChanged();
210 }
211 }
212
213 /**
214 * redraw to (possibly) get rid of helper line if selection changes.
215 */
216 public void eventDispatched(AWTEvent event) {
217 if(Main.map == null || Main.map.mapView == null || !Main.map.mapView.isActiveLayerDrawable())
218 return;
219 updateKeyModifiers((InputEvent) event);
220 computeHelperLine();
221 addHighlighting();
222 redrawIfRequired();
223 }
224 /**
225 * redraw to (possibly) get rid of helper line if selection changes.
226 */
227 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
228 if(!Main.map.mapView.isActiveLayerDrawable())
229 return;
230 computeHelperLine();
231 addHighlighting();
232 redrawIfRequired();
233 }
234
235 private void tryAgain(MouseEvent e) {
236 getCurrentDataSet().setSelected();
237 mouseReleased(e);
238 }
239
240 /**
241 * This function should be called when the user wishes to finish his current draw action.
242 * If Potlatch Style is enabled, it will switch to select tool, otherwise simply disable
243 * the helper line until the user chooses to draw something else.
244 */
245 private void finishDrawing() {
246 // let everybody else know about the current selection
247 //
248 Main.main.getCurrentDataSet().fireSelectionChanged();
249 lastUsedNode = null;
250 wayIsFinished = true;
251 Main.map.selectSelectTool(true);
252
253 // Redraw to remove the helper line stub
254 computeHelperLine();
255 removeHighlighting();
256 redrawIfRequired();
257 }
258
259 /**
260 * If user clicked with the left button, add a node at the current mouse
261 * position.
262 *
263 * If in nodeway mode, insert the node into the way.
264 */
265 @Override public void mouseReleased(MouseEvent e) {
266 if (e.getButton() != MouseEvent.BUTTON1)
267 return;
268 if(!Main.map.mapView.isActiveLayerDrawable())
269 return;
270 // request focus in order to enable the expected keyboard shortcuts
271 //
272 Main.map.mapView.requestFocus();
273
274 if(e.getClickCount() > 1 && mousePos != null && mousePos.equals(oldMousePos)) {
275 // A double click equals "user clicked last node again, finish way"
276 // Change draw tool only if mouse position is nearly the same, as
277 // otherwise fast clicks will count as a double click
278 finishDrawing();
279 return;
280 }
281 oldMousePos = mousePos;
282
283 // we copy ctrl/alt/shift from the event just in case our global
284 // AWTEvent didn't make it through the security manager. Unclear
285 // if that can ever happen but better be safe.
286 updateKeyModifiers(e);
287 mousePos = e.getPoint();
288
289 DataSet ds = getCurrentDataSet();
290 Collection<OsmPrimitive> selection = new ArrayList<OsmPrimitive>(ds.getSelected());
291 Collection<Command> cmds = new LinkedList<Command>();
292 Collection<OsmPrimitive> newSelection = new LinkedList<OsmPrimitive>(ds.getSelected());
293
294 ArrayList<Way> reuseWays = new ArrayList<Way>(),
295 replacedWays = new ArrayList<Way>();
296 boolean newNode = false;
297 Node n = null;
298
299 if (!ctrl) {
300 n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
301 }
302
303 if (n != null) {
304 // user clicked on node
305 if (selection.isEmpty() || wayIsFinished) {
306 // select the clicked node and do nothing else
307 // (this is just a convenience option so that people don't
308 // have to switch modes)
309
310 getCurrentDataSet().setSelected(n);
311 // If we extend/continue an existing way, select it already now to make it obvious
312 Way continueFrom = getWayForNode(n);
313 if (continueFrom != null) {
314 getCurrentDataSet().addSelected(continueFrom);
315 }
316
317 // The user explicitly selected a node, so let him continue drawing
318 wayIsFinished = false;
319 return;
320 }
321 } else {
322 // no node found in clicked area
323 n = new Node(Main.map.mapView.getLatLon(e.getX(), e.getY()));
324 if (n.getCoor().isOutSideWorld()) {
325 JOptionPane.showMessageDialog(
326 Main.parent,
327 tr("Cannot add a node outside of the world."),
328 tr("Warning"),
329 JOptionPane.WARNING_MESSAGE
330 );
331 return;
332 }
333 newNode = true;
334
335 cmds.add(new AddCommand(n));
336
337 if (!ctrl) {
338 // Insert the node into all the nearby way segments
339 List<WaySegment> wss = Main.map.mapView.getNearestWaySegments(e.getPoint(), OsmPrimitive.isSelectablePredicate);
340 Map<Way, List<Integer>> insertPoints = new HashMap<Way, List<Integer>>();
341 for (WaySegment ws : wss) {
342 List<Integer> is;
343 if (insertPoints.containsKey(ws.way)) {
344 is = insertPoints.get(ws.way);
345 } else {
346 is = new ArrayList<Integer>();
347 insertPoints.put(ws.way, is);
348 }
349
350 is.add(ws.lowerIndex);
351 }
352
353 Set<Pair<Node,Node>> segSet = new HashSet<Pair<Node,Node>>();
354
355 for (Map.Entry<Way, List<Integer>> insertPoint : insertPoints.entrySet()) {
356 Way w = insertPoint.getKey();
357 List<Integer> is = insertPoint.getValue();
358
359 Way wnew = new Way(w);
360
361 pruneSuccsAndReverse(is);
362 for (int i : is) {
363 segSet.add(
364 Pair.sort(new Pair<Node,Node>(w.getNode(i), w.getNode(i+1))));
365 }
366 for (int i : is) {
367 wnew.addNode(i + 1, n);
368 }
369
370 // If ALT is pressed, a new way should be created and that new way should get
371 // selected. This works everytime unless the ways the nodes get inserted into
372 // are already selected. This is the case when creating a self-overlapping way
373 // but pressing ALT prevents this. Therefore we must de-select the way manually
374 // here so /only/ the new way will be selected after this method finishes.
375 if(alt) {
376 newSelection.add(insertPoint.getKey());
377 }
378
379 cmds.add(new ChangeCommand(insertPoint.getKey(), wnew));
380 replacedWays.add(insertPoint.getKey());
381 reuseWays.add(wnew);
382 }
383
384 adjustNode(segSet, n);
385 }
386 }
387
388 // This part decides whether or not a "segment" (i.e. a connection) is made to an
389 // existing node.
390
391 // For a connection to be made, the user must either have a node selected (connection
392 // is made to that node), or he must have a way selected *and* one of the endpoints
393 // of that way must be the last used node (connection is made to last used node), or
394 // he must have a way and a node selected (connection is made to the selected node).
395
396 // If the above does not apply, the selection is cleared and a new try is started
397
398 boolean extendedWay = false;
399 boolean wayIsFinishedTemp = wayIsFinished;
400 wayIsFinished = false;
401
402 // don't draw lines if shift is held
403 if (selection.size() > 0 && !shift) {
404 Node selectedNode = null;
405 Way selectedWay = null;
406
407 for (OsmPrimitive p : selection) {
408 if (p instanceof Node) {
409 if (selectedNode != null) {
410 // Too many nodes selected to do something useful
411 tryAgain(e);
412 return;
413 }
414 selectedNode = (Node) p;
415 } else if (p instanceof Way) {
416 if (selectedWay != null) {
417 // Too many ways selected to do something useful
418 tryAgain(e);
419 return;
420 }
421 selectedWay = (Way) p;
422 }
423 }
424
425 // the node from which we make a connection
426 Node n0 = findNodeToContinueFrom(selectedNode, selectedWay);
427 // We have a selection but it isn't suitable. Try again.
428 if(n0 == null) {
429 tryAgain(e);
430 return;
431 }
432 if(!wayIsFinishedTemp){
433 if(isSelfContainedWay(selectedWay, n0, n))
434 return;
435
436 // User clicked last node again, finish way
437 if(n0 == n) {
438 finishDrawing();
439 return;
440 }
441
442 // Ok we know now that we'll insert a line segment, but will it connect to an
443 // existing way or make a new way of its own? The "alt" modifier means that the
444 // user wants a new way.
445 Way way = alt ? null : (selectedWay != null) ? selectedWay : getWayForNode(n0);
446 Way wayToSelect;
447
448 // Don't allow creation of self-overlapping ways
449 if(way != null) {
450 int nodeCount=0;
451 for (Node p : way.getNodes())
452 if(p.equals(n0)) {
453 nodeCount++;
454 }
455 if(nodeCount > 1) {
456 way = null;
457 }
458 }
459
460 if (way == null) {
461 way = new Way();
462 way.addNode(n0);
463 cmds.add(new AddCommand(way));
464 wayToSelect = way;
465 } else {
466 int i;
467 if ((i = replacedWays.indexOf(way)) != -1) {
468 way = reuseWays.get(i);
469 wayToSelect = way;
470 } else {
471 wayToSelect = way;
472 Way wnew = new Way(way);
473 cmds.add(new ChangeCommand(way, wnew));
474 way = wnew;
475 }
476 }
477
478 // Connected to a node that's already in the way
479 if(way.containsNode(n)) {
480 wayIsFinished = true;
481 selection.clear();
482 }
483
484 // Add new node to way
485 if (way.getNode(way.getNodesCount() - 1) == n0) {
486 way.addNode(n);
487 } else {
488 way.addNode(0, n);
489 }
490
491 extendedWay = true;
492 newSelection.clear();
493 newSelection.add(wayToSelect);
494 }
495 }
496
497 String title;
498 if (!extendedWay) {
499 if (!newNode)
500 return; // We didn't do anything.
501 else if (reuseWays.isEmpty()) {
502 title = tr("Add node");
503 } else {
504 title = tr("Add node into way");
505 for (Way w : reuseWays) {
506 newSelection.remove(w);
507 }
508 }
509 newSelection.clear();
510 newSelection.add(n);
511 } else if (!newNode) {
512 title = tr("Connect existing way to node");
513 } else if (reuseWays.isEmpty()) {
514 title = tr("Add a new node to an existing way");
515 } else {
516 title = tr("Add node into way and connect");
517 }
518
519 Command c = new SequenceCommand(title, cmds);
520
521 Main.main.undoRedo.add(c);
522 if(!wayIsFinished) {
523 lastUsedNode = n;
524 }
525
526 getCurrentDataSet().setSelected(newSelection);
527
528 // "viewport following" mode for tracing long features
529 // from aerial imagery or GPS tracks.
530 if (n != null && Main.map.mapView.viewportFollowing) {
531 Main.map.mapView.smoothScrollTo(n.getEastNorth());
532 };
533 computeHelperLine();
534 removeHighlighting();
535 redrawIfRequired();
536 }
537
538 /**
539 * Prevent creation of ways that look like this: <---->
540 * This happens if users want to draw a no-exit-sideway from the main way like this:
541 * ^
542 * |<---->
543 * |
544 * The solution isn't ideal because the main way will end in the side way, which is bad for
545 * navigation software ("drive straight on") but at least easier to fix. Maybe users will fix
546 * it on their own, too. At least it's better than producing an error.
547 *
548 * @param Way the way to check
549 * @param Node the current node (i.e. the one the connection will be made from)
550 * @param Node the target node (i.e. the one the connection will be made to)
551 * @return Boolean True if this would create a selfcontaining way, false otherwise.
552 */
553 private boolean isSelfContainedWay(Way selectedWay, Node currentNode, Node targetNode) {
554 if(selectedWay != null) {
555 int posn0 = selectedWay.getNodes().indexOf(currentNode);
556 if( posn0 != -1 && // n0 is part of way
557 (posn0 >= 1 && targetNode.equals(selectedWay.getNode(posn0-1))) || // previous node
558 (posn0 < selectedWay.getNodesCount()-1) && targetNode.equals(selectedWay.getNode(posn0+1))) { // next node
559 getCurrentDataSet().setSelected(targetNode);
560 lastUsedNode = targetNode;
561 return true;
562 }
563 }
564
565 return false;
566 }
567
568 /**
569 * Finds a node to continue drawing from. Decision is based upon given node and way.
570 * @param selectedNode Currently selected node, may be null
571 * @param selectedWay Currently selected way, may be null
572 * @return Node if a suitable node is found, null otherwise
573 */
574 private Node findNodeToContinueFrom(Node selectedNode, Way selectedWay) {
575 // No nodes or ways have been selected, this occurs when a relation
576 // has been selected or the selection is empty
577 if(selectedNode == null && selectedWay == null)
578 return null;
579
580 if (selectedNode == null) {
581 if (selectedWay.isFirstLastNode(lastUsedNode))
582 return lastUsedNode;
583
584 // We have a way selected, but no suitable node to continue from. Start anew.
585 return null;
586 }
587
588 if (selectedWay == null)
589 return selectedNode;
590
591 if (selectedWay.isFirstLastNode(selectedNode))
592 return selectedNode;
593
594 // We have a way and node selected, but it's not at the start/end of the way. Start anew.
595 return null;
596 }
597
598 @Override public void mouseDragged(MouseEvent e) {
599 mouseMoved(e);
600 }
601
602 @Override public void mouseMoved(MouseEvent e) {
603 if(!Main.map.mapView.isActiveLayerDrawable())
604 return;
605
606 // we copy ctrl/alt/shift from the event just in case our global
607 // AWTEvent didn't make it through the security manager. Unclear
608 // if that can ever happen but better be safe.
609 updateKeyModifiers(e);
610 mousePos = e.getPoint();
611
612 computeHelperLine();
613 addHighlighting();
614 redrawIfRequired();
615 }
616
617 /**
618 * This method prepares data required for painting the "helper line" from
619 * the last used position to the mouse cursor. It duplicates some code from
620 * mouseReleased() (FIXME).
621 */
622 private void computeHelperLine() {
623 MapView mv = Main.map.mapView;
624 if (mousePos == null) {
625 // Don't draw the line.
626 currentMouseEastNorth = null;
627 currentBaseNode = null;
628 return;
629 }
630
631 double distance = -1;
632 double angle = -1;
633
634 Collection<OsmPrimitive> selection = getCurrentDataSet().getSelected();
635
636 Node selectedNode = null;
637 Way selectedWay = null;
638 Node currentMouseNode = null;
639 mouseOnExistingNode = null;
640 mouseOnExistingWays = new HashSet<Way>();
641
642 Main.map.statusLine.setAngle(-1);
643 Main.map.statusLine.setHeading(-1);
644 Main.map.statusLine.setDist(-1);
645
646 if (!ctrl && mousePos != null) {
647 currentMouseNode = mv.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
648 }
649
650 // We need this for highlighting and we'll only do so if we actually want to re-use
651 // *and* there is no node nearby (because nodes beat ways when re-using)
652 if(!ctrl && currentMouseNode == null) {
653 List<WaySegment> wss = mv.getNearestWaySegments(mousePos, OsmPrimitive.isSelectablePredicate);
654 for(WaySegment ws : wss) {
655 mouseOnExistingWays.add(ws.way);
656 }
657 }
658
659 if (currentMouseNode != null) {
660 // user clicked on node
661 if (selection.isEmpty()) return;
662 currentMouseEastNorth = currentMouseNode.getEastNorth();
663 mouseOnExistingNode = currentMouseNode;
664 } else {
665 // no node found in clicked area
666 currentMouseEastNorth = mv.getEastNorth(mousePos.x, mousePos.y);
667 }
668
669 for (OsmPrimitive p : selection) {
670 if (p instanceof Node) {
671 if (selectedNode != null) return;
672 selectedNode = (Node) p;
673 } else if (p instanceof Way) {
674 if (selectedWay != null) return;
675 selectedWay = (Way) p;
676 }
677 }
678
679 // the node from which we make a connection
680 currentBaseNode = null;
681 Node previousNode = null;
682
683 if (selectedNode == null) {
684 if (selectedWay == null)
685 return;
686 if (selectedWay.isFirstLastNode(lastUsedNode)) {
687 currentBaseNode = lastUsedNode;
688 if (lastUsedNode == selectedWay.getNode(selectedWay.getNodesCount()-1) && selectedWay.getNodesCount() > 1) {
689 previousNode = selectedWay.getNode(selectedWay.getNodesCount()-2);
690 }
691 }
692 } else if (selectedWay == null) {
693 currentBaseNode = selectedNode;
694 } else {
695 if (selectedNode == selectedWay.getNode(0) || selectedNode == selectedWay.getNode(selectedWay.getNodesCount()-1)) {
696 currentBaseNode = selectedNode;
697 }
698 }
699
700 if (currentBaseNode == null || currentBaseNode == currentMouseNode)
701 return; // Don't create zero length way segments.
702
703 // find out the distance, in metres, between the base point and the mouse cursor
704 LatLon mouseLatLon = mv.getProjection().eastNorth2latlon(currentMouseEastNorth);
705 distance = currentBaseNode.getCoor().greatCircleDistance(mouseLatLon);
706
707 double hdg = Math.toDegrees(currentBaseNode.getEastNorth()
708 .heading(currentMouseEastNorth));
709 if (previousNode != null) {
710 angle = hdg - Math.toDegrees(previousNode.getEastNorth()
711 .heading(currentBaseNode.getEastNorth()));
712 angle += angle < 0 ? 360 : 0;
713 }
714
715 Main.map.statusLine.setAngle(angle);
716 Main.map.statusLine.setHeading(hdg);
717 Main.map.statusLine.setDist(distance);
718 // Now done in redrawIfRequired()
719 //updateStatusLine();
720 }
721
722 /**
723 * Repaint on mouse exit so that the helper line goes away.
724 */
725 @Override public void mouseExited(MouseEvent e) {
726 if(!Main.map.mapView.isActiveLayerDrawable())
727 return;
728 mousePos = e.getPoint();
729 Main.map.mapView.repaint();
730 }
731
732 /**
733 * @return If the node is the end of exactly one way, return this.
734 * <code>null</code> otherwise.
735 */
736 public Way getWayForNode(Node n) {
737 Way way = null;
738 for (Way w : Utils.filteredCollection(n.getReferrers(), Way.class)) {
739 if (!w.isUsable() || w.getNodesCount() < 1) {
740 continue;
741 }
742 Node firstNode = w.getNode(0);
743 Node lastNode = w.getNode(w.getNodesCount() - 1);
744 if ((firstNode == n || lastNode == n) && (firstNode != lastNode)) {
745 if (way != null)
746 return null;
747 way = w;
748 }
749 }
750 return way;
751 }
752
753 public Node getCurrentBaseNode() {
754 return currentBaseNode;
755 }
756
757 private static void pruneSuccsAndReverse(List<Integer> is) {
758 //if (is.size() < 2) return;
759
760 HashSet<Integer> is2 = new HashSet<Integer>();
761 for (int i : is) {
762 if (!is2.contains(i - 1) && !is2.contains(i + 1)) {
763 is2.add(i);
764 }
765 }
766 is.clear();
767 is.addAll(is2);
768 Collections.sort(is);
769 Collections.reverse(is);
770 }
771
772 /**
773 * Adjusts the position of a node to lie on a segment (or a segment
774 * intersection).
775 *
776 * If one or more than two segments are passed, the node is adjusted
777 * to lie on the first segment that is passed.
778 *
779 * If two segments are passed, the node is adjusted to be at their
780 * intersection.
781 *
782 * No action is taken if no segments are passed.
783 *
784 * @param segs the segments to use as a reference when adjusting
785 * @param n the node to adjust
786 */
787 private static void adjustNode(Collection<Pair<Node,Node>> segs, Node n) {
788
789 switch (segs.size()) {
790 case 0:
791 return;
792 case 2:
793 // This computes the intersection between
794 // the two segments and adjusts the node position.
795 Iterator<Pair<Node,Node>> i = segs.iterator();
796 Pair<Node,Node> seg = i.next();
797 EastNorth A = seg.a.getEastNorth();
798 EastNorth B = seg.b.getEastNorth();
799 seg = i.next();
800 EastNorth C = seg.a.getEastNorth();
801 EastNorth D = seg.b.getEastNorth();
802
803 double u=det(B.east() - A.east(), B.north() - A.north(), C.east() - D.east(), C.north() - D.north());
804
805 // Check for parallel segments and do nothing if they are
806 // In practice this will probably only happen when a way has been duplicated
807
808 if (u == 0) return;
809
810 // q is a number between 0 and 1
811 // It is the point in the segment where the intersection occurs
812 // if the segment is scaled to lenght 1
813
814 double q = det(B.north() - C.north(), B.east() - C.east(), D.north() - C.north(), D.east() - C.east()) / u;
815 EastNorth intersection = new EastNorth(
816 B.east() + q * (A.east() - B.east()),
817 B.north() + q * (A.north() - B.north()));
818
819 int snapToIntersectionThreshold
820 = Main.pref.getInteger("edit.snap-intersection-threshold",10);
821
822 // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise
823 // fall through to default action.
824 // (for semi-parallel lines, intersection might be miles away!)
825 if (Main.map.mapView.getPoint(n).distance(Main.map.mapView.getPoint(intersection)) < snapToIntersectionThreshold) {
826 n.setEastNorth(intersection);
827 return;
828 }
829
830 default:
831 EastNorth P = n.getEastNorth();
832 seg = segs.iterator().next();
833 A = seg.a.getEastNorth();
834 B = seg.b.getEastNorth();
835 double a = P.distanceSq(B);
836 double b = P.distanceSq(A);
837 double c = A.distanceSq(B);
838 q = (a - b + c) / (2*c);
839 n.setEastNorth(new EastNorth(B.east() + q * (A.east() - B.east()), B.north() + q * (A.north() - B.north())));
840 }
841 }
842
843 // helper for adjustNode
844 static double det(double a, double b, double c, double d) {
845 return a * d - b * c;
846 }
847
848 public void paint(Graphics2D g, MapView mv, Bounds box) {
849 if (!drawHelperLine || wayIsFinished || shift) return;
850
851 // sanity checks
852 if (Main.map.mapView == null) return;
853 if (mousePos == null) return;
854
855 // don't draw line if we don't know where from or where to
856 if (currentBaseNode == null || currentMouseEastNorth == null) return;
857
858 // don't draw line if mouse is outside window
859 if (!Main.map.mapView.getBounds().contains(mousePos)) return;
860
861 Graphics2D g2 = g;
862 g2.setColor(selectedColor);
863 g2.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
864 GeneralPath b = new GeneralPath();
865 Point p1=mv.getPoint(currentBaseNode);
866 Point p2=mv.getPoint(currentMouseEastNorth);
867
868 double t = Math.atan2(p2.y-p1.y, p2.x-p1.x) + Math.PI;
869
870 b.moveTo(p1.x,p1.y); b.lineTo(p2.x, p2.y);
871
872 // if alt key is held ("start new way"), draw a little perpendicular line
873 if (alt) {
874 b.moveTo((int)(p1.x + 8*Math.cos(t+PHI)), (int)(p1.y + 8*Math.sin(t+PHI)));
875 b.lineTo((int)(p1.x + 8*Math.cos(t-PHI)), (int)(p1.y + 8*Math.sin(t-PHI)));
876 }
877
878 g2.draw(b);
879 g2.setStroke(new BasicStroke(1));
880 }
881
882 @Override public String getModeHelpText() {
883 String rv = "";
884 /*
885 * No modifiers: all (Connect, Node Re-Use, Auto-Weld)
886 * CTRL: disables node re-use, auto-weld
887 * Shift: do not make connection
888 * ALT: make connection but start new way in doing so
889 */
890
891 /*
892 * Status line text generation is split into two parts to keep it maintainable.
893 * First part looks at what will happen to the new node inserted on click and
894 * the second part will look if a connection is made or not.
895 *
896 * Note that this help text is not absolutely accurate as it doesn't catch any special
897 * cases (e.g. when preventing <---> ways). The only special that it catches is when
898 * a way is about to be finished.
899 *
900 * First check what happens to the new node.
901 */
902
903 // oldHighlights stores the current highlights. If this
904 // list is empty we can assume that we won't do any joins
905 if (ctrl || oldHighlights.isEmpty()) {
906 rv = tr("Create new node.");
907 } else {
908 // oldHighlights may store a node or way, check if it's a node
909 OsmPrimitive x = oldHighlights.iterator().next();
910 if (x instanceof Node) {
911 rv = tr("Select node under cursor.");
912 } else {
913 rv = trn("Insert new node into way.", "Insert new node into {0} ways.",
914 oldHighlights.size(), oldHighlights.size());
915 }
916 }
917
918 /*
919 * Check whether a connection will be made
920 */
921 if (currentBaseNode != null && !wayIsFinished) {
922 if (alt) {
923 rv += " " + tr("Start new way from last node.");
924 } else {
925 rv += " " + tr("Continue way from last node.");
926 }
927 }
928
929 Node n = mouseOnExistingNode;
930 /*
931 * Handle special case: Highlighted node == selected node => finish drawing
932 */
933 if (n != null && getCurrentDataSet() != null && getCurrentDataSet().getSelectedNodes().contains(n)) {
934 if (wayIsFinished) {
935 rv = tr("Select node under cursor.");
936 } else {
937 rv = tr("Finish drawing.");
938 }
939 }
940
941 /*
942 * Handle special case: Self-Overlapping or closing way
943 */
944 if (getCurrentDataSet() != null && getCurrentDataSet().getSelectedWays().size() > 0 && !wayIsFinished && !alt) {
945 Way w = getCurrentDataSet().getSelectedWays().iterator().next();
946 for (Node m : w.getNodes()) {
947 if (m.equals(mouseOnExistingNode) || mouseOnExistingWays.contains(w)) {
948 rv += " " + tr("Finish drawing.");
949 break;
950 }
951 }
952 }
953 return rv;
954 }
955
956 @Override public boolean layerIsSupported(Layer l) {
957 return l instanceof OsmDataLayer;
958 }
959
960 @Override
961 protected void updateEnabledState() {
962 setEnabled(getEditLayer() != null);
963 }
964
965 @Override
966 public void destroy() {
967 super.destroy();
968 Main.unregisterActionShortcut(extraShortcut);
969 }
970}
Note: See TracBrowser for help on using the repository browser.