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

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

applied #3676 - patch by Dave Hansen - cleanup selection handling interface

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