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