001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.tr;
006
007import java.awt.event.ActionEvent;
008import java.awt.event.KeyEvent;
009import java.util.ArrayList;
010import java.util.Arrays;
011import java.util.Collection;
012import java.util.Collections;
013import java.util.HashMap;
014import java.util.HashSet;
015import java.util.Iterator;
016import java.util.LinkedList;
017import java.util.List;
018import java.util.Map;
019import java.util.Set;
020
021import javax.swing.JOptionPane;
022
023import org.openstreetmap.josm.Main;
024import org.openstreetmap.josm.command.Command;
025import org.openstreetmap.josm.command.MoveCommand;
026import org.openstreetmap.josm.command.SequenceCommand;
027import org.openstreetmap.josm.data.coor.EastNorth;
028import org.openstreetmap.josm.data.coor.PolarCoor;
029import org.openstreetmap.josm.data.osm.Node;
030import org.openstreetmap.josm.data.osm.OsmPrimitive;
031import org.openstreetmap.josm.data.osm.Way;
032import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
033import org.openstreetmap.josm.gui.MainApplication;
034import org.openstreetmap.josm.gui.Notification;
035import org.openstreetmap.josm.tools.Geometry;
036import org.openstreetmap.josm.tools.JosmRuntimeException;
037import org.openstreetmap.josm.tools.Logging;
038import org.openstreetmap.josm.tools.Shortcut;
039import org.openstreetmap.josm.tools.Utils;
040
041/**
042 * Tools / Orthogonalize
043 *
044 * Align edges of a way so all angles are angles of 90 or 180 degrees.
045 * See USAGE String below.
046 */
047public final class OrthogonalizeAction extends JosmAction {
048    private static final String USAGE = tr(
049            "<h3>When one or more ways are selected, the shape is adjusted such, that all angles are 90 or 180 degrees.</h3>"+
050            "You can add two nodes to the selection. Then, the direction is fixed by these two reference nodes. "+
051            "(Afterwards, you can undo the movement for certain nodes:<br>"+
052            "Select them and press the shortcut for Orthogonalize / Undo. The default is Shift-Q.)");
053
054    private static final double EPSILON = 1E-6;
055
056    /**
057     * Constructs a new {@code OrthogonalizeAction}.
058     */
059    public OrthogonalizeAction() {
060        super(tr("Orthogonalize Shape"),
061                "ortho",
062                tr("Move nodes so all angles are 90 or 180 degrees"),
063                Shortcut.registerShortcut("tools:orthogonalize", tr("Tool: {0}", tr("Orthogonalize Shape")),
064                        KeyEvent.VK_Q,
065                        Shortcut.DIRECT), true);
066        putValue("help", ht("/Action/OrthogonalizeShape"));
067    }
068
069    /**
070     * excepted deviation from an angle of 0, 90, 180, 360 degrees
071     * maximum value: 45 degrees
072     *
073     * Current policy is to except just everything, no matter how strange the result would be.
074     */
075    private static final double TOLERANCE1 = Utils.toRadians(45.);   // within a way
076    private static final double TOLERANCE2 = Utils.toRadians(45.);   // ways relative to each other
077
078    /**
079     * Remember movements, so the user can later undo it for certain nodes
080     */
081    private static final Map<Node, EastNorth> rememberMovements = new HashMap<>();
082
083    /**
084     * Undo the previous orthogonalization for certain nodes.
085     *
086     * This is useful, if the way shares nodes that you don't like to change, e.g. imports or
087     * work of another user.
088     *
089     * This action can be triggered by shortcut only.
090     */
091    public static class Undo extends JosmAction {
092        /**
093         * Constructor
094         */
095        public Undo() {
096            super(tr("Orthogonalize Shape / Undo"), "ortho",
097                    tr("Undo orthogonalization for certain nodes"),
098                    Shortcut.registerShortcut("tools:orthogonalizeUndo", tr("Tool: {0}", tr("Orthogonalize Shape / Undo")),
099                            KeyEvent.VK_Q,
100                            Shortcut.SHIFT),
101                    true, "action/orthogonalize/undo", true);
102        }
103
104        @Override
105        public void actionPerformed(ActionEvent e) {
106            if (!isEnabled())
107                return;
108            final Collection<Command> commands = new LinkedList<>();
109            final Collection<OsmPrimitive> sel = getLayerManager().getEditDataSet().getSelected();
110            try {
111                for (OsmPrimitive p : sel) {
112                    if (!(p instanceof Node)) throw new InvalidUserInputException("selected object is not a node");
113                    Node n = (Node) p;
114                    if (rememberMovements.containsKey(n)) {
115                        EastNorth tmp = rememberMovements.get(n);
116                        commands.add(new MoveCommand(n, -tmp.east(), -tmp.north()));
117                        rememberMovements.remove(n);
118                    }
119                }
120                if (!commands.isEmpty()) {
121                    MainApplication.undoRedo.add(new SequenceCommand(tr("Orthogonalize / Undo"), commands));
122                } else {
123                    throw new InvalidUserInputException("Commands are empty");
124                }
125            } catch (InvalidUserInputException ex) {
126                Logging.debug(ex);
127                new Notification(
128                        tr("Orthogonalize Shape / Undo<br>"+
129                        "Please select nodes that were moved by the previous Orthogonalize Shape action!"))
130                        .setIcon(JOptionPane.INFORMATION_MESSAGE)
131                        .show();
132            }
133        }
134
135        @Override
136        protected void updateEnabledState() {
137            updateEnabledStateOnCurrentSelection();
138        }
139
140        @Override
141        protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
142            updateEnabledStateOnModifiableSelection(selection);
143        }
144    }
145
146    @Override
147    public void actionPerformed(ActionEvent e) {
148        if (!isEnabled())
149            return;
150        if ("EPSG:4326".equals(Main.getProjection().toString())) {
151            String msg = tr("<html>You are using the EPSG:4326 projection which might lead<br>" +
152                    "to undesirable results when doing rectangular alignments.<br>" +
153                    "Change your projection to get rid of this warning.<br>" +
154            "Do you want to continue?</html>");
155            if (!ConditionalOptionPaneUtil.showConfirmationDialog(
156                    "align_rectangular_4326",
157                    Main.parent,
158                    msg,
159                    tr("Warning"),
160                    JOptionPane.YES_NO_OPTION,
161                    JOptionPane.QUESTION_MESSAGE,
162                    JOptionPane.YES_OPTION))
163                return;
164        }
165
166        final Collection<OsmPrimitive> sel = getLayerManager().getEditDataSet().getSelected();
167
168        try {
169            MainApplication.undoRedo.add(orthogonalize(sel));
170        } catch (InvalidUserInputException ex) {
171            Logging.debug(ex);
172            String msg;
173            if ("usage".equals(ex.getMessage())) {
174                msg = "<h2>" + tr("Usage") + "</h2>" + USAGE;
175            } else {
176                msg = ex.getMessage() + "<br><hr><h2>" + tr("Usage") + "</h2>" + USAGE;
177            }
178            new Notification(msg)
179                    .setIcon(JOptionPane.INFORMATION_MESSAGE)
180                    .setDuration(Notification.TIME_DEFAULT)
181                    .show();
182        }
183    }
184
185    /**
186     * Rectifies the selection
187     * @param selection the selection which should be rectified
188     * @return a rectifying command
189     * @throws InvalidUserInputException if the selection is invalid
190     * @since 13670
191     */
192    public static SequenceCommand orthogonalize(Iterable<OsmPrimitive> selection) throws InvalidUserInputException {
193        final List<Node> nodeList = new ArrayList<>();
194        final List<WayData> wayDataList = new ArrayList<>();
195        // collect nodes and ways from the selection
196        for (OsmPrimitive p : selection) {
197            if (p instanceof Node) {
198                nodeList.add((Node) p);
199            } else if (p instanceof Way) {
200                if (!p.isIncomplete()) {
201                    wayDataList.add(new WayData(((Way) p).getNodes()));
202                }
203            } else {
204                throw new InvalidUserInputException(tr("Selection must consist only of ways and nodes."));
205            }
206        }
207        final int nodesCount = nodeList.size();
208        if (wayDataList.isEmpty() && nodesCount > 2) {
209            final WayData data = new WayData(nodeList);
210            final Collection<Command> commands = orthogonalize(Collections.singletonList(data), Collections.<Node>emptyList());
211            return new SequenceCommand(tr("Orthogonalize"), commands);
212        } else if (wayDataList.isEmpty()) {
213            throw new InvalidUserInputException("usage");
214        } else {
215            if (nodesCount <= 2) {
216                OrthogonalizeAction.rememberMovements.clear();
217                final Collection<Command> commands = new LinkedList<>();
218
219                if (nodesCount == 2) {  // fixed direction, or single node to move
220                    commands.addAll(orthogonalize(wayDataList, nodeList));
221                } else if (nodesCount == 1) {
222                    commands.add(orthogonalize(wayDataList, nodeList.get(0)));
223                } else if (nodesCount == 0) {
224                    for (List<WayData> g : buildGroups(wayDataList)) {
225                        commands.addAll(orthogonalize(g, nodeList));
226                    }
227                }
228
229                return new SequenceCommand(tr("Orthogonalize"), commands);
230
231            } else {
232                throw new InvalidUserInputException("usage");
233            }
234        }
235    }
236
237    /**
238     * Collect groups of ways with common nodes in order to orthogonalize each group separately.
239     * @param wayDataList list of ways
240     * @return groups of ways with common nodes
241     */
242    private static List<List<WayData>> buildGroups(List<WayData> wayDataList) {
243        List<List<WayData>> groups = new ArrayList<>();
244        Set<WayData> remaining = new HashSet<>(wayDataList);
245        while (!remaining.isEmpty()) {
246            List<WayData> group = new ArrayList<>();
247            groups.add(group);
248            Iterator<WayData> it = remaining.iterator();
249            WayData next = it.next();
250            it.remove();
251            extendGroupRec(group, next, new ArrayList<>(remaining));
252            remaining.removeAll(group);
253        }
254        return groups;
255    }
256
257    private static void extendGroupRec(List<WayData> group, WayData newGroupMember, List<WayData> remaining) {
258        group.add(newGroupMember);
259        for (int i = 0; i < remaining.size(); ++i) {
260            WayData candidate = remaining.get(i);
261            if (candidate == null) continue;
262            if (!Collections.disjoint(candidate.wayNodes, newGroupMember.wayNodes)) {
263                remaining.set(i, null);
264                extendGroupRec(group, candidate, remaining);
265            }
266        }
267    }
268
269    /**
270     * Try to orthogonalize the given ways by moving only a single given node
271     * @param wayDataList list of ways
272     * @param singleNode common node to ways to orthogonalize. Only this one will be moved
273     * @return the command to move the node
274     * @throws InvalidUserInputException if the command cannot be computed
275     */
276    private static Command orthogonalize(List<WayData> wayDataList, Node singleNode) throws InvalidUserInputException {
277        List<EastNorth> rightAnglePositions = new ArrayList<>();
278        int wayCount = wayDataList.size();
279        for (WayData wd : wayDataList) {
280            int n = wd.wayNodes.size();
281            int i = wd.wayNodes.indexOf(singleNode);
282            Node n0, n2;
283            if (i == 0 && n >= 3 && singleNode.equals(wd.wayNodes.get(n-1))) {
284                n0 = wd.wayNodes.get(n-2);
285                n2 = wd.wayNodes.get(1);
286            } else if (i > 0 && i < n-1) {
287                n0 = wd.wayNodes.get(i-1);
288                n2 = wd.wayNodes.get(i+1);
289            } else {
290                continue;
291            }
292            EastNorth n0en = n0.getEastNorth();
293            EastNorth n1en = singleNode.getEastNorth();
294            EastNorth n2en = n2.getEastNorth();
295            double angle = Geometry.getNormalizedAngleInDegrees(Geometry.getCornerAngle(n0en, n1en, n2en));
296            if (wayCount == 1 || (80 <= angle && angle <= 100)) {
297                EastNorth c = n0en.getCenter(n2en);
298                double r = n0en.distance(n2en) / 2d;
299                double vX = n1en.east() - c.east();
300                double vY = n1en.north() - c.north();
301                double magV = Math.sqrt(vX*vX + vY*vY);
302                rightAnglePositions.add(new EastNorth(c.east() + vX / magV * r,
303                                                     c.north() + vY / magV * r));
304            }
305        }
306        if (rightAnglePositions.isEmpty()) {
307            throw new InvalidUserInputException("Unable to orthogonalize " + singleNode);
308        }
309        return new MoveCommand(singleNode, Main.getProjection().eastNorth2latlon(Geometry.getCentroidEN(rightAnglePositions)));
310    }
311
312    /**
313     *
314     *  Outline:
315     *  1. Find direction of all segments
316     *      - direction = 0..3 (right,up,left,down)
317     *      - right is not really right, you may have to turn your screen
318     *  2. Find average heading of all segments
319     *      - heading = angle of a vector in polar coordinates
320     *      - sum up horizontal segments (those with direction 0 or 2)
321     *      - sum up vertical segments
322     *      - turn the vertical sum by 90 degrees and add it to the horizontal sum
323     *      - get the average heading from this total sum
324     *  3. Rotate all nodes by the average heading so that right is really right
325     *      and all segments are approximately NS or EW.
326     *  4. If nodes are connected by a horizontal segment: Replace their y-Coordinate by
327     *      the mean value of their y-Coordinates.
328     *      - The same for vertical segments.
329     *  5. Rotate back.
330     * @param wayDataList list of ways
331     * @param headingNodes list of heading nodes
332     * @return list of commands to perform
333     * @throws InvalidUserInputException if selected ways have an angle different from 90 or 180 degrees
334     **/
335    private static Collection<Command> orthogonalize(List<WayData> wayDataList, List<Node> headingNodes) throws InvalidUserInputException {
336        // find average heading
337        double headingAll;
338        try {
339            if (headingNodes.isEmpty()) {
340                // find directions of the segments and make them consistent between different ways
341                wayDataList.get(0).calcDirections(Direction.RIGHT);
342                double refHeading = wayDataList.get(0).heading;
343                EastNorth totSum = new EastNorth(0., 0.);
344                for (WayData w : wayDataList) {
345                    w.calcDirections(Direction.RIGHT);
346                    int directionOffset = angleToDirectionChange(w.heading - refHeading, TOLERANCE2);
347                    w.calcDirections(Direction.RIGHT.changeBy(directionOffset));
348                    if (angleToDirectionChange(refHeading - w.heading, TOLERANCE2) != 0)
349                        throw new JosmRuntimeException("orthogonalize error");
350                    totSum = EN.sum(totSum, w.segSum);
351                }
352                headingAll = EN.polar(EastNorth.ZERO, totSum);
353            } else {
354                headingAll = EN.polar(headingNodes.get(0).getEastNorth(), headingNodes.get(1).getEastNorth());
355                for (WayData w : wayDataList) {
356                    w.calcDirections(Direction.RIGHT);
357                    int directionOffset = angleToDirectionChange(w.heading - headingAll, TOLERANCE2);
358                    w.calcDirections(Direction.RIGHT.changeBy(directionOffset));
359                }
360            }
361        } catch (RejectedAngleException ex) {
362            throw new InvalidUserInputException(
363                    tr("<html>Please make sure all selected ways head in a similar direction<br>"+
364                    "or orthogonalize them one by one.</html>"), ex);
365        }
366
367        // put the nodes of all ways in a set
368        final Set<Node> allNodes = new HashSet<>();
369        for (WayData w : wayDataList) {
370            allNodes.addAll(w.wayNodes);
371        }
372
373        // the new x and y value for each node
374        final Map<Node, Double> nX = new HashMap<>();
375        final Map<Node, Double> nY = new HashMap<>();
376
377        // calculate the centroid of all nodes
378        // it is used as rotation center
379        EastNorth pivot = EastNorth.ZERO;
380        for (Node n : allNodes) {
381            pivot = EN.sum(pivot, n.getEastNorth());
382        }
383        pivot = new EastNorth(pivot.east() / allNodes.size(), pivot.north() / allNodes.size());
384
385        // rotate
386        for (Node n: allNodes) {
387            EastNorth tmp = EN.rotateCC(pivot, n.getEastNorth(), -headingAll);
388            nX.put(n, tmp.east());
389            nY.put(n, tmp.north());
390        }
391
392        // orthogonalize
393        final Direction[] horizontal = {Direction.RIGHT, Direction.LEFT};
394        final Direction[] vertical = {Direction.UP, Direction.DOWN};
395        final Direction[][] orientations = {horizontal, vertical};
396        for (Direction[] orientation : orientations) {
397            final Set<Node> s = new HashSet<>(allNodes);
398            int size = s.size();
399            for (int dummy = 0; dummy < size; ++dummy) {
400                if (s.isEmpty()) {
401                    break;
402                }
403                final Node dummyN = s.iterator().next();     // pick arbitrary element of s
404
405                final Set<Node> cs = new HashSet<>(); // will contain each node that can be reached from dummyN
406                cs.add(dummyN);                      // walking only on horizontal / vertical segments
407
408                boolean somethingHappened = true;
409                while (somethingHappened) {
410                    somethingHappened = false;
411                    for (WayData w : wayDataList) {
412                        for (int i = 0; i < w.nSeg; ++i) {
413                            Node n1 = w.wayNodes.get(i);
414                            Node n2 = w.wayNodes.get(i+1);
415                            if (Arrays.asList(orientation).contains(w.segDirections[i])) {
416                                if (cs.contains(n1) && !cs.contains(n2)) {
417                                    cs.add(n2);
418                                    somethingHappened = true;
419                                }
420                                if (cs.contains(n2) && !cs.contains(n1)) {
421                                    cs.add(n1);
422                                    somethingHappened = true;
423                                }
424                            }
425                        }
426                    }
427                }
428
429                final Map<Node, Double> nC = (orientation == horizontal) ? nY : nX;
430
431                double average = 0;
432                for (Node n : cs) {
433                    s.remove(n);
434                    average += nC.get(n).doubleValue();
435                }
436                average = average / cs.size();
437
438                // if one of the nodes is a heading node, forget about the average and use its value
439                for (Node fn : headingNodes) {
440                    if (cs.contains(fn)) {
441                        average = nC.get(fn);
442                    }
443                }
444
445                // At this point, the two heading nodes (if any) are horizontally aligned, i.e. they
446                // have the same y coordinate. So in general we shouldn't find them in a vertical string
447                // of segments. This can still happen in some pathological cases (see #7889). To avoid
448                // both heading nodes collapsing to one point, we simply skip this segment string and
449                // don't touch the node coordinates.
450                if (orientation == vertical && headingNodes.size() == 2 && cs.containsAll(headingNodes)) {
451                    continue;
452                }
453
454                for (Node n : cs) {
455                    nC.put(n, average);
456                }
457            }
458            if (!s.isEmpty()) throw new JosmRuntimeException("orthogonalize error");
459        }
460
461        // rotate back and log the change
462        final Collection<Command> commands = new LinkedList<>();
463        for (Node n: allNodes) {
464            EastNorth tmp = new EastNorth(nX.get(n), nY.get(n));
465            tmp = EN.rotateCC(pivot, tmp, headingAll);
466            final double dx = tmp.east() - n.getEastNorth().east();
467            final double dy = tmp.north() - n.getEastNorth().north();
468            if (headingNodes.contains(n)) { // The heading nodes should not have changed
469                if (Math.abs(dx) > Math.abs(EPSILON * tmp.east()) ||
470                    Math.abs(dy) > Math.abs(EPSILON * tmp.east()))
471                    throw new AssertionError("heading node has changed");
472            } else {
473                OrthogonalizeAction.rememberMovements.put(n, new EastNorth(dx, dy));
474                commands.add(new MoveCommand(n, dx, dy));
475            }
476        }
477        return commands;
478    }
479
480    /**
481     * Class contains everything we need to know about a single way.
482     */
483    private static class WayData {
484        /** The assigned way */
485        public final List<Node> wayNodes;
486        /** Number of Segments of the Way */
487        public final int nSeg;
488        /** Number of Nodes of the Way */
489        public final int nNode;
490        /** Direction of the segments */
491        public final Direction[] segDirections;
492        // segment i goes from node i to node (i+1)
493        /** (Vector-)sum of all horizontal segments plus the sum of all vertical */
494        public EastNorth segSum;
495        // segments turned by 90 degrees
496        /** heading of segSum == approximate heading of the way */
497        public double heading;
498
499        WayData(List<Node> wayNodes) {
500            this.wayNodes = wayNodes;
501            this.nNode = wayNodes.size();
502            this.nSeg = nNode - 1;
503            this.segDirections = new Direction[nSeg];
504        }
505
506        /**
507         * Estimate the direction of the segments, given the first segment points in the
508         * direction <code>pInitialDirection</code>.
509         * Then sum up all horizontal / vertical segments to have a good guess for the
510         * heading of the entire way.
511         * @param pInitialDirection initial direction
512         * @throws InvalidUserInputException if selected ways have an angle different from 90 or 180 degrees
513         */
514        public void calcDirections(Direction pInitialDirection) throws InvalidUserInputException {
515            final EastNorth[] en = new EastNorth[nNode]; // alias: wayNodes.get(i).getEastNorth() ---> en[i]
516            for (int i = 0; i < nNode; i++) {
517                en[i] = wayNodes.get(i).getEastNorth();
518            }
519            Direction direction = pInitialDirection;
520            segDirections[0] = direction;
521            for (int i = 0; i < nSeg - 1; i++) {
522                double h1 = EN.polar(en[i], en[i+1]);
523                double h2 = EN.polar(en[i+1], en[i+2]);
524                try {
525                    direction = direction.changeBy(angleToDirectionChange(h2 - h1, TOLERANCE1));
526                } catch (RejectedAngleException ex) {
527                    throw new InvalidUserInputException(tr("Please select ways with angles of approximately 90 or 180 degrees."), ex);
528                }
529                segDirections[i+1] = direction;
530            }
531
532            // sum up segments
533            EastNorth h = new EastNorth(0., 0.);
534            EastNorth v = new EastNorth(0., 0.);
535            for (int i = 0; i < nSeg; ++i) {
536                EastNorth segment = EN.diff(en[i+1], en[i]);
537                if (segDirections[i] == Direction.RIGHT) {
538                    h = EN.sum(h, segment);
539                } else if (segDirections[i] == Direction.UP) {
540                    v = EN.sum(v, segment);
541                } else if (segDirections[i] == Direction.LEFT) {
542                    h = EN.diff(h, segment);
543                } else if (segDirections[i] == Direction.DOWN) {
544                    v = EN.diff(v, segment);
545                } else throw new IllegalStateException();
546            }
547            // rotate the vertical vector by 90 degrees (clockwise) and add it to the horizontal vector
548            segSum = EN.sum(h, new EastNorth(v.north(), -v.east()));
549            this.heading = EN.polar(new EastNorth(0., 0.), segSum);
550        }
551    }
552
553    enum Direction {
554        RIGHT, UP, LEFT, DOWN;
555        public Direction changeBy(int directionChange) {
556            int tmp = (this.ordinal() + directionChange) % 4;
557            if (tmp < 0) {
558                tmp += 4;          // the % operator can return negative value
559            }
560            return Direction.values()[tmp];
561        }
562    }
563
564    /**
565     * Make sure angle (up to 2*Pi) is in interval [ 0, 2*Pi ).
566     * @param a angle
567     * @return correct angle
568     */
569    private static double standardAngle0to2PI(double a) {
570        while (a >= 2 * Math.PI) {
571            a -= 2 * Math.PI;
572        }
573        while (a < 0) {
574            a += 2 * Math.PI;
575        }
576        return a;
577    }
578
579    /**
580     * Make sure angle (up to 2*Pi) is in interval ( -Pi, Pi ].
581     * @param a angle
582     * @return correct angle
583     */
584    private static double standardAngleMPItoPI(double a) {
585        while (a > Math.PI) {
586            a -= 2 * Math.PI;
587        }
588        while (a <= -Math.PI) {
589            a += 2 * Math.PI;
590        }
591        return a;
592    }
593
594    /**
595     * Class contains some auxiliary functions
596     */
597    static final class EN {
598        private EN() {
599            // Hide implicit public constructor for utility class
600        }
601
602        /**
603         * Rotate counter-clock-wise.
604         * @param pivot pivot
605         * @param en original east/north
606         * @param angle angle, in radians
607         * @return new east/north
608         */
609        public static EastNorth rotateCC(EastNorth pivot, EastNorth en, double angle) {
610            double cosPhi = Math.cos(angle);
611            double sinPhi = Math.sin(angle);
612            double x = en.east() - pivot.east();
613            double y = en.north() - pivot.north();
614            double nx = cosPhi * x - sinPhi * y + pivot.east();
615            double ny = sinPhi * x + cosPhi * y + pivot.north();
616            return new EastNorth(nx, ny);
617        }
618
619        public static EastNorth sum(EastNorth en1, EastNorth en2) {
620            return new EastNorth(en1.east() + en2.east(), en1.north() + en2.north());
621        }
622
623        public static EastNorth diff(EastNorth en1, EastNorth en2) {
624            return new EastNorth(en1.east() - en2.east(), en1.north() - en2.north());
625        }
626
627        public static double polar(EastNorth en1, EastNorth en2) {
628            return PolarCoor.computeAngle(en2, en1);
629        }
630    }
631
632    /**
633     * Recognize angle to be approximately 0, 90, 180 or 270 degrees.
634     * returns an integral value, corresponding to a counter clockwise turn.
635     * @param a angle, in radians
636     * @param deltaMax maximum tolerance, in radians
637     * @return an integral value, corresponding to a counter clockwise turn
638     * @throws RejectedAngleException in case of invalid angle
639     */
640    private static int angleToDirectionChange(double a, double deltaMax) throws RejectedAngleException {
641        a = standardAngleMPItoPI(a);
642        double d0 = Math.abs(a);
643        double d90 = Math.abs(a - Math.PI / 2);
644        double dm90 = Math.abs(a + Math.PI / 2);
645        int dirChange;
646        if (d0 < deltaMax) {
647            dirChange = 0;
648        } else if (d90 < deltaMax) {
649            dirChange = 1;
650        } else if (dm90 < deltaMax) {
651            dirChange = -1;
652        } else {
653            a = standardAngle0to2PI(a);
654            double d180 = Math.abs(a - Math.PI);
655            if (d180 < deltaMax) {
656                dirChange = 2;
657            } else
658                throw new RejectedAngleException();
659        }
660        return dirChange;
661    }
662
663    /**
664     * Exception: unsuited user input
665     * @since 13670
666     */
667    public static final class InvalidUserInputException extends Exception {
668        InvalidUserInputException(String message) {
669            super(message);
670        }
671
672        InvalidUserInputException(String message, Throwable cause) {
673            super(message, cause);
674        }
675    }
676
677    /**
678     * Exception: angle cannot be recognized as 0, 90, 180 or 270 degrees
679     */
680    protected static class RejectedAngleException extends Exception {
681        RejectedAngleException() {
682            super();
683        }
684    }
685
686    @Override
687    protected void updateEnabledState() {
688        updateEnabledStateOnCurrentSelection();
689    }
690
691    @Override
692    protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
693        updateEnabledStateOnModifiableSelection(selection);
694    }
695}