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