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

Last change on this file since 2558 was 2558, checked in by bastiK, 14 years ago

fix #3838 - DrawAction: Wrong start point for helper line after adding node with double click

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