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