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

Last change on this file since 9783 was 9473, checked in by simon04, 8 years ago

fix #12343 - Display at most 20 primitives for some confirmation dialogs (e.g., deletion of relations)

  • Property svn:eol-style set to native
File size: 21.8 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.EnumSet;
13import java.util.HashMap;
14import java.util.HashSet;
15import java.util.Iterator;
16import java.util.LinkedList;
17import java.util.List;
18import java.util.Map;
19import java.util.Map.Entry;
20import java.util.Objects;
21import java.util.Set;
22
23import javax.swing.Icon;
24import javax.swing.JOptionPane;
25import javax.swing.JPanel;
26
27import org.openstreetmap.josm.Main;
28import org.openstreetmap.josm.actions.SplitWayAction;
29import org.openstreetmap.josm.data.osm.Node;
30import org.openstreetmap.josm.data.osm.OsmPrimitive;
31import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
32import org.openstreetmap.josm.data.osm.PrimitiveData;
33import org.openstreetmap.josm.data.osm.Relation;
34import org.openstreetmap.josm.data.osm.RelationToChildReference;
35import org.openstreetmap.josm.data.osm.Way;
36import org.openstreetmap.josm.data.osm.WaySegment;
37import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
38import org.openstreetmap.josm.gui.DefaultNameFormatter;
39import org.openstreetmap.josm.gui.dialogs.DeleteFromRelationConfirmationDialog;
40import org.openstreetmap.josm.gui.layer.OsmDataLayer;
41import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
42import org.openstreetmap.josm.tools.CheckParameterUtil;
43import org.openstreetmap.josm.tools.ImageProvider;
44import org.openstreetmap.josm.tools.Utils;
45
46/**
47 * A command to delete a number of primitives from the dataset.
48 * @since 23
49 */
50public class DeleteCommand extends Command {
51 /**
52 * The primitives that get deleted.
53 */
54 private final Collection<? extends OsmPrimitive> toDelete;
55 private final Map<OsmPrimitive, PrimitiveData> clonedPrimitives = new HashMap<>();
56
57 /**
58 * Constructor. Deletes a collection of primitives in the current edit layer.
59 *
60 * @param data the primitives to delete. Must neither be null nor empty.
61 * @throws IllegalArgumentException if data is null or empty
62 */
63 public DeleteCommand(Collection<? extends OsmPrimitive> data) {
64 CheckParameterUtil.ensureParameterNotNull(data, "data");
65 if (data.isEmpty())
66 throw new IllegalArgumentException(tr("At least one object to delete required, got empty collection"));
67 this.toDelete = data;
68 checkConsistency();
69 }
70
71 /**
72 * Constructor. Deletes a single primitive in the current edit layer.
73 *
74 * @param data the primitive to delete. Must not be null.
75 * @throws IllegalArgumentException if data is null
76 */
77 public DeleteCommand(OsmPrimitive data) {
78 this(Collections.singleton(data));
79 }
80
81 /**
82 * Constructor for a single data item. Use the collection constructor to delete multiple
83 * objects.
84 *
85 * @param layer the layer context for deleting this primitive. Must not be null.
86 * @param data the primitive to delete. Must not be null.
87 * @throws IllegalArgumentException if data is null
88 * @throws IllegalArgumentException if layer is null
89 */
90 public DeleteCommand(OsmDataLayer layer, OsmPrimitive data) {
91 this(layer, Collections.singleton(data));
92 }
93
94 /**
95 * Constructor for a collection of data to be deleted in the context of
96 * a specific layer
97 *
98 * @param layer the layer context for deleting these primitives. Must not be null.
99 * @param data the primitives to delete. Must neither be null nor empty.
100 * @throws IllegalArgumentException if layer is null
101 * @throws IllegalArgumentException if data is null or empty
102 */
103 public DeleteCommand(OsmDataLayer layer, Collection<? extends OsmPrimitive> data) {
104 super(layer);
105 CheckParameterUtil.ensureParameterNotNull(data, "data");
106 if (data.isEmpty())
107 throw new IllegalArgumentException(tr("At least one object to delete required, got empty collection"));
108 this.toDelete = data;
109 checkConsistency();
110 }
111
112 private void checkConsistency() {
113 for (OsmPrimitive p : toDelete) {
114 if (p == null) {
115 throw new IllegalArgumentException("Primitive to delete must not be null");
116 } else if (p.getDataSet() == null) {
117 throw new IllegalArgumentException("Primitive to delete must be in a dataset");
118 }
119 }
120 }
121
122 @Override
123 public boolean executeCommand() {
124 // Make copy and remove all references (to prevent inconsistent dataset (delete referenced) while command is executed)
125 for (OsmPrimitive osm: toDelete) {
126 if (osm.isDeleted())
127 throw new IllegalArgumentException(osm + " is already deleted");
128 clonedPrimitives.put(osm, osm.save());
129
130 if (osm instanceof Way) {
131 ((Way) osm).setNodes(null);
132 } else if (osm instanceof Relation) {
133 ((Relation) osm).setMembers(null);
134 }
135 }
136
137 for (OsmPrimitive osm: toDelete) {
138 osm.setDeleted(true);
139 }
140
141 return true;
142 }
143
144 @Override
145 public void undoCommand() {
146 for (OsmPrimitive osm: toDelete) {
147 osm.setDeleted(false);
148 }
149
150 for (Entry<OsmPrimitive, PrimitiveData> entry: clonedPrimitives.entrySet()) {
151 entry.getKey().load(entry.getValue());
152 }
153 }
154
155 @Override
156 public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted,
157 Collection<OsmPrimitive> added) {
158 }
159
160 private Set<OsmPrimitiveType> getTypesToDelete() {
161 Set<OsmPrimitiveType> typesToDelete = EnumSet.noneOf(OsmPrimitiveType.class);
162 for (OsmPrimitive osm : toDelete) {
163 typesToDelete.add(OsmPrimitiveType.from(osm));
164 }
165 return typesToDelete;
166 }
167
168 @Override
169 public String getDescriptionText() {
170 if (toDelete.size() == 1) {
171 OsmPrimitive primitive = toDelete.iterator().next();
172 String msg = "";
173 switch(OsmPrimitiveType.from(primitive)) {
174 case NODE: msg = marktr("Delete node {0}"); break;
175 case WAY: msg = marktr("Delete way {0}"); break;
176 case RELATION:msg = marktr("Delete relation {0}"); break;
177 }
178
179 return tr(msg, primitive.getDisplayName(DefaultNameFormatter.getInstance()));
180 } else {
181 Set<OsmPrimitiveType> typesToDelete = getTypesToDelete();
182 String msg = "";
183 if (typesToDelete.size() > 1) {
184 msg = trn("Delete {0} object", "Delete {0} objects", toDelete.size(), toDelete.size());
185 } else {
186 OsmPrimitiveType t = typesToDelete.iterator().next();
187 switch(t) {
188 case NODE: msg = trn("Delete {0} node", "Delete {0} nodes", toDelete.size(), toDelete.size()); break;
189 case WAY: msg = trn("Delete {0} way", "Delete {0} ways", toDelete.size(), toDelete.size()); break;
190 case RELATION: msg = trn("Delete {0} relation", "Delete {0} relations", toDelete.size(), toDelete.size()); break;
191 }
192 }
193 return msg;
194 }
195 }
196
197 @Override
198 public Icon getDescriptionIcon() {
199 if (toDelete.size() == 1)
200 return ImageProvider.get(toDelete.iterator().next().getDisplayType());
201 Set<OsmPrimitiveType> typesToDelete = getTypesToDelete();
202 if (typesToDelete.size() > 1)
203 return ImageProvider.get("data", "object");
204 else
205 return ImageProvider.get(typesToDelete.iterator().next());
206 }
207
208 @Override public Collection<PseudoCommand> getChildren() {
209 if (toDelete.size() == 1)
210 return null;
211 else {
212 List<PseudoCommand> children = new ArrayList<>(toDelete.size());
213 for (final OsmPrimitive osm : toDelete) {
214 children.add(new PseudoCommand() {
215
216 @Override public String getDescriptionText() {
217 return tr("Deleted ''{0}''", osm.getDisplayName(DefaultNameFormatter.getInstance()));
218 }
219
220 @Override public Icon getDescriptionIcon() {
221 return ImageProvider.get(osm.getDisplayType());
222 }
223
224 @Override public Collection<? extends OsmPrimitive> getParticipatingPrimitives() {
225 return Collections.singleton(osm);
226 }
227
228 });
229 }
230 return children;
231
232 }
233 }
234
235 @Override public Collection<? extends OsmPrimitive> getParticipatingPrimitives() {
236 return toDelete;
237 }
238
239 /**
240 * Delete the primitives and everything they reference.
241 *
242 * If a node is deleted, the node and all ways and relations the node is part of are deleted as well.
243 * If a way is deleted, all relations the way is member of are also deleted.
244 * If a way is deleted, only the way and no nodes are deleted.
245 *
246 * @param layer the {@link OsmDataLayer} in whose context primitives are deleted. Must not be null.
247 * @param selection The list of all object to be deleted.
248 * @param silent Set to true if the user should not be bugged with additional dialogs
249 * @return command A command to perform the deletions, or null of there is nothing to delete.
250 * @throws IllegalArgumentException if layer is null
251 */
252 public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection, boolean silent) {
253 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
254 if (selection == null || selection.isEmpty()) return null;
255 Set<OsmPrimitive> parents = OsmPrimitive.getReferrer(selection);
256 parents.addAll(selection);
257
258 if (parents.isEmpty())
259 return null;
260 if (!silent && !checkAndConfirmOutlyingDelete(parents, null))
261 return null;
262 return new DeleteCommand(layer, parents);
263 }
264
265 /**
266 * Delete the primitives and everything they reference.
267 *
268 * If a node is deleted, the node and all ways and relations the node is part of are deleted as well.
269 * If a way is deleted, all relations the way is member of are also deleted.
270 * If a way is deleted, only the way and no nodes are deleted.
271 *
272 * @param layer the {@link OsmDataLayer} in whose context primitives are deleted. Must not be null.
273 * @param selection The list of all object to be deleted.
274 * @return command A command to perform the deletions, or null of there is nothing to delete.
275 * @throws IllegalArgumentException if layer is null
276 */
277 public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) {
278 return deleteWithReferences(layer, selection, false);
279 }
280
281 /**
282 * Try to delete all given primitives.
283 *
284 * If a node is used by a way, it's removed from that way. If a node or a way is used by a
285 * relation, inform the user and do not delete.
286 *
287 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If
288 * they are part of a relation, inform the user and do not delete.
289 *
290 * @param layer the {@link OsmDataLayer} in whose context the primitives are deleted
291 * @param selection the objects to delete.
292 * @return command a command to perform the deletions, or null if there is nothing to delete.
293 */
294 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) {
295 return delete(layer, selection, true, false);
296 }
297
298 /**
299 * Replies the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which
300 * can be deleted too. A node can be deleted if
301 * <ul>
302 * <li>it is untagged (see {@link Node#isTagged()}</li>
303 * <li>it is not referred to by other non-deleted primitives outside of <code>primitivesToDelete</code></li>
304 * </ul>
305 * @param primitivesToDelete the primitives to delete
306 * @return the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which
307 * can be deleted too
308 */
309 protected static Collection<Node> computeNodesToDelete(Collection<OsmPrimitive> primitivesToDelete) {
310 Collection<Node> nodesToDelete = new HashSet<>();
311 for (Way way : OsmPrimitive.getFilteredList(primitivesToDelete, Way.class)) {
312 for (Node n : way.getNodes()) {
313 if (n.isTagged()) {
314 continue;
315 }
316 Collection<OsmPrimitive> referringPrimitives = n.getReferrers();
317 referringPrimitives.removeAll(primitivesToDelete);
318 int count = 0;
319 for (OsmPrimitive p : referringPrimitives) {
320 if (!p.isDeleted()) {
321 count++;
322 }
323 }
324 if (count == 0) {
325 nodesToDelete.add(n);
326 }
327 }
328 }
329 return nodesToDelete;
330 }
331
332 /**
333 * Try to delete all given primitives.
334 *
335 * If a node is used by a way, it's removed from that way. If a node or a way is used by a
336 * relation, inform the user and do not delete.
337 *
338 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If
339 * they are part of a relation, inform the user and do not delete.
340 *
341 * @param layer the {@link OsmDataLayer} in whose context the primitives are deleted
342 * @param selection the objects to delete.
343 * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well
344 * @return command a command to perform the deletions, or null if there is nothing to delete.
345 */
346 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection,
347 boolean alsoDeleteNodesInWay) {
348 return delete(layer, selection, alsoDeleteNodesInWay, false /* not silent */);
349 }
350
351 /**
352 * Try to delete all given primitives.
353 *
354 * If a node is used by a way, it's removed from that way. If a node or a way is used by a
355 * relation, inform the user and do not delete.
356 *
357 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If
358 * they are part of a relation, inform the user and do not delete.
359 *
360 * @param layer the {@link OsmDataLayer} in whose context the primitives are deleted
361 * @param selection the objects to delete.
362 * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well
363 * @param silent set to true if the user should not be bugged with additional questions
364 * @return command a command to perform the deletions, or null if there is nothing to delete.
365 */
366 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection,
367 boolean alsoDeleteNodesInWay, boolean silent) {
368 if (selection == null || selection.isEmpty())
369 return null;
370
371 // Diamond operator does not work with Java 9 here
372 Set<OsmPrimitive> primitivesToDelete = new HashSet<OsmPrimitive>(selection);
373
374 Collection<Relation> relationsToDelete = Utils.filteredCollection(primitivesToDelete, Relation.class);
375 if (!relationsToDelete.isEmpty() && !silent && !confirmRelationDeletion(relationsToDelete))
376 return null;
377
378 if (alsoDeleteNodesInWay) {
379 // delete untagged nodes only referenced by primitives in primitivesToDelete, too
380 Collection<Node> nodesToDelete = computeNodesToDelete(primitivesToDelete);
381 primitivesToDelete.addAll(nodesToDelete);
382 }
383
384 if (!silent && !checkAndConfirmOutlyingDelete(
385 primitivesToDelete, Utils.filteredCollection(primitivesToDelete, Way.class)))
386 return null;
387
388 Collection<Way> waysToBeChanged = new HashSet<>(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.isClosed()) {
443 // If the way is circular (first and last nodes are the same), the way shouldn't be splitted
444
445 List<Node> n = new ArrayList<>();
446
447 n.addAll(ws.way.getNodes().subList(ws.lowerIndex + 1, ws.way.getNodesCount() - 1));
448 n.addAll(ws.way.getNodes().subList(0, ws.lowerIndex + 1));
449
450 Way wnew = new Way(ws.way);
451 wnew.setNodes(n);
452
453 return new ChangeCommand(ws.way, wnew);
454 }
455
456 List<Node> n1 = new ArrayList<>();
457 List<Node> 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,
479 Collection<? extends OsmPrimitive> ignore) {
480 return Command.checkAndConfirmOutlyingOperation("delete",
481 tr("Delete confirmation"),
482 tr("You are about to delete nodes outside of the area you have downloaded."
483 + "<br>"
484 + "This can cause problems because other objects (that you do not see) might use them."
485 + "<br>"
486 + "Do you really want to delete?"),
487 tr("You are about to delete incomplete objects."
488 + "<br>"
489 + "This will cause problems because you don''t see the real object."
490 + "<br>" + "Do you really want to delete?"),
491 primitives, ignore);
492 }
493
494 private static boolean confirmRelationDeletion(Collection<Relation> relations) {
495 JPanel msg = new JPanel(new GridBagLayout());
496 msg.add(new JMultilineLabel("<html>" + trn(
497 "You are about to delete {0} relation: {1}"
498 + "<br/>"
499 + "This step is rarely necessary and cannot be undone easily after being uploaded to the server."
500 + "<br/>"
501 + "Do you really want to delete?",
502 "You are about to delete {0} relations: {1}"
503 + "<br/>"
504 + "This step is rarely necessary and cannot be undone easily after being uploaded to the server."
505 + "<br/>"
506 + "Do you really want to delete?",
507 relations.size(), relations.size(), DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(relations, 20))
508 + "</html>"));
509 return ConditionalOptionPaneUtil.showConfirmationDialog(
510 "delete_relations",
511 Main.parent,
512 msg,
513 tr("Delete relation?"),
514 JOptionPane.YES_NO_OPTION,
515 JOptionPane.QUESTION_MESSAGE,
516 JOptionPane.YES_OPTION);
517 }
518
519 @Override
520 public int hashCode() {
521 return Objects.hash(super.hashCode(), toDelete, clonedPrimitives);
522 }
523
524 @Override
525 public boolean equals(Object obj) {
526 if (this == obj) return true;
527 if (obj == null || getClass() != obj.getClass()) return false;
528 if (!super.equals(obj)) return false;
529 DeleteCommand that = (DeleteCommand) obj;
530 return Objects.equals(toDelete, that.toDelete) &&
531 Objects.equals(clonedPrimitives, that.clonedPrimitives);
532 }
533}
Note: See TracBrowser for help on using the repository browser.