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