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