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

Last change on this file since 2537 was 2521, checked in by jttt, 14 years ago

Fixed #3704 Relation memberships are not handled at all when a way is splitted or deleted by deleting a segment, rewritten DeleteAction a bit (delete commands are no longer build in updateCursor())

  • Property svn:eol-style set to native
File size: 19.6 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.command;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.awt.GridBagLayout;
8import java.awt.geom.Area;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.Collections;
12import java.util.HashSet;
13import java.util.Iterator;
14import java.util.LinkedList;
15import java.util.List;
16import java.util.Set;
17
18import javax.swing.JLabel;
19import javax.swing.JOptionPane;
20import javax.swing.JPanel;
21import javax.swing.tree.DefaultMutableTreeNode;
22import javax.swing.tree.MutableTreeNode;
23
24import org.openstreetmap.josm.Main;
25import org.openstreetmap.josm.actions.SplitWayAction;
26import org.openstreetmap.josm.data.osm.BackreferencedDataSet;
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.Relation;
31import org.openstreetmap.josm.data.osm.Way;
32import org.openstreetmap.josm.data.osm.WaySegment;
33import org.openstreetmap.josm.data.osm.BackreferencedDataSet.RelationToChildReference;
34import org.openstreetmap.josm.data.osm.visitor.CollectBackReferencesVisitor;
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.tools.ImageProvider;
40
41/**
42 * A command to delete a number of primitives from the dataset.
43 *
44 */
45public class DeleteCommand extends Command {
46 /**
47 * The primitives that get deleted.
48 */
49 private final Collection<? extends OsmPrimitive> toDelete;
50
51 /**
52 * Constructor. Deletes a collection of primitives in the current edit layer.
53 *
54 * @param data the primitives to delete. Must neither be null nor empty.
55 * @throws IllegalArgumentException thrown if data is null or empty
56 */
57 public DeleteCommand(Collection<? extends OsmPrimitive> data) throws IllegalArgumentException {
58 if (data == null)
59 throw new IllegalArgumentException(tr("Parameter ''{0}'' must not be empty"));
60 if (data.isEmpty())
61 throw new IllegalArgumentException(tr("At least one object to delete required, got empty collection"));
62 this.toDelete = data;
63 }
64
65 /**
66 * Constructor. Deletes a single primitive in the current edit layer.
67 *
68 * @param data the primitive to delete. Must not be null.
69 * @throws IllegalArgumentException thrown if data is null
70 */
71 public DeleteCommand(OsmPrimitive data) throws IllegalArgumentException {
72 if (data == null)
73 throw new IllegalArgumentException(tr("Parameter ''{0}'' must not be null", "data"));
74 this.toDelete = Collections.singleton(data);
75 }
76
77 /**
78 * Constructor for a single data item. Use the collection constructor to delete multiple
79 * objects.
80 *
81 * @param layer the layer context for deleting this primitive. Must not be null.
82 * @param data the primitive to delete. Must not be null.
83 * @throws IllegalArgumentException thrown if data is null
84 * @throws IllegalArgumentException thrown if layer is null
85 */
86 public DeleteCommand(OsmDataLayer layer, OsmPrimitive data) throws IllegalArgumentException {
87 super(layer);
88 if (data == null)
89 throw new IllegalArgumentException(tr("Parameter ''{0}'' must not be null", "data"));
90 this.toDelete = Collections.singleton(data);
91 }
92
93 /**
94 * Constructor for a collection of data to be deleted in the context of
95 * a specific layer
96 *
97 * @param layer the layer context for deleting these primitives. Must not be null.
98 * @param data the primitives to delete. Must neither be null nor empty.
99 * @throws IllegalArgumentException thrown if layer is null
100 * @throws IllegalArgumentException thrown if data is null or empty
101 */
102 public DeleteCommand(OsmDataLayer layer, Collection<? extends OsmPrimitive> data) throws IllegalArgumentException{
103 super(layer);
104 if (data == null)
105 throw new IllegalArgumentException(tr("Parameter ''{0}'' must not be empty"));
106 if (data.isEmpty())
107 throw new IllegalArgumentException(tr("At least one object to delete requird, got empty collection"));
108 this.toDelete = data;
109 }
110
111 protected void removeNewNodesFromDeletedWay(Way w) {
112 // #2707: ways to be deleted can include new nodes (with node.id == 0).
113 // Remove them from the way before the way is deleted. Otherwise the
114 // deleted way is saved (or sent to the API) with a dangling reference to a node
115 // Example:
116 // <node id='2' action='delete' visible='true' version='1' ... />
117 // <node id='1' action='delete' visible='true' version='1' ... />
118 // <!-- missing node with id -1 because new deleted nodes are not persisted -->
119 // <way id='3' action='delete' visible='true' version='1'>
120 // <nd ref='1' />
121 // <nd ref='-1' /> <!-- here's the problem -->
122 // <nd ref='2' />
123 // </way>
124 if (w.isNew())
125 return; // process existing ways only
126 List<Node> nodesToKeep = new ArrayList<Node>();
127 // lookup new nodes which have been added to the set of deleted
128 // nodes ...
129 Iterator<Node> it = nodesToKeep.iterator();
130 while(it.hasNext()) {
131 Node n = it.next();
132 if (n.isNew()) {
133 it.remove();
134 }
135 }
136 w.setNodes(nodesToKeep);
137 }
138
139 @Override
140 public boolean executeCommand() {
141 super.executeCommand();
142 for (OsmPrimitive osm : toDelete) {
143 osm.setDeleted(true);
144 if (osm instanceof Way) {
145 removeNewNodesFromDeletedWay((Way)osm);
146 }
147 }
148 return true;
149 }
150
151 @Override
152 public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted,
153 Collection<OsmPrimitive> added) {
154 deleted.addAll(toDelete);
155 }
156
157 @Override
158 public MutableTreeNode description() {
159 if (toDelete.size() == 1) {
160 OsmPrimitive primitive = toDelete.iterator().next();
161 String msg = "";
162 switch(OsmPrimitiveType.from(primitive)) {
163 case NODE: msg = "Delete node {0}"; break;
164 case WAY: msg = "Delete way {0}"; break;
165 case RELATION:msg = "Delete relation {0}"; break;
166 }
167
168 return new DefaultMutableTreeNode(new JLabel(tr(msg, primitive.getDisplayName(DefaultNameFormatter.getInstance())),
169 ImageProvider.get(OsmPrimitiveType.from(primitive)), JLabel.HORIZONTAL));
170 }
171
172 Set<OsmPrimitiveType> typesToDelete = new HashSet<OsmPrimitiveType>();
173 for (OsmPrimitive osm : toDelete) {
174 typesToDelete.add(OsmPrimitiveType.from(osm));
175 }
176 String msg = "";
177 String apiname = "object";
178 if (typesToDelete.size() > 1) {
179 msg = trn("Delete {0} object", "Delete {0} objects", toDelete.size(), toDelete.size());
180 } else {
181 OsmPrimitiveType t = typesToDelete.iterator().next();
182 apiname = t.getAPIName();
183 switch(t) {
184 case NODE: msg = trn("Delete {0} node", "Delete {0} nodes", toDelete.size(), toDelete.size()); break;
185 case WAY: msg = trn("Delete {0} way", "Delete {0} ways", toDelete.size(), toDelete.size()); break;
186 case RELATION: msg = trn("Delete {0} relation", "Delete {0} relations", toDelete.size(), toDelete.size()); break;
187 }
188 }
189 DefaultMutableTreeNode root = new DefaultMutableTreeNode(
190 new JLabel(msg, ImageProvider.get("data", apiname), JLabel.HORIZONTAL)
191 );
192 for (OsmPrimitive osm : toDelete) {
193 root.add(new DefaultMutableTreeNode(new JLabel(
194 osm.getDisplayName(DefaultNameFormatter.getInstance()),
195 ImageProvider.get(OsmPrimitiveType.from(osm)), JLabel.HORIZONTAL)));
196 }
197 return root;
198 }
199
200 /**
201 * Delete the primitives and everything they reference.
202 *
203 * If a node is deleted, the node and all ways and relations the node is part of are deleted as
204 * well.
205 *
206 * If a way is deleted, all relations the way is member of are also deleted.
207 *
208 * If a way is deleted, only the way and no nodes are deleted.
209 *
210 * @param layer the {@see OsmDataLayer} in whose context primitives are deleted. Must not be null.
211 * @param selection The list of all object to be deleted.
212 * @param silent Set to true if the user should not be bugged with additional dialogs
213 * @return command A command to perform the deletions, or null of there is nothing to delete.
214 * @throws IllegalArgumentException thrown if layer is null
215 */
216 public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection, boolean silent) throws IllegalArgumentException {
217 if (layer == null)
218 throw new IllegalArgumentException(tr("Parameter ''{0}'' must not be null", "layer"));
219 if (selection == null || selection.isEmpty()) return null;
220 CollectBackReferencesVisitor v = new CollectBackReferencesVisitor(layer.data);
221 v.initialize();
222 for (OsmPrimitive osm : selection) {
223 osm.visit(v);
224 }
225 v.getData().addAll(selection);
226 if (v.getData().isEmpty())
227 return null;
228 if (!checkAndConfirmOutlyingDeletes(layer,v.getData()) && !silent)
229 return null;
230 return new DeleteCommand(layer,v.getData());
231 }
232
233 public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) {
234 return deleteWithReferences(layer, selection, false);
235 }
236
237 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) {
238 return delete(layer, selection, true, false);
239 }
240
241 /**
242 * Replies the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which
243 * can be deleted too. A node can be deleted if
244 * <ul>
245 * <li>it is untagged (see {@see Node#isTagged()}</li>
246 * <li>it is not referred to by other non-deleted primitives outside of <code>primitivesToDelete</code></li>
247 * <ul>
248 * @param backreferences backreference data structure
249 * @param layer the layer in whose context primitives are deleted
250 * @param primitivesToDelete the primitives to delete
251 * @return the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which
252 * can be deleted too
253 */
254 protected static Collection<Node> computeNodesToDelete(BackreferencedDataSet backreferences, OsmDataLayer layer, Collection<OsmPrimitive> primitivesToDelete) {
255 Collection<Node> nodesToDelete = new HashSet<Node>();
256 for (Way way : OsmPrimitive.getFilteredList(primitivesToDelete, Way.class)) {
257 for (Node n : way.getNodes()) {
258 if (n.isTagged()) {
259 continue;
260 }
261 Collection<OsmPrimitive> referringPrimitives = backreferences.getParents(n);
262 referringPrimitives.removeAll(primitivesToDelete);
263 int count = 0;
264 for (OsmPrimitive p : referringPrimitives) {
265 if (!p.isDeleted()) {
266 count++;
267 }
268 }
269 if (count == 0) {
270 nodesToDelete.add(n);
271 }
272 }
273 }
274 return nodesToDelete;
275 }
276
277 /**
278 * Try to delete all given primitives.
279 *
280 * If a node is used by a way, it's removed from that way. If a node or a way is used by a
281 * relation, inform the user and do not delete.
282 *
283 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If
284 * they are part of a relation, inform the user and do not delete.
285 *
286 * @param layer the {@see OsmDataLayer} in whose context the primitives are deleted
287 * @param selection the objects to delete.
288 * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well
289 * @return command a command to perform the deletions, or null if there is nothing to delete.
290 */
291 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection,
292 boolean alsoDeleteNodesInWay) {
293 return delete(layer, selection, alsoDeleteNodesInWay, false /* not silent */);
294 }
295
296 /**
297 * Try to delete all given primitives.
298 *
299 * If a node is used by a way, it's removed from that way. If a node or a way is used by a
300 * relation, inform the user and do not delete.
301 *
302 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If
303 * they are part of a relation, inform the user and do not delete.
304 *
305 * @param layer the {@see OsmDataLayer} in whose context the primitives are deleted
306 * @param selection the objects to delete.
307 * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well
308 * @param silent set to true if the user should not be bugged with additional questions
309 * @return command a command to perform the deletions, or null if there is nothing to delete.
310 */
311 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection,
312 boolean alsoDeleteNodesInWay, boolean silent) {
313 if (selection == null || selection.isEmpty())
314 return null;
315
316 BackreferencedDataSet backreferences = new BackreferencedDataSet();
317 Set<OsmPrimitive> primitivesToDelete = new HashSet<OsmPrimitive>(selection);
318 Collection<Way> waysToBeChanged = new HashSet<Way>();
319
320 if (alsoDeleteNodesInWay) {
321 // delete untagged nodes only referenced by primitives in primitivesToDelete,
322 // too
323 Collection<Node> nodesToDelete = computeNodesToDelete(backreferences, layer, primitivesToDelete);
324 primitivesToDelete.addAll(nodesToDelete);
325 }
326
327 if (!silent && !checkAndConfirmOutlyingDeletes(layer,primitivesToDelete))
328 return null;
329
330 waysToBeChanged.addAll(OsmPrimitive.getFilteredSet(backreferences.getParents(primitivesToDelete), Way.class));
331
332 Collection<Command> cmds = new LinkedList<Command>();
333 for (Way w : waysToBeChanged) {
334 Way wnew = new Way(w);
335 wnew.removeNodes(primitivesToDelete);
336 if (wnew.getNodesCount() < 2) {
337 primitivesToDelete.add(w);
338 } else {
339 cmds.add(new ChangeCommand(w, wnew));
340 }
341 }
342
343 // get a confirmation that the objects to delete can be removed from their parent
344 // relations
345 //
346 if (!silent) {
347 Set<RelationToChildReference> references = backreferences.getRelationToChildReferences(primitivesToDelete);
348 Iterator<RelationToChildReference> it = references.iterator();
349 while(it.hasNext()) {
350 RelationToChildReference ref = it.next();
351 if (ref.getParent().isDeleted()) {
352 it.remove();
353 }
354 }
355 if (!references.isEmpty()) {
356 DeleteFromRelationConfirmationDialog dialog = DeleteFromRelationConfirmationDialog.getInstance();
357 dialog.getModel().populate(references);
358 dialog.setVisible(true);
359 if (dialog.isCanceled())
360 return null;
361 }
362 }
363
364 // remove the objects from their parent relations
365 //
366 Iterator<Relation> iterator = OsmPrimitive.getFilteredSet(backreferences.getParents(primitivesToDelete), Relation.class).iterator();
367 while (iterator.hasNext()) {
368 Relation cur = iterator.next();
369 Relation rel = new Relation(cur);
370 rel.removeMembersFor(primitivesToDelete);
371 cmds.add(new ChangeCommand(cur, rel));
372 }
373
374 // build the delete command
375 //
376 if (!primitivesToDelete.isEmpty()) {
377 cmds.add(new DeleteCommand(layer,primitivesToDelete));
378 }
379
380 return new SequenceCommand(tr("Delete"), cmds);
381 }
382
383 public static Command deleteWaySegment(OsmDataLayer layer, WaySegment ws) {
384 if (ws.way.getNodesCount() < 3)
385 return delete(layer, Collections.singleton(ws.way));
386
387 if (ws.way.firstNode() == ws.way.lastNode()) {
388 // If the way is circular (first and last nodes are the same),
389 // the way shouldn't be splitted
390
391 List<Node> n = new ArrayList<Node>();
392
393 n.addAll(ws.way.getNodes().subList(ws.lowerIndex + 1, ws.way.getNodesCount() - 1));
394 n.addAll(ws.way.getNodes().subList(0, ws.lowerIndex + 1));
395
396 Way wnew = new Way(ws.way);
397 wnew.setNodes(n);
398
399 return new ChangeCommand(ws.way, wnew);
400 }
401
402 List<Node> n1 = new ArrayList<Node>(), n2 = new ArrayList<Node>();
403
404 n1.addAll(ws.way.getNodes().subList(0, ws.lowerIndex + 1));
405 n2.addAll(ws.way.getNodes().subList(ws.lowerIndex + 1, ws.way.getNodesCount()));
406
407 Way wnew = new Way(ws.way);
408
409 if (n1.size() < 2) {
410 wnew.setNodes(n2);
411 return new ChangeCommand(ws.way, wnew);
412 } else if (n2.size() < 2) {
413 wnew.setNodes(n1);
414 return new ChangeCommand(ws.way, wnew);
415 } else {
416 List<List<Node>> chunks = new ArrayList<List<Node>>(2);
417 chunks.add(n1);
418 chunks.add(n2);
419 return SplitWayAction.splitWay(ws.way, chunks).getCommand();
420 }
421 }
422
423 /**
424 * Check whether user is about to delete data outside of the download area. Request confirmation
425 * if he is.
426 *
427 * @param layer the layer in whose context data is deleted
428 * @param primitivesToDelete the primitives to delete
429 * @return true, if deleting outlying primitives is OK; false, otherwise
430 */
431 private static boolean checkAndConfirmOutlyingDeletes(OsmDataLayer layer, Collection<OsmPrimitive> primitivesToDelete) {
432 Area a = layer.data.getDataSourceArea();
433 if (a != null) {
434 for (OsmPrimitive osm : primitivesToDelete) {
435 if (osm instanceof Node && !osm.isNew()) {
436 Node n = (Node) osm;
437 if (!a.contains(n.getCoor())) {
438 JPanel msg = new JPanel(new GridBagLayout());
439 msg.add(new JLabel(
440 "<html>" +
441 // leave message in one tr() as there is a grammatical
442 // connection.
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 don't see) might use them."
446 + "<br>" + "Do you really want to delete?") + "</html>"));
447 return ConditionalOptionPaneUtil.showConfirmationDialog(
448 "delete_outside_nodes",
449 Main.parent,
450 msg,
451 tr("Delete confirmation"),
452 JOptionPane.YES_NO_OPTION,
453 JOptionPane.QUESTION_MESSAGE,
454 JOptionPane.YES_OPTION
455 );
456 }
457 }
458 }
459 }
460 return true;
461 }
462}
Note: See TracBrowser for help on using the repository browser.