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;
006import static org.openstreetmap.josm.tools.I18n.trn;
007
008import java.awt.GridBagLayout;
009import java.awt.event.ActionEvent;
010import java.awt.event.KeyEvent;
011import java.util.ArrayList;
012import java.util.Arrays;
013import java.util.Collection;
014import java.util.Collections;
015import java.util.HashSet;
016import java.util.LinkedList;
017import java.util.List;
018import java.util.Set;
019import java.util.stream.Collectors;
020
021import javax.swing.BorderFactory;
022import javax.swing.JCheckBox;
023import javax.swing.JLabel;
024import javax.swing.JOptionPane;
025import javax.swing.JPanel;
026import javax.swing.JSpinner;
027import javax.swing.SpinnerNumberModel;
028import javax.swing.SwingUtilities;
029
030import org.openstreetmap.josm.command.ChangeCommand;
031import org.openstreetmap.josm.command.Command;
032import org.openstreetmap.josm.command.DeleteCommand;
033import org.openstreetmap.josm.command.SequenceCommand;
034import org.openstreetmap.josm.data.SystemOfMeasurement;
035import org.openstreetmap.josm.data.UndoRedoHandler;
036import org.openstreetmap.josm.data.osm.DataSet;
037import org.openstreetmap.josm.data.osm.Node;
038import org.openstreetmap.josm.data.osm.OsmPrimitive;
039import org.openstreetmap.josm.data.osm.Way;
040import org.openstreetmap.josm.data.projection.Ellipsoid;
041import org.openstreetmap.josm.gui.ExtendedDialog;
042import org.openstreetmap.josm.gui.HelpAwareOptionPane;
043import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
044import org.openstreetmap.josm.gui.MainApplication;
045import org.openstreetmap.josm.gui.Notification;
046import org.openstreetmap.josm.spi.preferences.Config;
047import org.openstreetmap.josm.spi.preferences.IPreferences;
048import org.openstreetmap.josm.tools.GBC;
049import org.openstreetmap.josm.tools.ImageProvider;
050import org.openstreetmap.josm.tools.Shortcut;
051
052/**
053 * Delete unnecessary nodes from a way
054 * @since 2575
055 */
056public class SimplifyWayAction extends JosmAction {
057
058    /**
059     * Constructs a new {@code SimplifyWayAction}.
060     */
061    public SimplifyWayAction() {
062        super(tr("Simplify Way"), "simplify", tr("Delete unnecessary nodes from a way."),
063                Shortcut.registerShortcut("tools:simplify", tr("Tool: {0}", tr("Simplify Way")), KeyEvent.VK_Y, Shortcut.SHIFT), true);
064        setHelpId(ht("/Action/SimplifyWay"));
065    }
066
067    protected boolean confirmWayWithNodesOutsideBoundingBox(List<? extends OsmPrimitive> primitives) {
068        return DeleteAction.checkAndConfirmOutlyingDelete(primitives, null);
069    }
070
071    protected void alertSelectAtLeastOneWay() {
072        SwingUtilities.invokeLater(() ->
073            new Notification(
074                    tr("Please select at least one way to simplify."))
075                    .setIcon(JOptionPane.WARNING_MESSAGE)
076                    .setDuration(Notification.TIME_SHORT)
077                    .setHelpTopic(ht("/Action/SimplifyWay#SelectAWayToSimplify"))
078                    .show()
079        );
080    }
081
082    protected boolean confirmSimplifyManyWays(int numWays) {
083        ButtonSpec[] options = {
084                new ButtonSpec(
085                        tr("Yes"),
086                        new ImageProvider("ok"),
087                        tr("Simplify all selected ways"),
088                        null),
089                new ButtonSpec(
090                        tr("Cancel"),
091                        new ImageProvider("cancel"),
092                        tr("Cancel operation"),
093                        null)
094        };
095        return 0 == HelpAwareOptionPane.showOptionDialog(
096                MainApplication.getMainFrame(),
097                tr("The selection contains {0} ways. Are you sure you want to simplify them all?", numWays),
098                tr("Simplify ways?"),
099                JOptionPane.WARNING_MESSAGE,
100                null, // no special icon
101                options,
102                options[0],
103                ht("/Action/SimplifyWay#ConfirmSimplifyAll")
104                );
105    }
106
107    /**
108     * Asks the user for max-err value used to simplify ways, if not remembered before
109     * @param text the text being shown
110     * @param auto whether it's called automatically (conversion) or by the user
111     * @return the max-err value or -1 if canceled
112     * @since 15419
113     */
114    public static double askSimplifyWays(String text, boolean auto) {
115        IPreferences s = Config.getPref();
116        String key = "simplify-way." + (auto ? "auto." : "");
117        String keyRemember = key + "remember";
118        String keyError = key + "max-error";
119
120        String r = s.get(keyRemember, "ask");
121        if (auto && "no".equals(r)) {
122            return -1;
123        } else if ("yes".equals(r)) {
124            return s.getDouble(keyError, 3.0);
125        }
126
127        JPanel p = new JPanel(new GridBagLayout());
128        p.add(new JLabel("<html><body style=\"width: 375px;\">" + text + "<br><br>" +
129                tr("This reduces unnecessary nodes along the way and is especially recommended if GPS tracks were recorded by time "
130                 + "(e.g. one point per second) or when the accuracy was low (reduces \"zigzag\" tracks).")
131                + "</body></html>"), GBC.eol());
132        p.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 5));
133        JPanel q = new JPanel(new GridBagLayout());
134        q.add(new JLabel(tr("Maximum error (meters): ")));
135        JSpinner n = new JSpinner(new SpinnerNumberModel(
136                s.getDouble(keyError, 3.0), 0.01, null, 0.5));
137        ((JSpinner.DefaultEditor) n.getEditor()).getTextField().setColumns(4);
138        q.add(n);
139        q.setBorder(BorderFactory.createEmptyBorder(14, 0, 10, 0));
140        p.add(q, GBC.eol());
141        JCheckBox c = new JCheckBox(tr("Do not ask again"));
142        p.add(c, GBC.eol());
143
144        ExtendedDialog ed = new ExtendedDialog(MainApplication.getMainFrame(),
145                tr("Simplify way"), tr("Simplify"),
146                auto ? tr("Proceed without simplifying") : tr("Cancel"))
147                .setContent(p)
148                .configureContextsensitiveHelp(("Action/SimplifyWay"), true);
149        if (auto) {
150            ed.setButtonIcons("simplify", "ok");
151        } else {
152            ed.setButtonIcons("ok", "cancel");
153        }
154
155        int ret = ed.showDialog().getValue();
156        double val = (double) n.getValue();
157        if (ret == 1) {
158            s.putDouble(keyError, val);
159            if (c.isSelected()) {
160                s.put(keyRemember, "yes");
161            }
162            return val;
163        } else {
164            if (auto && c.isSelected()) { //do not remember cancel for manual simplify, otherwise nothing would happen
165                s.put(keyRemember, "no");
166            }
167            return -1;
168        }
169    }
170
171    @Override
172    public void actionPerformed(ActionEvent e) {
173        DataSet ds = getLayerManager().getEditDataSet();
174        ds.beginUpdate();
175        try {
176            List<Way> ways = ds.getSelectedWays().stream()
177                    .filter(p -> !p.isIncomplete())
178                    .collect(Collectors.toList());
179            if (ways.isEmpty()) {
180                alertSelectAtLeastOneWay();
181                return;
182            } else if (!confirmWayWithNodesOutsideBoundingBox(ways) || (ways.size() > 10 && !confirmSimplifyManyWays(ways.size()))) {
183                return;
184            }
185
186            String lengthstr = SystemOfMeasurement.getSystemOfMeasurement().getDistText(
187                    ways.stream().mapToDouble(Way::getLength).sum());
188
189            double err = askSimplifyWays(trn(
190                    "You are about to simplify {0} way with a total length of {1}.",
191                    "You are about to simplify {0} ways with a total length of {1}.",
192                    ways.size(), ways.size(), lengthstr), false);
193
194            if (err > 0) {
195                simplifyWays(ways, err);
196            }
197        } finally {
198            ds.endUpdate();
199        }
200    }
201
202    /**
203     * Replies true if <code>node</code> is a required node which can't be removed
204     * in order to simplify the way.
205     *
206     * @param way the way to be simplified
207     * @param node the node to check
208     * @param multipleUseNodes set of nodes which is used more than once in the way
209     * @return true if <code>node</code> is a required node which can't be removed
210     * in order to simplify the way.
211     */
212    protected static boolean isRequiredNode(Way way, Node node, Set<Node> multipleUseNodes) {
213        boolean isRequired = node.isTagged();
214        if (!isRequired && multipleUseNodes.contains(node)) {
215            int frequency = Collections.frequency(way.getNodes(), node);
216            if ((way.getNode(0) == node) && (way.getNode(way.getNodesCount()-1) == node)) {
217                frequency = frequency - 1; // closed way closing node counted only once
218            }
219            isRequired = frequency > 1;
220        }
221        if (!isRequired) {
222            List<OsmPrimitive> parents = new LinkedList<>();
223            parents.addAll(node.getReferrers());
224            parents.remove(way);
225            isRequired = !parents.isEmpty();
226        }
227        return isRequired;
228    }
229
230    /**
231     * Calculate a set of nodes which occurs more than once in the way
232     * @param w the way
233     * @return a set of nodes which occurs more than once in the way
234     */
235    private static Set<Node> getMultiUseNodes(Way w) {
236        Set<Node> multipleUseNodes = new HashSet<>();
237        Set<Node> allNodes = new HashSet<>();
238        for (Node n : w.getNodes()) {
239            if (!allNodes.add(n))
240                multipleUseNodes.add(n);
241        }
242        return multipleUseNodes;
243    }
244
245    /**
246     * Runs the commands to simplify the ways with the given threshold
247     *
248     * @param ways the ways to simplify
249     * @param threshold the max error threshold
250     * @since 15419
251     */
252    public static void simplifyWays(List<Way> ways, double threshold) {
253        Collection<Command> allCommands = new LinkedList<>();
254        for (Way way : ways) {
255            SequenceCommand simplifyCommand = createSimplifyCommand(way, threshold);
256            if (simplifyCommand == null) {
257                continue;
258            }
259            allCommands.add(simplifyCommand);
260        }
261        if (allCommands.isEmpty())
262            return;
263        SequenceCommand rootCommand = new SequenceCommand(
264                trn("Simplify {0} way", "Simplify {0} ways", allCommands.size(), allCommands.size()),
265                allCommands);
266        UndoRedoHandler.getInstance().add(rootCommand);
267    }
268
269    /**
270     * Creates the SequenceCommand to simplify a way with default threshold.
271     *
272     * @param w the way to simplify
273     * @return The sequence of commands to run
274     * @since 6411
275     * @deprecated Replaced by {@link #createSimplifyCommand(Way)}. You can also use {@link #simplifyWays(List, double)} directly.
276     */
277    @Deprecated
278    public final SequenceCommand simplifyWay(Way w) {
279        return createSimplifyCommand(w);
280    }
281
282    /**
283     * Creates the SequenceCommand to simplify a way with a given threshold.
284     *
285     * @param w the way to simplify
286     * @param threshold the max error threshold
287     * @return The sequence of commands to run
288     * @since 6411
289     * @deprecated Replaced by {@link #createSimplifyCommand(Way, double)}. You can also use {@link #simplifyWays(List, double)} directly.
290     */
291    @Deprecated
292    public static SequenceCommand simplifyWay(Way w, double threshold) {
293        return createSimplifyCommand(w, threshold);
294    }
295
296    /**
297     * Creates the SequenceCommand to simplify a way with default threshold.
298     *
299     * @param w the way to simplify
300     * @return The sequence of commands to run
301     * @since 15419
302     */
303    public static SequenceCommand createSimplifyCommand(Way w) {
304        return createSimplifyCommand(w, Config.getPref().getDouble("simplify-way.max-error", 3.0));
305    }
306
307    /**
308     * Creates the SequenceCommand to simplify a way with a given threshold.
309     *
310     * @param w the way to simplify
311     * @param threshold the max error threshold
312     * @return The sequence of commands to run
313     * @since 15419
314     */
315    public static SequenceCommand createSimplifyCommand(Way w, double threshold) {
316        int lower = 0;
317        int i = 0;
318
319        Set<Node> multipleUseNodes = getMultiUseNodes(w);
320        List<Node> newNodes = new ArrayList<>(w.getNodesCount());
321        while (i < w.getNodesCount()) {
322            if (isRequiredNode(w, w.getNode(i), multipleUseNodes)) {
323                // copy a required node to the list of new nodes. Simplify not possible
324                newNodes.add(w.getNode(i));
325                i++;
326                lower++;
327                continue;
328            }
329            i++;
330            // find the longest sequence of not required nodes ...
331            while (i < w.getNodesCount() && !isRequiredNode(w, w.getNode(i), multipleUseNodes)) {
332                i++;
333            }
334            // ... and simplify them
335            buildSimplifiedNodeList(w.getNodes(), lower, Math.min(w.getNodesCount()-1, i), threshold, newNodes);
336            lower = i;
337            i++;
338        }
339
340        // Closed way, check if the first node could also be simplified ...
341        if (newNodes.size() > 3 && newNodes.get(0) == newNodes.get(newNodes.size() - 1)
342                && !isRequiredNode(w, newNodes.get(0), multipleUseNodes)) {
343            final List<Node> l1 = Arrays.asList(newNodes.get(newNodes.size() - 2), newNodes.get(0), newNodes.get(1));
344            final List<Node> l2 = new ArrayList<>(3);
345            buildSimplifiedNodeList(l1, 0, 2, threshold, l2);
346            if (!l2.contains(newNodes.get(0))) {
347                newNodes.remove(0);
348                newNodes.set(newNodes.size() - 1, newNodes.get(0)); // close the way
349            }
350        }
351
352        if (newNodes.size() == w.getNodesCount()) return null;
353
354        Set<Node> delNodes = new HashSet<>(w.getNodes());
355        delNodes.removeAll(newNodes);
356
357        if (delNodes.isEmpty()) return null;
358
359        Collection<Command> cmds = new LinkedList<>();
360        Way newWay = new Way(w);
361        newWay.setNodes(newNodes);
362        cmds.add(new ChangeCommand(w, newWay));
363        cmds.add(new DeleteCommand(w.getDataSet(), delNodes));
364        w.getDataSet().clearSelection(delNodes);
365        return new SequenceCommand(
366                trn("Simplify Way (remove {0} node)", "Simplify Way (remove {0} nodes)", delNodes.size(), delNodes.size()), cmds);
367    }
368
369    /**
370     * Builds the simplified list of nodes for a way segment given by a lower index <code>from</code>
371     * and an upper index <code>to</code>
372     *
373     * @param wnew the way to simplify
374     * @param from the lower index
375     * @param to the upper index
376     * @param threshold the max error threshold
377     * @param simplifiedNodes list that will contain resulting nodes
378     */
379    protected static void buildSimplifiedNodeList(List<Node> wnew, int from, int to, double threshold, List<Node> simplifiedNodes) {
380
381        Node fromN = wnew.get(from);
382        Node toN = wnew.get(to);
383
384        // Get max xte
385        int imax = -1;
386        double xtemax = 0;
387        for (int i = from + 1; i < to; i++) {
388            Node n = wnew.get(i);
389            // CHECKSTYLE.OFF: SingleSpaceSeparator
390            double xte = Math.abs(Ellipsoid.WGS84.a
391                    * xtd(fromN.lat() * Math.PI / 180, fromN.lon() * Math.PI / 180, toN.lat() * Math.PI / 180,
392                            toN.lon() * Math.PI / 180,     n.lat() * Math.PI / 180,   n.lon() * Math.PI / 180));
393            // CHECKSTYLE.ON: SingleSpaceSeparator
394            if (xte > xtemax) {
395                xtemax = xte;
396                imax = i;
397            }
398        }
399
400        if (imax != -1 && xtemax >= threshold) {
401            // Segment cannot be simplified - try shorter segments
402            buildSimplifiedNodeList(wnew, from, imax, threshold, simplifiedNodes);
403            buildSimplifiedNodeList(wnew, imax, to, threshold, simplifiedNodes);
404        } else {
405            // Simplify segment
406            if (simplifiedNodes.isEmpty() || simplifiedNodes.get(simplifiedNodes.size()-1) != fromN) {
407                simplifiedNodes.add(fromN);
408            }
409            if (fromN != toN) {
410                simplifiedNodes.add(toN);
411            }
412        }
413    }
414
415    /* From Aviaton Formulary v1.3
416     * http://williams.best.vwh.net/avform.htm
417     */
418    private static double dist(double lat1, double lon1, double lat2, double lon2) {
419        return 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2), 2) + Math.cos(lat1) * Math.cos(lat2)
420                * Math.pow(Math.sin((lon1 - lon2) / 2), 2)));
421    }
422
423    private static double course(double lat1, double lon1, double lat2, double lon2) {
424        return Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
425                * Math.cos(lat2) * Math.cos(lon1 - lon2))
426                % (2 * Math.PI);
427    }
428
429    private static double xtd(double lat1, double lon1, double lat2, double lon2, double lat3, double lon3) {
430        double distAD = dist(lat1, lon1, lat3, lon3);
431        double crsAD = course(lat1, lon1, lat3, lon3);
432        double crsAB = course(lat1, lon1, lat2, lon2);
433        return Math.asin(Math.sin(distAD) * Math.sin(crsAD - crsAB));
434    }
435
436    @Override
437    protected void updateEnabledState() {
438        updateEnabledStateOnCurrentSelection();
439    }
440
441    @Override
442    protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
443        updateEnabledStateOnModifiableSelection(selection);
444    }
445}