001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.actions.mapmode; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.awt.Cursor; 007import java.awt.event.ActionEvent; 008import java.awt.event.KeyEvent; 009import java.awt.event.MouseEvent; 010import java.util.Collection; 011import java.util.Collections; 012import java.util.HashSet; 013import java.util.List; 014import java.util.Set; 015import java.util.stream.Collectors; 016 017import org.openstreetmap.josm.command.Command; 018import org.openstreetmap.josm.command.DeleteCommand; 019import org.openstreetmap.josm.data.UndoRedoHandler; 020import org.openstreetmap.josm.data.osm.DataSet; 021import org.openstreetmap.josm.data.osm.Node; 022import org.openstreetmap.josm.data.osm.OsmPrimitive; 023import org.openstreetmap.josm.data.osm.Relation; 024import org.openstreetmap.josm.data.osm.WaySegment; 025import org.openstreetmap.josm.gui.ExtendedDialog; 026import org.openstreetmap.josm.gui.MainApplication; 027import org.openstreetmap.josm.gui.MapFrame; 028import org.openstreetmap.josm.gui.MapView; 029import org.openstreetmap.josm.gui.dialogs.relation.RelationDialogManager; 030import org.openstreetmap.josm.gui.layer.Layer; 031import org.openstreetmap.josm.gui.layer.MainLayerManager; 032import org.openstreetmap.josm.gui.layer.OsmDataLayer; 033import org.openstreetmap.josm.gui.util.HighlightHelper; 034import org.openstreetmap.josm.gui.util.ModifierExListener; 035import org.openstreetmap.josm.spi.preferences.Config; 036import org.openstreetmap.josm.tools.CheckParameterUtil; 037import org.openstreetmap.josm.tools.ImageProvider; 038import org.openstreetmap.josm.tools.Shortcut; 039 040/** 041 * A map mode that enables the user to delete nodes and other objects. 042 * 043 * The user can click on an object, which gets deleted if possible. When Ctrl is 044 * pressed when releasing the button, the objects and all its references are deleted. 045 * 046 * If the user did not press Ctrl and the object has any references, the user 047 * is informed and nothing is deleted. 048 * 049 * If the user enters the mapmode and any object is selected, all selected 050 * objects are deleted, if possible. 051 * 052 * @author imi 053 */ 054public class DeleteAction extends MapMode implements ModifierExListener { 055 // Cache previous mouse event (needed when only the modifier keys are pressed but the mouse isn't moved) 056 private MouseEvent oldEvent; 057 058 /** 059 * elements that have been highlighted in the previous iteration. Used 060 * to remove the highlight from them again as otherwise the whole data 061 * set would have to be checked. 062 */ 063 private transient WaySegment oldHighlightedWaySegment; 064 065 private static final HighlightHelper HIGHLIGHT_HELPER = new HighlightHelper(); 066 private boolean drawTargetHighlight; 067 068 enum DeleteMode { 069 none(/* ICON(cursor/modifier/) */ "delete"), 070 segment(/* ICON(cursor/modifier/) */ "delete_segment"), 071 node(/* ICON(cursor/modifier/) */ "delete_node"), 072 node_with_references(/* ICON(cursor/modifier/) */ "delete_node"), 073 way(/* ICON(cursor/modifier/) */ "delete_way_only"), 074 way_with_references(/* ICON(cursor/modifier/) */ "delete_way_normal"), 075 way_with_nodes(/* ICON(cursor/modifier/) */ "delete_way_node_only"); 076 077 @SuppressWarnings("ImmutableEnumChecker") 078 private final Cursor c; 079 080 DeleteMode(String cursorName) { 081 c = ImageProvider.getCursor("normal", cursorName); 082 } 083 084 /** 085 * Returns the mode cursor. 086 * @return the mode cursor 087 */ 088 public Cursor cursor() { 089 return c; 090 } 091 } 092 093 private static final class DeleteParameters { 094 private DeleteMode mode; 095 private Node nearestNode; 096 private WaySegment nearestSegment; 097 } 098 099 /** 100 * Construct a new DeleteAction. Mnemonic is the delete - key. 101 * @since 11713 102 */ 103 public DeleteAction() { 104 super(tr("Delete Mode"), 105 "delete", 106 tr("Delete nodes or ways."), 107 Shortcut.registerShortcut("mapmode:delete", tr("Mode: {0}", tr("Delete")), 108 KeyEvent.VK_DELETE, Shortcut.CTRL), 109 ImageProvider.getCursor("normal", "delete")); 110 } 111 112 @Override 113 public void enterMode() { 114 super.enterMode(); 115 if (!isEnabled()) 116 return; 117 118 drawTargetHighlight = Config.getPref().getBoolean("draw.target-highlight", true); 119 120 MapFrame map = MainApplication.getMap(); 121 map.mapView.addMouseListener(this); 122 map.mapView.addMouseMotionListener(this); 123 // This is required to update the cursors when ctrl/shift/alt is pressed 124 map.keyDetector.addModifierExListener(this); 125 } 126 127 @Override 128 public void exitMode() { 129 super.exitMode(); 130 MapFrame map = MainApplication.getMap(); 131 map.mapView.removeMouseListener(this); 132 map.mapView.removeMouseMotionListener(this); 133 map.keyDetector.removeModifierExListener(this); 134 removeHighlighting(); 135 } 136 137 @Override 138 public void actionPerformed(ActionEvent e) { 139 super.actionPerformed(e); 140 doActionPerformed(e); 141 } 142 143 /** 144 * Invoked when the action occurs. 145 * @param e Action event 146 */ 147 public void doActionPerformed(ActionEvent e) { 148 MainLayerManager lm = MainApplication.getLayerManager(); 149 OsmDataLayer editLayer = lm.getEditLayer(); 150 if (editLayer == null) { 151 return; 152 } 153 154 updateKeyModifiers(e); 155 156 Command c; 157 if (ctrl) { 158 c = DeleteCommand.deleteWithReferences(lm.getEditDataSet().getSelected()); 159 } else { 160 c = DeleteCommand.delete(lm.getEditDataSet().getSelected(), !alt /* also delete nodes in way */); 161 } 162 // if c is null, an error occurred or the user aborted. Don't do anything in that case. 163 if (c != null) { 164 UndoRedoHandler.getInstance().add(c); 165 if (changesHiddenWay(c)) { 166 final ConfirmDeleteDialog ed = new ConfirmDeleteDialog(); 167 ed.setContent(tr("Are you sure that you want to delete elements with attached ways that are hidden by filters?")); 168 ed.toggleEnable("deletedHiddenElements"); 169 if (ed.showDialog().getValue() != 1) { 170 UndoRedoHandler.getInstance().undo(1); 171 return; 172 } 173 } 174 175 //FIXME: This should not be required, DeleteCommand should update the selection, otherwise undo/redo won't work. 176 lm.getEditDataSet().setSelected(); 177 } 178 } 179 180 @Override 181 public void mouseDragged(MouseEvent e) { 182 mouseMoved(e); 183 } 184 185 /** 186 * Listen to mouse move to be able to update the cursor (and highlights) 187 * @param e The mouse event that has been captured 188 */ 189 @Override 190 public void mouseMoved(MouseEvent e) { 191 if (isPanning()) { 192 return; 193 } 194 oldEvent = e; 195 giveUserFeedback(e); 196 } 197 198 /** 199 * removes any highlighting that may have been set beforehand. 200 */ 201 private void removeHighlighting() { 202 HIGHLIGHT_HELPER.clear(); 203 DataSet ds = getLayerManager().getEditDataSet(); 204 if (ds != null) { 205 ds.clearHighlightedWaySegments(); 206 } 207 } 208 209 /** 210 * handles everything related to highlighting primitives and way 211 * segments for the given pointer position (via MouseEvent) and modifiers. 212 * @param e current mouse event 213 * @param modifiers extended mouse modifiers, not necessarily taken from the given mouse event 214 */ 215 private void addHighlighting(MouseEvent e, int modifiers) { 216 if (!drawTargetHighlight) 217 return; 218 219 DeleteParameters parameters = getDeleteParameters(e, modifiers); 220 221 if (parameters.mode == DeleteMode.segment) { 222 // deleting segments is the only action not working on OsmPrimitives 223 // so we have to handle them separately. 224 repaintIfRequired(Collections.emptySet(), parameters.nearestSegment); 225 } else { 226 // don't call buildDeleteCommands for DeleteMode.segment because it doesn't support 227 // silent operation and SplitWayAction will show dialogs. A lot. 228 Command delCmd = buildDeleteCommands(e, modifiers, true); 229 // all other cases delete OsmPrimitives directly, so we can safely do the following 230 repaintIfRequired(delCmd == null ? Collections.emptySet() : new HashSet<>(delCmd.getParticipatingPrimitives()), null); 231 } 232 } 233 234 private void repaintIfRequired(Set<OsmPrimitive> newHighlights, WaySegment newHighlightedWaySegment) { 235 boolean needsRepaint = false; 236 OsmDataLayer editLayer = getLayerManager().getEditLayer(); 237 238 if (newHighlightedWaySegment == null && oldHighlightedWaySegment != null) { 239 if (editLayer != null) { 240 editLayer.data.clearHighlightedWaySegments(); 241 needsRepaint = true; 242 } 243 oldHighlightedWaySegment = null; 244 } else if (newHighlightedWaySegment != null && !newHighlightedWaySegment.equals(oldHighlightedWaySegment)) { 245 if (editLayer != null) { 246 editLayer.data.setHighlightedWaySegments(Collections.singleton(newHighlightedWaySegment)); 247 needsRepaint = true; 248 } 249 oldHighlightedWaySegment = newHighlightedWaySegment; 250 } 251 needsRepaint |= HIGHLIGHT_HELPER.highlightOnly(newHighlights); 252 if (needsRepaint && editLayer != null) { 253 editLayer.invalidate(); 254 } 255 } 256 257 /** 258 * This function handles all work related to updating the cursor and highlights 259 * 260 * @param e current mouse event 261 * @param modifiers extended mouse modifiers, not necessarily taken from the given mouse event 262 */ 263 private void updateCursor(MouseEvent e, int modifiers) { 264 if (!MainApplication.isDisplayingMapView()) 265 return; 266 MapFrame map = MainApplication.getMap(); 267 if (!map.mapView.isActiveLayerVisible() || e == null) 268 return; 269 270 DeleteParameters parameters = getDeleteParameters(e, modifiers); 271 map.mapView.setNewCursor(parameters.mode.cursor(), this); 272 } 273 274 /** 275 * Gives the user feedback for the action he/she is about to do. Currently 276 * calls the cursor and target highlighting routines. Allows for modifiers 277 * not taken from the given mouse event. 278 * 279 * Normally the mouse event also contains the modifiers. However, when the 280 * mouse is not moved and only modifier keys are pressed, no mouse event 281 * occurs. We can use AWTEvent to catch those but still lack a proper 282 * mouseevent. Instead we copy the previous event and only update the modifiers. 283 * @param e mouse event 284 * @param modifiers mouse modifiers 285 */ 286 private void giveUserFeedback(MouseEvent e, int modifiers) { 287 updateCursor(e, modifiers); 288 addHighlighting(e, modifiers); 289 } 290 291 /** 292 * Gives the user feedback for the action he/she is about to do. Currently 293 * calls the cursor and target highlighting routines. Extracts modifiers 294 * from mouse event. 295 * @param e mouse event 296 */ 297 private void giveUserFeedback(MouseEvent e) { 298 giveUserFeedback(e, e.getModifiersEx()); 299 } 300 301 /** 302 * If user clicked with the left button, delete the nearest object. 303 */ 304 @Override 305 public void mouseReleased(MouseEvent e) { 306 if (e.getButton() != MouseEvent.BUTTON1) 307 return; 308 MapFrame map = MainApplication.getMap(); 309 if (!map.mapView.isActiveLayerVisible()) 310 return; 311 312 // request focus in order to enable the expected keyboard shortcuts 313 // 314 map.mapView.requestFocus(); 315 316 Command c = buildDeleteCommands(e, e.getModifiersEx(), false); 317 if (c != null) { 318 UndoRedoHandler.getInstance().add(c); 319 } 320 321 getLayerManager().getEditDataSet().setSelected(); 322 giveUserFeedback(e); 323 } 324 325 @Override 326 public String getModeHelpText() { 327 // CHECKSTYLE.OFF: LineLength 328 return tr("Click to delete. Shift: delete way segment. Alt: do not delete unused nodes when deleting a way. Ctrl: delete referring objects."); 329 // CHECKSTYLE.ON: LineLength 330 } 331 332 @Override 333 public boolean layerIsSupported(Layer l) { 334 return isEditableDataLayer(l); 335 } 336 337 @Override 338 protected void updateEnabledState() { 339 setEnabled(MainApplication.isDisplayingMapView() && MainApplication.getMap().mapView.isActiveLayerDrawable()); 340 } 341 342 /** 343 * Deletes the relation in the context of the given layer. 344 * 345 * @param layer the layer in whose context the relation is deleted. Must not be null. 346 * @param toDelete the relation to be deleted. Must not be null. 347 * @throws IllegalArgumentException if layer is null 348 * @throws IllegalArgumentException if toDelete is null 349 */ 350 public static void deleteRelation(OsmDataLayer layer, Relation toDelete) { 351 deleteRelations(layer, Collections.singleton(toDelete)); 352 } 353 354 /** 355 * Deletes the relations in the context of the given layer. 356 * 357 * @param layer the layer in whose context the relations are deleted. Must not be null. 358 * @param toDelete the relations to be deleted. Must not be null. 359 * @throws IllegalArgumentException if layer is null 360 * @throws IllegalArgumentException if toDelete is null 361 */ 362 public static void deleteRelations(OsmDataLayer layer, Collection<Relation> toDelete) { 363 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 364 CheckParameterUtil.ensureParameterNotNull(toDelete, "toDelete"); 365 366 final Command cmd = DeleteCommand.delete(toDelete); 367 if (cmd != null) { 368 // cmd can be null if the user cancels dialogs DialogCommand displays 369 List<Relation> toUnselect = toDelete.stream().filter(Relation::isSelected).collect(Collectors.toList()); 370 UndoRedoHandler.getInstance().add(cmd); 371 toDelete.forEach(relation -> RelationDialogManager.getRelationDialogManager().close(layer, relation)); 372 toUnselect.forEach(layer.data::toggleSelected); 373 } 374 } 375 376 private DeleteParameters getDeleteParameters(MouseEvent e, int modifiers) { 377 updateKeyModifiersEx(modifiers); 378 379 DeleteParameters result = new DeleteParameters(); 380 381 MapView mapView = MainApplication.getMap().mapView; 382 result.nearestNode = mapView.getNearestNode(e.getPoint(), OsmPrimitive::isSelectable); 383 if (result.nearestNode == null) { 384 result.nearestSegment = mapView.getNearestWaySegment(e.getPoint(), OsmPrimitive::isSelectable); 385 if (result.nearestSegment != null) { 386 if (shift) { 387 result.mode = DeleteMode.segment; 388 } else if (ctrl) { 389 result.mode = DeleteMode.way_with_references; 390 } else { 391 result.mode = alt ? DeleteMode.way : DeleteMode.way_with_nodes; 392 } 393 } else { 394 result.mode = DeleteMode.none; 395 } 396 } else if (ctrl) { 397 result.mode = DeleteMode.node_with_references; 398 } else { 399 result.mode = DeleteMode.node; 400 } 401 402 return result; 403 } 404 405 /** 406 * This function takes any mouse event argument and builds the list of elements 407 * that should be deleted but does not actually delete them. 408 * @param e MouseEvent from which modifiers and position are taken 409 * @param modifiers For explanation, see {@link #updateCursor} 410 * @param silent Set to true if the user should not be bugged with additional dialogs 411 * @return delete command 412 */ 413 private Command buildDeleteCommands(MouseEvent e, int modifiers, boolean silent) { 414 DeleteParameters parameters = getDeleteParameters(e, modifiers); 415 switch (parameters.mode) { 416 case node: 417 return DeleteCommand.delete(Collections.singleton(parameters.nearestNode), false, silent); 418 case node_with_references: 419 return DeleteCommand.deleteWithReferences(Collections.singleton(parameters.nearestNode), silent); 420 case segment: 421 return DeleteCommand.deleteWaySegment(parameters.nearestSegment); 422 case way: 423 return DeleteCommand.delete(Collections.singleton(parameters.nearestSegment.getWay()), false, silent); 424 case way_with_nodes: 425 return DeleteCommand.delete(Collections.singleton(parameters.nearestSegment.getWay()), true, silent); 426 case way_with_references: 427 return DeleteCommand.deleteWithReferences(Collections.singleton(parameters.nearestSegment.getWay()), true); 428 default: 429 return null; 430 } 431 } 432 433 /** 434 * This is required to update the cursors when ctrl/shift/alt is pressed 435 */ 436 @Override 437 public void modifiersExChanged(int modifiers) { 438 if (oldEvent == null) 439 return; 440 // We don't have a mouse event, so we pass the old mouse event but the new modifiers. 441 giveUserFeedback(oldEvent, modifiers); 442 } 443 444 private static boolean changesHiddenWay(Command c) { 445 return c.getParticipatingPrimitives().stream().anyMatch(OsmPrimitive::isDisabledAndHidden); 446 } 447 448 static class ConfirmDeleteDialog extends ExtendedDialog { 449 ConfirmDeleteDialog() { 450 super(MainApplication.getMainFrame(), 451 tr("Delete elements"), 452 tr("Delete them"), tr("Undo delete")); 453 setButtonIcons("dialogs/delete", "cancel"); 454 setCancelButton(2); 455 } 456 } 457 458}