001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions.mapmode;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.marktr;
006import static org.openstreetmap.josm.tools.I18n.tr;
007import static org.openstreetmap.josm.tools.I18n.trn;
008
009import java.awt.BasicStroke;
010import java.awt.Color;
011import java.awt.Cursor;
012import java.awt.Graphics2D;
013import java.awt.Point;
014import java.awt.Stroke;
015import java.awt.event.ActionEvent;
016import java.awt.event.KeyEvent;
017import java.awt.event.MouseEvent;
018import java.awt.event.MouseListener;
019import java.awt.geom.GeneralPath;
020import java.util.ArrayList;
021import java.util.Arrays;
022import java.util.Collection;
023import java.util.Collections;
024import java.util.HashMap;
025import java.util.HashSet;
026import java.util.Iterator;
027import java.util.LinkedList;
028import java.util.List;
029import java.util.Map;
030import java.util.Set;
031
032import javax.swing.AbstractAction;
033import javax.swing.JCheckBoxMenuItem;
034import javax.swing.JMenuItem;
035import javax.swing.JOptionPane;
036import javax.swing.JPopupMenu;
037
038import org.openstreetmap.josm.Main;
039import org.openstreetmap.josm.actions.JosmAction;
040import org.openstreetmap.josm.command.AddCommand;
041import org.openstreetmap.josm.command.ChangeCommand;
042import org.openstreetmap.josm.command.Command;
043import org.openstreetmap.josm.command.SequenceCommand;
044import org.openstreetmap.josm.data.Bounds;
045import org.openstreetmap.josm.data.SelectionChangedListener;
046import org.openstreetmap.josm.data.coor.EastNorth;
047import org.openstreetmap.josm.data.coor.LatLon;
048import org.openstreetmap.josm.data.osm.DataSet;
049import org.openstreetmap.josm.data.osm.Node;
050import org.openstreetmap.josm.data.osm.OsmPrimitive;
051import org.openstreetmap.josm.data.osm.Way;
052import org.openstreetmap.josm.data.osm.WaySegment;
053import org.openstreetmap.josm.data.osm.visitor.paint.PaintColors;
054import org.openstreetmap.josm.gui.MainMenu;
055import org.openstreetmap.josm.gui.MapFrame;
056import org.openstreetmap.josm.gui.MapView;
057import org.openstreetmap.josm.gui.NavigatableComponent;
058import org.openstreetmap.josm.gui.layer.Layer;
059import org.openstreetmap.josm.gui.layer.MapViewPaintable;
060import org.openstreetmap.josm.gui.layer.OsmDataLayer;
061import org.openstreetmap.josm.gui.util.GuiHelper;
062import org.openstreetmap.josm.gui.util.KeyPressReleaseListener;
063import org.openstreetmap.josm.gui.util.ModifierListener;
064import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
065import org.openstreetmap.josm.tools.Geometry;
066import org.openstreetmap.josm.tools.ImageProvider;
067import org.openstreetmap.josm.tools.Pair;
068import org.openstreetmap.josm.tools.Shortcut;
069import org.openstreetmap.josm.tools.Utils;
070
071/**
072 * Mapmode to add nodes, create and extend ways.
073 */
074public class DrawAction extends MapMode implements MapViewPaintable, SelectionChangedListener, KeyPressReleaseListener, ModifierListener {
075
076    private static final Color ORANGE_TRANSPARENT = new Color(Color.ORANGE.getRed(), Color.ORANGE.getGreen(), Color.ORANGE.getBlue(), 128);
077    private static final double PHI = Math.toRadians(90);
078
079    private final Cursor cursorJoinNode;
080    private final Cursor cursorJoinWay;
081
082    private transient Node lastUsedNode;
083    private double toleranceMultiplier;
084
085    private transient Node mouseOnExistingNode;
086    private transient Set<Way> mouseOnExistingWays = new HashSet<>();
087    // old highlights store which primitives are currently highlighted. This
088    // is true, even if target highlighting is disabled since the status bar
089    // derives its information from this list as well.
090    private transient Set<OsmPrimitive> oldHighlights = new HashSet<>();
091    // new highlights contains a list of primitives that should be highlighted
092    // but haven’t been so far. The idea is to compare old and new and only
093    // repaint if there are changes.
094    private transient Set<OsmPrimitive> newHighlights = new HashSet<>();
095    private boolean drawHelperLine;
096    private boolean wayIsFinished;
097    private boolean drawTargetHighlight;
098    private Point mousePos;
099    private Point oldMousePos;
100    private Color rubberLineColor;
101
102    private transient Node currentBaseNode;
103    private transient Node previousNode;
104    private EastNorth currentMouseEastNorth;
105
106    private final transient SnapHelper snapHelper = new SnapHelper();
107
108    private final transient Shortcut backspaceShortcut;
109    private final BackSpaceAction backspaceAction;
110    private final transient Shortcut snappingShortcut;
111    private boolean ignoreNextKeyRelease;
112
113    private final SnapChangeAction snapChangeAction;
114    private final JCheckBoxMenuItem snapCheckboxMenuItem;
115    private boolean useRepeatedShortcut;
116    private transient Stroke rubberLineStroke;
117    private static final BasicStroke BASIC_STROKE = new BasicStroke(1);
118
119    private static int snapToIntersectionThreshold;
120
121    /**
122     * Constructs a new {@code DrawAction}.
123     * @param mapFrame Map frame
124     */
125    public DrawAction(MapFrame mapFrame) {
126        super(tr("Draw"), "node/autonode", tr("Draw nodes"),
127                Shortcut.registerShortcut("mapmode:draw", tr("Mode: {0}", tr("Draw")), KeyEvent.VK_A, Shortcut.DIRECT),
128                mapFrame, ImageProvider.getCursor("crosshair", null));
129
130        snappingShortcut = Shortcut.registerShortcut("mapmode:drawanglesnapping",
131                tr("Mode: Draw Angle snapping"), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE);
132        snapChangeAction = new SnapChangeAction();
133        snapCheckboxMenuItem = addMenuItem();
134        snapHelper.setMenuCheckBox(snapCheckboxMenuItem);
135        backspaceShortcut = Shortcut.registerShortcut("mapmode:backspace",
136                tr("Backspace in Add mode"), KeyEvent.VK_BACK_SPACE, Shortcut.DIRECT);
137        backspaceAction = new BackSpaceAction();
138        cursorJoinNode = ImageProvider.getCursor("crosshair", "joinnode");
139        cursorJoinWay = ImageProvider.getCursor("crosshair", "joinway");
140
141        readPreferences();
142        snapHelper.init();
143    }
144
145    private JCheckBoxMenuItem addMenuItem() {
146        int n = Main.main.menu.editMenu.getItemCount();
147        for (int i = n-1; i > 0; i--) {
148            JMenuItem item = Main.main.menu.editMenu.getItem(i);
149            if (item != null && item.getAction() != null && item.getAction() instanceof SnapChangeAction) {
150                Main.main.menu.editMenu.remove(i);
151            }
152        }
153        return MainMenu.addWithCheckbox(Main.main.menu.editMenu, snapChangeAction, MainMenu.WINDOW_MENU_GROUP.VOLATILE);
154    }
155
156    /**
157     * Checks if a map redraw is required and does so if needed. Also updates the status bar.
158     * @return true if a repaint is needed
159     */
160    private boolean redrawIfRequired() {
161        updateStatusLine();
162        // repaint required if the helper line is active.
163        boolean needsRepaint = drawHelperLine && !wayIsFinished;
164        if (drawTargetHighlight) {
165            // move newHighlights to oldHighlights; only update changed primitives
166            for (OsmPrimitive x : newHighlights) {
167                if (oldHighlights.contains(x)) {
168                    continue;
169                }
170                x.setHighlighted(true);
171                needsRepaint = true;
172            }
173            oldHighlights.removeAll(newHighlights);
174            for (OsmPrimitive x : oldHighlights) {
175                x.setHighlighted(false);
176                needsRepaint = true;
177            }
178        }
179        // required in order to print correct help text
180        oldHighlights = newHighlights;
181
182        if (!needsRepaint && !drawTargetHighlight)
183            return false;
184
185        // update selection to reflect which way being modified
186        DataSet currentDataSet = getCurrentDataSet();
187        if (getCurrentBaseNode() != null && currentDataSet != null && !currentDataSet.getSelected().isEmpty()) {
188            Way continueFrom = getWayForNode(getCurrentBaseNode());
189            if (alt && continueFrom != null && (!getCurrentBaseNode().isSelected() || continueFrom.isSelected())) {
190                addRemoveSelection(currentDataSet, getCurrentBaseNode(), continueFrom);
191                needsRepaint = true;
192            } else if (!alt && continueFrom != null && !continueFrom.isSelected()) {
193                currentDataSet.addSelected(continueFrom);
194                needsRepaint = true;
195            }
196        }
197
198        if (needsRepaint) {
199            Main.map.mapView.repaint();
200        }
201        return needsRepaint;
202    }
203
204    private static void addRemoveSelection(DataSet ds, OsmPrimitive toAdd, OsmPrimitive toRemove) {
205        ds.beginUpdate(); // to prevent the selection listener to screw around with the state
206        ds.addSelected(toAdd);
207        ds.clearSelection(toRemove);
208        ds.endUpdate();
209    }
210
211    @Override
212    public void enterMode() {
213        if (!isEnabled())
214            return;
215        super.enterMode();
216        readPreferences();
217
218        // determine if selection is suitable to continue drawing. If it
219        // isn't, set wayIsFinished to true to avoid superfluous repaints.
220        determineCurrentBaseNodeAndPreviousNode(getCurrentDataSet().getSelected());
221        wayIsFinished = getCurrentBaseNode() == null;
222
223        toleranceMultiplier = 0.01 * NavigatableComponent.PROP_SNAP_DISTANCE.get();
224
225        snapHelper.init();
226        snapCheckboxMenuItem.getAction().setEnabled(true);
227
228        Main.map.statusLine.getAnglePanel().addMouseListener(snapHelper.anglePopupListener);
229        Main.registerActionShortcut(backspaceAction, backspaceShortcut);
230
231        Main.map.mapView.addMouseListener(this);
232        Main.map.mapView.addMouseMotionListener(this);
233        Main.map.mapView.addTemporaryLayer(this);
234        DataSet.addSelectionListener(this);
235
236        Main.map.keyDetector.addKeyListener(this);
237        Main.map.keyDetector.addModifierListener(this);
238        ignoreNextKeyRelease = true;
239    }
240
241    private void readPreferences() {
242        rubberLineColor = Main.pref.getColor(marktr("helper line"), null);
243        if (rubberLineColor == null) rubberLineColor = PaintColors.SELECTED.get();
244
245        rubberLineStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.stroke.helper-line", "3"));
246        drawHelperLine = Main.pref.getBoolean("draw.helper-line", true);
247        drawTargetHighlight = Main.pref.getBoolean("draw.target-highlight", true);
248        snapToIntersectionThreshold = Main.pref.getInteger("edit.snap-intersection-threshold", 10);
249    }
250
251    @Override
252    public void exitMode() {
253        super.exitMode();
254        Main.map.mapView.removeMouseListener(this);
255        Main.map.mapView.removeMouseMotionListener(this);
256        Main.map.mapView.removeTemporaryLayer(this);
257        DataSet.removeSelectionListener(this);
258        Main.unregisterActionShortcut(backspaceAction, backspaceShortcut);
259        snapHelper.unsetFixedMode();
260        snapCheckboxMenuItem.getAction().setEnabled(false);
261
262        Main.map.statusLine.getAnglePanel().removeMouseListener(snapHelper.anglePopupListener);
263        Main.map.statusLine.activateAnglePanel(false);
264
265        removeHighlighting();
266        Main.map.keyDetector.removeKeyListener(this);
267        Main.map.keyDetector.removeModifierListener(this);
268
269        // when exiting we let everybody know about the currently selected
270        // primitives
271        //
272        DataSet ds = getCurrentDataSet();
273        if (ds != null) {
274            ds.fireSelectionChanged();
275        }
276    }
277
278    /**
279     * redraw to (possibly) get rid of helper line if selection changes.
280     */
281    @Override
282    public void modifiersChanged(int modifiers) {
283        if (!Main.isDisplayingMapView() || !Main.map.mapView.isActiveLayerDrawable())
284            return;
285        updateKeyModifiers(modifiers);
286        computeHelperLine();
287        addHighlighting();
288    }
289
290    @Override
291    public void doKeyPressed(KeyEvent e) {
292        if (!snappingShortcut.isEvent(e) && !(useRepeatedShortcut && getShortcut().isEvent(e)))
293            return;
294        snapHelper.setFixedMode();
295        computeHelperLine();
296        redrawIfRequired();
297    }
298
299    @Override
300    public void doKeyReleased(KeyEvent e) {
301        if (!snappingShortcut.isEvent(e) && !(useRepeatedShortcut && getShortcut().isEvent(e)))
302            return;
303        if (ignoreNextKeyRelease) {
304            ignoreNextKeyRelease = false;
305            return;
306        }
307        snapHelper.unFixOrTurnOff();
308        computeHelperLine();
309        redrawIfRequired();
310    }
311
312    /**
313     * redraw to (possibly) get rid of helper line if selection changes.
314     */
315    @Override
316    public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
317        if (!Main.map.mapView.isActiveLayerDrawable())
318            return;
319        computeHelperLine();
320        addHighlighting();
321    }
322
323    private void tryAgain(MouseEvent e) {
324        getCurrentDataSet().setSelected();
325        mouseReleased(e);
326    }
327
328    /**
329     * This function should be called when the user wishes to finish his current draw action.
330     * If Potlatch Style is enabled, it will switch to select tool, otherwise simply disable
331     * the helper line until the user chooses to draw something else.
332     */
333    private void finishDrawing() {
334        // let everybody else know about the current selection
335        //
336        Main.main.getCurrentDataSet().fireSelectionChanged();
337        lastUsedNode = null;
338        wayIsFinished = true;
339        Main.map.selectSelectTool(true);
340        snapHelper.noSnapNow();
341
342        // Redraw to remove the helper line stub
343        computeHelperLine();
344        removeHighlighting();
345    }
346
347    private Point rightClickPressPos;
348
349    @Override
350    public void mousePressed(MouseEvent e) {
351        if (e.getButton() == MouseEvent.BUTTON3) {
352            rightClickPressPos = e.getPoint();
353        }
354    }
355
356    /**
357     * If user clicked with the left button, add a node at the current mouse
358     * position.
359     *
360     * If in nodeway mode, insert the node into the way.
361     */
362    @Override
363    public void mouseReleased(MouseEvent e) {
364        if (e.getButton() == MouseEvent.BUTTON3) {
365            Point curMousePos = e.getPoint();
366            if (curMousePos.equals(rightClickPressPos)) {
367                tryToSetBaseSegmentForAngleSnap();
368            }
369            return;
370        }
371        if (e.getButton() != MouseEvent.BUTTON1)
372            return;
373        if (!Main.map.mapView.isActiveLayerDrawable())
374            return;
375        // request focus in order to enable the expected keyboard shortcuts
376        //
377        Main.map.mapView.requestFocus();
378
379        if (e.getClickCount() > 1 && mousePos != null && mousePos.equals(oldMousePos)) {
380            // A double click equals "user clicked last node again, finish way"
381            // Change draw tool only if mouse position is nearly the same, as
382            // otherwise fast clicks will count as a double click
383            finishDrawing();
384            return;
385        }
386        oldMousePos = mousePos;
387
388        // we copy ctrl/alt/shift from the event just in case our global
389        // keyDetector didn't make it through the security manager. Unclear
390        // if that can ever happen but better be safe.
391        updateKeyModifiers(e);
392        mousePos = e.getPoint();
393
394        DataSet ds = getCurrentDataSet();
395        Collection<OsmPrimitive> selection = new ArrayList<>(ds.getSelected());
396        Collection<Command> cmds = new LinkedList<>();
397        Collection<OsmPrimitive> newSelection = new LinkedList<>(ds.getSelected());
398
399        List<Way> reuseWays = new ArrayList<>(),
400                replacedWays = new ArrayList<>();
401        boolean newNode = false;
402        Node n = null;
403
404        n = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
405        if (ctrl) {
406            Iterator<Way> it = getCurrentDataSet().getSelectedWays().iterator();
407            if (it.hasNext()) {
408                // ctrl-click on node of selected way = reuse node despite of ctrl
409                if (!it.next().containsNode(n)) n = null;
410            } else {
411                n = null; // ctrl-click + no selected way = new node
412            }
413        }
414
415        if (n != null && !snapHelper.isActive()) {
416            // user clicked on node
417            if (selection.isEmpty() || wayIsFinished) {
418                // select the clicked node and do nothing else
419                // (this is just a convenience option so that people don't
420                // have to switch modes)
421
422                getCurrentDataSet().setSelected(n);
423                // If we extend/continue an existing way, select it already now to make it obvious
424                Way continueFrom = getWayForNode(n);
425                if (continueFrom != null) {
426                    getCurrentDataSet().addSelected(continueFrom);
427                }
428
429                // The user explicitly selected a node, so let him continue drawing
430                wayIsFinished = false;
431                return;
432            }
433        } else {
434            EastNorth newEN;
435            if (n != null) {
436                EastNorth foundPoint = n.getEastNorth();
437                // project found node to snapping line
438                newEN = snapHelper.getSnapPoint(foundPoint);
439                // do not add new node if there is some node within snapping distance
440                double tolerance = Main.map.mapView.getDist100Pixel() * toleranceMultiplier;
441                if (foundPoint.distance(newEN) > tolerance) {
442                    n = new Node(newEN); // point != projected, so we create new node
443                    newNode = true;
444                }
445            } else { // n==null, no node found in clicked area
446                EastNorth mouseEN = Main.map.mapView.getEastNorth(e.getX(), e.getY());
447                newEN = snapHelper.isSnapOn() ? snapHelper.getSnapPoint(mouseEN) : mouseEN;
448                n = new Node(newEN); //create node at clicked point
449                newNode = true;
450            }
451            snapHelper.unsetFixedMode();
452        }
453
454        if (newNode) {
455            if (n.getCoor().isOutSideWorld()) {
456                JOptionPane.showMessageDialog(
457                        Main.parent,
458                        tr("Cannot add a node outside of the world."),
459                        tr("Warning"),
460                        JOptionPane.WARNING_MESSAGE
461                        );
462                return;
463            }
464            cmds.add(new AddCommand(n));
465
466            if (!ctrl) {
467                // Insert the node into all the nearby way segments
468                List<WaySegment> wss = Main.map.mapView.getNearestWaySegments(
469                        Main.map.mapView.getPoint(n), OsmPrimitive.isSelectablePredicate);
470                if (snapHelper.isActive()) {
471                    tryToMoveNodeOnIntersection(wss, n);
472                }
473                insertNodeIntoAllNearbySegments(wss, n, newSelection, cmds, replacedWays, reuseWays);
474            }
475        }
476        // now "n" is newly created or reused node that shoud be added to some way
477
478        // This part decides whether or not a "segment" (i.e. a connection) is made to an existing node.
479
480        // For a connection to be made, the user must either have a node selected (connection
481        // is made to that node), or he must have a way selected *and* one of the endpoints
482        // of that way must be the last used node (connection is made to last used node), or
483        // he must have a way and a node selected (connection is made to the selected node).
484
485        // If the above does not apply, the selection is cleared and a new try is started
486
487        boolean extendedWay = false;
488        boolean wayIsFinishedTemp = wayIsFinished;
489        wayIsFinished = false;
490
491        // don't draw lines if shift is held
492        if (!selection.isEmpty() && !shift) {
493            Node selectedNode = null;
494            Way selectedWay = null;
495
496            for (OsmPrimitive p : selection) {
497                if (p instanceof Node) {
498                    if (selectedNode != null) {
499                        // Too many nodes selected to do something useful
500                        tryAgain(e);
501                        return;
502                    }
503                    selectedNode = (Node) p;
504                } else if (p instanceof Way) {
505                    if (selectedWay != null) {
506                        // Too many ways selected to do something useful
507                        tryAgain(e);
508                        return;
509                    }
510                    selectedWay = (Way) p;
511                }
512            }
513
514            // the node from which we make a connection
515            Node n0 = findNodeToContinueFrom(selectedNode, selectedWay);
516            // We have a selection but it isn't suitable. Try again.
517            if (n0 == null) {
518                tryAgain(e);
519                return;
520            }
521            if (!wayIsFinishedTemp) {
522                if (isSelfContainedWay(selectedWay, n0, n))
523                    return;
524
525                // User clicked last node again, finish way
526                if (n0 == n) {
527                    finishDrawing();
528                    return;
529                }
530
531                // Ok we know now that we'll insert a line segment, but will it connect to an
532                // existing way or make a new way of its own? The "alt" modifier means that the
533                // user wants a new way.
534                Way way = alt ? null : (selectedWay != null) ? selectedWay : getWayForNode(n0);
535                Way wayToSelect;
536
537                // Don't allow creation of self-overlapping ways
538                if (way != null) {
539                    int nodeCount = 0;
540                    for (Node p : way.getNodes()) {
541                        if (p.equals(n0)) {
542                            nodeCount++;
543                        }
544                    }
545                    if (nodeCount > 1) {
546                        way = null;
547                    }
548                }
549
550                if (way == null) {
551                    way = new Way();
552                    way.addNode(n0);
553                    cmds.add(new AddCommand(way));
554                    wayToSelect = way;
555                } else {
556                    int i;
557                    if ((i = replacedWays.indexOf(way)) != -1) {
558                        way = reuseWays.get(i);
559                        wayToSelect = way;
560                    } else {
561                        wayToSelect = way;
562                        Way wnew = new Way(way);
563                        cmds.add(new ChangeCommand(way, wnew));
564                        way = wnew;
565                    }
566                }
567
568                // Connected to a node that's already in the way
569                if (way.containsNode(n)) {
570                    wayIsFinished = true;
571                    selection.clear();
572                }
573
574                // Add new node to way
575                if (way.getNode(way.getNodesCount() - 1) == n0) {
576                    way.addNode(n);
577                } else {
578                    way.addNode(0, n);
579                }
580
581                extendedWay = true;
582                newSelection.clear();
583                newSelection.add(wayToSelect);
584            }
585        }
586
587        String title;
588        if (!extendedWay) {
589            if (!newNode)
590                return; // We didn't do anything.
591            else if (reuseWays.isEmpty()) {
592                title = tr("Add node");
593            } else {
594                title = tr("Add node into way");
595                for (Way w : reuseWays) {
596                    newSelection.remove(w);
597                }
598            }
599            newSelection.clear();
600            newSelection.add(n);
601        } else if (!newNode) {
602            title = tr("Connect existing way to node");
603        } else if (reuseWays.isEmpty()) {
604            title = tr("Add a new node to an existing way");
605        } else {
606            title = tr("Add node into way and connect");
607        }
608
609        Command c = new SequenceCommand(title, cmds);
610
611        Main.main.undoRedo.add(c);
612        if (!wayIsFinished) {
613            lastUsedNode = n;
614        }
615
616        getCurrentDataSet().setSelected(newSelection);
617
618        // "viewport following" mode for tracing long features
619        // from aerial imagery or GPS tracks.
620        if (n != null && Main.map.mapView.viewportFollowing) {
621            Main.map.mapView.smoothScrollTo(n.getEastNorth());
622        }
623        computeHelperLine();
624        removeHighlighting();
625    }
626
627    private void insertNodeIntoAllNearbySegments(List<WaySegment> wss, Node n, Collection<OsmPrimitive> newSelection,
628            Collection<Command> cmds, List<Way> replacedWays, List<Way> reuseWays) {
629        Map<Way, List<Integer>> insertPoints = new HashMap<>();
630        for (WaySegment ws : wss) {
631            List<Integer> is;
632            if (insertPoints.containsKey(ws.way)) {
633                is = insertPoints.get(ws.way);
634            } else {
635                is = new ArrayList<>();
636                insertPoints.put(ws.way, is);
637            }
638
639            is.add(ws.lowerIndex);
640        }
641
642        Set<Pair<Node, Node>> segSet = new HashSet<>();
643
644        for (Map.Entry<Way, List<Integer>> insertPoint : insertPoints.entrySet()) {
645            Way w = insertPoint.getKey();
646            List<Integer> is = insertPoint.getValue();
647
648            Way wnew = new Way(w);
649
650            pruneSuccsAndReverse(is);
651            for (int i : is) {
652                segSet.add(Pair.sort(new Pair<>(w.getNode(i), w.getNode(i+1))));
653                wnew.addNode(i + 1, n);
654            }
655
656            // If ALT is pressed, a new way should be created and that new way should get
657            // selected. This works everytime unless the ways the nodes get inserted into
658            // are already selected. This is the case when creating a self-overlapping way
659            // but pressing ALT prevents this. Therefore we must de-select the way manually
660            // here so /only/ the new way will be selected after this method finishes.
661            if (alt) {
662                newSelection.add(insertPoint.getKey());
663            }
664
665            cmds.add(new ChangeCommand(insertPoint.getKey(), wnew));
666            replacedWays.add(insertPoint.getKey());
667            reuseWays.add(wnew);
668        }
669
670        adjustNode(segSet, n);
671    }
672
673    /**
674     * Prevent creation of ways that look like this: &lt;----&gt;
675     * This happens if users want to draw a no-exit-sideway from the main way like this:
676     * ^
677     * |&lt;----&gt;
678     * |
679     * The solution isn't ideal because the main way will end in the side way, which is bad for
680     * navigation software ("drive straight on") but at least easier to fix. Maybe users will fix
681     * it on their own, too. At least it's better than producing an error.
682     *
683     * @param selectedWay the way to check
684     * @param currentNode the current node (i.e. the one the connection will be made from)
685     * @param targetNode the target node (i.e. the one the connection will be made to)
686     * @return {@code true} if this would create a selfcontaining way, {@code false} otherwise.
687     */
688    private boolean isSelfContainedWay(Way selectedWay, Node currentNode, Node targetNode) {
689        if (selectedWay != null) {
690            int posn0 = selectedWay.getNodes().indexOf(currentNode);
691            if (posn0 != -1 && // n0 is part of way
692                    (posn0 >= 1                             && targetNode.equals(selectedWay.getNode(posn0-1))) || // previous node
693                    (posn0 < selectedWay.getNodesCount()-1) && targetNode.equals(selectedWay.getNode(posn0+1))) {  // next node
694                getCurrentDataSet().setSelected(targetNode);
695                lastUsedNode = targetNode;
696                return true;
697            }
698        }
699
700        return false;
701    }
702
703    /**
704     * Finds a node to continue drawing from. Decision is based upon given node and way.
705     * @param selectedNode Currently selected node, may be null
706     * @param selectedWay Currently selected way, may be null
707     * @return Node if a suitable node is found, null otherwise
708     */
709    private Node findNodeToContinueFrom(Node selectedNode, Way selectedWay) {
710        // No nodes or ways have been selected, this occurs when a relation
711        // has been selected or the selection is empty
712        if (selectedNode == null && selectedWay == null)
713            return null;
714
715        if (selectedNode == null) {
716            if (selectedWay.isFirstLastNode(lastUsedNode))
717                return lastUsedNode;
718
719            // We have a way selected, but no suitable node to continue from. Start anew.
720            return null;
721        }
722
723        if (selectedWay == null)
724            return selectedNode;
725
726        if (selectedWay.isFirstLastNode(selectedNode))
727            return selectedNode;
728
729        // We have a way and node selected, but it's not at the start/end of the way. Start anew.
730        return null;
731    }
732
733    @Override
734    public void mouseDragged(MouseEvent e) {
735        mouseMoved(e);
736    }
737
738    @Override
739    public void mouseMoved(MouseEvent e) {
740        if (!Main.map.mapView.isActiveLayerDrawable())
741            return;
742
743        // we copy ctrl/alt/shift from the event just in case our global
744        // keyDetector didn't make it through the security manager. Unclear
745        // if that can ever happen but better be safe.
746        updateKeyModifiers(e);
747        mousePos = e.getPoint();
748        if (snapHelper.isSnapOn() && ctrl)
749            tryToSetBaseSegmentForAngleSnap();
750
751        computeHelperLine();
752        addHighlighting();
753    }
754
755    /**
756     * This method is used to detect segment under mouse and use it as reference for angle snapping
757     */
758    private void tryToSetBaseSegmentForAngleSnap() {
759        WaySegment seg = Main.map.mapView.getNearestWaySegment(mousePos, OsmPrimitive.isSelectablePredicate);
760        if (seg != null) {
761            snapHelper.setBaseSegment(seg);
762        }
763    }
764
765    /**
766     * This method prepares data required for painting the "helper line" from
767     * the last used position to the mouse cursor. It duplicates some code from
768     * mouseReleased() (FIXME).
769     */
770    private void computeHelperLine() {
771        MapView mv = Main.map.mapView;
772        if (mousePos == null) {
773            // Don't draw the line.
774            currentMouseEastNorth = null;
775            currentBaseNode = null;
776            return;
777        }
778
779        Collection<OsmPrimitive> selection = getCurrentDataSet().getSelected();
780
781        Node currentMouseNode = null;
782        mouseOnExistingNode = null;
783        mouseOnExistingWays = new HashSet<>();
784
785        showStatusInfo(-1, -1, -1, snapHelper.isSnapOn());
786
787        if (!ctrl && mousePos != null) {
788            currentMouseNode = mv.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
789        }
790
791        // We need this for highlighting and we'll only do so if we actually want to re-use
792        // *and* there is no node nearby (because nodes beat ways when re-using)
793        if (!ctrl && currentMouseNode == null) {
794            List<WaySegment> wss = mv.getNearestWaySegments(mousePos, OsmPrimitive.isSelectablePredicate);
795            for (WaySegment ws : wss) {
796                mouseOnExistingWays.add(ws.way);
797            }
798        }
799
800        if (currentMouseNode != null) {
801            // user clicked on node
802            if (selection.isEmpty()) return;
803            currentMouseEastNorth = currentMouseNode.getEastNorth();
804            mouseOnExistingNode = currentMouseNode;
805        } else {
806            // no node found in clicked area
807            currentMouseEastNorth = mv.getEastNorth(mousePos.x, mousePos.y);
808        }
809
810        determineCurrentBaseNodeAndPreviousNode(selection);
811        if (previousNode == null) {
812            snapHelper.noSnapNow();
813        }
814
815        if (getCurrentBaseNode() == null || getCurrentBaseNode() == currentMouseNode)
816            return; // Don't create zero length way segments.
817
818
819        double curHdg = Math.toDegrees(getCurrentBaseNode().getEastNorth()
820                .heading(currentMouseEastNorth));
821        double baseHdg = -1;
822        if (previousNode != null) {
823            EastNorth en = previousNode.getEastNorth();
824            if (en != null) {
825                baseHdg = Math.toDegrees(en.heading(getCurrentBaseNode().getEastNorth()));
826            }
827        }
828
829        snapHelper.checkAngleSnapping(currentMouseEastNorth, baseHdg, curHdg);
830
831        // status bar was filled by snapHelper
832    }
833
834    private static void showStatusInfo(double angle, double hdg, double distance, boolean activeFlag) {
835        Main.map.statusLine.setAngle(angle);
836        Main.map.statusLine.activateAnglePanel(activeFlag);
837        Main.map.statusLine.setHeading(hdg);
838        Main.map.statusLine.setDist(distance);
839    }
840
841    /**
842     * Helper function that sets fields currentBaseNode and previousNode
843     * @param selection
844     * uses also lastUsedNode field
845     */
846    private void determineCurrentBaseNodeAndPreviousNode(Collection<OsmPrimitive>  selection) {
847        Node selectedNode = null;
848        Way selectedWay = null;
849        for (OsmPrimitive p : selection) {
850            if (p instanceof Node) {
851                if (selectedNode != null)
852                    return;
853                selectedNode = (Node) p;
854            } else if (p instanceof Way) {
855                if (selectedWay != null)
856                    return;
857                selectedWay = (Way) p;
858            }
859        }
860        // we are here, if not more than 1 way or node is selected,
861
862        // the node from which we make a connection
863        currentBaseNode = null;
864        previousNode = null;
865
866        // Try to find an open way to measure angle from it. The way is not to be continued!
867        // warning: may result in changes of currentBaseNode and previousNode
868        // please remove if bugs arise
869        if (selectedWay == null && selectedNode != null) {
870            for (OsmPrimitive p: selectedNode.getReferrers()) {
871                if (p.isUsable() && p instanceof Way && ((Way) p).isFirstLastNode(selectedNode)) {
872                    if (selectedWay != null) { // two uncontinued ways, nothing to take as reference
873                        selectedWay = null;
874                        break;
875                    } else {
876                        // set us ~continue this way (measure angle from it)
877                        selectedWay = (Way) p;
878                    }
879                }
880            }
881        }
882
883        if (selectedNode == null) {
884            if (selectedWay == null)
885                return;
886            continueWayFromNode(selectedWay, lastUsedNode);
887        } else if (selectedWay == null) {
888            currentBaseNode = selectedNode;
889        } else if (!selectedWay.isDeleted()) { // fix #7118
890            continueWayFromNode(selectedWay, selectedNode);
891        }
892    }
893
894    /**
895     * if one of the ends of @param way is given @param node ,
896     * then set  currentBaseNode = node and previousNode = adjacent node of way
897     */
898    private void continueWayFromNode(Way way, Node node) {
899        int n = way.getNodesCount();
900        if (node == way.firstNode()) {
901            currentBaseNode = node;
902            if (n > 1) previousNode = way.getNode(1);
903        } else if (node == way.lastNode()) {
904            currentBaseNode = node;
905            if (n > 1) previousNode = way.getNode(n-2);
906        }
907    }
908
909    /**
910     * Repaint on mouse exit so that the helper line goes away.
911     */
912    @Override
913    public void mouseExited(MouseEvent e) {
914        if (!Main.map.mapView.isActiveLayerDrawable())
915            return;
916        mousePos = e.getPoint();
917        snapHelper.noSnapNow();
918        boolean repaintIssued = removeHighlighting();
919        // force repaint in case snapHelper needs one. If removeHighlighting
920        // caused one already, don’t do it again.
921        if (!repaintIssued) {
922            Main.map.mapView.repaint();
923        }
924    }
925
926    /**
927     * @return If the node is the end of exactly one way, return this.
928     *  <code>null</code> otherwise.
929     */
930    public static Way getWayForNode(Node n) {
931        Way way = null;
932        for (Way w : Utils.filteredCollection(n.getReferrers(), Way.class)) {
933            if (!w.isUsable() || w.getNodesCount() < 1) {
934                continue;
935            }
936            Node firstNode = w.getNode(0);
937            Node lastNode = w.getNode(w.getNodesCount() - 1);
938            if ((firstNode == n || lastNode == n) && (firstNode != lastNode)) {
939                if (way != null)
940                    return null;
941                way = w;
942            }
943        }
944        return way;
945    }
946
947    /**
948     * Replies the current base node, after having checked it is still usable (see #11105).
949     * @return the current base node (can be null). If not-null, it's guaranteed the node is usable
950     */
951    public Node getCurrentBaseNode() {
952        if (currentBaseNode != null && (currentBaseNode.getDataSet() == null || !currentBaseNode.isUsable())) {
953            currentBaseNode = null;
954        }
955        return currentBaseNode;
956    }
957
958    private static void pruneSuccsAndReverse(List<Integer> is) {
959        Set<Integer> is2 = new HashSet<>();
960        for (int i : is) {
961            if (!is2.contains(i - 1) && !is2.contains(i + 1)) {
962                is2.add(i);
963            }
964        }
965        is.clear();
966        is.addAll(is2);
967        Collections.sort(is);
968        Collections.reverse(is);
969    }
970
971    /**
972     * Adjusts the position of a node to lie on a segment (or a segment
973     * intersection).
974     *
975     * If one or more than two segments are passed, the node is adjusted
976     * to lie on the first segment that is passed.
977     *
978     * If two segments are passed, the node is adjusted to be at their
979     * intersection.
980     *
981     * No action is taken if no segments are passed.
982     *
983     * @param segs the segments to use as a reference when adjusting
984     * @param n the node to adjust
985     */
986    private static void adjustNode(Collection<Pair<Node, Node>> segs, Node n) {
987
988        switch (segs.size()) {
989        case 0:
990            return;
991        case 2:
992            // This computes the intersection between the two segments and adjusts the node position.
993            Iterator<Pair<Node, Node>> i = segs.iterator();
994            Pair<Node, Node> seg = i.next();
995            EastNorth A = seg.a.getEastNorth();
996            EastNorth B = seg.b.getEastNorth();
997            seg = i.next();
998            EastNorth C = seg.a.getEastNorth();
999            EastNorth D = seg.b.getEastNorth();
1000
1001            double u = det(B.east() - A.east(), B.north() - A.north(), C.east() - D.east(), C.north() - D.north());
1002
1003            // Check for parallel segments and do nothing if they are
1004            // In practice this will probably only happen when a way has been duplicated
1005
1006            if (u == 0)
1007                return;
1008
1009            // q is a number between 0 and 1
1010            // It is the point in the segment where the intersection occurs
1011            // if the segment is scaled to lenght 1
1012
1013            double q = det(B.north() - C.north(), B.east() - C.east(), D.north() - C.north(), D.east() - C.east()) / u;
1014            EastNorth intersection = new EastNorth(
1015                    B.east() + q * (A.east() - B.east()),
1016                    B.north() + q * (A.north() - B.north()));
1017
1018
1019            // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise
1020            // fall through to default action.
1021            // (for semi-parallel lines, intersection might be miles away!)
1022            if (Main.map.mapView.getPoint2D(n).distance(Main.map.mapView.getPoint2D(intersection)) < snapToIntersectionThreshold) {
1023                n.setEastNorth(intersection);
1024                return;
1025            }
1026        default:
1027            EastNorth P = n.getEastNorth();
1028            seg = segs.iterator().next();
1029            A = seg.a.getEastNorth();
1030            B = seg.b.getEastNorth();
1031            double a = P.distanceSq(B);
1032            double b = P.distanceSq(A);
1033            double c = A.distanceSq(B);
1034            q = (a - b + c) / (2*c);
1035            n.setEastNorth(new EastNorth(B.east() + q * (A.east() - B.east()), B.north() + q * (A.north() - B.north())));
1036        }
1037    }
1038
1039    // helper for adjustNode
1040    static double det(double a, double b, double c, double d) {
1041        return a * d - b * c;
1042    }
1043
1044    private void tryToMoveNodeOnIntersection(List<WaySegment> wss, Node n) {
1045        if (wss.isEmpty())
1046            return;
1047        WaySegment ws = wss.get(0);
1048        EastNorth p1 = ws.getFirstNode().getEastNorth();
1049        EastNorth p2 = ws.getSecondNode().getEastNorth();
1050        if (snapHelper.dir2 != null && getCurrentBaseNode() != null) {
1051            EastNorth xPoint = Geometry.getSegmentSegmentIntersection(p1, p2, snapHelper.dir2,
1052                    getCurrentBaseNode().getEastNorth());
1053            if (xPoint != null) {
1054                n.setEastNorth(xPoint);
1055            }
1056        }
1057    }
1058
1059    /**
1060     * Takes the data from computeHelperLine to determine which ways/nodes should be highlighted
1061     * (if feature enabled). Also sets the target cursor if appropriate. It adds the to-be-
1062     * highlighted primitives to newHighlights but does not actually highlight them. This work is
1063     * done in redrawIfRequired. This means, calling addHighlighting() without redrawIfRequired()
1064     * will leave the data in an inconsistent state.
1065     *
1066     * The status bar derives its information from oldHighlights, so in order to update the status
1067     * bar both addHighlighting() and repaintIfRequired() are needed, since former fills newHighlights
1068     * and latter processes them into oldHighlights.
1069     */
1070    private void addHighlighting() {
1071        newHighlights = new HashSet<>();
1072
1073        // if ctrl key is held ("no join"), don't highlight anything
1074        if (ctrl) {
1075            Main.map.mapView.setNewCursor(cursor, this);
1076            redrawIfRequired();
1077            return;
1078        }
1079
1080        // This happens when nothing is selected, but we still want to highlight the "target node"
1081        if (mouseOnExistingNode == null && getCurrentDataSet().getSelected().isEmpty()
1082                && mousePos != null) {
1083            mouseOnExistingNode = Main.map.mapView.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
1084        }
1085
1086        if (mouseOnExistingNode != null) {
1087            Main.map.mapView.setNewCursor(cursorJoinNode, this);
1088            newHighlights.add(mouseOnExistingNode);
1089            redrawIfRequired();
1090            return;
1091        }
1092
1093        // Insert the node into all the nearby way segments
1094        if (mouseOnExistingWays.isEmpty()) {
1095            Main.map.mapView.setNewCursor(cursor, this);
1096            redrawIfRequired();
1097            return;
1098        }
1099
1100        Main.map.mapView.setNewCursor(cursorJoinWay, this);
1101        newHighlights.addAll(mouseOnExistingWays);
1102        redrawIfRequired();
1103    }
1104
1105    /**
1106     * Removes target highlighting from primitives. Issues repaint if required.
1107     * @return true if a repaint has been issued.
1108     */
1109    private boolean removeHighlighting() {
1110        newHighlights = new HashSet<>();
1111        return redrawIfRequired();
1112    }
1113
1114    @Override
1115    public void paint(Graphics2D g, MapView mv, Bounds box) {
1116        // sanity checks
1117        if (Main.map.mapView == null || mousePos == null
1118                // don't draw line if we don't know where from or where to
1119                || getCurrentBaseNode() == null || currentMouseEastNorth == null
1120                // don't draw line if mouse is outside window
1121                || !Main.map.mapView.getBounds().contains(mousePos))
1122            return;
1123
1124        Graphics2D g2 = g;
1125        snapHelper.drawIfNeeded(g2, mv);
1126        if (!drawHelperLine || wayIsFinished || shift)
1127            return;
1128
1129        if (!snapHelper.isActive()) { // else use color and stoke from  snapHelper.draw
1130            g2.setColor(rubberLineColor);
1131            g2.setStroke(rubberLineStroke);
1132        } else if (!snapHelper.drawConstructionGeometry)
1133            return;
1134        GeneralPath b = new GeneralPath();
1135        Point p1 = mv.getPoint(getCurrentBaseNode());
1136        Point p2 = mv.getPoint(currentMouseEastNorth);
1137
1138        double t = Math.atan2(p2.y-p1.y, p2.x-p1.x) + Math.PI;
1139
1140        b.moveTo(p1.x, p1.y);
1141        b.lineTo(p2.x, p2.y);
1142
1143        // if alt key is held ("start new way"), draw a little perpendicular line
1144        if (alt) {
1145            b.moveTo((int) (p1.x + 8*Math.cos(t+PHI)), (int) (p1.y + 8*Math.sin(t+PHI)));
1146            b.lineTo((int) (p1.x + 8*Math.cos(t-PHI)), (int) (p1.y + 8*Math.sin(t-PHI)));
1147        }
1148
1149        g2.draw(b);
1150        g2.setStroke(BASIC_STROKE);
1151    }
1152
1153    @Override
1154    public String getModeHelpText() {
1155        StringBuilder rv;
1156        /*
1157         *  No modifiers: all (Connect, Node Re-Use, Auto-Weld)
1158         *  CTRL: disables node re-use, auto-weld
1159         *  Shift: do not make connection
1160         *  ALT: make connection but start new way in doing so
1161         */
1162
1163        /*
1164         * Status line text generation is split into two parts to keep it maintainable.
1165         * First part looks at what will happen to the new node inserted on click and
1166         * the second part will look if a connection is made or not.
1167         *
1168         * Note that this help text is not absolutely accurate as it doesn't catch any special
1169         * cases (e.g. when preventing <---> ways). The only special that it catches is when
1170         * a way is about to be finished.
1171         *
1172         * First check what happens to the new node.
1173         */
1174
1175        // oldHighlights stores the current highlights. If this
1176        // list is empty we can assume that we won't do any joins
1177        if (ctrl || oldHighlights.isEmpty()) {
1178            rv = new StringBuilder(tr("Create new node."));
1179        } else {
1180            // oldHighlights may store a node or way, check if it's a node
1181            OsmPrimitive x = oldHighlights.iterator().next();
1182            if (x instanceof Node) {
1183                rv = new StringBuilder(tr("Select node under cursor."));
1184            } else {
1185                rv = new StringBuilder(trn("Insert new node into way.", "Insert new node into {0} ways.",
1186                        oldHighlights.size(), oldHighlights.size()));
1187            }
1188        }
1189
1190        /*
1191         * Check whether a connection will be made
1192         */
1193        if (getCurrentBaseNode() != null && !wayIsFinished) {
1194            if (alt) {
1195                rv.append(' ').append(tr("Start new way from last node."));
1196            } else {
1197                rv.append(' ').append(tr("Continue way from last node."));
1198            }
1199            if (snapHelper.isSnapOn()) {
1200                rv.append(' ').append(tr("Angle snapping active."));
1201            }
1202        }
1203
1204        Node n = mouseOnExistingNode;
1205        /*
1206         * Handle special case: Highlighted node == selected node => finish drawing
1207         */
1208        if (n != null && getCurrentDataSet() != null && getCurrentDataSet().getSelectedNodes().contains(n)) {
1209            if (wayIsFinished) {
1210                rv = new StringBuilder(tr("Select node under cursor."));
1211            } else {
1212                rv = new StringBuilder(tr("Finish drawing."));
1213            }
1214        }
1215
1216        /*
1217         * Handle special case: Self-Overlapping or closing way
1218         */
1219        if (getCurrentDataSet() != null && !getCurrentDataSet().getSelectedWays().isEmpty() && !wayIsFinished && !alt) {
1220            Way w = getCurrentDataSet().getSelectedWays().iterator().next();
1221            for (Node m : w.getNodes()) {
1222                if (m.equals(mouseOnExistingNode) || mouseOnExistingWays.contains(w)) {
1223                    rv.append(' ').append(tr("Finish drawing."));
1224                    break;
1225                }
1226            }
1227        }
1228        return rv.toString();
1229    }
1230
1231    /**
1232     * Get selected primitives, while draw action is in progress.
1233     *
1234     * While drawing a way, technically the last node is selected.
1235     * This is inconvenient when the user tries to add/edit tags to the way.
1236     * For this case, this method returns the current way as selection,
1237     * to work around this issue.
1238     * Otherwise the normal selection of the current data layer is returned.
1239     * @return selected primitives, while draw action is in progress
1240     */
1241    public Collection<OsmPrimitive> getInProgressSelection() {
1242        DataSet ds = getCurrentDataSet();
1243        if (ds == null) return null;
1244        if (getCurrentBaseNode() != null && !ds.getSelected().isEmpty()) {
1245            Way continueFrom = getWayForNode(getCurrentBaseNode());
1246            if (continueFrom != null)
1247                return Collections.<OsmPrimitive>singleton(continueFrom);
1248        }
1249        return ds.getSelected();
1250    }
1251
1252    @Override
1253    public boolean layerIsSupported(Layer l) {
1254        return l instanceof OsmDataLayer;
1255    }
1256
1257    @Override
1258    protected void updateEnabledState() {
1259        setEnabled(getEditLayer() != null);
1260    }
1261
1262    @Override
1263    public void destroy() {
1264        super.destroy();
1265        snapChangeAction.destroy();
1266    }
1267
1268    public class BackSpaceAction extends AbstractAction {
1269
1270        @Override
1271        public void actionPerformed(ActionEvent e) {
1272            Main.main.undoRedo.undo();
1273            Node n = null;
1274            Command lastCmd = Main.main.undoRedo.commands.peekLast();
1275            if (lastCmd == null) return;
1276            for (OsmPrimitive p: lastCmd.getParticipatingPrimitives()) {
1277                if (p instanceof Node) {
1278                    if (n == null) {
1279                        n = (Node) p; // found one node
1280                        wayIsFinished = false;
1281                    }  else {
1282                        // if more than 1 node were affected by previous command,
1283                        // we have no way to continue, so we forget about found node
1284                        n = null;
1285                        break;
1286                    }
1287                }
1288            }
1289            // select last added node - maybe we will continue drawing from it
1290            if (n != null) {
1291                getCurrentDataSet().addSelected(n);
1292            }
1293        }
1294    }
1295
1296    private class SnapHelper {
1297        private final class AnglePopupMenu extends JPopupMenu {
1298
1299            private final JCheckBoxMenuItem repeatedCb = new JCheckBoxMenuItem(
1300                    new AbstractAction(tr("Toggle snapping by {0}", getShortcut().getKeyText())) {
1301                @Override
1302                public void actionPerformed(ActionEvent e) {
1303                    boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
1304                    Main.pref.put("draw.anglesnap.toggleOnRepeatedA", sel);
1305                    init();
1306                }
1307            });
1308
1309            private final JCheckBoxMenuItem helperCb = new JCheckBoxMenuItem(
1310                    new AbstractAction(tr("Show helper geometry")) {
1311                @Override
1312                public void actionPerformed(ActionEvent e) {
1313                    boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
1314                    Main.pref.put("draw.anglesnap.drawConstructionGeometry", sel);
1315                    Main.pref.put("draw.anglesnap.drawProjectedPoint", sel);
1316                    Main.pref.put("draw.anglesnap.showAngle", sel);
1317                    init();
1318                    enableSnapping();
1319                }
1320            });
1321
1322            private final JCheckBoxMenuItem projectionCb = new JCheckBoxMenuItem(
1323                    new AbstractAction(tr("Snap to node projections")) {
1324                @Override
1325                public void actionPerformed(ActionEvent e) {
1326                    boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
1327                    Main.pref.put("draw.anglesnap.projectionsnap", sel);
1328                    init();
1329                    enableSnapping();
1330                }
1331            });
1332
1333            private AnglePopupMenu() {
1334                helperCb.setState(Main.pref.getBoolean("draw.anglesnap.drawConstructionGeometry", true));
1335                projectionCb.setState(Main.pref.getBoolean("draw.anglesnap.projectionsnapgvff", true));
1336                repeatedCb.setState(Main.pref.getBoolean("draw.anglesnap.toggleOnRepeatedA", true));
1337                add(repeatedCb);
1338                add(helperCb);
1339                add(projectionCb);
1340                add(new AbstractAction(tr("Disable")) {
1341                    @Override public void actionPerformed(ActionEvent e) {
1342                        saveAngles("180");
1343                        init();
1344                        enableSnapping();
1345                    }
1346                });
1347                add(new AbstractAction(tr("0,90,...")) {
1348                    @Override public void actionPerformed(ActionEvent e) {
1349                        saveAngles("0", "90", "180");
1350                        init();
1351                        enableSnapping();
1352                    }
1353                });
1354                add(new AbstractAction(tr("0,45,90,...")) {
1355                    @Override public void actionPerformed(ActionEvent e) {
1356                        saveAngles("0", "45", "90", "135", "180");
1357                        init();
1358                        enableSnapping();
1359                    }
1360                });
1361                add(new AbstractAction(tr("0,30,45,60,90,...")) {
1362                    @Override public void actionPerformed(ActionEvent e) {
1363                        saveAngles("0", "30", "45", "60", "90", "120", "135", "150", "180");
1364                        init();
1365                        enableSnapping();
1366                    }
1367                });
1368            }
1369        }
1370
1371        private boolean snapOn; // snapping is turned on
1372
1373        private boolean active; // snapping is active for current mouse position
1374        private boolean fixed; // snap angle is fixed
1375        private boolean absoluteFix; // snap angle is absolute
1376
1377        private boolean drawConstructionGeometry;
1378        private boolean showProjectedPoint;
1379        private boolean showAngle;
1380
1381        private boolean snapToProjections;
1382
1383        private EastNorth dir2;
1384        private EastNorth projected;
1385        private String labelText;
1386        private double lastAngle;
1387
1388        private double customBaseHeading = -1; // angle of base line, if not last segment)
1389        private EastNorth segmentPoint1; // remembered first point of base segment
1390        private EastNorth segmentPoint2; // remembered second point of base segment
1391        private EastNorth projectionSource; // point that we are projecting to the line
1392
1393        private double[] snapAngles;
1394        private double snapAngleTolerance;
1395
1396        private double pe, pn; // (pe, pn) - direction of snapping line
1397        private double e0, n0; // (e0, n0) - origin of snapping line
1398
1399        private final String fixFmt = "%d "+tr("FIX");
1400        private Color snapHelperColor;
1401        private Color highlightColor;
1402
1403        private Stroke normalStroke;
1404        private Stroke helperStroke;
1405        private Stroke highlightStroke;
1406
1407        private JCheckBoxMenuItem checkBox;
1408
1409        private MouseListener anglePopupListener = new PopupMenuLauncher(new AnglePopupMenu()) {
1410            @Override
1411            public void mouseClicked(MouseEvent e) {
1412                super.mouseClicked(e);
1413                if (e.getButton() == MouseEvent.BUTTON1) {
1414                    toggleSnapping();
1415                    updateStatusLine();
1416                }
1417            }
1418        };
1419
1420        public void init() {
1421            snapOn = false;
1422            checkBox.setState(snapOn);
1423            fixed = false;
1424            absoluteFix = false;
1425
1426            Collection<String> angles = Main.pref.getCollection("draw.anglesnap.angles",
1427                    Arrays.asList("0", "30", "45", "60", "90", "120", "135", "150", "180"));
1428
1429            snapAngles = new double[2*angles.size()];
1430            int i = 0;
1431            for (String s: angles) {
1432                try {
1433                    snapAngles[i] = Double.parseDouble(s); i++;
1434                    snapAngles[i] = 360-Double.parseDouble(s); i++;
1435                } catch (NumberFormatException e) {
1436                    Main.warn("Incorrect number in draw.anglesnap.angles preferences: "+s);
1437                    snapAngles[i] = 0; i++;
1438                    snapAngles[i] = 0; i++;
1439                }
1440            }
1441            snapAngleTolerance = Main.pref.getDouble("draw.anglesnap.tolerance", 5.0);
1442            drawConstructionGeometry = Main.pref.getBoolean("draw.anglesnap.drawConstructionGeometry", true);
1443            showProjectedPoint = Main.pref.getBoolean("draw.anglesnap.drawProjectedPoint", true);
1444            snapToProjections = Main.pref.getBoolean("draw.anglesnap.projectionsnap", true);
1445
1446            showAngle = Main.pref.getBoolean("draw.anglesnap.showAngle", true);
1447            useRepeatedShortcut = Main.pref.getBoolean("draw.anglesnap.toggleOnRepeatedA", true);
1448
1449            normalStroke = rubberLineStroke;
1450            snapHelperColor = Main.pref.getColor(marktr("draw angle snap"), Color.ORANGE);
1451
1452            highlightColor = Main.pref.getColor(marktr("draw angle snap highlight"), ORANGE_TRANSPARENT);
1453            highlightStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.anglesnap.stroke.highlight", "10"));
1454            helperStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.anglesnap.stroke.helper", "1 4"));
1455        }
1456
1457        public void saveAngles(String ... angles) {
1458            Main.pref.putCollection("draw.anglesnap.angles", Arrays.asList(angles));
1459        }
1460
1461        public void setMenuCheckBox(JCheckBoxMenuItem checkBox) {
1462            this.checkBox = checkBox;
1463        }
1464
1465        public void drawIfNeeded(Graphics2D g2, MapView mv) {
1466            if (!snapOn || !active)
1467                return;
1468            Point p1 = mv.getPoint(getCurrentBaseNode());
1469            Point p2 = mv.getPoint(dir2);
1470            Point p3 = mv.getPoint(projected);
1471            GeneralPath b;
1472            if (drawConstructionGeometry) {
1473                g2.setColor(snapHelperColor);
1474                g2.setStroke(helperStroke);
1475
1476                b = new GeneralPath();
1477                if (absoluteFix) {
1478                    b.moveTo(p2.x, p2.y);
1479                    b.lineTo(2*p1.x-p2.x, 2*p1.y-p2.y); // bi-directional line
1480                } else {
1481                    b.moveTo(p2.x, p2.y);
1482                    b.lineTo(p3.x, p3.y);
1483                }
1484                g2.draw(b);
1485            }
1486            if (projectionSource != null) {
1487                g2.setColor(snapHelperColor);
1488                g2.setStroke(helperStroke);
1489                b = new GeneralPath();
1490                b.moveTo(p3.x, p3.y);
1491                Point pp = mv.getPoint(projectionSource);
1492                b.lineTo(pp.x, pp.y);
1493                g2.draw(b);
1494            }
1495
1496            if (customBaseHeading >= 0) {
1497                g2.setColor(highlightColor);
1498                g2.setStroke(highlightStroke);
1499                b = new GeneralPath();
1500                Point pp1 = mv.getPoint(segmentPoint1);
1501                Point pp2 = mv.getPoint(segmentPoint2);
1502                b.moveTo(pp1.x, pp1.y);
1503                b.lineTo(pp2.x, pp2.y);
1504                g2.draw(b);
1505            }
1506
1507            g2.setColor(rubberLineColor);
1508            g2.setStroke(normalStroke);
1509            b = new GeneralPath();
1510            b.moveTo(p1.x, p1.y);
1511            b.lineTo(p3.x, p3.y);
1512            g2.draw(b);
1513
1514            g2.drawString(labelText, p3.x-5, p3.y+20);
1515            if (showProjectedPoint) {
1516                g2.setStroke(normalStroke);
1517                g2.drawOval(p3.x-5, p3.y-5, 10, 10); // projected point
1518            }
1519
1520            g2.setColor(snapHelperColor);
1521            g2.setStroke(helperStroke);
1522        }
1523
1524        /* If mouse position is close to line at 15-30-45-... angle, remembers this direction
1525         */
1526        public void checkAngleSnapping(EastNorth currentEN, double baseHeading, double curHeading) {
1527            EastNorth p0 = getCurrentBaseNode().getEastNorth();
1528            EastNorth snapPoint = currentEN;
1529            double angle = -1;
1530
1531            double activeBaseHeading = (customBaseHeading >= 0) ? customBaseHeading : baseHeading;
1532
1533            if (snapOn && (activeBaseHeading >= 0)) {
1534                angle = curHeading - activeBaseHeading;
1535                if (angle < 0) {
1536                    angle += 360;
1537                }
1538                if (angle > 360) {
1539                    angle = 0;
1540                }
1541
1542                double nearestAngle;
1543                if (fixed) {
1544                    nearestAngle = lastAngle; // if direction is fixed use previous angle
1545                    active = true;
1546                } else {
1547                    nearestAngle = getNearestAngle(angle);
1548                    if (getAngleDelta(nearestAngle, angle) < snapAngleTolerance) {
1549                        active = (customBaseHeading >= 0) ? true : Math.abs(nearestAngle - 180) > 1e-3;
1550                        // if angle is to previous segment, exclude 180 degrees
1551                        lastAngle = nearestAngle;
1552                    } else {
1553                        active = false;
1554                    }
1555                }
1556
1557                if (active) {
1558                    double phi;
1559                    e0 = p0.east();
1560                    n0 = p0.north();
1561                    buildLabelText((nearestAngle <= 180) ? nearestAngle : nearestAngle-360);
1562
1563                    phi = (nearestAngle + activeBaseHeading) * Math.PI / 180;
1564                    // (pe,pn) - direction of snapping line
1565                    pe = Math.sin(phi);
1566                    pn = Math.cos(phi);
1567                    double scale = 20 * Main.map.mapView.getDist100Pixel();
1568                    dir2 = new EastNorth(e0 + scale * pe, n0 + scale * pn);
1569                    snapPoint = getSnapPoint(currentEN);
1570                } else {
1571                    noSnapNow();
1572                }
1573            }
1574
1575            // find out the distance, in metres, between the base point and projected point
1576            LatLon mouseLatLon = Main.map.mapView.getProjection().eastNorth2latlon(snapPoint);
1577            double distance = getCurrentBaseNode().getCoor().greatCircleDistance(mouseLatLon);
1578            double hdg = Math.toDegrees(p0.heading(snapPoint));
1579            // heading of segment from current to calculated point, not to mouse position
1580
1581            if (baseHeading >= 0) { // there is previous line segment with some heading
1582                angle = hdg - baseHeading;
1583                if (angle < 0) {
1584                    angle += 360;
1585                }
1586                if (angle > 360) {
1587                    angle = 0;
1588                }
1589            }
1590            showStatusInfo(angle, hdg, distance, isSnapOn());
1591        }
1592
1593        private void buildLabelText(double nearestAngle) {
1594            if (showAngle) {
1595                if (fixed) {
1596                    if (absoluteFix) {
1597                        labelText = "=";
1598                    } else {
1599                        labelText = String.format(fixFmt, (int) nearestAngle);
1600                    }
1601                } else {
1602                    labelText = String.format("%d", (int) nearestAngle);
1603                }
1604            } else {
1605                if (fixed) {
1606                    if (absoluteFix) {
1607                        labelText = "=";
1608                    } else {
1609                        labelText = String.format(tr("FIX"), 0);
1610                    }
1611                } else {
1612                    labelText = "";
1613                }
1614            }
1615        }
1616
1617        public EastNorth getSnapPoint(EastNorth p) {
1618            if (!active)
1619                return p;
1620            double de = p.east()-e0;
1621            double dn = p.north()-n0;
1622            double l = de*pe+dn*pn;
1623            double delta = Main.map.mapView.getDist100Pixel()/20;
1624            if (!absoluteFix && l < delta) {
1625                active = false;
1626                return p;
1627            } //  do not go backward!
1628
1629            projectionSource = null;
1630            if (snapToProjections) {
1631                DataSet ds = getCurrentDataSet();
1632                Collection<Way> selectedWays = ds.getSelectedWays();
1633                if (selectedWays.size() == 1) {
1634                    Way w = selectedWays.iterator().next();
1635                    Collection<EastNorth> pointsToProject = new ArrayList<>();
1636                    if (w.getNodesCount() < 1000) {
1637                        for (Node n: w.getNodes()) {
1638                            pointsToProject.add(n.getEastNorth());
1639                        }
1640                    }
1641                    if (customBaseHeading >= 0) {
1642                        pointsToProject.add(segmentPoint1);
1643                        pointsToProject.add(segmentPoint2);
1644                    }
1645                    EastNorth enOpt = null;
1646                    double dOpt = 1e5;
1647                    for (EastNorth en: pointsToProject) { // searching for besht projection
1648                        double l1 = (en.east()-e0)*pe+(en.north()-n0)*pn;
1649                        double d1 = Math.abs(l1-l);
1650                        if (d1 < delta && d1 < dOpt) {
1651                            l = l1;
1652                            enOpt = en;
1653                            dOpt = d1;
1654                        }
1655                    }
1656                    if (enOpt != null) {
1657                        projectionSource =  enOpt;
1658                    }
1659                }
1660            }
1661            return projected = new EastNorth(e0+l*pe, n0+l*pn);
1662        }
1663
1664        public void noSnapNow() {
1665            active = false;
1666            dir2 = null;
1667            projected = null;
1668            labelText = null;
1669        }
1670
1671        public void setBaseSegment(WaySegment seg) {
1672            if (seg == null) return;
1673            segmentPoint1 = seg.getFirstNode().getEastNorth();
1674            segmentPoint2 = seg.getSecondNode().getEastNorth();
1675
1676            double hdg = segmentPoint1.heading(segmentPoint2);
1677            hdg = Math.toDegrees(hdg);
1678            if (hdg < 0) {
1679                hdg += 360;
1680            }
1681            if (hdg > 360) {
1682                hdg -= 360;
1683            }
1684            customBaseHeading = hdg;
1685        }
1686
1687        private void nextSnapMode() {
1688            if (snapOn) {
1689                // turn off snapping if we are in fixed mode or no actile snapping line exist
1690                if (fixed || !active) {
1691                    snapOn = false;
1692                    unsetFixedMode();
1693                } else {
1694                    setFixedMode();
1695                }
1696            } else {
1697                snapOn = true;
1698                unsetFixedMode();
1699            }
1700            checkBox.setState(snapOn);
1701            customBaseHeading = -1;
1702        }
1703
1704        private void enableSnapping() {
1705            snapOn = true;
1706            checkBox.setState(snapOn);
1707            customBaseHeading = -1;
1708            unsetFixedMode();
1709        }
1710
1711        private void toggleSnapping() {
1712            snapOn = !snapOn;
1713            checkBox.setState(snapOn);
1714            customBaseHeading = -1;
1715            unsetFixedMode();
1716        }
1717
1718        public void setFixedMode() {
1719            if (active) {
1720                fixed = true;
1721            }
1722        }
1723
1724        public  void unsetFixedMode() {
1725            fixed = false;
1726            absoluteFix = false;
1727            lastAngle = 0;
1728            active = false;
1729        }
1730
1731        public  boolean isActive() {
1732            return active;
1733        }
1734
1735        public  boolean isSnapOn() {
1736            return snapOn;
1737        }
1738
1739        private double getNearestAngle(double angle) {
1740            double delta, minDelta = 1e5, bestAngle = 0.0;
1741            for (double snapAngle : snapAngles) {
1742                delta = getAngleDelta(angle, snapAngle);
1743                if (delta < minDelta) {
1744                    minDelta = delta;
1745                    bestAngle = snapAngle;
1746                }
1747            }
1748            if (Math.abs(bestAngle-360) < 1e-3) {
1749                bestAngle = 0;
1750            }
1751            return bestAngle;
1752        }
1753
1754        private double getAngleDelta(double a, double b) {
1755            double delta = Math.abs(a-b);
1756            if (delta > 180)
1757                return 360-delta;
1758            else
1759                return delta;
1760        }
1761
1762        private void unFixOrTurnOff() {
1763            if (absoluteFix) {
1764                unsetFixedMode();
1765            } else {
1766                toggleSnapping();
1767            }
1768        }
1769    }
1770
1771    private class SnapChangeAction extends JosmAction {
1772        /**
1773         * Constructs a new {@code SnapChangeAction}.
1774         */
1775        SnapChangeAction() {
1776            super(tr("Angle snapping"), /* ICON() */ "anglesnap",
1777                    tr("Switch angle snapping mode while drawing"), null, false);
1778            putValue("help", ht("/Action/Draw/AngleSnap"));
1779        }
1780
1781        @Override
1782        public void actionPerformed(ActionEvent e) {
1783            if (snapHelper != null) {
1784                snapHelper.toggleSnapping();
1785            }
1786        }
1787    }
1788}