001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.command;
003
004import static org.openstreetmap.josm.command.SplitWayCommand.MissingMemberStrategy.GO_AHEAD_WITHOUT_DOWNLOADS;
005import static org.openstreetmap.josm.command.SplitWayCommand.MissingMemberStrategy.GO_AHEAD_WITH_DOWNLOADS;
006import static org.openstreetmap.josm.command.SplitWayCommand.MissingMemberStrategy.USER_ABORTED;
007import static org.openstreetmap.josm.command.SplitWayCommand.WhenRelationOrderUncertain.ASK_USER_FOR_CONSENT_TO_DOWNLOAD;
008import static org.openstreetmap.josm.tools.I18n.tr;
009import static org.openstreetmap.josm.tools.I18n.trn;
010
011import java.util.ArrayList;
012import java.util.Arrays;
013import java.util.Collection;
014import java.util.Collections;
015import java.util.EnumSet;
016import java.util.HashMap;
017import java.util.HashSet;
018import java.util.Iterator;
019import java.util.LinkedList;
020import java.util.List;
021import java.util.Map;
022import java.util.Objects;
023import java.util.Optional;
024import java.util.Set;
025import java.util.function.Consumer;
026import java.util.stream.Collectors;
027
028import javax.swing.JOptionPane;
029
030import org.openstreetmap.josm.data.osm.DataSet;
031import org.openstreetmap.josm.data.osm.DefaultNameFormatter;
032import org.openstreetmap.josm.data.osm.Node;
033import org.openstreetmap.josm.data.osm.OsmPrimitive;
034import org.openstreetmap.josm.data.osm.PrimitiveId;
035import org.openstreetmap.josm.data.osm.Relation;
036import org.openstreetmap.josm.data.osm.RelationMember;
037import org.openstreetmap.josm.data.osm.Way;
038import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
039import org.openstreetmap.josm.gui.ExceptionDialogUtil;
040import org.openstreetmap.josm.gui.MainApplication;
041import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
042import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
043import org.openstreetmap.josm.io.MultiFetchServerObjectReader;
044import org.openstreetmap.josm.io.OsmTransferException;
045import org.openstreetmap.josm.spi.preferences.Config;
046import org.openstreetmap.josm.tools.CheckParameterUtil;
047import org.openstreetmap.josm.tools.Logging;
048
049/**
050 * Splits a way into multiple ways (all identical except for their node list).
051 * <p>
052 * Ways are just split at the selected nodes.  The nodes remain in their
053 * original order.  Selected nodes at the end of a way are ignored.
054 *
055 * @since 12828 ({@code SplitWayAction} converted to a {@link Command})
056 */
057public class SplitWayCommand extends SequenceCommand {
058
059    private static volatile Consumer<String> warningNotifier = Logging::warn;
060    private static final String DOWNLOAD_MISSING_PREF_KEY = "split_way_download_missing_members";
061
062    private static final class RelationInformation {
063        boolean warnme;
064        boolean insert;
065        Relation relation;
066    }
067
068    /**
069     * Sets the global warning notifier.
070     * @param notifier warning notifier in charge of displaying warning message, if any. Must not be null
071     */
072    public static void setWarningNotifier(Consumer<String> notifier) {
073        warningNotifier = Objects.requireNonNull(notifier);
074    }
075
076    private final List<? extends PrimitiveId> newSelection;
077    private final Way originalWay;
078    private final List<Way> newWays;
079
080    private static final String RESTRICTION = "restriction";
081    /** Map&lt;Restriction type, type to treat it as&gt; */
082    private static final Map<String, String> relationSpecialTypes = new HashMap<>();
083    static {
084        relationSpecialTypes.put(RESTRICTION, RESTRICTION);
085        relationSpecialTypes.put("destination_sign", RESTRICTION);
086        relationSpecialTypes.put("connectivity", RESTRICTION);
087    }
088
089    /**
090     * Create a new {@code SplitWayCommand}.
091     * @param name The description text
092     * @param commandList The sequence of commands that should be executed.
093     * @param newSelection The new list of selected primitives ids (which is saved for later retrieval with {@link #getNewSelection})
094     * @param originalWay The original way being split (which is saved for later retrieval with {@link #getOriginalWay})
095     * @param newWays The resulting new ways (which is saved for later retrieval with {@link #getNewWays})
096     */
097    public SplitWayCommand(String name, Collection<Command> commandList,
098            List<? extends PrimitiveId> newSelection, Way originalWay, List<Way> newWays) {
099        super(name, commandList);
100        this.newSelection = newSelection;
101        this.originalWay = originalWay;
102        this.newWays = newWays;
103    }
104
105    /**
106     * Replies the new list of selected primitives ids
107     * @return The new list of selected primitives ids
108     */
109    public List<? extends PrimitiveId> getNewSelection() {
110        return newSelection;
111    }
112
113    /**
114     * Replies the original way being split
115     * @return The original way being split
116     */
117    public Way getOriginalWay() {
118        return originalWay;
119    }
120
121    /**
122     * Replies the resulting new ways
123     * @return The resulting new ways
124     */
125    public List<Way> getNewWays() {
126        return newWays;
127    }
128
129    /**
130     * Determines which way chunk should reuse the old id and its history
131     */
132    @FunctionalInterface
133    public interface Strategy {
134
135        /**
136         * Determines which way chunk should reuse the old id and its history.
137         *
138         * @param wayChunks the way chunks
139         * @return the way to keep
140         */
141        Way determineWayToKeep(Iterable<Way> wayChunks);
142
143        /**
144         * Returns a strategy which selects the way chunk with the highest node count to keep.
145         * @return strategy which selects the way chunk with the highest node count to keep
146         */
147        static Strategy keepLongestChunk() {
148            return wayChunks -> {
149                    Way wayToKeep = null;
150                    for (Way i : wayChunks) {
151                        if (wayToKeep == null || i.getNodesCount() > wayToKeep.getNodesCount()) {
152                            wayToKeep = i;
153                        }
154                    }
155                    return wayToKeep;
156                };
157        }
158
159        /**
160         * Returns a strategy which selects the first way chunk.
161         * @return strategy which selects the first way chunk
162         */
163        static Strategy keepFirstChunk() {
164            return wayChunks -> wayChunks.iterator().next();
165        }
166    }
167
168    /**
169     * Splits the nodes of {@code wayToSplit} into a list of node sequences
170     * which are separated at the nodes in {@code splitPoints}.
171     * <p>
172     * This method displays warning messages if {@code wayToSplit} and/or
173     * {@code splitPoints} aren't consistent.
174     * <p>
175     * Returns null, if building the split chunks fails.
176     *
177     * @param wayToSplit the way to split. Must not be null.
178     * @param splitPoints the nodes where the way is split. Must not be null.
179     * @return the list of chunks
180     */
181    public static List<List<Node>> buildSplitChunks(Way wayToSplit, List<Node> splitPoints) {
182        CheckParameterUtil.ensureParameterNotNull(wayToSplit, "wayToSplit");
183        CheckParameterUtil.ensureParameterNotNull(splitPoints, "splitPoints");
184
185        Set<Node> nodeSet = new HashSet<>(splitPoints);
186        List<List<Node>> wayChunks = new LinkedList<>();
187        List<Node> currentWayChunk = new ArrayList<>();
188        wayChunks.add(currentWayChunk);
189
190        Iterator<Node> it = wayToSplit.getNodes().iterator();
191        while (it.hasNext()) {
192            Node currentNode = it.next();
193            boolean atEndOfWay = currentWayChunk.isEmpty() || !it.hasNext();
194            currentWayChunk.add(currentNode);
195            if (nodeSet.contains(currentNode) && !atEndOfWay) {
196                currentWayChunk = new ArrayList<>();
197                currentWayChunk.add(currentNode);
198                wayChunks.add(currentWayChunk);
199            }
200        }
201
202        // Handle circular ways specially.
203        // If you split at a circular way at two nodes, you just want to split
204        // it at these points, not also at the former endpoint.
205        // So if the last node is the same first node, join the last and the
206        // first way chunk.
207        List<Node> lastWayChunk = wayChunks.get(wayChunks.size() - 1);
208        if (wayChunks.size() >= 2
209                && wayChunks.get(0).get(0) == lastWayChunk.get(lastWayChunk.size() - 1)
210                && !nodeSet.contains(wayChunks.get(0).get(0))) {
211            if (wayChunks.size() == 2) {
212                warningNotifier.accept(tr("You must select two or more nodes to split a circular way."));
213                return null;
214            }
215            lastWayChunk.remove(lastWayChunk.size() - 1);
216            lastWayChunk.addAll(wayChunks.get(0));
217            wayChunks.remove(wayChunks.size() - 1);
218            wayChunks.set(0, lastWayChunk);
219        }
220
221        if (wayChunks.size() < 2) {
222            if (wayChunks.get(0).get(0) == wayChunks.get(0).get(wayChunks.get(0).size() - 1)) {
223                warningNotifier.accept(
224                        tr("You must select two or more nodes to split a circular way."));
225            } else {
226                warningNotifier.accept(
227                        tr("The way cannot be split at the selected nodes. (Hint: Select nodes in the middle of the way.)"));
228            }
229            return null;
230        }
231        return wayChunks;
232    }
233
234    /**
235     * Creates new way objects for the way chunks and transfers the keys from the original way.
236     * @param way the original way whose  keys are transferred
237     * @param wayChunks the way chunks
238     * @return the new way objects
239     */
240    public static List<Way> createNewWaysFromChunks(Way way, Iterable<List<Node>> wayChunks) {
241        final List<Way> newWays = new ArrayList<>();
242        for (List<Node> wayChunk : wayChunks) {
243            Way wayToAdd = new Way();
244            wayToAdd.setKeys(way.getKeys());
245            wayToAdd.setNodes(wayChunk);
246            newWays.add(wayToAdd);
247        }
248        return newWays;
249    }
250
251    /**
252     * Splits the way {@code way} into chunks of {@code wayChunks} and replies
253     * the result of this process in an instance of {@link SplitWayCommand}.
254     * <p>
255     * Note that changes are not applied to the data yet. You have to
256     * submit the command first, i.e. {@code UndoRedoHandler.getInstance().add(result)}.
257     *
258     * @param way the way to split. Must not be null.
259     * @param wayChunks the list of way chunks into the way is split. Must not be null.
260     * @param selection The list of currently selected primitives
261     * @return the result from the split operation
262     */
263    public static SplitWayCommand splitWay(Way way, List<List<Node>> wayChunks, Collection<? extends OsmPrimitive> selection) {
264        return splitWay(way, wayChunks, selection, Strategy.keepLongestChunk());
265    }
266
267    /**
268     * Splits the way {@code way} into chunks of {@code wayChunks} and replies the result of this process in an instance
269     * of {@link SplitWayCommand}. The {@link SplitWayCommand.Strategy} is used to determine which way chunk should
270     * reuse the old id and its history.
271     * <p>
272     * If the split way is part of relations, and the order of the new parts in these relations cannot be determined due
273     * to missing relation members, the user will be asked to consent to downloading these missing members.
274     * <p>
275     * Note that changes are not applied to the data yet. You have to submit the command first, i.e. {@code
276     * UndoRedoHandler.getInstance().add(result)}.
277     *
278     * @param way           the way to split. Must not be null.
279     * @param wayChunks     the list of way chunks into the way is split. Must not be null.
280     * @param selection     The list of currently selected primitives
281     * @param splitStrategy The strategy used to determine which way chunk should reuse the old id and its history
282     * @return the result from the split operation
283     */
284    public static SplitWayCommand splitWay(Way way,
285                                           List<List<Node>> wayChunks,
286                                           Collection<? extends OsmPrimitive> selection,
287                                           Strategy splitStrategy) {
288
289        // This method could be refactored to use an Optional in the future, but would need to be deprecated first
290        // to phase out use by plugins.
291        return splitWay(way, wayChunks, selection, splitStrategy, ASK_USER_FOR_CONSENT_TO_DOWNLOAD).orElse(null);
292    }
293
294    /**
295     * Splits the way {@code way} into chunks of {@code wayChunks} and replies the result of this process in an instance
296     * of {@link SplitWayCommand}. The {@link SplitWayCommand.Strategy} is used to determine which way chunk should
297     * reuse the old id and its history.
298     * <p>
299     * Note that changes are not applied to the data yet. You have to submit the command first, i.e. {@code
300     * UndoRedoHandler.getInstance().add(result)}.
301     *
302     * @param way                        the way to split. Must not be null.
303     * @param wayChunks                  the list of way chunks into the way is split. Must not be null.
304     * @param selection                  The list of currently selected primitives
305     * @param splitStrategy              The strategy used to determine which way chunk should reuse the old id and its
306     *                                   history
307     * @param whenRelationOrderUncertain What to do when the split way is part of relations, and the order of the new
308     *                                   parts in the relation cannot be determined without downloading missing relation
309     *                                   members.
310     * @return The result from the split operation, may be an empty {@link Optional} if the operation is aborted.
311     */
312    public static Optional<SplitWayCommand> splitWay(Way way,
313                                                     List<List<Node>> wayChunks,
314                                                     Collection<? extends OsmPrimitive> selection,
315                                                     Strategy splitStrategy,
316                                                     WhenRelationOrderUncertain whenRelationOrderUncertain) {
317        // build a list of commands, and also a new selection list
318        final List<OsmPrimitive> newSelection = new ArrayList<>(selection.size() + wayChunks.size());
319        newSelection.addAll(selection);
320
321        // Create all potential new ways
322        final List<Way> newWays = createNewWaysFromChunks(way, wayChunks);
323
324        // Determine which part reuses the existing way
325        final Way wayToKeep = splitStrategy.determineWayToKeep(newWays);
326
327        return wayToKeep != null
328                ? doSplitWay(way, wayToKeep, newWays, newSelection, whenRelationOrderUncertain)
329                : Optional.empty();
330    }
331
332    /**
333     * Effectively constructs the {@link SplitWayCommand}.
334     * This method is only public for {@code SplitWayAction}.
335     *
336     * @param way the way to split. Must not be null.
337     * @param wayToKeep way chunk which should reuse the old id and its history
338     * @param newWays potential new ways
339     * @param newSelection new selection list to update (optional: can be null)
340     * @param whenRelationOrderUncertain Action to perform when the order of the new parts in relations the way is
341     *                                   member of could not be reliably determined. See
342     *                                   {@link WhenRelationOrderUncertain}.
343     * @return the {@code SplitWayCommand}
344     */
345    public static Optional<SplitWayCommand> doSplitWay(Way way,
346                                                       Way wayToKeep,
347                                                       List<Way> newWays,
348                                                       List<OsmPrimitive> newSelection,
349                                                       WhenRelationOrderUncertain whenRelationOrderUncertain) {
350        if (whenRelationOrderUncertain == null) whenRelationOrderUncertain = ASK_USER_FOR_CONSENT_TO_DOWNLOAD;
351
352        final int indexOfWayToKeep = newWays.indexOf(wayToKeep);
353        newWays.remove(wayToKeep);
354
355        // Figure out the order of relation members (if any).
356        Analysis analysis = analyseSplit(way, wayToKeep, newWays);
357
358        // If there are relations that cannot be split properly without downloading more members,
359        // present the user with an option to do so, or to abort the split.
360        Set<Relation> relationsNeedingMoreMembers = new HashSet<>();
361        Set<OsmPrimitive> incompleteMembers = new HashSet<>();
362        for (RelationAnalysis relationAnalysis : analysis.getRelationAnalyses()) {
363            if (!relationAnalysis.getNeededIncompleteMembers().isEmpty()) {
364                incompleteMembers.addAll(relationAnalysis.getNeededIncompleteMembers());
365                relationsNeedingMoreMembers.add(relationAnalysis.getRelation());
366            }
367        }
368
369        MissingMemberStrategy missingMemberStrategy = USER_ABORTED; // default case
370        if (relationsNeedingMoreMembers.isEmpty()) {
371            // The split can be performed without any extra downloads.
372            missingMemberStrategy = GO_AHEAD_WITHOUT_DOWNLOADS;
373        } else {
374            switch (whenRelationOrderUncertain) {
375                case ASK_USER_FOR_CONSENT_TO_DOWNLOAD:
376                    // If the analysis shows that for some relations missing members should be downloaded, offer the user the
377                    // chance to consent to this.
378
379                    // Only ask the user about downloading missing members when they haven't consented to this before.
380                    if (ConditionalOptionPaneUtil.getDialogReturnValue(DOWNLOAD_MISSING_PREF_KEY) == Integer.MAX_VALUE) {
381                        // User has previously told us downloading missing relation members is fine.
382                        missingMemberStrategy = GO_AHEAD_WITH_DOWNLOADS;
383                    } else {
384                        // Ask the user.
385                        missingMemberStrategy = offerToDownloadMissingMembersIfNeeded(analysis, relationsNeedingMoreMembers.size());
386                    }
387                    break;
388                case SPLIT_ANYWAY:
389                    missingMemberStrategy = GO_AHEAD_WITHOUT_DOWNLOADS;
390                    break;
391                case DOWNLOAD_MISSING_MEMBERS:
392                    missingMemberStrategy = GO_AHEAD_WITH_DOWNLOADS;
393                    break;
394                case ABORT:
395                    missingMemberStrategy = USER_ABORTED;
396                    break;
397            }
398        }
399
400        try {
401            switch (missingMemberStrategy) {
402            case GO_AHEAD_WITH_DOWNLOADS:
403                try {
404                    downloadMissingMembers(incompleteMembers);
405                } catch (OsmTransferException e) {
406                    ExceptionDialogUtil.explainException(e);
407                    return Optional.empty();
408                }
409                // If missing relation members were downloaded, perform the analysis again to find the relation
410                // member order for all relations.
411                analysis.cleanup();
412                analysis = analyseSplit(way, wayToKeep, newWays);
413                break;
414            case GO_AHEAD_WITHOUT_DOWNLOADS:
415                // Proceed with the split with the information we have.
416                // This can mean that there are no missing members we want, or that the user chooses to continue
417                // the split without downloading them.
418                break;
419            case USER_ABORTED:
420                return Optional.empty();
421            }
422            return Optional.of(splitBasedOnAnalyses(way, newWays, newSelection, analysis, indexOfWayToKeep));
423        } finally {
424            // see #19885
425            wayToKeep.setNodes(null);
426            analysis.cleanup();
427        }
428    }
429
430    static Analysis analyseSplit(Way way,
431                                 Way wayToKeep,
432                                 List<Way> newWays) {
433        Collection<Command> commandList = new ArrayList<>();
434        Collection<String> nowarnroles = Config.getPref().getList("way.split.roles.nowarn",
435                Arrays.asList("outer", "inner", "forward", "backward", "north", "south", "east", "west"));
436
437        // Change the original way
438        final List<Node> changedWayNodes = wayToKeep.getNodes();
439        commandList.add(new ChangeNodesCommand(way, changedWayNodes));
440        for (Way wayToAdd : newWays) {
441            commandList.add(new AddCommand(way.getDataSet(), wayToAdd));
442        }
443
444        List<RelationAnalysis> relationAnalyses = new ArrayList<>();
445        EnumSet<WarningType> warnings = EnumSet.noneOf(WarningType.class);
446        int numberOfRelations = 0;
447
448        for (Relation r : OsmPrimitive.getParentRelations(Collections.singleton(way))) {
449            if (!r.isUsable()) {
450                continue;
451            }
452
453            numberOfRelations++;
454            boolean isSimpleCase = true;
455
456            Relation c = null;
457            String type = Optional.ofNullable(r.get("type")).orElse("");
458            // Known types of ordered relations.
459            boolean isOrderedRelation = "route".equals(type) || "multipolygon".equals(type) || "boundary".equals(type);
460
461            for (int ir = 0; ir < r.getMembersCount(); ir++) {
462                RelationMember rm = r.getMember(ir);
463                if (rm.getMember() == way) {
464                    boolean insert = true;
465                    if (relationSpecialTypes.containsKey(type) && RESTRICTION.equals(relationSpecialTypes.get(type))) {
466                        RelationInformation rValue = treatAsRestriction(r, rm, c, newWays, way, changedWayNodes);
467                        if (rValue.warnme) warnings.add(WarningType.GENERIC);
468                        insert = rValue.insert;
469                        c = rValue.relation; // Value.relation is null or contains a modified copy
470                    } else if (!isOrderedRelation) {
471                        // Warn the user when relations that are not a route or multipolygon are modified as a result
472                        // of splitting up the way, because we can't tell if this might break anything.
473                        warnings.add(WarningType.GENERIC);
474                    }
475
476                    if (insert) {
477                        if (c == null) {
478                            c = new Relation(r);
479                        }
480                        if (rm.hasRole() && !nowarnroles.contains(rm.getRole())) {
481                            warnings.add(WarningType.ROLE);
482                        }
483
484                        // Attempt to determine the direction the ways in the relation are ordered.
485                        Direction direction = Direction.UNKNOWN;
486                        Set<Way> missingWays = new HashSet<>();
487                        if (isOrderedRelation) {
488                            if (way.lastNode() == way.firstNode()) {
489                                // Self-closing way.
490                                direction = direction.merge(Direction.IRRELEVANT);
491                            } else {
492                                // For ordered relations, looking beyond the nearest neighbour members is not required,
493                                // and can even cause the wrong direction to be guessed (with closed loops).
494                                if (ir - 1 >= 0 && r.getMember(ir - 1).isWay()) {
495                                    Way w = r.getMember(ir - 1).getWay();
496                                    if (w.isIncomplete())
497                                        missingWays.add(w);
498                                    else {
499                                        if (w.lastNode() == way.firstNode() || w.firstNode() == way.firstNode()) {
500                                            direction = direction.merge(Direction.FORWARDS);
501                                        } else if (w.firstNode() == way.lastNode() || w.lastNode() == way.lastNode()) {
502                                            direction = direction.merge(Direction.BACKWARDS);
503                                        }
504                                    }
505                                }
506                                if (ir + 1 < r.getMembersCount() && r.getMember(ir + 1).isWay()) {
507                                    Way w = r.getMember(ir + 1).getWay();
508                                    if (w.isIncomplete())
509                                        missingWays.add(w);
510                                    else {
511                                        if (w.lastNode() == way.firstNode() || w.firstNode() == way.firstNode()) {
512                                            direction = direction.merge(Direction.BACKWARDS);
513                                        } else if (w.firstNode() == way.lastNode() || w.lastNode() == way.lastNode()) {
514                                            direction = direction.merge(Direction.FORWARDS);
515                                        }
516                                    }
517                                }
518
519                                if (direction == Direction.UNKNOWN && missingWays.isEmpty()) {
520                                    // we cannot detect the direction and no way is missing.
521                                    // We can safely assume that the direction doesn't matter.
522                                    direction = Direction.IRRELEVANT;
523                                }
524                            }
525                        } else {
526                            int k = 1;
527                            while (ir - k >= 0 || ir + k < r.getMembersCount()) {
528                                if (ir - k >= 0 && r.getMember(ir - k).isWay()) {
529                                    Way w = r.getMember(ir - k).getWay();
530                                    if (w.lastNode() == way.firstNode() || w.firstNode() == way.firstNode()) {
531                                        direction = direction.merge(Direction.FORWARDS);
532                                    } else if (w.firstNode() == way.lastNode() || w.lastNode() == way.lastNode()) {
533                                        direction = direction.merge(Direction.BACKWARDS);
534                                    }
535                                    break;
536                                }
537                                if (ir + k < r.getMembersCount() && r.getMember(ir + k).isWay()) {
538                                    Way w = r.getMember(ir + k).getWay();
539                                    if (w.lastNode() == way.firstNode() || w.firstNode() == way.firstNode()) {
540                                        direction = direction.merge(Direction.BACKWARDS);
541                                    } else if (w.firstNode() == way.lastNode() || w.lastNode() == way.lastNode()) {
542                                        direction = direction.merge(Direction.FORWARDS);
543                                    }
544                                    break;
545                                }
546                                k++;
547                            }
548                        }
549
550                        if (direction == Direction.UNKNOWN) {
551                            // We don't have enough information to determine the order of the new ways in this relation.
552                            // This may cause relations to be saved with the two new way sections in reverse order.
553                            //
554                            // This often breaks routes.
555                            //
556                        } else {
557                            missingWays = Collections.emptySet();
558                        }
559                        relationAnalyses.add(new RelationAnalysis(c, rm, direction, missingWays));
560                        isSimpleCase = false;
561                    }
562                }
563            }
564            if (c != null && isSimpleCase) {
565                if (!r.getMembers().equals(c.getMembers())) {
566                    commandList.add(new ChangeMembersCommand(r, new ArrayList<>(c.getMembers())));
567                }
568                c.setMembers(null); // see #19885
569            }
570        }
571        return new Analysis(relationAnalyses, commandList, warnings, numberOfRelations);
572    }
573
574    static class Analysis {
575        List<RelationAnalysis> relationAnalyses;
576        Collection<Command> commands;
577        EnumSet<WarningType> warningTypes;
578        private final int numberOfRelations;
579
580        Analysis(List<RelationAnalysis> relationAnalyses,
581                 Collection<Command> commandList,
582                 EnumSet<WarningType> warnings,
583                 int numberOfRelations) {
584            this.relationAnalyses = relationAnalyses;
585            commands = commandList;
586            warningTypes = warnings;
587            this.numberOfRelations = numberOfRelations;
588        }
589
590        /**
591         * Unlink temporary copies of relations. See #19885
592         */
593        void cleanup() {
594            for (RelationAnalysis ra : relationAnalyses) {
595                if (ra.relation.getDataSet() == null)
596                    ra.relation.setMembers(null);
597            }
598        }
599
600        List<RelationAnalysis> getRelationAnalyses() {
601            return relationAnalyses;
602        }
603
604        Collection<Command> getCommands() {
605            return commands;
606        }
607
608        EnumSet<WarningType> getWarningTypes() {
609            return warningTypes;
610        }
611
612        public int getNumberOfRelations() {
613            return numberOfRelations;
614        }
615    }
616
617    static MissingMemberStrategy offerToDownloadMissingMembersIfNeeded(Analysis analysis,
618                                                                       int numRelationsNeedingMoreMembers) {
619        String[] options = {
620                tr("Yes, download the missing members"),
621                tr("No, abort the split operation"),
622                tr("No, perform the split without downloading")
623        };
624
625        String msgMemberOfRelations = trn(
626                "This way is part of a relation.",
627                "This way is part of {0} relations.",
628                analysis.getNumberOfRelations(),
629                analysis.getNumberOfRelations()
630        );
631
632        String msgReferToRelations;
633        if (analysis.getNumberOfRelations() == 1) {
634            msgReferToRelations = tr("this relation");
635        } else if (analysis.getNumberOfRelations() == numRelationsNeedingMoreMembers) {
636            msgReferToRelations = tr("these relations");
637        } else {
638            msgReferToRelations = trn(
639                    "one relation",
640                    "{0} relations",
641                    numRelationsNeedingMoreMembers,
642                    numRelationsNeedingMoreMembers
643            );
644        }
645
646        String msgRelationsMissingData = tr(
647                "For {0} the correct order of the new way parts could not be determined. " +
648                        "To fix this, some missing relation members should be downloaded first.",
649                msgReferToRelations
650        );
651
652        JMultilineLabel msg = new JMultilineLabel(msgMemberOfRelations + " " + msgRelationsMissingData);
653        msg.setMaxWidth(600);
654
655        int ret = JOptionPane.showOptionDialog(
656                MainApplication.getMainFrame(),
657                msg,
658                tr("Download missing relation members?"),
659                JOptionPane.OK_CANCEL_OPTION,
660                JOptionPane.QUESTION_MESSAGE,
661                null,
662                options,
663                options[0]
664        );
665
666        switch (ret) {
667            case JOptionPane.OK_OPTION:
668                // Ask the user if they want to do this automatically from now on. We only ask this for the download
669                // action, because automatically cancelling is confusing (the user can't tell why this happened), and
670                // automatically performing the split without downloading missing members despite needing them is
671                // likely to break a lot of routes. The user also can't tell the difference between a split that needs
672                // no downloads at all, and this special case where downloading missing relation members will prevent
673                // broken relations.
674                ConditionalOptionPaneUtil.showMessageDialog(
675                        DOWNLOAD_MISSING_PREF_KEY,
676                        MainApplication.getMainFrame(),
677                        tr("Missing relation members will be downloaded. Should this be done automatically from now on?"),
678                        tr("Downloading missing relation members"),
679                        JOptionPane.INFORMATION_MESSAGE
680                );
681                return GO_AHEAD_WITH_DOWNLOADS;
682            case JOptionPane.CANCEL_OPTION:
683                return GO_AHEAD_WITHOUT_DOWNLOADS;
684            default:
685                return USER_ABORTED;
686        }
687    }
688
689    static void downloadMissingMembers(Set<OsmPrimitive> incompleteMembers) throws OsmTransferException {
690        // Download the missing members.
691        MultiFetchServerObjectReader reader = MultiFetchServerObjectReader.create();
692        reader.append(incompleteMembers);
693
694        DataSet ds = reader.parseOsm(NullProgressMonitor.INSTANCE);
695        MainApplication.getLayerManager().getEditLayer().mergeFrom(ds);
696    }
697
698    static SplitWayCommand splitBasedOnAnalyses(Way way,
699                                                List<Way> newWays,
700                                                List<OsmPrimitive> newSelection,
701                                                Analysis analysis,
702                                                int indexOfWayToKeep) {
703        if (newSelection != null && !newSelection.contains(way)) {
704            newSelection.add(way);
705        }
706
707        if (newSelection != null) {
708            newSelection.addAll(newWays);
709        }
710
711        // Perform the split.
712        for (RelationAnalysis relationAnalysis : analysis.getRelationAnalyses()) {
713            RelationMember rm = relationAnalysis.getRelationMember();
714            Relation relation = relationAnalysis.getRelation();
715            Direction direction = relationAnalysis.getDirection();
716
717            for (int i = 0; i < relation.getMembersCount(); i++) {
718                // search for identical member (can't use indexOf() as it uses equals()
719                if (rm == relation.getMember(i)) {
720                    addSortedWays(i, indexOfWayToKeep, direction, newWays, relation);
721                    break;
722                }
723            }
724        }
725
726        // add one command for each complex case with relations
727        final DataSet ds = way.getDataSet();
728        for (Relation r : analysis.getRelationAnalyses().stream().map(RelationAnalysis::getRelation).collect(Collectors.toSet())) {
729            Relation orig = (Relation) ds.getPrimitiveById(r);
730            analysis.getCommands().add(new ChangeMembersCommand(orig, new ArrayList<>(r.getMembers())));
731            r.setMembers(null); // see #19885
732        }
733
734        EnumSet<WarningType> warnings = analysis.getWarningTypes();
735
736        if (warnings.contains(WarningType.ROLE)) {
737            warningNotifier.accept(
738                    tr("A role based relation membership was copied to all new ways.<br>You should verify this and correct it when necessary."));
739        } else if (warnings.contains(WarningType.GENERIC)) {
740            warningNotifier.accept(
741                    tr("A relation membership was copied to all new ways.<br>You should verify this and correct it when necessary."));
742        }
743
744        return new SplitWayCommand(
745                    /* for correct i18n of plural forms - see #9110 */
746                    trn("Split way {0} into {1} part", "Split way {0} into {1} parts", newWays.size() + 1,
747                            way.getDisplayName(DefaultNameFormatter.getInstance()), newWays.size() + 1),
748                    analysis.getCommands(),
749                    newSelection,
750                    way,
751                    newWays
752            );
753    }
754
755    /**
756     * Add ways in a sorted manner
757     * @param position The position of the relation member we are operating on
758     * @param indexOfWayToKeep The index of the way that is keeping history if it were in {@code newWays}
759     * @param direction The direction of the ways
760     * @param newWays The ways that are being added to the relation
761     * @param relation The relation we are operating on
762     */
763    private static void addSortedWays(final int position, final int indexOfWayToKeep, final Direction direction,
764                                      final List<Way> newWays, final Relation relation) {
765        // sanity check
766        if (position < 0) {
767            throw new AssertionError("Relation member not found");
768        }
769        final RelationMember rm = relation.getMember(position);
770        final boolean reverse = direction == Direction.BACKWARDS || needToReverseSplit(position, indexOfWayToKeep, relation, newWays);
771        final List<Way> waysToAddBefore = newWays.subList(0, indexOfWayToKeep);
772        int j = position;
773        for (Way wayToAdd : waysToAddBefore) {
774            RelationMember em = new RelationMember(rm.getRole(), wayToAdd);
775            j++;
776            if (reverse) {
777                relation.addMember(position + 1, em);
778            } else {
779                relation.addMember(j - 1, em);
780            }
781        }
782        final List<Way> waysToAddAfter = newWays.subList(indexOfWayToKeep, newWays.size());
783        for (Way wayToAdd : waysToAddAfter) {
784            RelationMember em = new RelationMember(rm.getRole(), wayToAdd);
785            j++;
786            if (reverse) {
787                relation.addMember(position, em);
788            } else {
789                relation.addMember(j, em);
790            }
791        }
792    }
793
794    /**
795     * This is only strictly necessary when we are splitting a route where it starts to loop back.
796     * Example: way1 → way2 → way2 → way1
797     *
798     * @param position         The position of the original way in the relation
799     * @param indexOfWayToKeep The index of the way to keep in relation to {@code newWays}
800     * @param relation         The relation we are working on
801     * @param newWays          The ways that are being added
802     * @return {@code true} if we need to reverse the direction of the ways
803     */
804    private static boolean needToReverseSplit(final int position, int indexOfWayToKeep, final Relation relation, final List<Way> newWays) {
805        final RelationMember rm = relation.getMember(position);
806        if (!rm.isWay()) {
807            return false;
808        }
809        final RelationMember previous = position <= 0 ? null : relation.getMember(position - 1);
810        final RelationMember next = position + 1 >= relation.getMembersCount() ? null : relation.getMember(position + 1);
811        final Way first = indexOfWayToKeep == 0 ? rm.getWay() : newWays.get(0);
812        final Way last = indexOfWayToKeep == newWays.size() ? rm.getWay() : newWays.get(newWays.size() - 1);
813        if (previous != null && previous.isWay() && previous.getWay().isUsable()) {
814            final Way compare = previous.getWay();
815            if (!(compare.isFirstLastNode(first.firstNode()) || compare.isFirstLastNode(first.lastNode()))) {
816                return true;
817            }
818        }
819        if (next != null && next.isWay() && next.getWay().isUsable()) {
820            final Way compare = next.getWay();
821            return !(compare.isFirstLastNode(last.firstNode()) || compare.isFirstLastNode(last.lastNode()));
822        }
823        return false;
824    }
825
826    private static RelationInformation treatAsRestriction(Relation r,
827            RelationMember rm, Relation c, Collection<Way> newWays, Way way,
828            List<Node> changedWayNodes) {
829        RelationInformation relationInformation = new RelationInformation();
830        /* this code assumes the restriction is correct. No real error checking done */
831        String role = rm.getRole();
832        String type = Optional.ofNullable(r.get("type")).orElse("");
833        if ("from".equals(role) || "to".equals(role)) {
834            List<Node> nodes = new ArrayList<>();
835            for (OsmPrimitive via : findVias(r, type)) {
836                if (via instanceof Node) {
837                    nodes.add((Node) via);
838                } else if (via instanceof Way) {
839                    nodes.add(((Way) via).lastNode());
840                    nodes.add(((Way) via).firstNode());
841                }
842            }
843            Way res = null;
844            for (Node n : nodes) {
845                if (changedWayNodes.get(0) == n || changedWayNodes.get(changedWayNodes.size() - 1) == n) {
846                    res = way;
847                }
848            }
849            if (res == null) {
850                for (Way wayToAdd : newWays) {
851                    for (Node n : nodes) {
852                        if (wayToAdd.isFirstLastNode(n)) {
853                            res = wayToAdd;
854                        }
855                    }
856                }
857                if (res != null) {
858                    if (c == null) {
859                        c = new Relation(r);
860                    }
861                    c.addMember(new RelationMember(role, res));
862                    c.removeMembersFor(way);
863                }
864            }
865        } else if (!"via".equals(role)) {
866            relationInformation.warnme = true;
867        } else {
868            relationInformation.insert = true;
869        }
870        relationInformation.relation = c;
871        return relationInformation;
872    }
873
874    static List<? extends OsmPrimitive> findVias(Relation r, String type) {
875        if (type != null) {
876            switch (type) {
877            case "connectivity":
878            case RESTRICTION:
879                return r.findRelationMembers("via");
880            case "destination_sign":
881                // Prefer intersection over sign, see #12347
882                List<? extends OsmPrimitive> intersections = r.findRelationMembers("intersection");
883                return intersections.isEmpty() ? r.findRelationMembers("sign") : intersections;
884            default:
885                break;
886            }
887        }
888        return Collections.emptyList();
889    }
890
891    /**
892     * Splits the way {@code way} at the nodes in {@code atNodes} and replies
893     * the result of this process in an instance of {@link SplitWayCommand}.
894     * <p>
895     * Note that changes are not applied to the data yet. You have to
896     * submit the command first, i.e. {@code UndoRedoHandler.getInstance().add(result)}.
897     * <p>
898     * Replies null if the way couldn't be split at the given nodes.
899     *
900     * @param way the way to split. Must not be null.
901     * @param atNodes the list of nodes where the way is split. Must not be null.
902     * @param selection The list of currently selected primitives
903     * @return the result from the split operation
904     */
905    public static SplitWayCommand split(Way way, List<Node> atNodes, Collection<? extends OsmPrimitive> selection) {
906        List<List<Node>> chunks = buildSplitChunks(way, atNodes);
907        return chunks != null ? splitWay(way, chunks, selection) : null;
908    }
909
910    /**
911     * Add relations that are treated in a specific way.
912     * @param relationType The value in the {@code type} key
913     * @param treatAs The type of relation to treat the {@code relationType} as.
914     * Currently only supports relations that can be handled like "restriction"
915     * relations.
916     * @return the previous value associated with relationType, or null if there was no mapping
917     * @since 15078
918     */
919    public static String addSpecialRelationType(String relationType, String treatAs) {
920        return relationSpecialTypes.put(relationType, treatAs);
921    }
922
923    /**
924     * Get the types of relations that are treated differently
925     * @return {@code Map<Relation Type, Type of Relation it is to be treated as>}
926     * @since 15078
927     */
928    public static Map<String, String> getSpecialRelationTypes() {
929        return relationSpecialTypes;
930    }
931
932    /**
933     * What to do when the split way is part of relations, and the order of the new parts in the relation cannot be
934     * determined without downloading missing relation members.
935     */
936    public enum WhenRelationOrderUncertain {
937        /**
938         * Ask the user to consent to downloading the missing members. The user can abort the operation or choose to
939         * proceed without downloading anything.
940         */
941        ASK_USER_FOR_CONSENT_TO_DOWNLOAD,
942        /**
943         * If there are relation members missing, and these are needed to determine the order of the new parts in
944         * that relation, abort the split operation.
945         */
946        ABORT,
947        /**
948         * If there are relation members missing, and these are needed to determine the order of the new parts in
949         * that relation, continue with the split operation anyway, without downloading anything. Caution: use this
950         * option with care.
951         */
952        SPLIT_ANYWAY,
953        /**
954         * If there are relation members missing, and these are needed to determine the order of the new parts in
955         * that relation, automatically download these without prompting the user.
956         */
957        DOWNLOAD_MISSING_MEMBERS
958    }
959
960    static class RelationAnalysis {
961        private final Relation relation;
962        private final RelationMember relationMember;
963        private final Direction direction;
964        private final Set<Way> neededIncompleteMembers;
965
966        RelationAnalysis(Relation relation,
967                                RelationMember relationMember,
968                                Direction direction,
969                                Set<Way> neededIncompleteMembers) {
970            this.relation = relation;
971            this.relationMember = relationMember;
972            this.direction = direction;
973            this.neededIncompleteMembers = neededIncompleteMembers;
974        }
975
976        RelationMember getRelationMember() {
977            return relationMember;
978        }
979
980        Direction getDirection() {
981            return direction;
982        }
983
984        public Set<Way> getNeededIncompleteMembers() {
985            return neededIncompleteMembers;
986        }
987
988        Relation getRelation() {
989            return relation;
990        }
991    }
992
993    enum Direction {
994        FORWARDS,
995        BACKWARDS,
996        UNKNOWN,
997        IRRELEVANT;
998
999        /**
1000         * Merge directions (this helps avoid overriding {@link #FORWARDS} with {@link #BACKWARDS}).
1001         * @param other The other direction to merge. {@link #UNKNOWN} will be overridden.
1002         * @return The merged direction
1003         */
1004        Direction merge(Direction other) {
1005            if (this == other) {
1006                return this;
1007            }
1008            if (this == IRRELEVANT || other == IRRELEVANT ||
1009                    (this == FORWARDS && other == BACKWARDS) ||
1010                    (other == FORWARDS && this == BACKWARDS)) {
1011                return IRRELEVANT;
1012            }
1013            if (this == UNKNOWN) {
1014                return other;
1015            }
1016            if (other == UNKNOWN) {
1017                return this;
1018            }
1019            return UNKNOWN;
1020        }
1021    }
1022
1023    enum WarningType {
1024        GENERIC,
1025        ROLE
1026    }
1027
1028    enum MissingMemberStrategy {
1029        GO_AHEAD_WITH_DOWNLOADS,
1030        GO_AHEAD_WITHOUT_DOWNLOADS,
1031        USER_ABORTED
1032    }
1033}