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

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

fix #2302 - patch by jttt - some code cleanup for better encapsulation

  • Property svn:eol-style set to native
File size: 34.3 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)
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 computeHelperLine();
256 addHighlighting();
257 redrawIfRequired();
258 }
259
260 private void tryAgain(MouseEvent e) {
261 Main.ds.setSelected();
262 mouseClicked(e);
263 }
264
265 /**
266 * This function should be called when the user wishes to finish his current draw action.
267 * If Potlatch Style is enabled, it will switch to select tool, otherwise simply disable
268 * the helper line until the user chooses to draw something else.
269 */
270 private void finishDrawing() {
271 lastUsedNode = null;
272 wayIsFinished = true;
273 Main.map.selectSelectTool(true);
274
275 // Redraw to remove the helper line stub
276 computeHelperLine();
277 removeHighlighting();
278 redrawIfRequired();
279 }
280
281 /**
282 * If user clicked with the left button, add a node at the current mouse
283 * position.
284 *
285 * If in nodeway mode, insert the node into the way.
286 */
287 @Override public void mouseClicked(MouseEvent e) {
288 if (e.getButton() != MouseEvent.BUTTON1)
289 return;
290 if(!Main.map.mapView.isDrawableLayer())
291 return;
292
293 if(e.getClickCount() > 1 && mousePos != null && mousePos.equals(oldMousePos)) {
294 // A double click equals "user clicked last node again, finish way"
295 // Change draw tool only if mouse position is nearly the same, as
296 // otherwise fast clicks will count as a double click
297 finishDrawing();
298 return;
299 }
300 oldMousePos = mousePos;
301
302 // we copy ctrl/alt/shift from the event just in case our global
303 // AWTEvent didn't make it through the security manager. Unclear
304 // if that can ever happen but better be safe.
305 updateKeyModifiers(e);
306 mousePos = e.getPoint();
307
308 Collection<OsmPrimitive> selection = Main.ds.getSelected();
309 Collection<Command> cmds = new LinkedList<Command>();
310
311 ArrayList<Way> reuseWays = new ArrayList<Way>(),
312 replacedWays = new ArrayList<Way>();
313 boolean newNode = false;
314 Node n = null;
315
316 if (!ctrl)
317 n = Main.map.mapView.getNearestNode(mousePos);
318
319 if (n != null) {
320 // user clicked on node
321 if (selection.isEmpty()) {
322 // select the clicked node and do nothing else
323 // (this is just a convenience option so that people don't
324 // have to switch modes)
325 Main.ds.setSelected(n);
326 selection = Main.ds.getSelected();
327 // The user explicitly selected a node, so let him continue drawing
328 wayIsFinished = false;
329 return;
330 }
331 } else {
332 // no node found in clicked area
333 n = new Node(Main.map.mapView.getLatLon(e.getX(), e.getY()));
334 if (n.coor.isOutSideWorld()) {
335 JOptionPane.showMessageDialog(Main.parent,
336 tr("Cannot add a node outside of the world."));
337 return;
338 }
339 newNode = true;
340
341 cmds.add(new AddCommand(n));
342
343 if (!ctrl) {
344 // Insert the node into all the nearby way segments
345 List<WaySegment> wss = Main.map.mapView.getNearestWaySegments(e.getPoint());
346 Map<Way, List<Integer>> insertPoints = new HashMap<Way, List<Integer>>();
347 for (WaySegment ws : wss) {
348 List<Integer> is;
349 if (insertPoints.containsKey(ws.way)) {
350 is = insertPoints.get(ws.way);
351 } else {
352 is = new ArrayList<Integer>();
353 insertPoints.put(ws.way, is);
354 }
355
356 is.add(ws.lowerIndex);
357 }
358
359 Set<Pair<Node,Node>> segSet = new HashSet<Pair<Node,Node>>();
360
361 for (Map.Entry<Way, List<Integer>> insertPoint : insertPoints.entrySet()) {
362 Way w = insertPoint.getKey();
363 List<Integer> is = insertPoint.getValue();
364
365 Way wnew = new Way(w);
366
367 pruneSuccsAndReverse(is);
368 for (int i : is) segSet.add(
369 Pair.sort(new Pair<Node,Node>(w.nodes.get(i), w.nodes.get(i+1))));
370 for (int i : is) wnew.addNode(i + 1, n);
371
372 // If ALT is pressed, a new way should be created and that new way should get
373 // selected. This works everytime unless the ways the nodes get inserted into
374 // are already selected. This is the case when creating a self-overlapping way
375 // but pressing ALT prevents this. Therefore we must de-select the way manually
376 // here so /only/ the new way will be selected after this method finishes.
377 if(alt) wnew.selected = false;
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
399
400 boolean extendedWay = false;
401 boolean wayIsFinishedTemp = wayIsFinished;
402 wayIsFinished = false;
403
404 // don't draw lines if shift is held
405 if (selection.size() > 0 && !shift) {
406 Node selectedNode = null;
407 Way selectedWay = null;
408
409 for (OsmPrimitive p : selection) {
410 if (p instanceof Node) {
411 if (selectedNode != null) {
412 // Too many nodes selected to do something useful
413 tryAgain(e);
414 return;
415 }
416 selectedNode = (Node) p;
417 } else if (p instanceof Way) {
418 if (selectedWay != null) {
419 // Too many ways selected to do something useful
420 tryAgain(e);
421 return;
422 }
423 selectedWay = (Way) p;
424 }
425 }
426
427 // the node from which we make a connection
428 Node n0 = findNodeToContinueFrom(selectedNode, selectedWay);
429 // We have a selection but it isn't suitable. Try again.
430 if(n0 == null) {
431 tryAgain(e);
432 return;
433 }
434 if(!wayIsFinishedTemp)
435 {
436 if(isSelfContainedWay(selectedWay, n0, n))
437 return;
438
439 // User clicked last node again, finish way
440 if(n0 == n) {
441 finishDrawing();
442 return;
443 }
444
445 // Ok we know now that we'll insert a line segment, but will it connect to an
446 // existing way or make a new way of its own? The "alt" modifier means that the
447 // user wants a new way.
448 Way way = alt ? null : (selectedWay != null) ? selectedWay : getWayForNode(n0);
449
450 // Don't allow creation of self-overlapping ways
451 if(way != null) {
452 int nodeCount=0;
453 for (Node p : way.nodes)
454 if(p.equals(n0)) nodeCount++;
455 if(nodeCount > 1) way = null;
456 }
457
458 if (way == null) {
459 way = new Way();
460 way.addNode(n0);
461 cmds.add(new AddCommand(way));
462 } else {
463 int i;
464 if ((i = replacedWays.indexOf(way)) != -1) {
465 way = reuseWays.get(i);
466 } else {
467 Way wnew = new Way(way);
468 cmds.add(new ChangeCommand(way, wnew));
469 way = wnew;
470 }
471 }
472
473 // Connected to a node that's already in the way
474 if(way.nodes.contains(n)) {
475 wayIsFinished = true;
476 selection.clear();
477 }
478
479 // Add new node to way
480 if (way.nodes.get(way.nodes.size() - 1) == n0)
481 way.addNode(n);
482 else
483 way.addNode(0, n);
484
485 extendedWay = true;
486 Main.ds.setSelected(way);
487 }
488 }
489
490 String title;
491 if (!extendedWay) {
492 if (!newNode) {
493 return; // We didn't do anything.
494 } else if (reuseWays.isEmpty()) {
495 title = tr("Add node");
496 } else {
497 title = tr("Add node into way");
498 for (Way w : reuseWays) w.selected = false;
499 }
500 Main.ds.setSelected(n);
501 } else if (!newNode) {
502 title = tr("Connect existing way to node");
503 } else if (reuseWays.isEmpty()) {
504 title = tr("Add a new node to an existing way");
505 } else {
506 title = tr("Add node into way and connect");
507 }
508
509 Command c = new SequenceCommand(title, cmds);
510
511 Main.main.undoRedo.add(c);
512 if(!wayIsFinished) lastUsedNode = n;
513
514 computeHelperLine();
515 removeHighlighting();
516 redrawIfRequired();
517 }
518
519 /**
520 * Prevent creation of ways that look like this: <---->
521 * This happens if users want to draw a no-exit-sideway from the main way like this:
522 * ^
523 * |<---->
524 * |
525 * The solution isn't ideal because the main way will end in the side way, which is bad for
526 * navigation software ("drive straight on") but at least easier to fix. Maybe users will fix
527 * it on their own, too. At least it's better than producing an error.
528 *
529 * @param Way the way to check
530 * @param Node the current node (i.e. the one the connection will be made from)
531 * @param Node the target node (i.e. the one the connection will be made to)
532 * @return Boolean True if this would create a selfcontaining way, false otherwise.
533 */
534 private boolean isSelfContainedWay(Way selectedWay, Node currentNode, Node targetNode) {
535 if(selectedWay != null && selectedWay.nodes != null) {
536 int posn0 = selectedWay.nodes.indexOf(currentNode);
537 if( posn0 != -1 && // n0 is part of way
538 (posn0 >= 1 && targetNode.equals(selectedWay.nodes.get(posn0-1))) || // previous node
539 (posn0 < selectedWay.nodes.size()-1) && targetNode.equals(selectedWay.nodes.get(posn0+1))) { // next node
540 Main.ds.setSelected(targetNode);
541 lastUsedNode = targetNode;
542 return true;
543 }
544 }
545
546 return false;
547 }
548
549 /**
550 * Finds a node to continue drawing from. Decision is based upon given node and way.
551 * @param selectedNode Currently selected node, may be null
552 * @param selectedWay Currently selected way, may be null
553 * @return Node if a suitable node is found, null otherwise
554 */
555 private Node findNodeToContinueFrom(Node selectedNode, Way selectedWay) {
556 // No nodes or ways have been selected, this occurs when a relation
557 // has been selected or the selection is empty
558 if(selectedNode == null && selectedWay == null)
559 return null;
560
561 if (selectedNode == null) {
562 if (selectedWay.isFirstLastNode(lastUsedNode))
563 return lastUsedNode;
564
565 // We have a way selected, but no suitable node to continue from. Start anew.
566 return null;
567 }
568
569 if (selectedWay == null)
570 return selectedNode;
571
572 if (selectedWay.isFirstLastNode(selectedNode))
573 return selectedNode;
574
575 // We have a way and node selected, but it's not at the start/end of the way. Start anew.
576 return null;
577 }
578
579 @Override public void mouseMoved(MouseEvent e) {
580 if(!Main.map.mapView.isDrawableLayer())
581 return;
582
583 // we copy ctrl/alt/shift from the event just in case our global
584 // AWTEvent didn't make it through the security manager. Unclear
585 // if that can ever happen but better be safe.
586 updateKeyModifiers(e);
587 mousePos = e.getPoint();
588
589 computeHelperLine();
590 addHighlighting();
591 redrawIfRequired();
592 }
593
594 private void updateKeyModifiers(InputEvent e) {
595 ctrl = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0;
596 alt = (e.getModifiers() & (ActionEvent.ALT_MASK|InputEvent.ALT_GRAPH_MASK)) != 0;
597 shift = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
598 }
599
600 private void updateKeyModifiers(MouseEvent e) {
601 ctrl = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0;
602 alt = (e.getModifiers() & (ActionEvent.ALT_MASK|InputEvent.ALT_GRAPH_MASK)) != 0;
603 shift = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
604 }
605
606 /**
607 * This method prepares data required for painting the "helper line" from
608 * the last used position to the mouse cursor. It duplicates some code from
609 * mouseClicked() (FIXME).
610 */
611 private void computeHelperLine() {
612 if (mousePos == null) {
613 // Don't draw the line.
614 currentMouseEastNorth = null;
615 currentBaseNode = null;
616 return;
617 }
618
619 double distance = -1;
620 double angle = -1;
621
622 Collection<OsmPrimitive> selection = Main.ds.getSelected();
623
624 Node selectedNode = null;
625 Way selectedWay = null;
626 Node currentMouseNode = null;
627 mouseOnExistingNode = null;
628 mouseOnExistingWays = new HashSet<Way>();
629
630 Main.map.statusLine.setAngle(-1);
631 Main.map.statusLine.setHeading(-1);
632 Main.map.statusLine.setDist(-1);
633
634 if (!ctrl && mousePos != null) {
635 currentMouseNode = Main.map.mapView.getNearestNode(mousePos);
636 }
637
638 // We need this for highlighting and we'll only do so if we actually want to re-use
639 // *and* there is no node nearby (because nodes beat ways when re-using)
640 if(!ctrl && currentMouseNode == null) {
641 List<WaySegment> wss = Main.map.mapView.getNearestWaySegments(mousePos);
642 for(WaySegment ws : wss)
643 mouseOnExistingWays.add(ws.way);
644 }
645
646 if (currentMouseNode != null) {
647 // user clicked on node
648 if (selection.isEmpty()) return;
649 currentMouseEastNorth = currentMouseNode.eastNorth;
650 mouseOnExistingNode = currentMouseNode;
651 } else {
652 // no node found in clicked area
653 currentMouseEastNorth = Main.map.mapView.getEastNorth(mousePos.x, mousePos.y);
654 }
655
656 for (OsmPrimitive p : selection) {
657 if (p instanceof Node) {
658 if (selectedNode != null) return;
659 selectedNode = (Node) p;
660 } else if (p instanceof Way) {
661 if (selectedWay != null) return;
662 selectedWay = (Way) p;
663 }
664 }
665
666 // the node from which we make a connection
667 currentBaseNode = null;
668 Node previousNode = null;
669
670 if (selectedNode == null) {
671 if (selectedWay == null)
672 return;
673 if (selectedWay.isFirstLastNode(lastUsedNode)) {
674 currentBaseNode = lastUsedNode;
675 if (lastUsedNode == selectedWay.nodes.get(selectedWay.nodes.size()-1) && selectedWay.nodes.size() > 1) {
676 previousNode = selectedWay.nodes.get(selectedWay.nodes.size()-2);
677 }
678 }
679 } else if (selectedWay == null) {
680 currentBaseNode = selectedNode;
681 } else {
682 if (selectedNode == selectedWay.nodes.get(0) || selectedNode == selectedWay.nodes.get(selectedWay.nodes.size()-1)) {
683 currentBaseNode = selectedNode;
684 }
685 }
686
687 if (currentBaseNode == null || currentBaseNode == currentMouseNode)
688 return; // Don't create zero length way segments.
689
690 // find out the distance, in metres, between the base point and the mouse cursor
691 LatLon mouseLatLon = Main.proj.eastNorth2latlon(currentMouseEastNorth);
692 distance = currentBaseNode.coor.greatCircleDistance(mouseLatLon);
693 double hdg = Math.toDegrees(currentBaseNode.coor.heading(mouseLatLon));
694 if (previousNode != null) {
695 angle = hdg - Math.toDegrees(previousNode.coor.heading(currentBaseNode.coor));
696 if (angle < 0) angle += 360;
697 }
698 Main.map.statusLine.setAngle(angle);
699 Main.map.statusLine.setHeading(hdg);
700 Main.map.statusLine.setDist(distance);
701 // Now done in redrawIfRequired()
702 //updateStatusLine();
703 }
704
705 /**
706 * Repaint on mouse exit so that the helper line goes away.
707 */
708 @Override public void mouseExited(MouseEvent e) {
709 if(!Main.map.mapView.isDrawableLayer())
710 return;
711 mousePos = e.getPoint();
712 Main.map.mapView.repaint();
713 }
714
715 /**
716 * @return If the node is the end of exactly one way, return this.
717 * <code>null</code> otherwise.
718 */
719 public static Way getWayForNode(Node n) {
720 Way way = null;
721 for (Way w : Main.ds.ways) {
722 if (w.deleted || w.incomplete || w.nodes.size() < 1) continue;
723 Node firstNode = w.nodes.get(0);
724 Node lastNode = w.nodes.get(w.nodes.size() - 1);
725 if ((firstNode == n || lastNode == n) && (firstNode != lastNode)) {
726 if (way != null)
727 return null;
728 way = w;
729 }
730 }
731 return way;
732 }
733
734 private static void pruneSuccsAndReverse(List<Integer> is) {
735 //if (is.size() < 2) return;
736
737 HashSet<Integer> is2 = new HashSet<Integer>();
738 for (int i : is) {
739 if (!is2.contains(i - 1) && !is2.contains(i + 1)) {
740 is2.add(i);
741 }
742 }
743 is.clear();
744 is.addAll(is2);
745 Collections.sort(is);
746 Collections.reverse(is);
747 }
748
749 /**
750 * Adjusts the position of a node to lie on a segment (or a segment
751 * intersection).
752 *
753 * If one or more than two segments are passed, the node is adjusted
754 * to lie on the first segment that is passed.
755 *
756 * If two segments are passed, the node is adjusted to be at their
757 * intersection.
758 *
759 * No action is taken if no segments are passed.
760 *
761 * @param segs the segments to use as a reference when adjusting
762 * @param n the node to adjust
763 */
764 private static void adjustNode(Collection<Pair<Node,Node>> segs, Node n) {
765
766 switch (segs.size()) {
767 case 0:
768 return;
769 case 2:
770 // This computes the intersection between
771 // the two segments and adjusts the node position.
772 Iterator<Pair<Node,Node>> i = segs.iterator();
773 Pair<Node,Node> seg = i.next();
774 EastNorth A = seg.a.eastNorth;
775 EastNorth B = seg.b.eastNorth;
776 seg = i.next();
777 EastNorth C = seg.a.eastNorth;
778 EastNorth D = seg.b.eastNorth;
779
780 double u=det(B.east() - A.east(), B.north() - A.north(), C.east() - D.east(), C.north() - D.north());
781
782 // Check for parallel segments and do nothing if they are
783 // In practice this will probably only happen when a way has been duplicated
784
785 if (u == 0) return;
786
787 // q is a number between 0 and 1
788 // It is the point in the segment where the intersection occurs
789 // if the segment is scaled to lenght 1
790
791 double q = det(B.north() - C.north(), B.east() - C.east(), D.north() - C.north(), D.east() - C.east()) / u;
792 EastNorth intersection = new EastNorth(
793 B.east() + q * (A.east() - B.east()),
794 B.north() + q * (A.north() - B.north()));
795
796 int snapToIntersectionThreshold
797 = Main.pref.getInteger("edit.snap-intersection-threshold",10);
798
799 // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise
800 // fall through to default action.
801 // (for semi-parallel lines, intersection might be miles away!)
802 if (Main.map.mapView.getPoint(n.eastNorth).distance(Main.map.mapView.getPoint(intersection)) < snapToIntersectionThreshold) {
803 n.setEastNorth(intersection);
804 return;
805 }
806
807 default:
808 EastNorth P = n.eastNorth;
809 seg = segs.iterator().next();
810 A = seg.a.eastNorth;
811 B = seg.b.eastNorth;
812 double a = P.distanceSq(B);
813 double b = P.distanceSq(A);
814 double c = A.distanceSq(B);
815 q = (a - b + c) / (2*c);
816 n.setEastNorth(B.east() + q * (A.east() - B.east()), B.north() + q * (A.north() - B.north()));
817 }
818 }
819
820 // helper for adjustNode
821 static double det(double a, double b, double c, double d) {
822 return a * d - b * c;
823 }
824
825 public void paint(Graphics g, MapView mv) {
826 if (!drawHelperLine || wayIsFinished || shift) return;
827
828 // sanity checks
829 if (Main.map.mapView == null) return;
830 if (mousePos == null) return;
831
832 // don't draw line if we don't know where from or where to
833 if (currentBaseNode == null || currentMouseEastNorth == null) return;
834
835 // don't draw line if mouse is outside window
836 if (!Main.map.mapView.getBounds().contains(mousePos)) return;
837
838 Graphics2D g2 = (Graphics2D) g;
839 g2.setColor(selectedColor);
840 g2.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
841 GeneralPath b = new GeneralPath();
842 Point p1=mv.getPoint(currentBaseNode.eastNorth);
843 Point p2=mv.getPoint(currentMouseEastNorth);
844
845 double t = Math.atan2(p2.y-p1.y, p2.x-p1.x) + Math.PI;
846
847 b.moveTo(p1.x,p1.y); b.lineTo(p2.x, p2.y);
848
849 // if alt key is held ("start new way"), draw a little perpendicular line
850 if (alt) {
851 b.moveTo((int)(p1.x + 8*Math.cos(t+PHI)), (int)(p1.y + 8*Math.sin(t+PHI)));
852 b.lineTo((int)(p1.x + 8*Math.cos(t-PHI)), (int)(p1.y + 8*Math.sin(t-PHI)));
853 }
854
855 g2.draw(b);
856 g2.setStroke(new BasicStroke(1));
857 }
858
859 @Override public String getModeHelpText() {
860 String rv = "";
861 /*
862 * No modifiers: all (Connect, Node Re-Use, Auto-Weld)
863 * CTRL: disables node re-use, auto-weld
864 * Shift: do not make connection
865 * ALT: make connection but start new way in doing so
866 */
867
868 /*
869 * Status line text generation is split into two parts to keep it maintainable.
870 * First part looks at what will happen to the new node inserted on click and
871 * the second part will look if a connection is made or not.
872 *
873 * Note that this help text is not absolutely accurate as it doesn't catch any special
874 * cases (e.g. when preventing <---> ways). The only special that it catches is when
875 * a way is about to be finished.
876 *
877 * First check what happens to the new node.
878 */
879
880 // oldHighlights stores the current highlights. If this
881 // list is empty we can assume that we won't do any joins
882 if (ctrl || oldHighlights.isEmpty()) {
883 rv = tr("Create new node.");
884 } else {
885 // oldHighlights may store a node or way, check if it's a node
886 OsmPrimitive x = oldHighlights.iterator().next();
887 if (x instanceof Node)
888 rv = tr("Select node under cursor.");
889 else
890 rv = trn("Insert new node into way.", "Insert new node into {0} ways.",
891 oldHighlights.size(), oldHighlights.size());
892 }
893
894 /*
895 * Check whether a connection will be made
896 */
897 if (currentBaseNode != null && !wayIsFinished) {
898 if (alt)
899 rv += " " + tr("Start new way from last node.");
900 else
901 rv += " " + tr("Continue way from last node.");
902 }
903
904 Node n = mouseOnExistingNode;
905 /*
906 * Handle special case: Highlighted node == selected node => finish drawing
907 */
908 if (n != null && Main.ds.getSelectedNodes().contains(n)) {
909 if (wayIsFinished)
910 rv = tr("Select node under cursor.");
911 else
912 rv = tr("Finish drawing.");
913 }
914
915 /*
916 * Handle special case: Self-Overlapping or closing way
917 */
918 if (Main.ds.getSelectedWays().size() > 0 && !wayIsFinished && !alt) {
919 Way w = (Way) Main.ds.getSelectedWays().iterator().next();
920 for (Node m : w.nodes) {
921 if (m.equals(mouseOnExistingNode) || mouseOnExistingWays.contains(w)) {
922 rv += " " + tr("Finish drawing.");
923 break;
924 }
925 }
926 }
927
928 return rv;
929 }
930
931 @Override public boolean layerIsSupported(Layer l) {
932 return l instanceof OsmDataLayer;
933 }
934}
Note: See TracBrowser for help on using the repository browser.