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

Last change on this file since 2407 was 2407, checked in by jttt, 14 years ago

Added support for referrers

  • 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.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;
33import java.util.logging.Logger;
34
35import javax.swing.JComponent;
36import javax.swing.JOptionPane;
37
38import org.openstreetmap.josm.Main;
39import org.openstreetmap.josm.command.AddCommand;
40import org.openstreetmap.josm.command.ChangeCommand;
41import org.openstreetmap.josm.command.Command;
42import org.openstreetmap.josm.command.SequenceCommand;
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 {
467 if(isSelfContainedWay(selectedWay, n0, n))
468 return;
469
470 // User clicked last node again, finish way
471 if(n0 == n) {
472 finishDrawing();
473 return;
474 }
475
476 // Ok we know now that we'll insert a line segment, but will it connect to an
477 // existing way or make a new way of its own? The "alt" modifier means that the
478 // user wants a new way.
479 Way way = alt ? null : (selectedWay != null) ? selectedWay : getWayForNode(n0);
480 Way wayToSelect;
481
482 // Don't allow creation of self-overlapping ways
483 if(way != null) {
484 int nodeCount=0;
485 for (Node p : way.getNodes())
486 if(p.equals(n0)) {
487 nodeCount++;
488 }
489 if(nodeCount > 1) {
490 way = null;
491 }
492 }
493
494 if (way == null) {
495 way = new Way();
496 way.addNode(n0);
497 cmds.add(new AddCommand(way));
498 wayToSelect = way;
499 } else {
500 int i;
501 if ((i = replacedWays.indexOf(way)) != -1) {
502 way = reuseWays.get(i);
503 wayToSelect = way;
504 } else {
505 wayToSelect = way;
506 Way wnew = new Way(way);
507 cmds.add(new ChangeCommand(way, wnew));
508 way = wnew;
509 }
510 }
511
512 // Connected to a node that's already in the way
513 if(way.containsNode(n)) {
514 wayIsFinished = true;
515 selection.clear();
516 }
517
518 // Add new node to way
519 if (way.getNode(way.getNodesCount() - 1) == n0) {
520 way.addNode(n);
521 } else {
522 way.addNode(0, n);
523 }
524
525 extendedWay = true;
526 newSelection.clear();
527 newSelection.add(wayToSelect);
528 }
529 }
530
531 String title;
532 if (!extendedWay) {
533 if (!newNode)
534 return; // We didn't do anything.
535 else if (reuseWays.isEmpty()) {
536 title = tr("Add node");
537 } else {
538 title = tr("Add node into way");
539 for (Way w : reuseWays) {
540 newSelection.remove(w);
541 }
542 }
543
544 newSelection.add(n);
545 } else if (!newNode) {
546 title = tr("Connect existing way to node");
547 } else if (reuseWays.isEmpty()) {
548 title = tr("Add a new node to an existing way");
549 } else {
550 title = tr("Add node into way and connect");
551 }
552
553 Command c = new SequenceCommand(title, cmds);
554
555 Main.main.undoRedo.add(c);
556 if(!wayIsFinished) {
557 lastUsedNode = n;
558 }
559
560 getCurrentDataSet().setSelected(newSelection);
561
562 computeHelperLine();
563 removeHighlighting();
564 redrawIfRequired();
565 }
566
567 /**
568 * Prevent creation of ways that look like this: <---->
569 * This happens if users want to draw a no-exit-sideway from the main way like this:
570 * ^
571 * |<---->
572 * |
573 * The solution isn't ideal because the main way will end in the side way, which is bad for
574 * navigation software ("drive straight on") but at least easier to fix. Maybe users will fix
575 * it on their own, too. At least it's better than producing an error.
576 *
577 * @param Way the way to check
578 * @param Node the current node (i.e. the one the connection will be made from)
579 * @param Node the target node (i.e. the one the connection will be made to)
580 * @return Boolean True if this would create a selfcontaining way, false otherwise.
581 */
582 private boolean isSelfContainedWay(Way selectedWay, Node currentNode, Node targetNode) {
583 if(selectedWay != null) {
584 int posn0 = selectedWay.getNodes().indexOf(currentNode);
585 if( posn0 != -1 && // n0 is part of way
586 (posn0 >= 1 && targetNode.equals(selectedWay.getNode(posn0-1))) || // previous node
587 (posn0 < selectedWay.getNodesCount()-1) && targetNode.equals(selectedWay.getNode(posn0+1))) { // next node
588 getCurrentDataSet().setSelected(targetNode);
589 lastUsedNode = targetNode;
590 return true;
591 }
592 }
593
594 return false;
595 }
596
597 /**
598 * Finds a node to continue drawing from. Decision is based upon given node and way.
599 * @param selectedNode Currently selected node, may be null
600 * @param selectedWay Currently selected way, may be null
601 * @return Node if a suitable node is found, null otherwise
602 */
603 private Node findNodeToContinueFrom(Node selectedNode, Way selectedWay) {
604 // No nodes or ways have been selected, this occurs when a relation
605 // has been selected or the selection is empty
606 if(selectedNode == null && selectedWay == null)
607 return null;
608
609 if (selectedNode == null) {
610 if (selectedWay.isFirstLastNode(lastUsedNode))
611 return lastUsedNode;
612
613 // We have a way selected, but no suitable node to continue from. Start anew.
614 return null;
615 }
616
617 if (selectedWay == null)
618 return selectedNode;
619
620 if (selectedWay.isFirstLastNode(selectedNode))
621 return selectedNode;
622
623 // We have a way and node selected, but it's not at the start/end of the way. Start anew.
624 return null;
625 }
626
627 @Override public void mouseMoved(MouseEvent e) {
628 if(!Main.map.mapView.isActiveLayerDrawable())
629 return;
630
631 // we copy ctrl/alt/shift from the event just in case our global
632 // AWTEvent didn't make it through the security manager. Unclear
633 // if that can ever happen but better be safe.
634 updateKeyModifiers(e);
635 mousePos = e.getPoint();
636
637 computeHelperLine();
638 addHighlighting();
639 redrawIfRequired();
640 }
641
642 private void updateKeyModifiers(InputEvent e) {
643 ctrl = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0;
644 alt = (e.getModifiers() & (ActionEvent.ALT_MASK|InputEvent.ALT_GRAPH_MASK)) != 0;
645 shift = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
646 }
647
648 private void updateKeyModifiers(MouseEvent e) {
649 ctrl = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0;
650 alt = (e.getModifiers() & (ActionEvent.ALT_MASK|InputEvent.ALT_GRAPH_MASK)) != 0;
651 shift = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
652 }
653
654 /**
655 * This method prepares data required for painting the "helper line" from
656 * the last used position to the mouse cursor. It duplicates some code from
657 * mouseClicked() (FIXME).
658 */
659 private void computeHelperLine() {
660 MapView mv = Main.map.mapView;
661 if (mousePos == null) {
662 // Don't draw the line.
663 currentMouseEastNorth = null;
664 currentBaseNode = null;
665 return;
666 }
667
668 double distance = -1;
669 double angle = -1;
670
671 Collection<OsmPrimitive> selection = getCurrentDataSet().getSelected();
672
673 Node selectedNode = null;
674 Way selectedWay = null;
675 Node currentMouseNode = null;
676 mouseOnExistingNode = null;
677 mouseOnExistingWays = new HashSet<Way>();
678
679 Main.map.statusLine.setAngle(-1);
680 Main.map.statusLine.setHeading(-1);
681 Main.map.statusLine.setDist(-1);
682
683 if (!ctrl && mousePos != null) {
684 currentMouseNode = mv.getNearestNode(mousePos);
685 }
686
687 // We need this for highlighting and we'll only do so if we actually want to re-use
688 // *and* there is no node nearby (because nodes beat ways when re-using)
689 if(!ctrl && currentMouseNode == null) {
690 List<WaySegment> wss = mv.getNearestWaySegments(mousePos);
691 for(WaySegment ws : wss) {
692 mouseOnExistingWays.add(ws.way);
693 }
694 }
695
696 if (currentMouseNode != null) {
697 // user clicked on node
698 if (selection.isEmpty()) return;
699 currentMouseEastNorth = currentMouseNode.getEastNorth();
700 mouseOnExistingNode = currentMouseNode;
701 } else {
702 // no node found in clicked area
703 currentMouseEastNorth = mv.getEastNorth(mousePos.x, mousePos.y);
704 }
705
706 for (OsmPrimitive p : selection) {
707 if (p instanceof Node) {
708 if (selectedNode != null) return;
709 selectedNode = (Node) p;
710 } else if (p instanceof Way) {
711 if (selectedWay != null) return;
712 selectedWay = (Way) p;
713 }
714 }
715
716 // the node from which we make a connection
717 currentBaseNode = null;
718 Node previousNode = null;
719
720 if (selectedNode == null) {
721 if (selectedWay == null)
722 return;
723 if (selectedWay.isFirstLastNode(lastUsedNode)) {
724 currentBaseNode = lastUsedNode;
725 if (lastUsedNode == selectedWay.getNode(selectedWay.getNodesCount()-1) && selectedWay.getNodesCount() > 1) {
726 previousNode = selectedWay.getNode(selectedWay.getNodesCount()-2);
727 }
728 }
729 } else if (selectedWay == null) {
730 currentBaseNode = selectedNode;
731 } else {
732 if (selectedNode == selectedWay.getNode(0) || selectedNode == selectedWay.getNode(selectedWay.getNodesCount()-1)) {
733 currentBaseNode = selectedNode;
734 }
735 }
736
737 if (currentBaseNode == null || currentBaseNode == currentMouseNode)
738 return; // Don't create zero length way segments.
739
740 // find out the distance, in metres, between the base point and the mouse cursor
741 LatLon mouseLatLon = mv.getProjection().eastNorth2latlon(currentMouseEastNorth);
742 distance = currentBaseNode.getCoor().greatCircleDistance(mouseLatLon);
743
744 double hdg = Math.toDegrees(currentBaseNode.getEastNorth()
745 .heading(currentMouseEastNorth));
746 if (previousNode != null) {
747 angle = hdg - Math.toDegrees(previousNode.getEastNorth()
748 .heading(currentBaseNode.getEastNorth()));
749 angle += angle < 0 ? 360 : 0;
750 }
751
752 Main.map.statusLine.setAngle(angle);
753 Main.map.statusLine.setHeading(hdg);
754 Main.map.statusLine.setDist(distance);
755 // Now done in redrawIfRequired()
756 //updateStatusLine();
757 }
758
759 /**
760 * Repaint on mouse exit so that the helper line goes away.
761 */
762 @Override public void mouseExited(MouseEvent e) {
763 if(!Main.map.mapView.isActiveLayerDrawable())
764 return;
765 mousePos = e.getPoint();
766 Main.map.mapView.repaint();
767 }
768
769 /**
770 * @return If the node is the end of exactly one way, return this.
771 * <code>null</code> otherwise.
772 */
773 public Way getWayForNode(Node n) {
774 Way way = null;
775 for (Way w : getCurrentDataSet().getWays()) {
776 if (!w.isUsable() || w.getNodesCount() < 1) {
777 continue;
778 }
779 Node firstNode = w.getNode(0);
780 Node lastNode = w.getNode(w.getNodesCount() - 1);
781 if ((firstNode == n || lastNode == n) && (firstNode != lastNode)) {
782 if (way != null)
783 return null;
784 way = w;
785 }
786 }
787 return way;
788 }
789
790 private static void pruneSuccsAndReverse(List<Integer> is) {
791 //if (is.size() < 2) return;
792
793 HashSet<Integer> is2 = new HashSet<Integer>();
794 for (int i : is) {
795 if (!is2.contains(i - 1) && !is2.contains(i + 1)) {
796 is2.add(i);
797 }
798 }
799 is.clear();
800 is.addAll(is2);
801 Collections.sort(is);
802 Collections.reverse(is);
803 }
804
805 /**
806 * Adjusts the position of a node to lie on a segment (or a segment
807 * intersection).
808 *
809 * If one or more than two segments are passed, the node is adjusted
810 * to lie on the first segment that is passed.
811 *
812 * If two segments are passed, the node is adjusted to be at their
813 * intersection.
814 *
815 * No action is taken if no segments are passed.
816 *
817 * @param segs the segments to use as a reference when adjusting
818 * @param n the node to adjust
819 */
820 private static void adjustNode(Collection<Pair<Node,Node>> segs, Node n) {
821
822 switch (segs.size()) {
823 case 0:
824 return;
825 case 2:
826 // This computes the intersection between
827 // the two segments and adjusts the node position.
828 Iterator<Pair<Node,Node>> i = segs.iterator();
829 Pair<Node,Node> seg = i.next();
830 EastNorth A = seg.a.getEastNorth();
831 EastNorth B = seg.b.getEastNorth();
832 seg = i.next();
833 EastNorth C = seg.a.getEastNorth();
834 EastNorth D = seg.b.getEastNorth();
835
836 double u=det(B.east() - A.east(), B.north() - A.north(), C.east() - D.east(), C.north() - D.north());
837
838 // Check for parallel segments and do nothing if they are
839 // In practice this will probably only happen when a way has been duplicated
840
841 if (u == 0) return;
842
843 // q is a number between 0 and 1
844 // It is the point in the segment where the intersection occurs
845 // if the segment is scaled to lenght 1
846
847 double q = det(B.north() - C.north(), B.east() - C.east(), D.north() - C.north(), D.east() - C.east()) / u;
848 EastNorth intersection = new EastNorth(
849 B.east() + q * (A.east() - B.east()),
850 B.north() + q * (A.north() - B.north()));
851
852 int snapToIntersectionThreshold
853 = Main.pref.getInteger("edit.snap-intersection-threshold",10);
854
855 // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise
856 // fall through to default action.
857 // (for semi-parallel lines, intersection might be miles away!)
858 if (Main.map.mapView.getPoint(n).distance(Main.map.mapView.getPoint(intersection)) < snapToIntersectionThreshold) {
859 n.setEastNorth(intersection);
860 return;
861 }
862
863 default:
864 EastNorth P = n.getEastNorth();
865 seg = segs.iterator().next();
866 A = seg.a.getEastNorth();
867 B = seg.b.getEastNorth();
868 double a = P.distanceSq(B);
869 double b = P.distanceSq(A);
870 double c = A.distanceSq(B);
871 q = (a - b + c) / (2*c);
872 n.setEastNorth(new EastNorth(B.east() + q * (A.east() - B.east()), B.north() + q * (A.north() - B.north())));
873 }
874 }
875
876 // helper for adjustNode
877 static double det(double a, double b, double c, double d) {
878 return a * d - b * c;
879 }
880
881 public void paint(Graphics g, MapView mv) {
882 if (!drawHelperLine || wayIsFinished || shift) return;
883
884 // sanity checks
885 if (Main.map.mapView == null) return;
886 if (mousePos == null) return;
887
888 // don't draw line if we don't know where from or where to
889 if (currentBaseNode == null || currentMouseEastNorth == null) return;
890
891 // don't draw line if mouse is outside window
892 if (!Main.map.mapView.getBounds().contains(mousePos)) return;
893
894 Graphics2D g2 = (Graphics2D) g;
895 g2.setColor(selectedColor);
896 g2.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
897 GeneralPath b = new GeneralPath();
898 Point p1=mv.getPoint(currentBaseNode);
899 Point p2=mv.getPoint(currentMouseEastNorth);
900
901 double t = Math.atan2(p2.y-p1.y, p2.x-p1.x) + Math.PI;
902
903 b.moveTo(p1.x,p1.y); b.lineTo(p2.x, p2.y);
904
905 // if alt key is held ("start new way"), draw a little perpendicular line
906 if (alt) {
907 b.moveTo((int)(p1.x + 8*Math.cos(t+PHI)), (int)(p1.y + 8*Math.sin(t+PHI)));
908 b.lineTo((int)(p1.x + 8*Math.cos(t-PHI)), (int)(p1.y + 8*Math.sin(t-PHI)));
909 }
910
911 g2.draw(b);
912 g2.setStroke(new BasicStroke(1));
913 }
914
915 @Override public String getModeHelpText() {
916 String rv = "";
917 /*
918 * No modifiers: all (Connect, Node Re-Use, Auto-Weld)
919 * CTRL: disables node re-use, auto-weld
920 * Shift: do not make connection
921 * ALT: make connection but start new way in doing so
922 */
923
924 /*
925 * Status line text generation is split into two parts to keep it maintainable.
926 * First part looks at what will happen to the new node inserted on click and
927 * the second part will look if a connection is made or not.
928 *
929 * Note that this help text is not absolutely accurate as it doesn't catch any special
930 * cases (e.g. when preventing <---> ways). The only special that it catches is when
931 * a way is about to be finished.
932 *
933 * First check what happens to the new node.
934 */
935
936 // oldHighlights stores the current highlights. If this
937 // list is empty we can assume that we won't do any joins
938 if (ctrl || oldHighlights.isEmpty()) {
939 rv = tr("Create new node.");
940 } else {
941 // oldHighlights may store a node or way, check if it's a node
942 OsmPrimitive x = oldHighlights.iterator().next();
943 if (x instanceof Node) {
944 rv = tr("Select node under cursor.");
945 } else {
946 rv = trn("Insert new node into way.", "Insert new node into {0} ways.",
947 oldHighlights.size(), oldHighlights.size());
948 }
949 }
950
951 /*
952 * Check whether a connection will be made
953 */
954 if (currentBaseNode != null && !wayIsFinished) {
955 if (alt) {
956 rv += " " + tr("Start new way from last node.");
957 } else {
958 rv += " " + tr("Continue way from last node.");
959 }
960 }
961
962 Node n = mouseOnExistingNode;
963 /*
964 * Handle special case: Highlighted node == selected node => finish drawing
965 */
966 if (n != null && getCurrentDataSet() != null && getCurrentDataSet().getSelectedNodes().contains(n)) {
967 if (wayIsFinished) {
968 rv = tr("Select node under cursor.");
969 } else {
970 rv = tr("Finish drawing.");
971 }
972 }
973
974 /*
975 * Handle special case: Self-Overlapping or closing way
976 */
977 if (getCurrentDataSet() != null && getCurrentDataSet().getSelectedWays().size() > 0 && !wayIsFinished && !alt) {
978 Way w = (Way) getCurrentDataSet().getSelectedWays().iterator().next();
979 for (Node m : w.getNodes()) {
980 if (m.equals(mouseOnExistingNode) || mouseOnExistingWays.contains(w)) {
981 rv += " " + tr("Finish drawing.");
982 break;
983 }
984 }
985 }
986 return rv;
987 }
988
989 @Override public boolean layerIsSupported(Layer l) {
990 return l instanceof OsmDataLayer;
991 }
992
993 @Override
994 protected void updateEnabledState() {
995 setEnabled(getEditLayer() != null);
996 }
997}
Note: See TracBrowser for help on using the repository browser.