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

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

removed dependencies to Main.ds, removed Main.ds
removed AddVisitor, NameVisitor, DeleteVisitor - unnecessary double dispatching for these simple cases

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