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.EnumSet; 013import java.util.HashMap; 014import java.util.HashSet; 015import java.util.Iterator; 016import java.util.LinkedList; 017import java.util.List; 018import java.util.Map; 019import java.util.Map.Entry; 020import java.util.Set; 021 022import javax.swing.Icon; 023import javax.swing.JOptionPane; 024import javax.swing.JPanel; 025 026import org.openstreetmap.josm.Main; 027import org.openstreetmap.josm.actions.SplitWayAction; 028import org.openstreetmap.josm.data.osm.Node; 029import org.openstreetmap.josm.data.osm.OsmPrimitive; 030import org.openstreetmap.josm.data.osm.OsmPrimitiveType; 031import org.openstreetmap.josm.data.osm.PrimitiveData; 032import org.openstreetmap.josm.data.osm.Relation; 033import org.openstreetmap.josm.data.osm.RelationToChildReference; 034import org.openstreetmap.josm.data.osm.Way; 035import org.openstreetmap.josm.data.osm.WaySegment; 036import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil; 037import org.openstreetmap.josm.gui.DefaultNameFormatter; 038import org.openstreetmap.josm.gui.dialogs.DeleteFromRelationConfirmationDialog; 039import org.openstreetmap.josm.gui.layer.OsmDataLayer; 040import org.openstreetmap.josm.gui.widgets.JMultilineLabel; 041import org.openstreetmap.josm.tools.CheckParameterUtil; 042import org.openstreetmap.josm.tools.ImageProvider; 043import org.openstreetmap.josm.tools.Utils; 044 045/** 046 * A command to delete a number of primitives from the dataset. 047 * @since 23 048 */ 049public class DeleteCommand extends Command { 050 /** 051 * The primitives that get deleted. 052 */ 053 private final Collection<? extends OsmPrimitive> toDelete; 054 private final Map<OsmPrimitive, PrimitiveData> clonedPrimitives = new HashMap<>(); 055 056 /** 057 * Constructor. Deletes a collection of primitives in the current edit layer. 058 * 059 * @param data the primitives to delete. Must neither be null nor empty. 060 * @throws IllegalArgumentException if data is null or empty 061 */ 062 public DeleteCommand(Collection<? extends OsmPrimitive> data) { 063 CheckParameterUtil.ensureParameterNotNull(data, "data"); 064 if (data.isEmpty()) 065 throw new IllegalArgumentException(tr("At least one object to delete required, got empty collection")); 066 this.toDelete = data; 067 checkConsistency(); 068 } 069 070 /** 071 * Constructor. Deletes a single primitive in the current edit layer. 072 * 073 * @param data the primitive to delete. Must not be null. 074 * @throws IllegalArgumentException if data is null 075 */ 076 public DeleteCommand(OsmPrimitive data) { 077 this(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 if data is null 087 * @throws IllegalArgumentException if layer is null 088 */ 089 public DeleteCommand(OsmDataLayer layer, OsmPrimitive data) { 090 this(layer, Collections.singleton(data)); 091 } 092 093 /** 094 * Constructor for a collection of data to be deleted in the context of 095 * a specific layer 096 * 097 * @param layer the layer context for deleting these primitives. Must not be null. 098 * @param data the primitives to delete. Must neither be null nor empty. 099 * @throws IllegalArgumentException if layer is null 100 * @throws IllegalArgumentException if data is null or empty 101 */ 102 public DeleteCommand(OsmDataLayer layer, Collection<? extends OsmPrimitive> data) { 103 super(layer); 104 CheckParameterUtil.ensureParameterNotNull(data, "data"); 105 if (data.isEmpty()) 106 throw new IllegalArgumentException(tr("At least one object to delete required, got empty collection")); 107 this.toDelete = data; 108 checkConsistency(); 109 } 110 111 private void checkConsistency() { 112 for (OsmPrimitive p : toDelete) { 113 if (p == null) { 114 throw new IllegalArgumentException("Primitive to delete must not be null"); 115 } else if (p.getDataSet() == null) { 116 throw new IllegalArgumentException("Primitive to delete must be in a dataset"); 117 } 118 } 119 } 120 121 @Override 122 public boolean executeCommand() { 123 // Make copy and remove all references (to prevent inconsistent dataset (delete referenced) while command is executed) 124 for (OsmPrimitive osm: toDelete) { 125 if (osm.isDeleted()) 126 throw new IllegalArgumentException(osm + " is already deleted"); 127 clonedPrimitives.put(osm, osm.save()); 128 129 if (osm instanceof Way) { 130 ((Way) osm).setNodes(null); 131 } else if (osm instanceof Relation) { 132 ((Relation) osm).setMembers(null); 133 } 134 } 135 136 for (OsmPrimitive osm: toDelete) { 137 osm.setDeleted(true); 138 } 139 140 return true; 141 } 142 143 @Override 144 public void undoCommand() { 145 for (OsmPrimitive osm: toDelete) { 146 osm.setDeleted(false); 147 } 148 149 for (Entry<OsmPrimitive, PrimitiveData> entry: clonedPrimitives.entrySet()) { 150 entry.getKey().load(entry.getValue()); 151 } 152 } 153 154 @Override 155 public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted, 156 Collection<OsmPrimitive> added) { 157 } 158 159 private Set<OsmPrimitiveType> getTypesToDelete() { 160 Set<OsmPrimitiveType> typesToDelete = EnumSet.noneOf(OsmPrimitiveType.class); 161 for (OsmPrimitive osm : toDelete) { 162 typesToDelete.add(OsmPrimitiveType.from(osm)); 163 } 164 return typesToDelete; 165 } 166 167 @Override 168 public String getDescriptionText() { 169 if (toDelete.size() == 1) { 170 OsmPrimitive primitive = toDelete.iterator().next(); 171 String msg = ""; 172 switch(OsmPrimitiveType.from(primitive)) { 173 case NODE: msg = marktr("Delete node {0}"); break; 174 case WAY: msg = marktr("Delete way {0}"); break; 175 case RELATION:msg = marktr("Delete relation {0}"); break; 176 } 177 178 return tr(msg, primitive.getDisplayName(DefaultNameFormatter.getInstance())); 179 } else { 180 Set<OsmPrimitiveType> typesToDelete = getTypesToDelete(); 181 String msg = ""; 182 if (typesToDelete.size() > 1) { 183 msg = trn("Delete {0} object", "Delete {0} objects", toDelete.size(), toDelete.size()); 184 } else { 185 OsmPrimitiveType t = typesToDelete.iterator().next(); 186 switch(t) { 187 case NODE: msg = trn("Delete {0} node", "Delete {0} nodes", toDelete.size(), toDelete.size()); break; 188 case WAY: msg = trn("Delete {0} way", "Delete {0} ways", toDelete.size(), toDelete.size()); break; 189 case RELATION: msg = trn("Delete {0} relation", "Delete {0} relations", toDelete.size(), toDelete.size()); break; 190 } 191 } 192 return msg; 193 } 194 } 195 196 @Override 197 public Icon getDescriptionIcon() { 198 if (toDelete.size() == 1) 199 return ImageProvider.get(toDelete.iterator().next().getDisplayType()); 200 Set<OsmPrimitiveType> typesToDelete = getTypesToDelete(); 201 if (typesToDelete.size() > 1) 202 return ImageProvider.get("data", "object"); 203 else 204 return ImageProvider.get(typesToDelete.iterator().next()); 205 } 206 207 @Override public Collection<PseudoCommand> getChildren() { 208 if (toDelete.size() == 1) 209 return null; 210 else { 211 List<PseudoCommand> children = new ArrayList<>(toDelete.size()); 212 for (final OsmPrimitive osm : toDelete) { 213 children.add(new PseudoCommand() { 214 215 @Override public String getDescriptionText() { 216 return tr("Deleted ''{0}''", osm.getDisplayName(DefaultNameFormatter.getInstance())); 217 } 218 219 @Override public Icon getDescriptionIcon() { 220 return ImageProvider.get(osm.getDisplayType()); 221 } 222 223 @Override public Collection<? extends OsmPrimitive> getParticipatingPrimitives() { 224 return Collections.singleton(osm); 225 } 226 227 }); 228 } 229 return children; 230 231 } 232 } 233 234 @Override public Collection<? extends OsmPrimitive> getParticipatingPrimitives() { 235 return toDelete; 236 } 237 238 /** 239 * Delete the primitives and everything they reference. 240 * 241 * If a node is deleted, the node and all ways and relations the node is part of are deleted as well. 242 * If a way is deleted, all relations the way is member of are also deleted. 243 * If a way is deleted, only the way and no nodes are deleted. 244 * 245 * @param layer the {@link OsmDataLayer} in whose context primitives are deleted. Must not be null. 246 * @param selection The list of all object to be deleted. 247 * @param silent Set to true if the user should not be bugged with additional dialogs 248 * @return command A command to perform the deletions, or null of there is nothing to delete. 249 * @throws IllegalArgumentException if layer is null 250 */ 251 public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection, boolean silent) { 252 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 253 if (selection == null || selection.isEmpty()) return null; 254 Set<OsmPrimitive> parents = OsmPrimitive.getReferrer(selection); 255 parents.addAll(selection); 256 257 if (parents.isEmpty()) 258 return null; 259 if (!silent && !checkAndConfirmOutlyingDelete(parents, null)) 260 return null; 261 return new DeleteCommand(layer, parents); 262 } 263 264 /** 265 * Delete the primitives and everything they reference. 266 * 267 * If a node is deleted, the node and all ways and relations the node is part of are deleted as well. 268 * If a way is deleted, all relations the way is member of are also deleted. 269 * If a way is deleted, only the way and no nodes are deleted. 270 * 271 * @param layer the {@link OsmDataLayer} in whose context primitives are deleted. Must not be null. 272 * @param selection The list of all object to be deleted. 273 * @return command A command to perform the deletions, or null of there is nothing to delete. 274 * @throws IllegalArgumentException if layer is null 275 */ 276 public static Command deleteWithReferences(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) { 277 return deleteWithReferences(layer, selection, false); 278 } 279 280 /** 281 * Try to delete all given primitives. 282 * 283 * If a node is used by a way, it's removed from that way. If a node or a way is used by a 284 * relation, inform the user and do not delete. 285 * 286 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If 287 * they are part of a relation, inform the user and do not delete. 288 * 289 * @param layer the {@link OsmDataLayer} in whose context the primitives are deleted 290 * @param selection the objects to delete. 291 * @return command a command to perform the deletions, or null if there is nothing to delete. 292 */ 293 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection) { 294 return delete(layer, selection, true, false); 295 } 296 297 /** 298 * Replies the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which 299 * can be deleted too. A node can be deleted if 300 * <ul> 301 * <li>it is untagged (see {@link Node#isTagged()}</li> 302 * <li>it is not referred to by other non-deleted primitives outside of <code>primitivesToDelete</code></li> 303 * </ul> 304 * @param primitivesToDelete the primitives to delete 305 * @return the collection of nodes referred to by primitives in <code>primitivesToDelete</code> which 306 * can be deleted too 307 */ 308 protected static Collection<Node> computeNodesToDelete(Collection<OsmPrimitive> primitivesToDelete) { 309 Collection<Node> nodesToDelete = new HashSet<>(); 310 for (Way way : OsmPrimitive.getFilteredList(primitivesToDelete, Way.class)) { 311 for (Node n : way.getNodes()) { 312 if (n.isTagged()) { 313 continue; 314 } 315 Collection<OsmPrimitive> referringPrimitives = n.getReferrers(); 316 referringPrimitives.removeAll(primitivesToDelete); 317 int count = 0; 318 for (OsmPrimitive p : referringPrimitives) { 319 if (!p.isDeleted()) { 320 count++; 321 } 322 } 323 if (count == 0) { 324 nodesToDelete.add(n); 325 } 326 } 327 } 328 return nodesToDelete; 329 } 330 331 /** 332 * Try to delete all given primitives. 333 * 334 * If a node is used by a way, it's removed from that way. If a node or a way is used by a 335 * relation, inform the user and do not delete. 336 * 337 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If 338 * they are part of a relation, inform the user and do not delete. 339 * 340 * @param layer the {@link OsmDataLayer} in whose context the primitives are deleted 341 * @param selection the objects to delete. 342 * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well 343 * @return command a command to perform the deletions, or null if there is nothing to delete. 344 */ 345 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection, 346 boolean alsoDeleteNodesInWay) { 347 return delete(layer, selection, alsoDeleteNodesInWay, false /* not silent */); 348 } 349 350 /** 351 * Try to delete all given primitives. 352 * 353 * If a node is used by a way, it's removed from that way. If a node or a way is used by a 354 * relation, inform the user and do not delete. 355 * 356 * If this would cause ways with less than 2 nodes to be created, delete these ways instead. If 357 * they are part of a relation, inform the user and do not delete. 358 * 359 * @param layer the {@link OsmDataLayer} in whose context the primitives are deleted 360 * @param selection the objects to delete. 361 * @param alsoDeleteNodesInWay <code>true</code> if nodes should be deleted as well 362 * @param silent set to true if the user should not be bugged with additional questions 363 * @return command a command to perform the deletions, or null if there is nothing to delete. 364 */ 365 public static Command delete(OsmDataLayer layer, Collection<? extends OsmPrimitive> selection, 366 boolean alsoDeleteNodesInWay, boolean silent) { 367 if (selection == null || selection.isEmpty()) 368 return null; 369 370 Set<OsmPrimitive> primitivesToDelete = new HashSet<OsmPrimitive>(selection); 371 372 Collection<Relation> relationsToDelete = Utils.filteredCollection(primitivesToDelete, Relation.class); 373 if (!relationsToDelete.isEmpty() && !silent && !confirmRelationDeletion(relationsToDelete)) 374 return null; 375 376 Collection<Way> waysToBeChanged = new HashSet<>(); 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 waysToBeChanged.addAll(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)) 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 final int prime = 31; 522 int result = super.hashCode(); 523 result = prime * result + ((clonedPrimitives == null) ? 0 : clonedPrimitives.hashCode()); 524 result = prime * result + ((toDelete == null) ? 0 : toDelete.hashCode()); 525 return result; 526 } 527 528 @Override 529 public boolean equals(Object obj) { 530 if (this == obj) 531 return true; 532 if (!super.equals(obj)) 533 return false; 534 if (getClass() != obj.getClass()) 535 return false; 536 DeleteCommand other = (DeleteCommand) obj; 537 if (clonedPrimitives == null) { 538 if (other.clonedPrimitives != null) 539 return false; 540 } else if (!clonedPrimitives.equals(other.clonedPrimitives)) 541 return false; 542 if (toDelete == null) { 543 if (other.toDelete != null) 544 return false; 545 } else if (!toDelete.equals(other.toDelete)) 546 return false; 547 return true; 548 } 549}