source: josm/trunk/src/org/openstreetmap/josm/command/DeleteCommand.java@ 8148

Last change on this file since 8148 was 7675, checked in by Don-vip, 9 years ago

see #10680 - detect invalid delete commands earlier

  • Property svn:eol-style set to native
File size: 21.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.command;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.GridBagLayout;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.Collections;
12import java.util.HashMap;
13import java.util.HashSet;
14import java.util.Iterator;
15import java.util.LinkedList;
16import java.util.List;
17import java.util.Map;
18import java.util.Map.Entry;
19import java.util.Set;
20
21import javax.swing.Icon;
22import javax.swing.JOptionPane;
23import javax.swing.JPanel;
24
25import org.openstreetmap.josm.Main;
26import org.openstreetmap.josm.actions.SplitWayAction;
27import org.openstreetmap.josm.data.osm.Node;
28import org.openstreetmap.josm.data.osm.OsmPrimitive;
29import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
30import org.openstreetmap.josm.data.osm.PrimitiveData;
31import org.openstreetmap.josm.data.osm.Relation;
32import org.openstreetmap.josm.data.osm.RelationToChildReference;
33import org.openstreetmap.josm.data.osm.Way;
34import org.openstreetmap.josm.data.osm.WaySegment;
35import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
36import org.openstreetmap.josm.gui.DefaultNameFormatter;
37import org.openstreetmap.josm.gui.actionsupport.DeleteFromRelationConfirmationDialog;
38import org.openstreetmap.josm.gui.layer.OsmDataLayer;
39import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
40import org.openstreetmap.josm.tools.CheckParameterUtil;
41import org.openstreetmap.josm.tools.ImageProvider;
42import org.openstreetmap.josm.tools.Utils;
43
44/**
45 * A command to delete a number of primitives from the dataset.
46 * @since 23
47 */
48public class DeleteCommand extends Command {
49 /**
50 * The primitives that get deleted.
51 */
52 private final Collection<? extends OsmPrimitive> toDelete;
53 private final Map<OsmPrimitive, PrimitiveData> clonedPrimitives = new HashMap<>();
54
55 /**
56 * Constructor. Deletes a collection of primitives in the current edit layer.
57 *
58 * @param data the primitives to delete. Must neither be null nor empty.
59 * @throws IllegalArgumentException thrown if data is null or empty
60 */
61 public DeleteCommand(Collection<? extends OsmPrimitive> data) throws IllegalArgumentException {
62 CheckParameterUtil.ensureParameterNotNull(data, "data");
63 if (data.isEmpty())
64 throw new IllegalArgumentException(tr("At least one object to delete required, got empty collection"));
65 this.toDelete = data;
66 checkConsistency();
67 }
68
69 /**
70 * Constructor. Deletes a single primitive in the current edit layer.
71 *
72 * @param data the primitive to delete. Must not be null.
73 * @throws IllegalArgumentException thrown if data is null
74 */
75 public DeleteCommand(OsmPrimitive data) throws IllegalArgumentException {
76 this(Collections.singleton(data));
77 }
78
79 /**
80 * Constructor for a single data item. Use the collection constructor to delete multiple
81 * objects.
82 *
83 * @param layer the layer context for deleting this primitive. Must not be null.
84 * @param data the primitive to delete. Must not be null.
85 * @throws IllegalArgumentException thrown if data is null
86 * @throws IllegalArgumentException thrown if layer is null
87 */
88 public DeleteCommand(OsmDataLayer layer, OsmPrimitive data) throws IllegalArgumentException {
89 this(layer, Collections.singleton(data));
90 }
91
92 /**
93 * Constructor for a collection of data to be deleted in the context of
94 * a specific layer
95 *
96 * @param layer the layer context for deleting these primitives. Must not be null.
97 * @param data the primitives to delete. Must neither be null nor empty.
98 * @throws IllegalArgumentException thrown if layer is null
99 * @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}
Note: See TracBrowser for help on using the repository browser.