001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.command; 003 004import static org.openstreetmap.josm.tools.I18n.marktr; 005import static org.openstreetmap.josm.tools.I18n.tr; 006import static org.openstreetmap.josm.tools.I18n.trn; 007 008import java.awt.GridBagLayout; 009import java.util.ArrayList; 010import java.util.Collection; 011import java.util.Collections; 012import java.util.HashMap; 013import java.util.HashSet; 014import java.util.Iterator; 015import java.util.LinkedList; 016import java.util.List; 017import java.util.Map; 018import java.util.Map.Entry; 019import java.util.Set; 020 021import javax.swing.Icon; 022import javax.swing.JOptionPane; 023import javax.swing.JPanel; 024 025import org.openstreetmap.josm.Main; 026import org.openstreetmap.josm.actions.SplitWayAction; 027import org.openstreetmap.josm.data.osm.Node; 028import org.openstreetmap.josm.data.osm.OsmPrimitive; 029import org.openstreetmap.josm.data.osm.OsmPrimitiveType; 030import org.openstreetmap.josm.data.osm.PrimitiveData; 031import org.openstreetmap.josm.data.osm.Relation; 032import org.openstreetmap.josm.data.osm.RelationToChildReference; 033import org.openstreetmap.josm.data.osm.Way; 034import org.openstreetmap.josm.data.osm.WaySegment; 035import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil; 036import org.openstreetmap.josm.gui.DefaultNameFormatter; 037import org.openstreetmap.josm.gui.actionsupport.DeleteFromRelationConfirmationDialog; 038import org.openstreetmap.josm.gui.layer.OsmDataLayer; 039import org.openstreetmap.josm.gui.widgets.JMultilineLabel; 040import org.openstreetmap.josm.tools.CheckParameterUtil; 041import org.openstreetmap.josm.tools.ImageProvider; 042import org.openstreetmap.josm.tools.Utils; 043 044/** 045 * A command to delete a number of primitives from the dataset. 046 * 047 */ 048public class DeleteCommand extends Command { 049 /** 050 * The primitives that get deleted. 051 */ 052 private final Collection<? extends OsmPrimitive> toDelete; 053 private final Map<OsmPrimitive, PrimitiveData> clonedPrimitives = new HashMap<>(); 054 055 /** 056 * Constructor. Deletes a collection of primitives in the current edit layer. 057 * 058 * @param data the primitives to delete. Must neither be null nor empty. 059 * @throws IllegalArgumentException thrown if data is null or empty 060 */ 061 public DeleteCommand(Collection<? extends OsmPrimitive> data) throws IllegalArgumentException { 062 if (data == null) 063 throw new IllegalArgumentException("Parameter 'data' must not be empty"); 064 if (data.isEmpty()) 065 throw new IllegalArgumentException(tr("At least one object to delete required, got empty collection")); 066 this.toDelete = data; 067 } 068 069 /** 070 * Constructor. Deletes a single primitive in the current edit layer. 071 * 072 * @param data the primitive to delete. Must not be null. 073 * @throws IllegalArgumentException thrown if data is null 074 */ 075 public DeleteCommand(OsmPrimitive data) throws IllegalArgumentException { 076 CheckParameterUtil.ensureParameterNotNull(data, "data"); 077 this.toDelete = Collections.singleton(data); 078 } 079 080 /** 081 * Constructor for a single data item. Use the collection constructor to delete multiple 082 * objects. 083 * 084 * @param layer the layer context for deleting this primitive. Must not be null. 085 * @param data the primitive to delete. Must not be null. 086 * @throws IllegalArgumentException thrown if data is null 087 * @throws IllegalArgumentException thrown if layer is null 088 */ 089 public DeleteCommand(OsmDataLayer layer, OsmPrimitive data) throws IllegalArgumentException { 090 super(layer); 091 CheckParameterUtil.ensureParameterNotNull(data, "data"); 092 this.toDelete = Collections.singleton(data); 093 } 094 095 /** 096 * Constructor for a collection of data to be deleted in the context of 097 * a specific layer 098 * 099 * @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 private Set<OsmPrimitiveType> getTypesToDelete() { 152 Set<OsmPrimitiveType> typesToDelete = new HashSet<>(); 153 for (OsmPrimitive osm : toDelete) { 154 typesToDelete.add(OsmPrimitiveType.from(osm)); 155 } 156 return typesToDelete; 157 } 158 159 @Override 160 public String getDescriptionText() { 161 if (toDelete.size() == 1) { 162 OsmPrimitive primitive = toDelete.iterator().next(); 163 String msg = ""; 164 switch(OsmPrimitiveType.from(primitive)) { 165 case NODE: msg = marktr("Delete node {0}"); break; 166 case WAY: msg = marktr("Delete way {0}"); break; 167 case RELATION:msg = marktr("Delete relation {0}"); break; 168 } 169 170 return tr(msg, primitive.getDisplayName(DefaultNameFormatter.getInstance())); 171 } else { 172 Set<OsmPrimitiveType> typesToDelete = getTypesToDelete(); 173 String msg = ""; 174 if (typesToDelete.size() > 1) { 175 msg = trn("Delete {0} object", "Delete {0} objects", toDelete.size(), toDelete.size()); 176 } else { 177 OsmPrimitiveType t = typesToDelete.iterator().next(); 178 switch(t) { 179 case NODE: msg = trn("Delete {0} node", "Delete {0} nodes", toDelete.size(), toDelete.size()); break; 180 case WAY: msg = trn("Delete {0} way", "Delete {0} ways", toDelete.size(), toDelete.size()); break; 181 case RELATION: msg = trn("Delete {0} relation", "Delete {0} relations", toDelete.size(), toDelete.size()); break; 182 } 183 } 184 return msg; 185 } 186 } 187 188 @Override 189 public Icon getDescriptionIcon() { 190 if (toDelete.size() == 1) 191 return ImageProvider.get(toDelete.iterator().next().getDisplayType()); 192 Set<OsmPrimitiveType> typesToDelete = getTypesToDelete(); 193 if (typesToDelete.size() > 1) 194 return ImageProvider.get("data", "object"); 195 else 196 return ImageProvider.get(typesToDelete.iterator().next()); 197 } 198 199 @Override public Collection<PseudoCommand> getChildren() { 200 if (toDelete.size() == 1) 201 return null; 202 else { 203 List<PseudoCommand> children = new ArrayList<>(toDelete.size()); 204 for (final OsmPrimitive osm : toDelete) { 205 children.add(new PseudoCommand() { 206 207 @Override public String getDescriptionText() { 208 return tr("Deleted ''{0}''", osm.getDisplayName(DefaultNameFormatter.getInstance())); 209 } 210 211 @Override public Icon getDescriptionIcon() { 212 return ImageProvider.get(osm.getDisplayType()); 213 } 214 215 @Override public Collection<? extends OsmPrimitive> getParticipatingPrimitives() { 216 return Collections.singleton(osm); 217 } 218 219 }); 220 } 221 return children; 222 223 } 224 } 225 226 @Override public Collection<? extends OsmPrimitive> getParticipatingPrimitives() { 227 return toDelete; 228 } 229 230 /** 231 * Delete the primitives and everything they reference. 232 * 233 * If a node is deleted, the node and all ways and relations the node is part of are deleted as 234 * well. 235 * 236 * If a way is deleted, all relations the way is member of are also deleted. 237 * 238 * If a way is deleted, only the way and no nodes are deleted. 239 * 240 * @param layer the {@link OsmDataLayer} in whose context primitives are deleted. Must not be null. 241 * @param selection The list of all object to be deleted. 242 * @param silent Set to true if the user should not be bugged with additional dialogs 243 * @return command A command to perform the deletions, or null of there is nothing to delete. 244 * @throws IllegalArgumentException thrown if layer is null 245 */ 246 public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection, boolean silent) throws IllegalArgumentException { 247 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 248 if (selection == null || selection.isEmpty()) return null; 249 Set<OsmPrimitive> parents = OsmPrimitive.getReferrer(selection); 250 parents.addAll(selection); 251 252 if (parents.isEmpty()) 253 return null; 254 if (!silent && !checkAndConfirmOutlyingDelete(parents, null)) 255 return null; 256 return new DeleteCommand(layer,parents); 257 } 258 259 public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) { 260 return deleteWithReferences(layer, selection, false); 261 } 262 263 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) { 264 return delete(layer, selection, true, false); 265 } 266 267 /** 268 * Replies the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which 269 * can be deleted too. A node can be deleted if 270 * <ul> 271 * <li>it is untagged (see {@link Node#isTagged()}</li> 272 * <li>it is not referred to by other non-deleted primitives outside of <code>primitivesToDelete</code></li> 273 * </ul> 274 * @param layer the layer in whose context primitives are deleted 275 * @param primitivesToDelete the primitives to delete 276 * @return the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which 277 * can be deleted too 278 */ 279 protected static Collection<Node> computeNodesToDelete(OsmDataLayer layer, Collection<OsmPrimitive> primitivesToDelete) { 280 Collection<Node> nodesToDelete = new HashSet<>(); 281 for (Way way : OsmPrimitive.getFilteredList(primitivesToDelete, Way.class)) { 282 for (Node n : way.getNodes()) { 283 if (n.isTagged()) { 284 continue; 285 } 286 Collection<OsmPrimitive> referringPrimitives = n.getReferrers(); 287 referringPrimitives.removeAll(primitivesToDelete); 288 int count = 0; 289 for (OsmPrimitive p : referringPrimitives) { 290 if (!p.isDeleted()) { 291 count++; 292 } 293 } 294 if (count == 0) { 295 nodesToDelete.add(n); 296 } 297 } 298 } 299 return nodesToDelete; 300 } 301 302 /** 303 * Try to delete all given primitives. 304 * 305 * If a node is used by a way, it's removed from that way. If a node or a way is used by a 306 * relation, inform the user and do not delete. 307 * 308 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If 309 * they are part of a relation, inform the user and do not delete. 310 * 311 * @param layer the {@link OsmDataLayer} in whose context the primitives are deleted 312 * @param selection the objects to delete. 313 * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well 314 * @return command a command to perform the deletions, or null if there is nothing to delete. 315 */ 316 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection, 317 boolean alsoDeleteNodesInWay) { 318 return delete(layer, selection, alsoDeleteNodesInWay, false /* not silent */); 319 } 320 321 /** 322 * Try to delete all given primitives. 323 * 324 * If a node is used by a way, it's removed from that way. If a node or a way is used by a 325 * relation, inform the user and do not delete. 326 * 327 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If 328 * they are part of a relation, inform the user and do not delete. 329 * 330 * @param layer the {@link OsmDataLayer} in whose context the primitives are deleted 331 * @param selection the objects to delete. 332 * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well 333 * @param silent set to true if the user should not be bugged with additional questions 334 * @return command a command to perform the deletions, or null if there is nothing to delete. 335 */ 336 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection, 337 boolean alsoDeleteNodesInWay, boolean silent) { 338 if (selection == null || selection.isEmpty()) 339 return null; 340 341 Set<OsmPrimitive> primitivesToDelete = new HashSet<>(selection); 342 343 Collection<Relation> relationsToDelete = Utils.filteredCollection(primitivesToDelete, Relation.class); 344 if (!relationsToDelete.isEmpty() && !silent && !confirmRelationDeletion(relationsToDelete)) 345 return null; 346 347 Collection<Way> waysToBeChanged = new HashSet<>(); 348 349 if (alsoDeleteNodesInWay) { 350 // delete untagged nodes only referenced by primitives in primitivesToDelete, too 351 Collection<Node> nodesToDelete = computeNodesToDelete(layer, primitivesToDelete); 352 primitivesToDelete.addAll(nodesToDelete); 353 } 354 355 if (!silent && !checkAndConfirmOutlyingDelete( 356 primitivesToDelete, Utils.filteredCollection(primitivesToDelete, Way.class))) 357 return null; 358 359 waysToBeChanged.addAll(OsmPrimitive.getFilteredSet(OsmPrimitive.getReferrer(primitivesToDelete), Way.class)); 360 361 Collection<Command> cmds = new LinkedList<>(); 362 for (Way w : waysToBeChanged) { 363 Way wnew = new Way(w); 364 wnew.removeNodes(OsmPrimitive.getFilteredSet(primitivesToDelete, Node.class)); 365 if (wnew.getNodesCount() < 2) { 366 primitivesToDelete.add(w); 367 } else { 368 cmds.add(new ChangeNodesCommand(w, wnew.getNodes())); 369 } 370 } 371 372 // get a confirmation that the objects to delete can be removed from their parent relations 373 // 374 if (!silent) { 375 Set<RelationToChildReference> references = RelationToChildReference.getRelationToChildReferences(primitivesToDelete); 376 Iterator<RelationToChildReference> it = references.iterator(); 377 while(it.hasNext()) { 378 RelationToChildReference ref = it.next(); 379 if (ref.getParent().isDeleted()) { 380 it.remove(); 381 } 382 } 383 if (!references.isEmpty()) { 384 DeleteFromRelationConfirmationDialog dialog = DeleteFromRelationConfirmationDialog.getInstance(); 385 dialog.getModel().populate(references); 386 dialog.setVisible(true); 387 if (dialog.isCanceled()) 388 return null; 389 } 390 } 391 392 // remove the objects from their parent relations 393 // 394 for (Relation cur : OsmPrimitive.getFilteredSet(OsmPrimitive.getReferrer(primitivesToDelete), Relation.class)) { 395 Relation rel = new Relation(cur); 396 rel.removeMembersFor(primitivesToDelete); 397 cmds.add(new ChangeCommand(cur, rel)); 398 } 399 400 // build the delete command 401 // 402 if (!primitivesToDelete.isEmpty()) { 403 cmds.add(new DeleteCommand(layer,primitivesToDelete)); 404 } 405 406 return new SequenceCommand(tr("Delete"), cmds); 407 } 408 409 public static Command deleteWaySegment(OsmDataLayer layer, WaySegment ws) { 410 if (ws.way.getNodesCount() < 3) 411 return delete(layer, Collections.singleton(ws.way), false); 412 413 if (ws.way.firstNode() == ws.way.lastNode()) { 414 // If the way is circular (first and last nodes are the same), 415 // the way shouldn't be splitted 416 417 List<Node> n = new ArrayList<>(); 418 419 n.addAll(ws.way.getNodes().subList(ws.lowerIndex + 1, ws.way.getNodesCount() - 1)); 420 n.addAll(ws.way.getNodes().subList(0, ws.lowerIndex + 1)); 421 422 Way wnew = new Way(ws.way); 423 wnew.setNodes(n); 424 425 return new ChangeCommand(ws.way, wnew); 426 } 427 428 List<Node> n1 = new ArrayList<>(), n2 = new ArrayList<>(); 429 430 n1.addAll(ws.way.getNodes().subList(0, ws.lowerIndex + 1)); 431 n2.addAll(ws.way.getNodes().subList(ws.lowerIndex + 1, ws.way.getNodesCount())); 432 433 Way wnew = new Way(ws.way); 434 435 if (n1.size() < 2) { 436 wnew.setNodes(n2); 437 return new ChangeCommand(ws.way, wnew); 438 } else if (n2.size() < 2) { 439 wnew.setNodes(n1); 440 return new ChangeCommand(ws.way, wnew); 441 } else { 442 List<List<Node>> chunks = new ArrayList<>(2); 443 chunks.add(n1); 444 chunks.add(n2); 445 return SplitWayAction.splitWay(layer,ws.way, chunks, Collections.<OsmPrimitive>emptyList()).getCommand(); 446 } 447 } 448 449 public static boolean checkAndConfirmOutlyingDelete(Collection<? extends OsmPrimitive> primitives, Collection<? extends OsmPrimitive> ignore) { 450 return Command.checkAndConfirmOutlyingOperation("delete", 451 tr("Delete confirmation"), 452 tr("You are about to delete nodes outside of the area you have downloaded." 453 + "<br>" 454 + "This can cause problems because other objects (that you do not see) might use them." 455 + "<br>" 456 + "Do you really want to delete?"), 457 tr("You are about to delete incomplete objects." 458 + "<br>" 459 + "This will cause problems because you don''t see the real object." 460 + "<br>" + "Do you really want to delete?"), 461 primitives, ignore); 462 } 463 464 private static boolean confirmRelationDeletion(Collection<Relation> relations) { 465 JPanel msg = new JPanel(new GridBagLayout()); 466 msg.add(new JMultilineLabel("<html>" + trn( 467 "You are about to delete {0} relation: {1}" 468 + "<br/>" 469 + "This step is rarely necessary and cannot be undone easily after being uploaded to the server." 470 + "<br/>" 471 + "Do you really want to delete?", 472 "You are about to delete {0} relations: {1}" 473 + "<br/>" 474 + "This step is rarely necessary and cannot be undone easily after being uploaded to the server." 475 + "<br/>" 476 + "Do you really want to delete?", 477 relations.size(), relations.size(), DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(relations)) 478 + "</html>")); 479 return ConditionalOptionPaneUtil.showConfirmationDialog( 480 "delete_relations", 481 Main.parent, 482 msg, 483 tr("Delete relation?"), 484 JOptionPane.YES_NO_OPTION, 485 JOptionPane.QUESTION_MESSAGE, 486 JOptionPane.YES_OPTION); 487 } 488}