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

Last change on this file since 11241 was 11240, checked in by Don-vip, 7 years ago

see #10387 - refactor various actions and commands so they can be used without data layer

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