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

Last change on this file since 1912 was 1912, checked in by Gubaer, 15 years ago

Updated w.getNodes().contains(..) to w.containsNode(...)

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