001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.command;
003
004import static org.openstreetmap.josm.tools.I18n.marktr;
005import static org.openstreetmap.josm.tools.I18n.tr;
006import static org.openstreetmap.josm.tools.I18n.trn;
007
008import java.awt.GridBagLayout;
009import java.util.ArrayList;
010import java.util.Arrays;
011import java.util.Collection;
012import java.util.Collections;
013import java.util.EnumSet;
014import java.util.HashMap;
015import java.util.HashSet;
016import java.util.Iterator;
017import java.util.LinkedList;
018import java.util.List;
019import java.util.Map;
020import java.util.Map.Entry;
021import java.util.Objects;
022import java.util.Set;
023
024import javax.swing.Icon;
025import javax.swing.JOptionPane;
026import javax.swing.JPanel;
027
028import org.openstreetmap.josm.Main;
029import org.openstreetmap.josm.actions.SplitWayAction;
030import org.openstreetmap.josm.actions.SplitWayAction.SplitWayResult;
031import org.openstreetmap.josm.data.osm.Node;
032import org.openstreetmap.josm.data.osm.OsmPrimitive;
033import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
034import org.openstreetmap.josm.data.osm.PrimitiveData;
035import org.openstreetmap.josm.data.osm.Relation;
036import org.openstreetmap.josm.data.osm.RelationToChildReference;
037import org.openstreetmap.josm.data.osm.Way;
038import org.openstreetmap.josm.data.osm.WaySegment;
039import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
040import org.openstreetmap.josm.gui.DefaultNameFormatter;
041import org.openstreetmap.josm.gui.dialogs.DeleteFromRelationConfirmationDialog;
042import org.openstreetmap.josm.gui.layer.OsmDataLayer;
043import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
044import org.openstreetmap.josm.tools.CheckParameterUtil;
045import org.openstreetmap.josm.tools.ImageProvider;
046import org.openstreetmap.josm.tools.Utils;
047
048/**
049 * A command to delete a number of primitives from the dataset.
050 * @since 23
051 */
052public class DeleteCommand extends Command {
053    private static final class DeleteChildCommand implements PseudoCommand {
054        private final OsmPrimitive osm;
055
056        private DeleteChildCommand(OsmPrimitive osm) {
057            this.osm = osm;
058        }
059
060        @Override
061        public String getDescriptionText() {
062            return tr("Deleted ''{0}''", osm.getDisplayName(DefaultNameFormatter.getInstance()));
063        }
064
065        @Override
066        public Icon getDescriptionIcon() {
067            return ImageProvider.get(osm.getDisplayType());
068        }
069
070        @Override
071        public Collection<? extends OsmPrimitive> getParticipatingPrimitives() {
072            return Collections.singleton(osm);
073        }
074
075        @Override
076        public String toString() {
077            return "DeleteChildCommand [osm=" + osm + "]";
078        }
079    }
080
081    /**
082     * The primitives that get deleted.
083     */
084    private final Collection<? extends OsmPrimitive> toDelete;
085    private final Map<OsmPrimitive, PrimitiveData> clonedPrimitives = new HashMap<>();
086
087    /**
088     * Constructor. Deletes a collection of primitives in the current edit layer.
089     *
090     * @param data the primitives to delete. Must neither be null nor empty.
091     * @throws IllegalArgumentException if data is null or empty
092     */
093    public DeleteCommand(Collection<? extends OsmPrimitive> data) {
094        CheckParameterUtil.ensureParameterNotNull(data, "data");
095        this.toDelete = data;
096        checkConsistency();
097    }
098
099    /**
100     * Constructor. Deletes a single primitive in the current edit layer.
101     *
102     * @param data  the primitive to delete. Must not be null.
103     * @throws IllegalArgumentException if data is null
104     */
105    public DeleteCommand(OsmPrimitive data) {
106        this(Collections.singleton(data));
107    }
108
109    /**
110     * Constructor for a single data item. Use the collection constructor to delete multiple
111     * objects.
112     *
113     * @param layer the layer context for deleting this primitive. Must not be null.
114     * @param data the primitive to delete. Must not be null.
115     * @throws IllegalArgumentException if data is null
116     * @throws IllegalArgumentException if layer is null
117     */
118    public DeleteCommand(OsmDataLayer layer, OsmPrimitive data) {
119        this(layer, Collections.singleton(data));
120    }
121
122    /**
123     * Constructor for a collection of data to be deleted in the context of
124     * a specific layer
125     *
126     * @param layer the layer context for deleting these primitives. Must not be null.
127     * @param data the primitives to delete. Must neither be null nor empty.
128     * @throws IllegalArgumentException if layer is null
129     * @throws IllegalArgumentException if data is null or empty
130     */
131    public DeleteCommand(OsmDataLayer layer, Collection<? extends OsmPrimitive> data) {
132        super(layer);
133        CheckParameterUtil.ensureParameterNotNull(data, "data");
134        this.toDelete = data;
135        checkConsistency();
136    }
137
138    private void checkConsistency() {
139        if (toDelete.isEmpty()) {
140            throw new IllegalArgumentException(tr("At least one object to delete required, got empty collection"));
141        }
142        for (OsmPrimitive p : toDelete) {
143            if (p == null) {
144                throw new IllegalArgumentException("Primitive to delete must not be null");
145            } else if (p.getDataSet() == null) {
146                throw new IllegalArgumentException("Primitive to delete must be in a dataset");
147            }
148        }
149    }
150
151    @Override
152    public boolean executeCommand() {
153        // Make copy and remove all references (to prevent inconsistent dataset (delete referenced) while command is executed)
154        for (OsmPrimitive osm: toDelete) {
155            if (osm.isDeleted())
156                throw new IllegalArgumentException(osm + " is already deleted");
157            clonedPrimitives.put(osm, osm.save());
158
159            if (osm instanceof Way) {
160                ((Way) osm).setNodes(null);
161            } else if (osm instanceof Relation) {
162                ((Relation) osm).setMembers(null);
163            }
164        }
165
166        for (OsmPrimitive osm: toDelete) {
167            osm.setDeleted(true);
168        }
169
170        return true;
171    }
172
173    @Override
174    public void undoCommand() {
175        for (OsmPrimitive osm: toDelete) {
176            osm.setDeleted(false);
177        }
178
179        for (Entry<OsmPrimitive, PrimitiveData> entry: clonedPrimitives.entrySet()) {
180            entry.getKey().load(entry.getValue());
181        }
182    }
183
184    @Override
185    public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted, Collection<OsmPrimitive> added) {
186        // Do nothing
187    }
188
189    private EnumSet<OsmPrimitiveType> getTypesToDelete() {
190        EnumSet<OsmPrimitiveType> typesToDelete = EnumSet.noneOf(OsmPrimitiveType.class);
191        for (OsmPrimitive osm : toDelete) {
192            typesToDelete.add(OsmPrimitiveType.from(osm));
193        }
194        return typesToDelete;
195    }
196
197    @Override
198    public String getDescriptionText() {
199        if (toDelete.size() == 1) {
200            OsmPrimitive primitive = toDelete.iterator().next();
201            String msg;
202            switch(OsmPrimitiveType.from(primitive)) {
203            case NODE: msg = marktr("Delete node {0}"); break;
204            case WAY: msg = marktr("Delete way {0}"); break;
205            case RELATION:msg = marktr("Delete relation {0}"); break;
206            default: throw new AssertionError();
207            }
208
209            return tr(msg, primitive.getDisplayName(DefaultNameFormatter.getInstance()));
210        } else {
211            Set<OsmPrimitiveType> typesToDelete = getTypesToDelete();
212            String msg;
213            if (typesToDelete.size() > 1) {
214                msg = trn("Delete {0} object", "Delete {0} objects", toDelete.size(), toDelete.size());
215            } else {
216                OsmPrimitiveType t = typesToDelete.iterator().next();
217                switch(t) {
218                case NODE: msg = trn("Delete {0} node", "Delete {0} nodes", toDelete.size(), toDelete.size()); break;
219                case WAY: msg = trn("Delete {0} way", "Delete {0} ways", toDelete.size(), toDelete.size()); break;
220                case RELATION: msg = trn("Delete {0} relation", "Delete {0} relations", toDelete.size(), toDelete.size()); break;
221                default: throw new AssertionError();
222                }
223            }
224            return msg;
225        }
226    }
227
228    @Override
229    public Icon getDescriptionIcon() {
230        if (toDelete.size() == 1)
231            return ImageProvider.get(toDelete.iterator().next().getDisplayType());
232        Set<OsmPrimitiveType> typesToDelete = getTypesToDelete();
233        if (typesToDelete.size() > 1)
234            return ImageProvider.get("data", "object");
235        else
236            return ImageProvider.get(typesToDelete.iterator().next());
237    }
238
239    @Override public Collection<PseudoCommand> getChildren() {
240        if (toDelete.size() == 1)
241            return null;
242        else {
243            List<PseudoCommand> children = new ArrayList<>(toDelete.size());
244            for (final OsmPrimitive osm : toDelete) {
245                children.add(new DeleteChildCommand(osm));
246            }
247            return children;
248
249        }
250    }
251
252    @Override public Collection<? extends OsmPrimitive> getParticipatingPrimitives() {
253        return toDelete;
254    }
255
256    /**
257     * Delete the primitives and everything they reference.
258     *
259     * If a node is deleted, the node and all ways and relations the node is part of are deleted as well.
260     * If a way is deleted, all relations the way is member of are also deleted.
261     * If a way is deleted, only the way and no nodes are deleted.
262     *
263     * @param layer the {@link OsmDataLayer} in whose context primitives are deleted. Must not be null.
264     * @param selection The list of all object to be deleted.
265     * @param silent  Set to true if the user should not be bugged with additional dialogs
266     * @return command A command to perform the deletions, or null of there is nothing to delete.
267     * @throws IllegalArgumentException if layer is null
268     */
269    public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection, boolean silent) {
270        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
271        if (selection == null || selection.isEmpty()) return null;
272        Set<OsmPrimitive> parents = OsmPrimitive.getReferrer(selection);
273        parents.addAll(selection);
274
275        if (parents.isEmpty())
276            return null;
277        if (!silent && !checkAndConfirmOutlyingDelete(parents, null))
278            return null;
279        return new DeleteCommand(layer, parents);
280    }
281
282    /**
283     * Delete the primitives and everything they reference.
284     *
285     * If a node is deleted, the node and all ways and relations the node is part of are deleted as well.
286     * If a way is deleted, all relations the way is member of are also deleted.
287     * If a way is deleted, only the way and no nodes are deleted.
288     *
289     * @param layer the {@link OsmDataLayer} in whose context primitives are deleted. Must not be null.
290     * @param selection The list of all object to be deleted.
291     * @return command A command to perform the deletions, or null of there is nothing to delete.
292     * @throws IllegalArgumentException if layer is null
293     */
294    public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) {
295        return deleteWithReferences(layer, selection, false);
296    }
297
298    /**
299     * Try to delete all given primitives.
300     *
301     * If a node is used by a way, it's removed from that way. If a node or a way is used by a
302     * relation, inform the user and do not delete.
303     *
304     * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If
305     * they are part of a relation, inform the user and do not delete.
306     *
307     * @param layer the {@link OsmDataLayer} in whose context the primitives are deleted
308     * @param selection the objects to delete.
309     * @return command a command to perform the deletions, or null if there is nothing to delete.
310     */
311    public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) {
312        return delete(layer, selection, true, false);
313    }
314
315    /**
316     * Replies the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which
317     * can be deleted too. A node can be deleted if
318     * <ul>
319     *    <li>it is untagged (see {@link Node#isTagged()}</li>
320     *    <li>it is not referred to by other non-deleted primitives outside of  <code>primitivesToDelete</code></li>
321     * </ul>
322     * @param primitivesToDelete  the primitives to delete
323     * @return the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which
324     * can be deleted too
325     */
326    protected static Collection<Node> computeNodesToDelete(Collection<OsmPrimitive> primitivesToDelete) {
327        Collection<Node> nodesToDelete = new HashSet<>();
328        for (Way way : OsmPrimitive.getFilteredList(primitivesToDelete, Way.class)) {
329            for (Node n : way.getNodes()) {
330                if (n.isTagged()) {
331                    continue;
332                }
333                Collection<OsmPrimitive> referringPrimitives = n.getReferrers();
334                referringPrimitives.removeAll(primitivesToDelete);
335                int count = 0;
336                for (OsmPrimitive p : referringPrimitives) {
337                    if (!p.isDeleted()) {
338                        count++;
339                    }
340                }
341                if (count == 0) {
342                    nodesToDelete.add(n);
343                }
344            }
345        }
346        return nodesToDelete;
347    }
348
349    /**
350     * Try to delete all given primitives.
351     *
352     * If a node is used by a way, it's removed from that way. If a node or a way is used by a
353     * relation, inform the user and do not delete.
354     *
355     * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If
356     * they are part of a relation, inform the user and do not delete.
357     *
358     * @param layer the {@link OsmDataLayer} in whose context the primitives are deleted
359     * @param selection the objects to delete.
360     * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well
361     * @return command a command to perform the deletions, or null if there is nothing to delete.
362     */
363    public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection,
364            boolean alsoDeleteNodesInWay) {
365        return delete(layer, selection, alsoDeleteNodesInWay, false /* not silent */);
366    }
367
368    /**
369     * Try to delete all given primitives.
370     *
371     * If a node is used by a way, it's removed from that way. If a node or a way is used by a
372     * relation, inform the user and do not delete.
373     *
374     * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If
375     * they are part of a relation, inform the user and do not delete.
376     *
377     * @param layer the {@link OsmDataLayer} in whose context the primitives are deleted
378     * @param selection the objects to delete.
379     * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well
380     * @param silent set to true if the user should not be bugged with additional questions
381     * @return command a command to perform the deletions, or null if there is nothing to delete.
382     */
383    public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection,
384            boolean alsoDeleteNodesInWay, boolean silent) {
385        if (selection == null || selection.isEmpty())
386            return null;
387
388        // Diamond operator does not work with Java 9 here
389        @SuppressWarnings("unused")
390        Set<OsmPrimitive> primitivesToDelete = new HashSet<OsmPrimitive>(selection);
391
392        Collection<Relation> relationsToDelete = Utils.filteredCollection(primitivesToDelete, Relation.class);
393        if (!relationsToDelete.isEmpty() && !silent && !confirmRelationDeletion(relationsToDelete))
394            return null;
395
396        if (alsoDeleteNodesInWay) {
397            // delete untagged nodes only referenced by primitives in primitivesToDelete, too
398            Collection<Node> nodesToDelete = computeNodesToDelete(primitivesToDelete);
399            primitivesToDelete.addAll(nodesToDelete);
400        }
401
402        if (!silent && !checkAndConfirmOutlyingDelete(
403                primitivesToDelete, Utils.filteredCollection(primitivesToDelete, Way.class)))
404            return null;
405
406        Collection<Way> waysToBeChanged = new HashSet<>(OsmPrimitive.getFilteredSet(OsmPrimitive.getReferrer(primitivesToDelete), Way.class));
407
408        Collection<Command> cmds = new LinkedList<>();
409        for (Way w : waysToBeChanged) {
410            Way wnew = new Way(w);
411            wnew.removeNodes(OsmPrimitive.getFilteredSet(primitivesToDelete, Node.class));
412            if (wnew.getNodesCount() < 2) {
413                primitivesToDelete.add(w);
414            } else {
415                cmds.add(new ChangeNodesCommand(w, wnew.getNodes()));
416            }
417        }
418
419        // get a confirmation that the objects to delete can be removed from their parent relations
420        //
421        if (!silent) {
422            Set<RelationToChildReference> references = RelationToChildReference.getRelationToChildReferences(primitivesToDelete);
423            Iterator<RelationToChildReference> it = references.iterator();
424            while (it.hasNext()) {
425                RelationToChildReference ref = it.next();
426                if (ref.getParent().isDeleted()) {
427                    it.remove();
428                }
429            }
430            if (!references.isEmpty()) {
431                DeleteFromRelationConfirmationDialog dialog = DeleteFromRelationConfirmationDialog.getInstance();
432                dialog.getModel().populate(references);
433                dialog.setVisible(true);
434                if (dialog.isCanceled())
435                    return null;
436            }
437        }
438
439        // remove the objects from their parent relations
440        //
441        for (Relation cur : OsmPrimitive.getFilteredSet(OsmPrimitive.getReferrer(primitivesToDelete), Relation.class)) {
442            Relation rel = new Relation(cur);
443            rel.removeMembersFor(primitivesToDelete);
444            cmds.add(new ChangeCommand(cur, rel));
445        }
446
447        // build the delete command
448        //
449        if (!primitivesToDelete.isEmpty()) {
450            cmds.add(new DeleteCommand(layer, primitivesToDelete));
451        }
452
453        return new SequenceCommand(tr("Delete"), cmds);
454    }
455
456    /**
457     * Create a command that deletes a single way segment. The way may be split by this.
458     * @param layer The layer the segment is in.
459     * @param ws The way segment that should be deleted
460     * @return A matching command to safely delete that segment.
461     */
462    public static Command deleteWaySegment(OsmDataLayer layer, WaySegment ws) {
463        if (ws.way.getNodesCount() < 3)
464            return delete(layer, Collections.singleton(ws.way), false);
465
466        if (ws.way.isClosed()) {
467            // If the way is circular (first and last nodes are the same), the way shouldn't be splitted
468
469            List<Node> n = new ArrayList<>();
470
471            n.addAll(ws.way.getNodes().subList(ws.lowerIndex + 1, ws.way.getNodesCount() - 1));
472            n.addAll(ws.way.getNodes().subList(0, ws.lowerIndex + 1));
473
474            Way wnew = new Way(ws.way);
475            wnew.setNodes(n);
476
477            return new ChangeCommand(ws.way, wnew);
478        }
479
480        List<Node> n1 = new ArrayList<>();
481        List<Node> n2 = new ArrayList<>();
482
483        n1.addAll(ws.way.getNodes().subList(0, ws.lowerIndex + 1));
484        n2.addAll(ws.way.getNodes().subList(ws.lowerIndex + 1, ws.way.getNodesCount()));
485
486        Way wnew = new Way(ws.way);
487
488        if (n1.size() < 2) {
489            wnew.setNodes(n2);
490            return new ChangeCommand(ws.way, wnew);
491        } else if (n2.size() < 2) {
492            wnew.setNodes(n1);
493            return new ChangeCommand(ws.way, wnew);
494        } else {
495            SplitWayResult split = SplitWayAction.splitWay(layer, ws.way, Arrays.asList(n1, n2), Collections.<OsmPrimitive>emptyList());
496            return split != null ? split.getCommand() : null;
497        }
498    }
499
500    public static boolean checkAndConfirmOutlyingDelete(Collection<? extends OsmPrimitive> primitives,
501            Collection<? extends OsmPrimitive> ignore) {
502        return Command.checkAndConfirmOutlyingOperation("delete",
503                tr("Delete confirmation"),
504                tr("You are about to delete nodes outside of the area you have downloaded."
505                        + "<br>"
506                        + "This can cause problems because other objects (that you do not see) might use them."
507                        + "<br>"
508                        + "Do you really want to delete?"),
509                tr("You are about to delete incomplete objects."
510                        + "<br>"
511                        + "This will cause problems because you don''t see the real object."
512                        + "<br>" + "Do you really want to delete?"),
513                primitives, ignore);
514    }
515
516    private static boolean confirmRelationDeletion(Collection<Relation> relations) {
517        JPanel msg = new JPanel(new GridBagLayout());
518        msg.add(new JMultilineLabel("<html>" + trn(
519                "You are about to delete {0} relation: {1}"
520                + "<br/>"
521                + "This step is rarely necessary and cannot be undone easily after being uploaded to the server."
522                + "<br/>"
523                + "Do you really want to delete?",
524                "You are about to delete {0} relations: {1}"
525                + "<br/>"
526                + "This step is rarely necessary and cannot be undone easily after being uploaded to the server."
527                + "<br/>"
528                + "Do you really want to delete?",
529                relations.size(), relations.size(), DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(relations, 20))
530                + "</html>"));
531        return ConditionalOptionPaneUtil.showConfirmationDialog(
532                "delete_relations",
533                Main.parent,
534                msg,
535                tr("Delete relation?"),
536                JOptionPane.YES_NO_OPTION,
537                JOptionPane.QUESTION_MESSAGE,
538                JOptionPane.YES_OPTION);
539    }
540
541    @Override
542    public int hashCode() {
543        return Objects.hash(super.hashCode(), toDelete, clonedPrimitives);
544    }
545
546    @Override
547    public boolean equals(Object obj) {
548        if (this == obj) return true;
549        if (obj == null || getClass() != obj.getClass()) return false;
550        if (!super.equals(obj)) return false;
551        DeleteCommand that = (DeleteCommand) obj;
552        return Objects.equals(toDelete, that.toDelete) &&
553                Objects.equals(clonedPrimitives, that.clonedPrimitives);
554    }
555}