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.event.ActionEvent;
009import java.awt.event.KeyEvent;
010import java.util.ArrayList;
011import java.util.Collection;
012import java.util.Collections;
013import java.util.LinkedHashSet;
014import java.util.LinkedList;
015import java.util.List;
016import java.util.Objects;
017import java.util.stream.Collectors;
018import java.util.stream.IntStream;
019
020import javax.swing.JOptionPane;
021
022import org.openstreetmap.josm.actions.corrector.ReverseWayTagCorrector;
023import org.openstreetmap.josm.command.ChangeNodesCommand;
024import org.openstreetmap.josm.command.Command;
025import org.openstreetmap.josm.command.DeleteCommand;
026import org.openstreetmap.josm.command.SequenceCommand;
027import org.openstreetmap.josm.data.UndoRedoHandler;
028import org.openstreetmap.josm.data.osm.DataSet;
029import org.openstreetmap.josm.data.osm.Node;
030import org.openstreetmap.josm.data.osm.NodeGraph;
031import org.openstreetmap.josm.data.osm.OsmPrimitive;
032import org.openstreetmap.josm.data.osm.OsmUtils;
033import org.openstreetmap.josm.data.osm.TagCollection;
034import org.openstreetmap.josm.data.osm.Way;
035import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon;
036import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.JoinedWay;
037import org.openstreetmap.josm.data.preferences.BooleanProperty;
038import org.openstreetmap.josm.data.validation.Test;
039import org.openstreetmap.josm.data.validation.tests.OverlappingWays;
040import org.openstreetmap.josm.data.validation.tests.SelfIntersectingWay;
041import org.openstreetmap.josm.gui.ExtendedDialog;
042import org.openstreetmap.josm.gui.MainApplication;
043import org.openstreetmap.josm.gui.Notification;
044import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
045import org.openstreetmap.josm.gui.util.GuiHelper;
046import org.openstreetmap.josm.tools.Logging;
047import org.openstreetmap.josm.tools.Pair;
048import org.openstreetmap.josm.tools.Shortcut;
049import org.openstreetmap.josm.tools.UserCancelException;
050import org.openstreetmap.josm.tools.Utils;
051
052/**
053 * Combines multiple ways into one.
054 * @since 213
055 */
056public class CombineWayAction extends JosmAction {
057
058    private static final BooleanProperty PROP_REVERSE_WAY = new BooleanProperty("tag-correction.reverse-way", true);
059
060    /**
061     * Constructs a new {@code CombineWayAction}.
062     */
063    public CombineWayAction() {
064        super(tr("Combine Way"), "combineway", tr("Combine several ways into one."),
065                Shortcut.registerShortcut("tools:combineway", tr("Tools: {0}", tr("Combine Way")), KeyEvent.VK_C, Shortcut.DIRECT), true);
066        setHelpId(ht("/Action/CombineWay"));
067    }
068
069    protected static boolean confirmChangeDirectionOfWays() {
070        return new ExtendedDialog(MainApplication.getMainFrame(),
071                tr("Change directions?"),
072                tr("Reverse and Combine"), tr("Cancel"))
073            .setButtonIcons("wayflip", "cancel")
074            .setContent(tr("The ways can not be combined in their current directions.  "
075                + "Do you want to reverse some of them?"))
076            .toggleEnable("combineway-reverse")
077            .showDialog()
078            .getValue() == 1;
079    }
080
081    protected static void warnCombiningImpossible() {
082        String msg = tr("Could not combine ways<br>"
083                + "(They could not be merged into a single string of nodes)");
084        new Notification(msg)
085                .setIcon(JOptionPane.INFORMATION_MESSAGE)
086                .show();
087    }
088
089    protected static Way getTargetWay(Collection<Way> combinedWays) {
090        // init with an arbitrary way
091        Way targetWay = combinedWays.iterator().next();
092
093        // look for the first way already existing on
094        // the server
095        for (Way w : combinedWays) {
096            targetWay = w;
097            if (!w.isNew()) {
098                break;
099            }
100        }
101        return targetWay;
102    }
103
104    /**
105     * Combine multiple ways into one.
106     * @param ways the way to combine to one way
107     * @return null if ways cannot be combined. Otherwise returns the combined ways and the commands to combine
108     * @throws UserCancelException if the user cancelled a dialog.
109     */
110    public static Pair<Way, Command> combineWaysWorker(Collection<Way> ways) throws UserCancelException {
111
112        // prepare and clean the list of ways to combine
113        //
114        if (Utils.isEmpty(ways))
115            return null;
116        ways.remove(null); // just in case -  remove all null ways from the collection
117
118        // remove duplicates, preserving order
119        ways = new LinkedHashSet<>(ways);
120        // remove incomplete ways
121        ways.removeIf(OsmPrimitive::isIncomplete);
122        // we need at least two ways
123        if (ways.size() < 2)
124            return null;
125
126        List<DataSet> dataSets = ways.stream().map(Way::getDataSet).filter(Objects::nonNull).distinct().collect(Collectors.toList());
127        if (dataSets.size() != 1) {
128            throw new IllegalArgumentException("Cannot combine ways of multiple data sets.");
129        }
130
131        // try to build a new way which includes all the combined ways
132        List<Node> path = new LinkedList<>(tryJoin(ways));
133        if (path.isEmpty()) {
134            warnCombiningImpossible();
135            return null;
136        }
137        // check whether any ways have been reversed in the process
138        // and build the collection of tags used by the ways to combine
139        //
140        TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
141
142        final List<Command> reverseWayTagCommands = new LinkedList<>();
143        List<Way> reversedWays = new LinkedList<>();
144        List<Way> unreversedWays = new LinkedList<>();
145        detectReversedWays(ways, path, reversedWays, unreversedWays);
146        // reverse path if all ways have been reversed
147        if (unreversedWays.isEmpty()) {
148            Collections.reverse(path);
149            unreversedWays = reversedWays;
150            reversedWays = null;
151        }
152        if ((reversedWays != null) && !reversedWays.isEmpty()) {
153            if (!confirmChangeDirectionOfWays()) return null;
154            // filter out ways that have no direction-dependent tags
155            unreversedWays = ReverseWayTagCorrector.irreversibleWays(unreversedWays);
156            reversedWays = ReverseWayTagCorrector.irreversibleWays(reversedWays);
157            // reverse path if there are more reversed than unreversed ways with direction-dependent tags
158            if (reversedWays.size() > unreversedWays.size()) {
159                Collections.reverse(path);
160                List<Way> tempWays = unreversedWays;
161                unreversedWays = null;
162                reversedWays = tempWays;
163            }
164            // if there are still reversed ways with direction-dependent tags, reverse their tags
165            if (!reversedWays.isEmpty() && Boolean.TRUE.equals(PROP_REVERSE_WAY.get())) {
166                List<Way> unreversedTagWays = new ArrayList<>(ways);
167                unreversedTagWays.removeAll(reversedWays);
168                ReverseWayTagCorrector reverseWayTagCorrector = new ReverseWayTagCorrector();
169                List<Way> reversedTagWays = new ArrayList<>(reversedWays.size());
170                for (Way w : reversedWays) {
171                    Way wnew = new Way(w);
172                    reversedTagWays.add(wnew);
173                    reverseWayTagCommands.addAll(reverseWayTagCorrector.execute(w, wnew));
174                }
175                if (!reverseWayTagCommands.isEmpty()) {
176                    // commands need to be executed for CombinePrimitiveResolverDialog
177                    UndoRedoHandler.getInstance().add(new SequenceCommand(tr("Reverse Ways"), reverseWayTagCommands));
178                }
179                wayTags = TagCollection.unionOfAllPrimitives(reversedTagWays);
180                wayTags.add(TagCollection.unionOfAllPrimitives(unreversedTagWays));
181            }
182        }
183
184        // create the new way and apply the new node list
185        //
186        Way targetWay = getTargetWay(ways);
187
188        final List<Command> resolution;
189        try {
190            resolution = CombinePrimitiveResolverDialog.launchIfNecessary(wayTags, ways, Collections.singleton(targetWay));
191        } finally {
192            if (!reverseWayTagCommands.isEmpty()) {
193                // undo reverseWayTagCorrector and merge into SequenceCommand below
194                UndoRedoHandler.getInstance().undo();
195            }
196        }
197
198        List<Command> cmds = new LinkedList<>();
199        List<Way> deletedWays = new LinkedList<>(ways);
200        deletedWays.remove(targetWay);
201
202        cmds.add(new ChangeNodesCommand(dataSets.get(0), targetWay, path));
203        cmds.addAll(reverseWayTagCommands);
204        cmds.addAll(resolution);
205        cmds.add(new DeleteCommand(dataSets.get(0), deletedWays));
206        final Command sequenceCommand = new SequenceCommand(/* for correct i18n of plural forms - see #9110 */
207                trn("Combine {0} way", "Combine {0} ways", ways.size(), ways.size()), cmds);
208
209        return new Pair<>(targetWay, sequenceCommand);
210    }
211
212    protected static void detectReversedWays(Collection<Way> ways, List<Node> path, List<Way> reversedWays,
213            List<Way> unreversedWays) {
214        for (Way w: ways) {
215            // Treat zero or one-node ways as unreversed as Combine action action is a good way to fix them (see #8971)
216            if (w.getNodesCount() < 2) {
217                unreversedWays.add(w);
218            } else {
219                int last = path.lastIndexOf(w.getNode(0));
220
221                boolean foundStartSegment = IntStream.rangeClosed(path.indexOf(w.getNode(0)), last)
222                        .anyMatch(i -> path.get(i) == w.getNode(0) && i + 1 < path.size() && w.getNode(1) == path.get(i + 1));
223                if (foundStartSegment) {
224                    unreversedWays.add(w);
225                } else {
226                    reversedWays.add(w);
227                }
228            }
229        }
230    }
231
232    protected static List<Node> tryJoin(Collection<Way> ways) {
233        List<Node> path = joinWithMultipolygonCode(ways);
234        if (path.isEmpty()) {
235            NodeGraph graph = NodeGraph.createNearlyUndirectedGraphFromNodeWays(ways);
236            path = graph.buildSpanningPathNoRemove();
237        }
238        return path;
239    }
240
241    /**
242     * Use {@link Multipolygon#joinWays(Collection)} to join ways.
243     * @param ways the ways
244     * @return List of nodes of the combined ways or null if ways could not be combined to a single way.
245     * Result may contain overlapping segments.
246     */
247    private static List<Node> joinWithMultipolygonCode(Collection<Way> ways) {
248        // sort so that old unclosed ways appear first
249        LinkedList<Way> toJoin = new LinkedList<>(ways);
250        toJoin.sort((o1, o2) -> {
251            int d = Boolean.compare(o1.isNew(), o2.isNew());
252            if (d == 0)
253                d = Boolean.compare(o1.isClosed(), o2.isClosed());
254            return d;
255        });
256        Collection<JoinedWay> list = Multipolygon.joinWays(toJoin);
257        if (list.size() == 1) {
258            // ways form a single line string
259            return Collections.unmodifiableList(new ArrayList<>(list.iterator().next().getNodes()));
260        }
261        return Collections.emptyList();
262    }
263
264    @Override
265    public void actionPerformed(ActionEvent event) {
266        final DataSet ds = getLayerManager().getEditDataSet();
267        if (ds == null)
268            return;
269        Collection<Way> selectedWays = new LinkedHashSet<>(ds.getSelectedWays());
270        selectedWays.removeIf(Way::isEmpty);
271        if (selectedWays.size() < 2) {
272            new Notification(
273                    tr("Please select at least two ways to combine."))
274                    .setIcon(JOptionPane.INFORMATION_MESSAGE)
275                    .setDuration(Notification.TIME_SHORT)
276                    .show();
277            return;
278        }
279
280        // combine and update gui
281        Pair<Way, Command> combineResult;
282        try {
283            combineResult = combineWaysWorker(selectedWays);
284        } catch (UserCancelException ex) {
285            Logging.trace(ex);
286            return;
287        }
288
289        if (combineResult == null)
290            return;
291
292        // see #18083: check if we will combine ways at nodes outside of the download area
293        if (!checkAndConfirmCombineOutlyingWays(selectedWays))
294            return;
295
296        final Way selectedWay = combineResult.a;
297        UndoRedoHandler.getInstance().add(combineResult.b);
298        Test test = new OverlappingWays();
299        test.startTest(null);
300        test.visit(combineResult.a);
301        test.endTest();
302        if (test.getErrors().isEmpty()) {
303            test = new SelfIntersectingWay();
304            test.startTest(null);
305            test.visit(combineResult.a);
306            test.endTest();
307        }
308        if (!test.getErrors().isEmpty()) {
309            new Notification(test.getErrors().get(0).getMessage())
310            .setIcon(JOptionPane.WARNING_MESSAGE)
311            .setDuration(Notification.TIME_SHORT)
312            .show();
313        }
314        if (selectedWay != null) {
315            GuiHelper.runInEDT(() -> ds.setSelected(selectedWay));
316        }
317    }
318
319    @Override
320    protected void updateEnabledState() {
321        updateEnabledStateOnCurrentSelection();
322    }
323
324    @Override
325    protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
326        int numWays = 0;
327        if (OsmUtils.isOsmCollectionEditable(selection)) {
328            for (OsmPrimitive osm : selection) {
329                if (osm instanceof Way && !osm.isIncomplete() && ++numWays >= 2) {
330                    break;
331                }
332            }
333        }
334        setEnabled(numWays >= 2);
335    }
336
337    /**
338     * Check whether user is about to combine ways with unknown parents.
339     * Request confirmation if he is.
340     * @param ways the primitives to operate on
341     * @return true, if operating on outlying primitives is OK; false, otherwise
342     */
343    private static boolean checkAndConfirmCombineOutlyingWays(Collection<Way> ways) {
344        DownloadReferrersAction action = MainApplication.getMenu().downloadReferrers;
345        final String downloadHint = tr("You should use {0}->{1}({2}) first.",
346                MainApplication.getMenu().fileMenu.getText(), action.getValue(NAME), action.getShortcut().toString());
347        return Boolean.TRUE.equals(GuiHelper.runInEDTAndWaitAndReturn(() -> checkAndConfirmOutlyingOperation("combine",
348                tr("Combine confirmation"),
349                tr("You are about to combine ways which can be members of relations not yet downloaded."
350                        + "<br>"
351                        + "This can lead to damaging these parent relations (that you do not see)."
352                        + "<br>"
353                        + "{0}"
354                        + "<br><br>"
355                        + "Do you really want to combine without downloading?", downloadHint),
356                "", // not used, we never combine incomplete ways
357                ways, Collections.emptyList())));
358    }
359
360}