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

Last change on this file since 4894 was 4677, checked in by simon04, 12 years ago

fix #3423 - Warn when deleting a large relation

  • Property svn:eol-style set to native
File size: 20.3 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.command;
3
4import java.awt.GridBagLayout;
5import java.awt.geom.Area;
6import static org.openstreetmap.josm.tools.I18n.marktr;
7import static org.openstreetmap.josm.tools.I18n.tr;
8import static org.openstreetmap.josm.tools.I18n.trn;
9
10import java.util.ArrayList;
11import java.util.Collection;
12import java.util.Collections;
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.Set;
20import java.util.Map.Entry;
21
22import javax.swing.JLabel;
23
24import javax.swing.JOptionPane;
25import javax.swing.JPanel;
26import org.openstreetmap.josm.Main;
27import org.openstreetmap.josm.actions.SplitWayAction;
28import org.openstreetmap.josm.data.osm.Node;
29import org.openstreetmap.josm.data.osm.OsmPrimitive;
30import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
31import org.openstreetmap.josm.data.osm.PrimitiveData;
32import org.openstreetmap.josm.data.osm.Relation;
33import org.openstreetmap.josm.data.osm.RelationToChildReference;
34import org.openstreetmap.josm.data.osm.Way;
35import org.openstreetmap.josm.data.osm.WaySegment;
36import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
37import org.openstreetmap.josm.gui.DefaultNameFormatter;
38import org.openstreetmap.josm.gui.actionsupport.DeleteFromRelationConfirmationDialog;
39import org.openstreetmap.josm.gui.layer.OsmDataLayer;
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 *
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<OsmPrimitive, PrimitiveData>();
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 if (data == null)
63 throw new IllegalArgumentException("Parameter 'data' must not be empty");
64 if (data.isEmpty())
65 throw new IllegalArgumentException(tr("At least one object to delete required, got empty collection"));
66 this.toDelete = data;
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 CheckParameterUtil.ensureParameterNotNull(data, "data");
77 this.toDelete = Collections.singleton(data);
78 }
79
80 /**
81 * Constructor for a single data item. Use the collection constructor to delete multiple
82 * objects.
83 *
84 * @param layer the layer context for deleting this primitive. Must not be null.
85 * @param data the primitive to delete. Must not be null.
86 * @throws IllegalArgumentException thrown if data is null
87 * @throws IllegalArgumentException thrown if layer is null
88 */
89 public DeleteCommand(OsmDataLayer layer, OsmPrimitive data) throws IllegalArgumentException {
90 super(layer);
91 CheckParameterUtil.ensureParameterNotNull(data, "data");
92 this.toDelete = Collections.singleton(data);
93 }
94
95 /**
96 * Constructor for a collection of data to be deleted in the context of
97 * a specific layer
98 *
99 * @param layer the layer context for deleting these primitives. Must not be null.
100 * @param data the primitives to delete. Must neither be null nor empty.
101 * @throws IllegalArgumentException thrown if layer is null
102 * @throws IllegalArgumentException thrown if data is null or empty
103 */
104 public DeleteCommand(OsmDataLayer layer, Collection<? extends OsmPrimitive> data) throws IllegalArgumentException{
105 super(layer);
106 if (data == null)
107 throw new IllegalArgumentException("Parameter 'data' must not be empty");
108 if (data.isEmpty())
109 throw new IllegalArgumentException(tr("At least one object to delete required, got empty collection"));
110 this.toDelete = data;
111 }
112
113 @Override
114 public boolean executeCommand() {
115 // Make copy and remove all references (to prevent inconsistent dataset (delete referenced) while command is executed)
116 for (OsmPrimitive osm: toDelete) {
117 if (osm.isDeleted())
118 throw new IllegalArgumentException(osm.toString() + " is already deleted");
119 clonedPrimitives.put(osm, osm.save());
120
121 if (osm instanceof Way) {
122 ((Way) osm).setNodes(null);
123 } else if (osm instanceof Relation) {
124 ((Relation) osm).setMembers(null);
125 }
126 }
127
128 for (OsmPrimitive osm: toDelete) {
129 osm.setDeleted(true);
130 }
131
132 return true;
133 }
134
135 @Override
136 public void undoCommand() {
137 for (OsmPrimitive osm: toDelete) {
138 osm.setDeleted(false);
139 }
140
141 for (Entry<OsmPrimitive, PrimitiveData> entry: clonedPrimitives.entrySet()) {
142 entry.getKey().load(entry.getValue());
143 }
144 }
145
146 @Override
147 public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted,
148 Collection<OsmPrimitive> added) {
149 }
150
151 @Override public JLabel getDescription() {
152 if (toDelete.size() == 1) {
153 OsmPrimitive primitive = toDelete.iterator().next();
154 String msg = "";
155 switch(OsmPrimitiveType.from(primitive)) {
156 case NODE: msg = marktr("Delete node {0}"); break;
157 case WAY: msg = marktr("Delete way {0}"); break;
158 case RELATION:msg = marktr("Delete relation {0}"); break;
159 }
160
161 return new JLabel(tr(msg, primitive.getDisplayName(DefaultNameFormatter.getInstance())),
162 ImageProvider.get(OsmPrimitiveType.from(primitive)), JLabel.HORIZONTAL);
163 } else {
164 Set<OsmPrimitiveType> typesToDelete = new HashSet<OsmPrimitiveType>();
165 for (OsmPrimitive osm : toDelete) {
166 typesToDelete.add(OsmPrimitiveType.from(osm));
167 }
168 String msg = "";
169 String apiname = "object";
170 if (typesToDelete.size() > 1) {
171 msg = trn("Delete {0} object", "Delete {0} objects", toDelete.size(), toDelete.size());
172 } else {
173 OsmPrimitiveType t = typesToDelete.iterator().next();
174 apiname = t.getAPIName();
175 switch(t) {
176 case NODE: msg = trn("Delete {0} node", "Delete {0} nodes", toDelete.size(), toDelete.size()); break;
177 case WAY: msg = trn("Delete {0} way", "Delete {0} ways", toDelete.size(), toDelete.size()); break;
178 case RELATION: msg = trn("Delete {0} relation", "Delete {0} relations", toDelete.size(), toDelete.size()); break;
179 }
180 }
181 return new JLabel(msg, ImageProvider.get("data", apiname), JLabel.HORIZONTAL);
182 }
183 }
184
185 @Override public Collection<PseudoCommand> getChildren() {
186 if (toDelete.size() == 1)
187 return null;
188 else {
189 List<PseudoCommand> children = new ArrayList<PseudoCommand>();
190 for (final OsmPrimitive osm : toDelete) {
191 children.add(new PseudoCommand() {
192 @Override public JLabel getDescription() {
193 return new JLabel(
194 tr("Deleted ''{0}''",
195 osm.getDisplayName(DefaultNameFormatter.getInstance())),
196 ImageProvider.get(OsmPrimitiveType.from(osm)), JLabel.HORIZONTAL);
197 }
198 @Override public Collection<? extends OsmPrimitive> getParticipatingPrimitives() {
199 return Collections.singleton(osm);
200 }
201
202 });
203 }
204 return children;
205
206 }
207 }
208
209 @Override public Collection<? extends OsmPrimitive> getParticipatingPrimitives() {
210 return toDelete;
211 }
212
213 /**
214 * Delete the primitives and everything they reference.
215 *
216 * If a node is deleted, the node and all ways and relations the node is part of are deleted as
217 * well.
218 *
219 * If a way is deleted, all relations the way is member of are also deleted.
220 *
221 * If a way is deleted, only the way and no nodes are deleted.
222 *
223 * @param layer the {@see OsmDataLayer} in whose context primitives are deleted. Must not be null.
224 * @param selection The list of all object to be deleted.
225 * @param silent Set to true if the user should not be bugged with additional dialogs
226 * @return command A command to perform the deletions, or null of there is nothing to delete.
227 * @throws IllegalArgumentException thrown if layer is null
228 */
229 public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection, boolean silent) throws IllegalArgumentException {
230 CheckParameterUtil.ensureParameterNotNull(layer, "layer");
231 if (selection == null || selection.isEmpty()) return null;
232 Set<OsmPrimitive> parents = OsmPrimitive.getReferrer(selection);
233 parents.addAll(selection);
234
235 if (parents.isEmpty())
236 return null;
237 if (!silent && !checkAndConfirmOutlyingDelete(layer, parents, null))
238 return null;
239 return new DeleteCommand(layer,parents);
240 }
241
242 public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) {
243 return deleteWithReferences(layer, selection, false);
244 }
245
246 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) {
247 return delete(layer, selection, true, false);
248 }
249
250 /**
251 * Replies the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which
252 * can be deleted too. A node can be deleted if
253 * <ul>
254 * <li>it is untagged (see {@see Node#isTagged()}</li>
255 * <li>it is not referred to by other non-deleted primitives outside of <code>primitivesToDelete</code></li>
256 * <ul>
257 * @param layer the layer in whose context primitives are deleted
258 * @param primitivesToDelete the primitives to delete
259 * @return the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which
260 * can be deleted too
261 */
262 protected static Collection<Node> computeNodesToDelete(OsmDataLayer layer, Collection<OsmPrimitive> primitivesToDelete) {
263 Collection<Node> nodesToDelete = new HashSet<Node>();
264 for (Way way : OsmPrimitive.getFilteredList(primitivesToDelete, Way.class)) {
265 for (Node n : way.getNodes()) {
266 if (n.isTagged()) {
267 continue;
268 }
269 Collection<OsmPrimitive> referringPrimitives = n.getReferrers();
270 referringPrimitives.removeAll(primitivesToDelete);
271 int count = 0;
272 for (OsmPrimitive p : referringPrimitives) {
273 if (!p.isDeleted()) {
274 count++;
275 }
276 }
277 if (count == 0) {
278 nodesToDelete.add(n);
279 }
280 }
281 }
282 return nodesToDelete;
283 }
284
285 /**
286 * Try to delete all given primitives.
287 *
288 * If a node is used by a way, it's removed from that way. If a node or a way is used by a
289 * relation, inform the user and do not delete.
290 *
291 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If
292 * they are part of a relation, inform the user and do not delete.
293 *
294 * @param layer the {@see OsmDataLayer} in whose context the primitives are deleted
295 * @param selection the objects to delete.
296 * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well
297 * @return command a command to perform the deletions, or null if there is nothing to delete.
298 */
299 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection,
300 boolean alsoDeleteNodesInWay) {
301 return delete(layer, selection, alsoDeleteNodesInWay, false /* not silent */);
302 }
303
304 /**
305 * Try to delete all given primitives.
306 *
307 * If a node is used by a way, it's removed from that way. If a node or a way is used by a
308 * relation, inform the user and do not delete.
309 *
310 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If
311 * they are part of a relation, inform the user and do not delete.
312 *
313 * @param layer the {@see OsmDataLayer} in whose context the primitives are deleted
314 * @param selection the objects to delete.
315 * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well
316 * @param silent set to true if the user should not be bugged with additional questions
317 * @return command a command to perform the deletions, or null if there is nothing to delete.
318 */
319 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection,
320 boolean alsoDeleteNodesInWay, boolean silent) {
321 if (selection == null || selection.isEmpty())
322 return null;
323
324 Set<OsmPrimitive> primitivesToDelete = new HashSet<OsmPrimitive>(selection);
325
326 Collection<Relation> relationsToDelete = Utils.filteredCollection(primitivesToDelete, Relation.class);
327 if(!relationsToDelete.isEmpty() && !silent && !confirmRelationDeletion(relationsToDelete)) {
328 return null;
329 }
330
331 Collection<Way> waysToBeChanged = new HashSet<Way>();
332
333 if (alsoDeleteNodesInWay) {
334 // delete untagged nodes only referenced by primitives in primitivesToDelete,
335 // too
336 Collection<Node> nodesToDelete = computeNodesToDelete(layer, primitivesToDelete);
337 primitivesToDelete.addAll(nodesToDelete);
338 }
339
340 if (!silent && !checkAndConfirmOutlyingDelete(layer, primitivesToDelete, null))
341 return null;
342
343 waysToBeChanged.addAll(OsmPrimitive.getFilteredSet(OsmPrimitive.getReferrer(primitivesToDelete), Way.class));
344
345 Collection<Command> cmds = new LinkedList<Command>();
346 for (Way w : waysToBeChanged) {
347 Way wnew = new Way(w);
348 wnew.removeNodes(primitivesToDelete);
349 if (wnew.getNodesCount() < 2) {
350 primitivesToDelete.add(w);
351 } else {
352 cmds.add(new ChangeCommand(w, wnew));
353 }
354 }
355
356 // get a confirmation that the objects to delete can be removed from their parent
357 // relations
358 //
359 if (!silent) {
360 Set<RelationToChildReference> references = RelationToChildReference.getRelationToChildReferences(primitivesToDelete);
361 Iterator<RelationToChildReference> it = references.iterator();
362 while(it.hasNext()) {
363 RelationToChildReference ref = it.next();
364 if (ref.getParent().isDeleted()) {
365 it.remove();
366 }
367 }
368 if (!references.isEmpty()) {
369 DeleteFromRelationConfirmationDialog dialog = DeleteFromRelationConfirmationDialog.getInstance();
370 dialog.getModel().populate(references);
371 dialog.setVisible(true);
372 if (dialog.isCanceled())
373 return null;
374 }
375 }
376
377 // remove the objects from their parent relations
378 //
379 Iterator<Relation> iterator = OsmPrimitive.getFilteredSet(OsmPrimitive.getReferrer(primitivesToDelete), Relation.class).iterator();
380 while (iterator.hasNext()) {
381 Relation cur = iterator.next();
382 Relation rel = new Relation(cur);
383 rel.removeMembersFor(primitivesToDelete);
384 cmds.add(new ChangeCommand(cur, rel));
385 }
386
387 // build the delete command
388 //
389 if (!primitivesToDelete.isEmpty()) {
390 cmds.add(new DeleteCommand(layer,primitivesToDelete));
391 }
392
393 return new SequenceCommand(tr("Delete"), cmds);
394 }
395
396 public static Command deleteWaySegment(OsmDataLayer layer, WaySegment ws) {
397 if (ws.way.getNodesCount() < 3)
398 return delete(layer, Collections.singleton(ws.way), false);
399
400 if (ws.way.firstNode() == ws.way.lastNode()) {
401 // If the way is circular (first and last nodes are the same),
402 // the way shouldn't be splitted
403
404 List<Node> n = new ArrayList<Node>();
405
406 n.addAll(ws.way.getNodes().subList(ws.lowerIndex + 1, ws.way.getNodesCount() - 1));
407 n.addAll(ws.way.getNodes().subList(0, ws.lowerIndex + 1));
408
409 Way wnew = new Way(ws.way);
410 wnew.setNodes(n);
411
412 return new ChangeCommand(ws.way, wnew);
413 }
414
415 List<Node> n1 = new ArrayList<Node>(), n2 = new ArrayList<Node>();
416
417 n1.addAll(ws.way.getNodes().subList(0, ws.lowerIndex + 1));
418 n2.addAll(ws.way.getNodes().subList(ws.lowerIndex + 1, ws.way.getNodesCount()));
419
420 Way wnew = new Way(ws.way);
421
422 if (n1.size() < 2) {
423 wnew.setNodes(n2);
424 return new ChangeCommand(ws.way, wnew);
425 } else if (n2.size() < 2) {
426 wnew.setNodes(n1);
427 return new ChangeCommand(ws.way, wnew);
428 } else {
429 List<List<Node>> chunks = new ArrayList<List<Node>>(2);
430 chunks.add(n1);
431 chunks.add(n2);
432 return SplitWayAction.splitWay(layer,ws.way, chunks, Collections.<OsmPrimitive>emptyList()).getCommand();
433 }
434 }
435
436 public static boolean checkAndConfirmOutlyingDelete(OsmDataLayer layer, Collection<? extends OsmPrimitive> primitives, OsmPrimitive ignore) {
437 return checkAndConfirmOutlyingDelete(layer.data.getDataSourceArea(), primitives, ignore);
438 }
439
440 public static boolean checkAndConfirmOutlyingDelete(Area area, Collection<? extends OsmPrimitive> primitives, OsmPrimitive ignore) {
441 return Command.checkAndConfirmOutlyingOperation("delete",
442 tr("Delete confirmation"),
443 tr("You are about to delete nodes outside of the area you have downloaded."
444 + "<br>"
445 + "This can cause problems because other objects (that you do not see) might use them."
446 + "<br>"
447 + "Do you really want to delete?"),
448 tr("You are about to delete incomplete objects."
449 + "<br>"
450 + "This will cause problems because you don''t see the real object."
451 + "<br>" + "Do you really want to delete?"),
452 area, primitives, ignore);
453 }
454
455 private static boolean confirmRelationDeletion(Collection<Relation> relations) {
456 String relationString = "<ul>";
457 for(Relation r:relations) {
458 relationString += "<li>"+DefaultNameFormatter.getInstance().format(r) + "</li>";
459 }
460 relationString += "</ul>";
461
462 JPanel msg = new JPanel(new GridBagLayout());
463 msg.add(new JLabel("<html>" + trn(
464 "You are about to delete {0} relation: {1}"
465 + "<br/>"
466 + "This step is rarely necessary and cannot be undone easily after being uploaded to the server."
467 + "<br/>"
468 + "Do you really want to delete?",
469 "You are about to delete {0} relations: {1}"
470 + "<br/>"
471 + "This step is rarely necessary and cannot be undone easily after being uploaded to the server."
472 + "<br/>"
473 + "Do you really want to delete?",
474 relations.size(), relations.size(), relationString) + "</html>"));
475 boolean answer = ConditionalOptionPaneUtil.showConfirmationDialog(
476 "delete_relations",
477 Main.parent,
478 msg,
479 tr("Delete relation?"),
480 JOptionPane.YES_NO_OPTION,
481 JOptionPane.QUESTION_MESSAGE,
482 JOptionPane.YES_OPTION);
483 return answer;
484 }
485}
Note: See TracBrowser for help on using the repository browser.