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