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

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

Fix some of "Keystroke %s is already assigned to %s, will be overridden by %s" warnings

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