001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004import static java.util.function.Predicate.not;
005import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
006import static org.openstreetmap.josm.tools.I18n.tr;
007
008import java.awt.event.ActionEvent;
009import java.awt.event.KeyEvent;
010import java.util.ArrayList;
011import java.util.Collection;
012import java.util.Collections;
013import java.util.HashSet;
014import java.util.LinkedList;
015import java.util.List;
016import java.util.Set;
017import java.util.SortedMap;
018import java.util.TreeMap;
019import java.util.stream.Collectors;
020
021import javax.swing.JOptionPane;
022
023import org.openstreetmap.josm.command.Command;
024import org.openstreetmap.josm.command.MoveCommand;
025import org.openstreetmap.josm.command.SequenceCommand;
026import org.openstreetmap.josm.data.UndoRedoHandler;
027import org.openstreetmap.josm.data.coor.EastNorth;
028import org.openstreetmap.josm.data.coor.PolarCoor;
029import org.openstreetmap.josm.data.osm.DataSet;
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.osm.visitor.paint.relations.Multipolygon;
034import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.JoinedWay;
035import org.openstreetmap.josm.data.validation.tests.CrossingWays;
036import org.openstreetmap.josm.data.validation.tests.SelfIntersectingWay;
037import org.openstreetmap.josm.gui.Notification;
038import org.openstreetmap.josm.tools.Geometry;
039import org.openstreetmap.josm.tools.Logging;
040import org.openstreetmap.josm.tools.Shortcut;
041
042/**
043 * Aligns all selected nodes within a circle. (Useful for roundabouts)
044 *
045 * @author Matthew Newton
046 * @author Petr Dlouhý
047 * @author Teemu Koskinen
048 * @author Alain Delplanque
049 * @author Gerd Petermann
050 *
051 * @since 146
052 */
053public final class AlignInCircleAction extends JosmAction {
054
055    /**
056     * Constructs a new {@code AlignInCircleAction}.
057     */
058    public AlignInCircleAction() {
059        super(tr("Align Nodes in Circle"), "aligncircle", tr("Move the selected nodes into a circle."),
060                Shortcut.registerShortcut("tools:aligncircle", tr("Tools: {0}", tr("Align Nodes in Circle")),
061                        KeyEvent.VK_O, Shortcut.DIRECT), true);
062        setHelpId(ht("/Action/AlignInCircle"));
063    }
064
065    /**
066     * InvalidSelection exception has to be raised when action can't be performed
067     */
068    public static class InvalidSelection extends Exception {
069
070        /**
071         * Create an InvalidSelection exception with default message
072         */
073        InvalidSelection() {
074            super(tr("Selection could not be used to align in circle."));
075        }
076
077        /**
078         * Create an InvalidSelection exception with specific message
079         * @param msg Message that will be displayed to the user
080         */
081        InvalidSelection(String msg) {
082            super(msg);
083        }
084    }
085
086    /**
087     * Add a {@link MoveCommand} to move a node to a PolarCoor if there is a significant move.
088     * @param n Node to move
089     * @param coor polar coordinate where to move the node
090     * @param cmds list of commands
091     * @since 17386
092     */
093    public static void addMoveCommandIfNeeded(Node n, PolarCoor coor, List<Command> cmds) {
094        EastNorth en = coor.toEastNorth();
095        double deltaEast = en.east() - n.getEastNorth().east();
096        double deltaNorth = en.north() - n.getEastNorth().north();
097
098        if (Math.abs(deltaEast) > 5e-6 || Math.abs(deltaNorth) > 5e-6) {
099            cmds.add(new MoveCommand(n, deltaEast, deltaNorth));
100        }
101    }
102
103    /**
104     * Perform AlignInCircle action.
105     *
106     */
107    @Override
108    public void actionPerformed(ActionEvent e) {
109        if (!isEnabled())
110            return;
111
112        try {
113            Command cmd = buildCommand(getLayerManager().getEditDataSet());
114            if (cmd != null)
115                UndoRedoHandler.getInstance().add(cmd);
116            else {
117                new Notification(tr("Nothing changed"))
118                .setIcon(JOptionPane.INFORMATION_MESSAGE)
119                .setDuration(Notification.TIME_SHORT)
120                .show();
121
122            }
123        } catch (InvalidSelection except) {
124            Logging.debug(except);
125            new Notification(except.getMessage())
126                .setIcon(JOptionPane.INFORMATION_MESSAGE)
127                .setDuration(Notification.TIME_SHORT)
128                .show();
129        }
130    }
131
132    /**
133     * Builds "align in circle" command depending on the selected objects.
134     * A fixed node is a node for which it is forbidden to change the angle relative to center of the circle.
135     * All other nodes are uniformly distributed.
136     * <p>
137     * Case 1: One unclosed way.
138     * → allow action, and align selected way nodes
139     * If nodes contained by this way are selected, there are fix.
140     * If nodes outside from the way are selected there are ignored.
141     * <p>
142     * Case 2: One or more ways are selected and can be joined into a polygon
143     * → allow action, and align selected ways nodes
144     * If 1 node outside of way is selected, it became center
145     * If 1 node outside and 1 node inside are selected there define center and radius
146     * If no outside node and 2 inside nodes are selected those 2 nodes define diameter
147     * In all other cases outside nodes are ignored
148     * In all cases, selected nodes are fix, nodes with more than one referrers are fix
149     * (first referrer is the selected way)
150     * <p>
151     * Case 3: Only nodes are selected
152     * → Align these nodes, all are fix
153     * <p>
154     * Case 4: Circularize selected ways
155     * → Circularize each way of the selection.
156     * @param ds data set in which the command operates
157     * @return the resulting command to execute to perform action, or null if nothing was changed
158     * @throws InvalidSelection if selection cannot be used
159     * @since 17386
160     *
161     */
162    public static Command buildCommand(DataSet ds) throws InvalidSelection {
163        Collection<OsmPrimitive> sel = ds.getSelected();
164        List<Node> selectedNodes = new LinkedList<>();
165        // fixNodes: All nodes for which the angle relative to center should not be modified
166        Set<Node> fixNodes = new HashSet<>();
167        List<Way> ways = new LinkedList<>();
168        EastNorth center = null;
169        double radius = 0;
170
171        for (OsmPrimitive osm : sel) {
172            if (osm instanceof Node) {
173                selectedNodes.add((Node) osm);
174            } else if (osm instanceof Way) {
175                ways.add((Way) osm);
176            }
177        }
178
179        // nodes on selected ways
180        List<Node> onWay = new ArrayList<>();
181        if (!ways.isEmpty()) {
182            List<Node> potentialCenter = new ArrayList<>();
183            for (Node n : selectedNodes) {
184                if (ways.stream().anyMatch(w -> w.containsNode(n))) {
185                    onWay.add(n);
186                } else {
187                    potentialCenter.add(n);
188                }
189            }
190            if (potentialCenter.size() == 1) {
191                // center is given
192                center = potentialCenter.get(0).getEastNorth();
193                if (onWay.size() == 1) {
194                    radius = center.distance(onWay.get(0).getEastNorth());
195                }
196            } else if (potentialCenter.size() > 1) {
197                throw new InvalidSelection(tr("Please select only one node as center."));
198            }
199
200        }
201
202        final List<Node> nodes;
203        if (ways.isEmpty()) {
204            nodes = sortByAngle(selectedNodes);
205            fixNodes.addAll(nodes);
206        } else if (ways.size() == 1 && !ways.get(0).isClosed()) {
207            // Case 1
208            Way w = ways.get(0);
209            fixNodes.add(w.firstNode());
210            fixNodes.add(w.lastNode());
211            fixNodes.addAll(onWay);
212            // Temporary closed way used to reorder nodes
213            Way closedWay = new Way(w);
214            try {
215                closedWay.addNode(w.firstNode());
216                nodes = collectNodesAnticlockwise(Collections.singletonList(closedWay));
217            } finally {
218                closedWay.setNodes(null); // see #19885
219            }
220        } else if (Multipolygon.joinWays(ways).size() == 1) {
221            // Case 2:
222            if (onWay.size() == 2) {
223                // 2 way nodes define diameter
224                EastNorth en0 = onWay.get(0).getEastNorth();
225                EastNorth en1 = onWay.get(1).getEastNorth();
226                radius = en0.distance(en1) / 2;
227                if (center == null) {
228                    center = en0.getCenter(en1);
229                }
230            }
231            fixNodes.addAll(onWay);
232            nodes = collectNodesAnticlockwise(ways);
233        } else if (!ways.isEmpty() && selectedNodes.isEmpty()) {
234            List<Command> rcmds = new LinkedList<>();
235            for (Way w : ways) {
236                if (!w.isDeleted() && w.isArea()) {
237                    List<Node> wnodes = w.getNodes();
238                    wnodes.remove(wnodes.size() - 1);
239                    if (validateGeometry(wnodes)) {
240                        center = Geometry.getCenter(wnodes);
241                    }
242                    if (center == null) {
243                        continue;
244                    }
245                    boolean skipThisWay = false;
246                    radius = 0;
247                    for (Node n : wnodes) {
248                        if (!n.isLatLonKnown()) {
249                            skipThisWay = true;
250                            break;
251                        } else {
252                            radius += center.distance(n.getEastNorth());
253                        }
254                    }
255                    if (skipThisWay) {
256                        continue;
257                    } else {
258                        radius /= wnodes.size();
259                    }
260                    Command c = moveNodesCommand(wnodes, Collections.emptySet(), center, radius);
261                    if (c != null) {
262                        rcmds.add(c);
263                    }
264                }
265            }
266            if (rcmds.isEmpty()) {
267                throw new InvalidSelection();
268            }
269            return new SequenceCommand(tr("Align each Way in Circle"), rcmds);
270        } else {
271            throw new InvalidSelection();
272        }
273        fixNodes.addAll(collectNodesWithExternReferrers(ways));
274
275        // Check if one or more nodes does not have all parents available
276        if (nodes.stream().anyMatch(not(Node::isReferrersDownloaded)))
277            throw new InvalidSelection(tr("One or more nodes involved in this action may have additional referrers."));
278
279
280        if (center == null) {
281            if (nodes.size() < 4) {
282                throw new InvalidSelection(tr("Not enough nodes to calculate center."));
283            }
284            if (validateGeometry(nodes)) {
285                // Compute the center of nodes
286                center = Geometry.getCenter(nodes);
287            }
288            if (center == null) {
289                throw new InvalidSelection(tr("Cannot determine center of circle for this geometry."));
290            }
291        }
292
293        // Now calculate the average distance to each node from the
294        // center. This method is ok as long as distances are short
295        // relative to the distance from the N or S poles.
296        if (radius == 0) {
297            for (Node n : nodes) {
298                radius += center.distance(n.getEastNorth());
299            }
300            radius = radius / nodes.size();
301        }
302        return moveNodesCommand(nodes, fixNodes, center, radius);
303    }
304
305    /**
306     * Move each node of the list of nodes to be arranged in a circle.
307     * @param nodes The list of nodes to be moved.
308     * @param fixNodes The list of nodes that must not be moved.
309     * @param center A center of the circle formed by the nodes.
310     * @param radius A radius of the circle formed by the nodes.
311     * @return the command that arranges the nodes in a circle.
312     * @since 18615
313     */
314    public static Command moveNodesCommand(
315            List<Node> nodes,
316            Set<Node> fixNodes,
317            EastNorth center,
318            double radius) {
319        List<Command> cmds = new LinkedList<>();
320
321        // Move each node to that distance from the center.
322        // Nodes that are not "fix" will be adjust making regular arcs.
323        int nodeCount = nodes.size();
324        // Search first fixed node
325        int startPosition;
326        for (startPosition = 0; startPosition < nodeCount; startPosition++) {
327            if (fixNodes.contains(nodes.get(startPosition % nodeCount)))
328                break;
329        }
330        int i = startPosition; // Start position for current arc
331        int j; // End position for current arc
332        while (i < startPosition + nodeCount) {
333            for (j = i + 1; j < startPosition + nodeCount; j++) {
334                if (fixNodes.contains(nodes.get(j % nodeCount)))
335                    break;
336            }
337            Node first = nodes.get(i % nodeCount);
338            PolarCoor pcFirst = new PolarCoor(radius, PolarCoor.computeAngle(first.getEastNorth(), center), center);
339            addMoveCommandIfNeeded(first, pcFirst, cmds);
340            if (j > i + 1) {
341                double delta;
342                if (j == i + nodeCount) {
343                    delta = 2 * Math.PI / nodeCount;
344                } else {
345                    PolarCoor pcLast = new PolarCoor(nodes.get(j % nodeCount).getEastNorth(), center);
346                    delta = pcLast.angle - pcFirst.angle;
347                    if (delta < 0) // Assume each PolarCoor.angle is in range ]-pi; pi]
348                        delta += 2*Math.PI;
349                    delta /= j - i;
350                }
351                for (int k = i+1; k < j; k++) {
352                    PolarCoor p = new PolarCoor(radius, pcFirst.angle + (k-i)*delta, center);
353                    addMoveCommandIfNeeded(nodes.get(k % nodeCount), p, cmds);
354                }
355            }
356            i = j; // Update start point for next iteration
357        }
358        if (cmds.isEmpty())
359            return null;
360        return new SequenceCommand(tr("Align Nodes in Circle"), cmds);
361    }
362
363    private static List<Node> sortByAngle(final List<Node> nodes) {
364        EastNorth sum = new EastNorth(0, 0);
365        for (Node n : nodes) {
366            EastNorth en = n.getEastNorth();
367            sum = sum.add(en.east(), en.north());
368        }
369        final EastNorth simpleCenter = new EastNorth(sum.east()/nodes.size(), sum.north()/nodes.size());
370
371        SortedMap<Double, List<Node>> orderedMap = new TreeMap<>();
372        for (Node n : nodes) {
373            double angle = new PolarCoor(n.getEastNorth(), simpleCenter).angle;
374            orderedMap.computeIfAbsent(angle, k-> new ArrayList<>()).add(n);
375        }
376        return orderedMap.values().stream().flatMap(List<Node>::stream).collect(Collectors.toList());
377    }
378
379    private static boolean validateGeometry(List<Node> nodes) {
380        Way test = new Way();
381        test.setNodes(nodes);
382        if (!test.isClosed()) {
383            test.addNode(test.firstNode());
384        }
385
386        try {
387            if (CrossingWays.isSelfCrossing(test))
388                return false;
389            return !SelfIntersectingWay.isSelfIntersecting(test);
390        } finally {
391            test.setNodes(null); // see #19855
392        }
393    }
394
395    /**
396     * Collect all nodes with more than one referrer.
397     * @param ways Ways from witch nodes are selected
398     * @return List of nodes with more than one referrer
399     */
400    private static List<Node> collectNodesWithExternReferrers(List<Way> ways) {
401        return ways.stream().flatMap(w -> w.getNodes().stream()).filter(n -> n.getReferrers().size() > 1).collect(Collectors.toList());
402    }
403
404    /**
405     * Assuming all ways can be joined into polygon, create an ordered list of node.
406     * @param ways List of ways to be joined
407     * @return Nodes anticlockwise ordered
408     * @throws InvalidSelection if selection cannot be used
409     */
410    private static List<Node> collectNodesAnticlockwise(List<Way> ways) throws InvalidSelection {
411        Collection<JoinedWay> rings = Multipolygon.joinWays(ways);
412        if (rings.size() != 1)
413            throw new InvalidSelection(); // we should never get here
414        List<Node> nodes = new ArrayList<>(rings.iterator().next().getNodes());
415        if (nodes.get(0) != nodes.get(nodes.size() - 1))
416            throw new InvalidSelection();
417        if (Geometry.isClockwise(nodes))
418            Collections.reverse(nodes);
419        nodes.remove(nodes.size() - 1);
420        return nodes;
421    }
422
423    @Override
424    protected void updateEnabledState() {
425        DataSet ds = getLayerManager().getEditDataSet();
426        setEnabled(ds != null && !ds.selectionEmpty());
427    }
428
429    @Override
430    protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
431        updateEnabledStateOnModifiableSelection(selection);
432    }
433}