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

Last change on this file since 1459 was 1459, checked in by stoecker, 15 years ago

fix translation

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