source: josm/trunk/src/org/openstreetmap/josm/actions/mapmode/SelectAction.java@ 12785

Last change on this file since 12785 was 12785, checked in by Don-vip, 7 years ago

fix #15268 - see #13036 - do not create empty MoveCommand in SelectAction

  • Property svn:eol-style set to native
File size: 50.8 KB
RevLine 
[6380]1// License: GPL. For details, see LICENSE file.
[358]2package org.openstreetmap.josm.actions.mapmode;
3
[3754]4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
[358]5import static org.openstreetmap.josm.tools.I18n.tr;
[1441]6import static org.openstreetmap.josm.tools.I18n.trn;
[358]7
8import java.awt.Cursor;
9import java.awt.Point;
10import java.awt.Rectangle;
11import java.awt.event.KeyEvent;
12import java.awt.event.MouseEvent;
[3594]13import java.awt.geom.Point2D;
[358]14import java.util.Collection;
[805]15import java.util.Collections;
[4327]16import java.util.HashSet;
[3593]17import java.util.Iterator;
[358]18import java.util.LinkedList;
[12592]19import java.util.Optional;
[358]20
21import javax.swing.JOptionPane;
22
23import org.openstreetmap.josm.Main;
[582]24import org.openstreetmap.josm.actions.MergeNodesAction;
[805]25import org.openstreetmap.josm.command.AddCommand;
[1405]26import org.openstreetmap.josm.command.ChangeCommand;
[358]27import org.openstreetmap.josm.command.Command;
28import org.openstreetmap.josm.command.MoveCommand;
29import org.openstreetmap.josm.command.RotateCommand;
[3702]30import org.openstreetmap.josm.command.ScaleCommand;
[805]31import org.openstreetmap.josm.command.SequenceCommand;
[358]32import org.openstreetmap.josm.data.coor.EastNorth;
[6215]33import org.openstreetmap.josm.data.coor.LatLon;
[1115]34import org.openstreetmap.josm.data.osm.DataSet;
[358]35import org.openstreetmap.josm.data.osm.Node;
36import org.openstreetmap.josm.data.osm.OsmPrimitive;
[805]37import org.openstreetmap.josm.data.osm.Way;
38import org.openstreetmap.josm.data.osm.WaySegment;
[358]39import org.openstreetmap.josm.data.osm.visitor.AllNodesVisitor;
[4087]40import org.openstreetmap.josm.data.osm.visitor.paint.WireframeMapRenderer;
[1712]41import org.openstreetmap.josm.gui.ExtendedDialog;
[12630]42import org.openstreetmap.josm.gui.MainApplication;
[358]43import org.openstreetmap.josm.gui.MapFrame;
[805]44import org.openstreetmap.josm.gui.MapView;
[10827]45import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
[358]46import org.openstreetmap.josm.gui.SelectionManager;
47import org.openstreetmap.josm.gui.SelectionManager.SelectionEnded;
[1405]48import org.openstreetmap.josm.gui.layer.Layer;
49import org.openstreetmap.josm.gui.layer.OsmDataLayer;
[5735]50import org.openstreetmap.josm.gui.util.GuiHelper;
[7218]51import org.openstreetmap.josm.gui.util.KeyPressReleaseListener;
[12517]52import org.openstreetmap.josm.gui.util.ModifierExListener;
[358]53import org.openstreetmap.josm.tools.ImageProvider;
[12620]54import org.openstreetmap.josm.tools.Logging;
[3594]55import org.openstreetmap.josm.tools.Pair;
[1084]56import org.openstreetmap.josm.tools.Shortcut;
[8977]57import org.openstreetmap.josm.tools.Utils;
[1023]58
[358]59/**
[655]60 * Move is an action that can move all kind of OsmPrimitives (except keys for now).
[358]61 *
62 * If an selected object is under the mouse when dragging, move all selected objects.
63 * If an unselected object is under the mouse when dragging, it becomes selected
64 * and will be moved.
65 * If no object is under the mouse, move all selected objects (if any)
[1023]66 *
[7000]67 * On Mac OS X, Ctrl + mouse button 1 simulates right click (map move), so the
[6993]68 * feature "selection remove" is disabled on this platform.
[358]69 */
[12517]70public class SelectAction extends MapMode implements ModifierExListener, KeyPressReleaseListener, SelectionEnded {
[4327]71
[11913]72 private static final String NORMAL = "normal";
73
[7543]74 /**
75 * Select action mode.
76 * @since 7543
77 */
78 public enum Mode {
79 /** "MOVE" means either dragging or select if no mouse movement occurs (i.e. just clicking) */
80 MOVE,
81 /** "ROTATE" allows to apply a rotation transformation on the selected object (see {@link RotateCommand}) */
82 ROTATE,
83 /** "SCALE" allows to apply a scaling transformation on the selected object (see {@link ScaleCommand}) */
84 SCALE,
85 /** "SELECT" means the selection rectangle */
86 SELECT
87 }
88
[4396]89 // contains all possible cases the cursor can be in the SelectAction
[11978]90 enum SelectActionCursor {
[11913]91
92 rect(NORMAL, "selection"),
93 rect_add(NORMAL, "select_add"),
94 rect_rm(NORMAL, "select_remove"),
95 way(NORMAL, "select_way"),
96 way_add(NORMAL, "select_way_add"),
97 way_rm(NORMAL, "select_way_remove"),
98 node(NORMAL, "select_node"),
99 node_add(NORMAL, "select_node_add"),
100 node_rm(NORMAL, "select_node_remove"),
101 virtual_node(NORMAL, "addnode"),
102 scale("scale", null),
103 rotate("rotate", null),
104 merge("crosshair", null),
105 lasso(NORMAL, "rope"),
106 merge_to_node("crosshair", "joinnode"),
[4396]107 move(Cursor.MOVE_CURSOR);
[4327]108
109 private final Cursor c;
[8674]110 SelectActionCursor(String main, String sub) {
[4327]111 c = ImageProvider.getCursor(main, sub);
112 }
[8510]113
[8674]114 SelectActionCursor(int systemCursor) {
[4396]115 c = Cursor.getPredefinedCursor(systemCursor);
116 }
[8510]117
[11978]118 /**
119 * Returns the action cursor.
120 * @return the cursor
121 */
[4327]122 public Cursor cursor() {
123 return c;
124 }
125 }
126
[8840]127 private boolean lassoMode;
[12284]128 private boolean repeatedKeySwitchLassoOption;
[5152]129
[4327]130 // Cache previous mouse event (needed when only the modifier keys are
131 // pressed but the mouse isn't moved)
[8840]132 private MouseEvent oldEvent;
[4327]133
[8840]134 private Mode mode;
[8308]135 private final transient SelectionManager selectionManager;
[8840]136 private boolean cancelDrawMode;
[4327]137 private boolean drawTargetHighlight;
[8840]138 private boolean didMouseDrag;
[1115]139 /**
[3594]140 * The component this SelectAction is associated with.
141 */
142 private final MapView mv;
143 /**
[1115]144 * The old cursor before the user pressed the mouse button.
145 */
[3702]146 private Point startingDraggingPos;
[1115]147 /**
[5418]148 * point where user pressed the mouse to start movement
149 */
[8285]150 private EastNorth startEN;
[5418]151 /**
[3702]152 * The last known position of the mouse.
153 */
154 private Point lastMousePos;
155 /**
[3594]156 * The time of the user mouse down event.
157 */
[8840]158 private long mouseDownTime;
[3594]159 /**
[4617]160 * The pressed button of the user mouse down event.
161 */
[8840]162 private int mouseDownButton;
[4617]163 /**
164 * The time of the user mouse down event.
165 */
[8840]166 private long mouseReleaseTime;
[4617]167 /**
[1115]168 * The time which needs to pass between click and release before something
169 * counts as a move, in milliseconds
170 */
[1245]171 private int initialMoveDelay;
[1115]172 /**
173 * The screen distance which needs to be travelled before something
174 * counts as a move, in pixels
175 */
[1245]176 private int initialMoveThreshold;
[8840]177 private boolean initialMoveThresholdExceeded;
[3594]178
[1115]179 /**
[4327]180 * elements that have been highlighted in the previous iteration. Used
181 * to remove the highlight from them again as otherwise the whole data
182 * set would have to be checked.
183 */
[12593]184 private transient Optional<OsmPrimitive> currentHighlight = Optional.empty();
[4327]185
186 /**
[1115]187 * Create a new SelectAction
188 * @param mapFrame The MapFrame this action belongs to.
189 */
190 public SelectAction(MapFrame mapFrame) {
[3702]191 super(tr("Select"), "move/move", tr("Select, move, scale and rotate objects"),
[4982]192 Shortcut.registerShortcut("mapmode:select", tr("Mode: {0}", tr("Select")), KeyEvent.VK_S, Shortcut.DIRECT),
[3919]193 ImageProvider.getCursor("normal", "selection"));
[3594]194 mv = mapFrame.mapView;
[4904]195 putValue("help", ht("/Action/Select"));
[3594]196 selectionManager = new SelectionManager(this, false, mv);
[1115]197 }
[358]198
[3702]199 @Override
200 public void enterMode() {
[1115]201 super.enterMode();
[3594]202 mv.addMouseListener(this);
203 mv.addMouseMotionListener(this);
[5152]204 mv.setVirtualNodesEnabled(Main.pref.getInteger("mappaint.node.virtual-size", 8) != 0);
[4767]205 drawTargetHighlight = Main.pref.getBoolean("draw.target-highlight", true);
[7009]206 initialMoveDelay = Main.pref.getInteger("edit.initial-move-delay", 200);
207 initialMoveThreshold = Main.pref.getInteger("edit.initial-move-threshold", 5);
[7218]208 repeatedKeySwitchLassoOption = Main.pref.getBoolean("mappaint.select.toggle-lasso-on-repeated-S", true);
[5394]209 cycleManager.init();
210 virtualManager.init();
[4396]211 // This is required to update the cursors when ctrl/shift/alt is pressed
[12630]212 MapFrame map = MainApplication.getMap();
213 map.keyDetector.addModifierExListener(this);
214 map.keyDetector.addKeyListener(this);
[1115]215 }
[358]216
[3702]217 @Override
218 public void exitMode() {
[1115]219 super.exitMode();
[3594]220 selectionManager.unregister(mv);
221 mv.removeMouseListener(this);
222 mv.removeMouseMotionListener(this);
223 mv.setVirtualNodesEnabled(false);
[12630]224 MapFrame map = MainApplication.getMap();
225 map.keyDetector.removeModifierExListener(this);
226 map.keyDetector.removeKeyListener(this);
[4327]227 removeHighlighting();
[1115]228 }
[358]229
[6084]230 @Override
[12517]231 public void modifiersExChanged(int modifiers) {
[12630]232 if (!MainApplication.isDisplayingMapView() || oldEvent == null) return;
[8510]233 if (giveUserFeedback(oldEvent, modifiers)) {
[5370]234 mv.repaint();
235 }
236 }
237
[1115]238 /**
[5370]239 * handles adding highlights and updating the cursor for the given mouse event.
240 * Please note that the highlighting for merging while moving is handled via mouseDragged.
[5909]241 * @param e {@code MouseEvent} which should be used as base for the feedback
242 * @return {@code true} if repaint is required
[5370]243 */
244 private boolean giveUserFeedback(MouseEvent e) {
[12517]245 return giveUserFeedback(e, e.getModifiersEx());
[5370]246 }
247
248 /**
249 * handles adding highlights and updating the cursor for the given mouse event.
250 * Please note that the highlighting for merging while moving is handled via mouseDragged.
[5909]251 * @param e {@code MouseEvent} which should be used as base for the feedback
[12517]252 * @param modifiers define custom keyboard extended modifiers if the ones from MouseEvent are outdated or similar
[5909]253 * @return {@code true} if repaint is required
[5370]254 */
255 private boolean giveUserFeedback(MouseEvent e, int modifiers) {
[12592]256 Optional<OsmPrimitive> c = Optional.ofNullable(
[7389]257 mv.getNearestNodeOrWay(e.getPoint(), mv.isSelectablePredicate, true));
[5370]258
[12517]259 updateKeyModifiersEx(modifiers);
[12592]260 determineMapMode(c.isPresent());
[5370]261
[12593]262 Optional<OsmPrimitive> newHighlight = Optional.empty();
[5370]263
264 virtualManager.clear();
[11385]265 if (mode == Mode.MOVE && !dragInProgress() && virtualManager.activateVirtualNodeNearPoint(e.getPoint())) {
266 DataSet ds = getLayerManager().getEditDataSet();
267 if (ds != null && drawTargetHighlight) {
268 ds.setHighlightedVirtualNodes(virtualManager.virtualWays);
[5370]269 }
[11385]270 mv.setNewCursor(SelectActionCursor.virtual_node.cursor(), this);
271 // don't highlight anything else if a virtual node will be
[12593]272 return repaintIfRequired(newHighlight);
[5370]273 }
274
275 mv.setNewCursor(getCursor(c), this);
276
277 // return early if there can't be any highlights
[12592]278 if (!drawTargetHighlight || mode != Mode.MOVE || !c.isPresent())
[12593]279 return repaintIfRequired(newHighlight);
[5370]280
281 // CTRL toggles selection, but if while dragging CTRL means merge
282 final boolean isToggleMode = ctrl && !dragInProgress();
[12592]283 if (c.isPresent() && (isToggleMode || !c.get().isSelected())) {
[5370]284 // only highlight primitives that will change the selection
285 // when clicked. I.e. don't highlight selected elements unless
286 // we are in toggle mode.
[12593]287 newHighlight = c;
[5370]288 }
[12593]289 return repaintIfRequired(newHighlight);
[5370]290 }
[6069]291
[5370]292 /**
[4327]293 * works out which cursor should be displayed for most of SelectAction's
294 * features. The only exception is the "move" cursor when actually dragging
295 * primitives.
296 * @param nearbyStuff primitives near the cursor
297 * @return the cursor that should be displayed
298 */
[12592]299 private Cursor getCursor(Optional<OsmPrimitive> nearbyStuff) {
[4327]300 String c = "rect";
301 switch(mode) {
[7543]302 case MOVE:
[8510]303 if (virtualManager.hasVirtualNode()) {
[4327]304 c = "virtual_node";
305 break;
306 }
[12592]307 final OsmPrimitive osm = nearbyStuff.orElse(null);
[4327]308
[8510]309 if (dragInProgress()) {
[4934]310 // only consider merge if ctrl is pressed and there are nodes in
311 // the selection that could be merged
[10382]312 if (!ctrl || getLayerManager().getEditDataSet().getSelectedNodes().isEmpty()) {
[4934]313 c = "move";
314 break;
[4396]315 }
[4934]316 // only show merge to node cursor if nearby node and that node is currently
317 // not being dragged
[6246]318 final boolean hasTarget = osm instanceof Node && !osm.isSelected();
[4934]319 c = hasTarget ? "merge_to_node" : "merge";
[4396]320 break;
321 }
[4327]322
323 c = (osm instanceof Node) ? "node" : c;
324 c = (osm instanceof Way) ? "way" : c;
[8510]325 if (shift) {
[4327]326 c += "_add";
[8510]327 } else if (ctrl) {
[4412]328 c += osm == null || osm.isSelected() ? "_rm" : "_add";
[4327]329 }
330 break;
[7543]331 case ROTATE:
[4327]332 c = "rotate";
333 break;
[7543]334 case SCALE:
[4327]335 c = "scale";
336 break;
[7543]337 case SELECT:
[5152]338 if (lassoMode) {
339 c = "lasso";
340 } else {
[6993]341 c = "rect" + (shift ? "_add" : (ctrl && !Main.isPlatformOsx() ? "_rm" : ""));
[5152]342 }
[4327]343 break;
344 }
345 return SelectActionCursor.valueOf(c).cursor();
346 }
347
348 /**
349 * Removes all existing highlights.
350 * @return true if a repaint is required
351 */
352 private boolean removeHighlighting() {
353 boolean needsRepaint = false;
[10382]354 DataSet ds = getLayerManager().getEditDataSet();
[8510]355 if (ds != null && !ds.getHighlightedVirtualNodes().isEmpty()) {
[4327]356 needsRepaint = true;
357 ds.clearHighlightedVirtualNodes();
358 }
[12593]359 if (!currentHighlight.isPresent()) {
[4327]360 return needsRepaint;
[12593]361 } else {
362 currentHighlight.get().setHighlighted(false);
[4327]363 }
[12593]364 currentHighlight = Optional.empty();
[4327]365 return true;
366 }
367
[12593]368 private boolean repaintIfRequired(Optional<OsmPrimitive> newHighlight) {
369 if (!drawTargetHighlight || currentHighlight.equals(newHighlight))
[5093]370 return false;
[12593]371 currentHighlight.ifPresent(osm -> osm.setHighlighted(false));
372 newHighlight.ifPresent(osm -> osm.setHighlighted(true));
373 currentHighlight = newHighlight;
374 return true;
[5093]375 }
[6069]376
[9073]377 /**
[5370]378 * Look, whether any object is selected. If not, select the nearest node.
379 * If there are no nodes in the dataset, do nothing.
380 *
381 * If the user did not press the left mouse button, do nothing.
382 *
383 * Also remember the starting position of the movement and change the mouse
384 * cursor to movement.
[4327]385 */
[5370]386 @Override
387 public void mousePressed(MouseEvent e) {
[5394]388 mouseDownButton = e.getButton();
[5370]389 // return early
[5394]390 if (!mv.isActiveLayerVisible() || !(Boolean) this.getValue("active") || mouseDownButton != MouseEvent.BUTTON1)
[5370]391 return;
[6069]392
[5370]393 // left-button mouse click only is processed here
[6069]394
[5370]395 // request focus in order to enable the expected keyboard shortcuts
396 mv.requestFocus();
[4327]397
[5370]398 // update which modifiers are pressed (shift, alt, ctrl)
399 updateKeyModifiers(e);
400
401 // We don't want to change to draw tool if the user tries to (de)select
402 // stuff but accidentally clicks in an empty area when selection is empty
[9970]403 cancelDrawMode = shift || ctrl;
[5370]404 didMouseDrag = false;
405 initialMoveThresholdExceeded = false;
406 mouseDownTime = System.currentTimeMillis();
407 lastMousePos = e.getPoint();
[8510]408 startEN = mv.getEastNorth(lastMousePos.x, lastMousePos.y);
[5370]409
410 // primitives under cursor are stored in c collection
[6069]411
[7389]412 OsmPrimitive nearestPrimitive = mv.getNearestNodeOrWay(e.getPoint(), mv.isSelectablePredicate, true);
[4327]413
[8510]414 determineMapMode(nearestPrimitive != null);
[6069]415
[5370]416 switch(mode) {
[7543]417 case ROTATE:
418 case SCALE:
[5394]419 // if nothing was selected, select primitive under cursor for scaling or rotating
[10382]420 DataSet ds = getLayerManager().getEditDataSet();
[10383]421 if (ds.selectionEmpty()) {
[10382]422 ds.setSelected(asColl(nearestPrimitive));
[4327]423 }
424
[5370]425 // Mode.select redraws when selectPrims is called
426 // Mode.move redraws when mouseDragged is called
427 // Mode.rotate redraws here
428 // Mode.scale redraws here
429 break;
[7543]430 case MOVE:
[5394]431 // also include case when some primitive is under cursor and no shift+ctrl / alt+ctrl is pressed
432 // so this is not movement, but selection on primitive under cursor
433 if (!cancelDrawMode && nearestPrimitive instanceof Way) {
[5435]434 virtualManager.activateVirtualNodeNearPoint(e.getPoint());
[4327]435 }
[5443]436 OsmPrimitive toSelect = cycleManager.cycleSetup(nearestPrimitive, e.getPoint());
[6992]437 selectPrims(asColl(toSelect), false, false);
[5418]438 useLastMoveCommandIfPossible();
[5735]439 // Schedule a timer to update status line "initialMoveDelay+1" ms in the future
[10601]440 GuiHelper.scheduleTimer(initialMoveDelay+1, evt -> updateStatusLine(), false);
[5370]441 break;
[7543]442 case SELECT:
[5370]443 default:
[6993]444 if (!(ctrl && Main.isPlatformOsx())) {
445 // start working with rectangle or lasso
446 selectionManager.register(mv, lassoMode);
447 selectionManager.mousePressed(e);
448 break;
449 }
[4327]450 }
[5446]451 if (giveUserFeedback(e)) {
452 mv.repaint();
453 }
[5370]454 updateStatusLine();
[4327]455 }
[6069]456
[5370]457 @Override
458 public void mouseMoved(MouseEvent e) {
[7543]459 // Mac OSX simulates with ctrl + mouse 1 the second mouse button hence no dragging events get fired.
460 if (Main.isPlatformOsx() && (mode == Mode.ROTATE || mode == Mode.SCALE)) {
[5370]461 mouseDragged(e);
[4327]462 return;
[5370]463 }
464 oldEvent = e;
[8510]465 if (giveUserFeedback(e)) {
[4396]466 mv.repaint();
467 }
[4327]468 }
[6069]469
[4327]470 /**
[1115]471 * If the left mouse button is pressed, move all currently selected
472 * objects (if one of them is under the mouse) or the current one under the
473 * mouse (which will become selected).
474 */
[3702]475 @Override
476 public void mouseDragged(MouseEvent e) {
477 if (!mv.isActiveLayerVisible())
[1418]478 return;
[6069]479
[4617]480 // Swing sends random mouseDragged events when closing dialogs by double-clicking their top-left icon on Windows
481 // Ignore such false events to prevent issues like #7078
[4934]482 if (mouseDownButton == MouseEvent.BUTTON1 && mouseReleaseTime > mouseDownTime)
[4617]483 return;
[6069]484
[1412]485 cancelDrawMode = true;
[7543]486 if (mode == Mode.SELECT) {
[7000]487 // Unregisters selectionManager if ctrl has been pressed after mouse click on Mac OS X in order to move the map
488 if (ctrl && Main.isPlatformOsx()) {
489 selectionManager.unregister(mv);
490 // Make sure correct cursor is displayed
491 mv.setNewCursor(Cursor.MOVE_CURSOR, this);
492 }
[3702]493 return;
[7000]494 }
[853]495
[1115]496 // do not count anything as a move if it lasts less than 100 milliseconds.
[7543]497 if ((mode == Mode.MOVE) && (System.currentTimeMillis() - mouseDownTime < initialMoveDelay))
[3702]498 return;
[365]499
[8395]500 if (mode != Mode.ROTATE && mode != Mode.SCALE && (e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) == 0) {
501 // button is pressed in rotate mode
502 return;
[3702]503 }
[358]504
[7543]505 if (mode == Mode.MOVE) {
[4396]506 // If ctrl is pressed we are in merge mode. Look for a nearby node,
507 // highlight it and adjust the cursor accordingly.
[10382]508 final boolean canMerge = ctrl && !getLayerManager().getEditDataSet().getSelectedNodes().isEmpty();
[8318]509 final OsmPrimitive p = canMerge ? findNodeToMergeTo(e.getPoint()) : null;
[4396]510 boolean needsRepaint = removeHighlighting();
[8510]511 if (p != null) {
[4396]512 p.setHighlighted(true);
[12593]513 currentHighlight = Optional.of(p);
[4396]514 needsRepaint = true;
515 }
[12592]516 mv.setNewCursor(getCursor(Optional.ofNullable(p)), this);
[4934]517 // also update the stored mouse event, so we can display the correct cursor
518 // when dragging a node onto another one and then press CTRL to merge
519 oldEvent = e;
[8510]520 if (needsRepaint) {
[4396]521 mv.repaint();
522 }
[1750]523 }
[358]524
[3702]525 if (startingDraggingPos == null) {
526 startingDraggingPos = new Point(e.getX(), e.getY());
527 }
528
[8444]529 if (lastMousePos == null) {
[4039]530 lastMousePos = e.getPoint();
531 return;
532 }
533
[1115]534 if (!initialMoveThresholdExceeded) {
[5418]535 int dp = (int) lastMousePos.distance(e.getX(), e.getY());
[3702]536 if (dp < initialMoveThreshold)
[5435]537 return; // ignore small drags
538 initialMoveThresholdExceeded = true; //no more ingnoring uintil nex mouse press
[1115]539 }
[5418]540 if (e.getPoint().equals(lastMousePos))
[1115]541 return;
[6069]542
[5435]543 EastNorth currentEN = mv.getEastNorth(e.getX(), e.getY());
544
545 if (virtualManager.hasVirtualWaysToBeConstructed()) {
546 virtualManager.createMiddleNodeFromVirtual(currentEN);
[1115]547 } else {
[5418]548 if (!updateCommandWhileDragging(currentEN)) return;
[1115]549 }
[358]550
[3594]551 mv.repaint();
[7543]552 if (mode != Mode.SCALE) {
[3702]553 lastMousePos = e.getPoint();
554 }
[454]555
[3594]556 didMouseDrag = true;
[1115]557 }
[358]558
[4327]559 @Override
560 public void mouseExited(MouseEvent e) {
[8510]561 if (removeHighlighting()) {
[4327]562 mv.repaint();
563 }
564 }
565
[3702]566 @Override
[3594]567 public void mouseReleased(MouseEvent e) {
[4327]568 if (!mv.isActiveLayerVisible())
[1418]569 return;
[1441]570
[3702]571 startingDraggingPos = null;
[4617]572 mouseReleaseTime = System.currentTimeMillis();
[12630]573 MapFrame map = MainApplication.getMap();
[3702]574
[7543]575 if (mode == Mode.SELECT) {
[8550]576 if (e.getButton() != MouseEvent.BUTTON1) {
577 return;
578 }
579 selectionManager.endSelecting(e);
[3594]580 selectionManager.unregister(mv);
[1412]581
582 // Select Draw Tool if no selection has been made
[11452]583 if (!cancelDrawMode && getLayerManager().getEditDataSet().selectionEmpty()) {
[12630]584 map.selectDrawTool(true);
[5734]585 updateStatusLine();
[1405]586 return;
[1412]587 }
[1115]588 }
[424]589
[7543]590 if (mode == Mode.MOVE && e.getButton() == MouseEvent.BUTTON1) {
[3594]591 if (!didMouseDrag) {
592 // only built in move mode
[5370]593 virtualManager.clear();
[4327]594 // do nothing if the click was to short too be recognized as a drag,
[3594]595 // but the release position is farther than 10px away from the press position
[4327]596 if (lastMousePos == null || lastMousePos.distanceSq(e.getPoint()) < 100) {
[5370]597 updateKeyModifiers(e);
598 selectPrims(cycleManager.cyclePrims(), true, false);
[3593]599
[3594]600 // If the user double-clicked a node, change to draw mode
[10382]601 Collection<OsmPrimitive> c = getLayerManager().getEditDataSet().getSelected();
[3702]602 if (e.getClickCount() >= 2 && c.size() == 1 && c.iterator().next() instanceof Node) {
[3594]603 // We need to do it like this as otherwise drawAction will see a double
604 // click and switch back to SelectMode
[12634]605 MainApplication.worker.execute(() -> map.selectDrawTool(true));
[3594]606 return;
[3593]607 }
608 }
[1115]609 } else {
[5370]610 confirmOrUndoMovement(e);
[1115]611 }
612 }
[424]613
[1115]614 mode = null;
[4360]615
616 // simply remove any highlights if the middle click popup is active because
617 // the highlights don't depend on the cursor position there. If something was
618 // selected beforehand this would put us into move mode as well, which breaks
619 // the cycling through primitives on top of each other (see #6739).
[8510]620 if (e.getButton() == MouseEvent.BUTTON2) {
[4360]621 removeHighlighting();
622 } else {
623 giveUserFeedback(e);
624 }
[1115]625 updateStatusLine();
626 }
[358]627
[5370]628 @Override
[3594]629 public void selectionEnded(Rectangle r, MouseEvent e) {
[4327]630 updateKeyModifiers(e);
[5370]631 selectPrims(selectionManager.getSelectedObjects(alt), true, true);
[1115]632 }
[372]633
[7218]634 @Override
635 public void doKeyPressed(KeyEvent e) {
[12630]636 if (!repeatedKeySwitchLassoOption || !MainApplication.isDisplayingMapView() || !getShortcut().isEvent(e))
[11452]637 return;
[12620]638 if (Logging.isDebugEnabled()) {
639 Logging.debug("{0} consuming event {1}", getClass().getName(), e);
[8441]640 }
[7218]641 e.consume();
[12630]642 MapFrame map = MainApplication.getMap();
[7218]643 if (!lassoMode) {
[12630]644 map.selectMapMode(map.mapModeSelectLasso);
[7218]645 } else {
[12630]646 map.selectMapMode(map.mapModeSelect);
[7218]647 }
648 }
649
650 @Override
651 public void doKeyReleased(KeyEvent e) {
[9989]652 // Do nothing
[7218]653 }
654
[3594]655 /**
[5370]656 * sets the mapmode according to key modifiers and if there are any
657 * selectables nearby. Everything has to be pre-determined for this
658 * function; its main purpose is to centralize what the modifiers do.
[8470]659 * @param hasSelectionNearby {@code true} if some primitves are selectable nearby
[3594]660 */
[5370]661 private void determineMapMode(boolean hasSelectionNearby) {
662 if (shift && ctrl) {
[7543]663 mode = Mode.ROTATE;
[5370]664 } else if (alt && ctrl) {
[7543]665 mode = Mode.SCALE;
[5370]666 } else if (hasSelectionNearby || dragInProgress()) {
[7543]667 mode = Mode.MOVE;
[5370]668 } else {
[7543]669 mode = Mode.SELECT;
[5370]670 }
671 }
[6069]672
[8931]673 /**
674 * Determines whenever elements have been grabbed and moved (i.e. the initial
675 * thresholds have been exceeded) and is still in progress (i.e. mouse button still pressed)
676 * @return true if a drag is in progress
[5370]677 */
[8512]678 private boolean dragInProgress() {
[5370]679 return didMouseDrag && startingDraggingPos != null;
680 }
[3593]681
[5370]682 /**
[6069]683 * Create or update data modification command while dragging mouse - implementation of
[5370]684 * continuous moving, scaling and rotation
[5418]685 * @param currentEN - mouse position
[5419]686 * @return status of action (<code>true</code> when action was performed)
[5370]687 */
[5418]688 private boolean updateCommandWhileDragging(EastNorth currentEN) {
[5370]689 // Currently we support only transformations which do not affect relations.
690 // So don't add them in the first place to make handling easier
[10382]691 DataSet ds = getLayerManager().getEditDataSet();
692 Collection<OsmPrimitive> selection = ds.getSelectedNodesAndWays();
[5443]693 if (selection.isEmpty()) { // if nothing was selected to drag, just select nearest node/way to the cursor
[7389]694 OsmPrimitive nearestPrimitive = mv.getNearestNodeOrWay(mv.getPoint(startEN), mv.isSelectablePredicate, true);
[10382]695 ds.setSelected(nearestPrimitive);
[5443]696 }
[6069]697
[5370]698 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
699 // for these transformations, having only one node makes no sense - quit silently
[7543]700 if (affectedNodes.size() < 2 && (mode == Mode.ROTATE || mode == Mode.SCALE)) {
[5370]701 return false;
702 }
[12053]703 Command c = getLastCommandInDataset(ds);
[7543]704 if (mode == Mode.MOVE) {
[5653]705 if (startEN == null) return false; // fix #8128
[10382]706 ds.beginUpdate();
[12065]707 try {
708 if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
709 ((MoveCommand) c).saveCheckpoint();
710 ((MoveCommand) c).applyVectorTo(currentEN);
[12785]711 } else if (!selection.isEmpty()) {
[12065]712 c = new MoveCommand(selection, startEN, currentEN);
[12641]713 MainApplication.undoRedo.add(c);
[3593]714 }
[12065]715 for (Node n : affectedNodes) {
716 LatLon ll = n.getCoor();
717 if (ll != null && ll.isOutSideWorld()) {
718 // Revert move
719 ((MoveCommand) c).resetToCheckpoint();
720 // TODO: We might use a simple notification in the lower left corner.
721 JOptionPane.showMessageDialog(
722 Main.parent,
723 tr("Cannot move objects outside of the world."),
724 tr("Warning"),
725 JOptionPane.WARNING_MESSAGE);
726 mv.setNewCursor(cursor, this);
727 return false;
728 }
729 }
730 } finally {
731 ds.endUpdate();
[3594]732 }
[5653]733 } else {
734 startEN = currentEN; // drag can continue after scaling/rotation
[6069]735
[7543]736 if (mode != Mode.ROTATE && mode != Mode.SCALE) {
[5991]737 return false;
738 }
[6069]739
[10382]740 ds.beginUpdate();
[12065]741 try {
742 if (mode == Mode.ROTATE) {
743 if (c instanceof RotateCommand && affectedNodes.equals(((RotateCommand) c).getTransformedNodes())) {
744 ((RotateCommand) c).handleEvent(currentEN);
745 } else {
[12641]746 MainApplication.undoRedo.add(new RotateCommand(selection, currentEN));
[12065]747 }
748 } else if (mode == Mode.SCALE) {
749 if (c instanceof ScaleCommand && affectedNodes.equals(((ScaleCommand) c).getTransformedNodes())) {
750 ((ScaleCommand) c).handleEvent(currentEN);
751 } else {
[12641]752 MainApplication.undoRedo.add(new ScaleCommand(selection, currentEN));
[12065]753 }
754 }
[6069]755
[12065]756 Collection<Way> ways = ds.getSelectedWays();
757 if (doesImpactStatusLine(affectedNodes, ways)) {
[12630]758 MainApplication.getMap().statusLine.setDist(ways);
[5653]759 }
[12065]760 } finally {
761 ds.endUpdate();
[3594]762 }
763 }
[5370]764 return true;
765 }
[6069]766
[8870]767 private static boolean doesImpactStatusLine(Collection<Node> affectedNodes, Collection<Way> selectedWays) {
[5991]768 for (Way w : selectedWays) {
769 for (Node n : w.getNodes()) {
770 if (affectedNodes.contains(n)) {
771 return true;
772 }
773 }
774 }
775 return false;
776 }
[6069]777
[5418]778 /**
[5419]779 * Adapt last move command (if it is suitable) to work with next drag, started at point startEN
[5418]780 */
781 private void useLastMoveCommandIfPossible() {
[12053]782 DataSet dataSet = getLayerManager().getEditDataSet();
[12313]783 if (dataSet == null) {
784 // It may happen that there is no edit layer.
785 return;
786 }
[12053]787 Command c = getLastCommandInDataset(dataSet);
788 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(dataSet.getSelected());
[5418]789 if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
790 // old command was created with different base point of movement, we need to recalculate it
791 ((MoveCommand) c).changeStartPoint(startEN);
792 }
793 }
[6069]794
[5418]795 /**
796 * Obtain command in undoRedo stack to "continue" when dragging
[12053]797 * @param ds The data set the command needs to be in.
[8931]798 * @return last command
[5418]799 */
[12060]800 private static Command getLastCommandInDataset(DataSet ds) {
[12641]801 Command lastCommand = MainApplication.undoRedo.getLastCommand();
[12316]802 if (lastCommand instanceof SequenceCommand) {
803 lastCommand = ((SequenceCommand) lastCommand).getLastCommand();
[5418]804 }
[12316]805 if (lastCommand != null && ds.equals(lastCommand.getAffectedDataSet())) {
806 return lastCommand;
807 } else {
808 return null;
809 }
[5418]810 }
[6069]811
[5419]812 /**
[8977]813 * Present warning in the following cases and undo unwanted movements: <ul>
814 * <li>large and possibly unwanted movements</li>
815 * <li>movement of node with attached ways that are hidden by filters</li>
816 * </ul>
[5419]817 *
818 * @param e the mouse event causing the action (mouse released)
819 */
[5370]820 private void confirmOrUndoMovement(MouseEvent e) {
[8977]821 if (movesHiddenWay()) {
822 final ExtendedDialog ed = new ConfirmMoveDialog();
823 ed.setContent(tr("Are you sure that you want to move elements with attached ways that are hidden by filters?"));
824 ed.toggleEnable("movedHiddenElements");
825 ed.showDialog();
826 if (ed.getValue() != 1) {
[12641]827 MainApplication.undoRedo.undo();
[8977]828 }
829 }
[5370]830 int max = Main.pref.getInteger("warn.move.maxelements", 20), limit = max;
[10382]831 for (OsmPrimitive osm : getLayerManager().getEditDataSet().getSelected()) {
[5370]832 if (osm instanceof Way) {
833 limit -= ((Way) osm).getNodes().size();
834 }
[10179]835 if (--limit < 0) {
[5370]836 break;
837 }
838 }
839 if (limit < 0) {
[8977]840 final ExtendedDialog ed = new ConfirmMoveDialog();
[6507]841 ed.setContent(
842 /* for correct i18n of plural forms - see #9110 */
[8540]843 trn("You moved more than {0} element. " + "Moving a large number of elements is often an error.\n" + "Really move them?",
844 "You moved more than {0} elements. " + "Moving a large number of elements is often an error.\n" + "Really move them?",
845 max, max));
[5370]846 ed.toggleEnable("movedManyElements");
847 ed.showDialog();
[3594]848
[5370]849 if (ed.getValue() != 1) {
[12641]850 MainApplication.undoRedo.undo();
[5370]851 }
852 } else {
853 // if small number of elements were moved,
854 updateKeyModifiers(e);
855 if (ctrl) mergePrims(e.getPoint());
856 }
[3594]857 }
[6069]858
[8977]859 static class ConfirmMoveDialog extends ExtendedDialog {
[8985]860 ConfirmMoveDialog() {
[8977]861 super(Main.parent,
862 tr("Move elements"),
[12279]863 tr("Move them"), tr("Undo move"));
864 setButtonIcons("reorder", "cancel");
[8977]865 setCancelButton(2);
866 }
867 }
868
[10448]869 private boolean movesHiddenWay() {
870 DataSet ds = getLayerManager().getEditDataSet();
871 final Collection<OsmPrimitive> elementsToTest = new HashSet<>(ds.getSelected());
[12314]872 for (Way osm : ds.getSelectedWays()) {
[8977]873 elementsToTest.addAll(osm.getNodes());
874 }
875 for (OsmPrimitive node : Utils.filteredCollection(elementsToTest, Node.class)) {
876 for (Way ref : Utils.filteredCollection(node.getReferrers(), Way.class)) {
877 if (ref.isDisabledAndHidden()) {
878 return true;
879 }
880 }
881 }
882 return false;
883 }
884
[5419]885 /**
[6202]886 * Merges the selected nodes to the one closest to the given mouse position if the control
[4396]887 * key is pressed. If there is no such node, no action will be done and no error will be
[5419]888 * reported. If there is, it will execute the merge and add it to the undo buffer.
[9231]889 * @param p mouse position
[5419]890 */
[8512]891 private void mergePrims(Point p) {
[10382]892 DataSet ds = getLayerManager().getEditDataSet();
893 Collection<Node> selNodes = ds.getSelectedNodes();
[5370]894 if (selNodes.isEmpty())
[4396]895 return;
[3594]896
[5370]897 Node target = findNodeToMergeTo(p);
[4396]898 if (target == null)
899 return;
900
[8343]901 if (selNodes.size() == 1) {
902 // Move all selected primitive to preserve shape #10748
[10382]903 Collection<OsmPrimitive> selection = ds.getSelectedNodesAndWays();
[8343]904 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
[12053]905 Command c = getLastCommandInDataset(ds);
[10382]906 ds.beginUpdate();
[12065]907 try {
908 if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
909 Node selectedNode = selNodes.iterator().next();
910 EastNorth selectedEN = selectedNode.getEastNorth();
911 EastNorth targetEN = target.getEastNorth();
912 ((MoveCommand) c).moveAgain(targetEN.getX() - selectedEN.getX(),
913 targetEN.getY() - selectedEN.getY());
914 }
915 } finally {
916 ds.endUpdate();
[8343]917 }
918 }
919
[7005]920 Collection<Node> nodesToMerge = new LinkedList<>(selNodes);
[4396]921 nodesToMerge.add(target);
[12636]922 mergeNodes(MainApplication.getLayerManager().getEditLayer(), nodesToMerge, target);
[3594]923 }
[3593]924
[5419]925 /**
[8343]926 * Merge nodes using {@code MergeNodesAction}.
927 * Can be overridden for testing purpose.
928 * @param layer layer the reference data layer. Must not be null
929 * @param nodes the collection of nodes. Ignored if null
930 * @param targetLocationNode this node's location will be used for the target node
931 */
932 public void mergeNodes(OsmDataLayer layer, Collection<Node> nodes,
933 Node targetLocationNode) {
934 MergeNodesAction.doMergeNodes(layer, nodes, targetLocationNode);
935 }
936
937 /**
[5419]938 * Tries to find a node to merge to when in move-merge mode for the current mouse
939 * position. Either returns the node or null, if no suitable one is nearby.
[9231]940 * @param p mouse position
[8931]941 * @return node to merge to, or null
[5419]942 */
[8512]943 private Node findNodeToMergeTo(Point p) {
[5370]944 Collection<Node> target = mv.getNearestNodes(p,
[10382]945 getLayerManager().getEditDataSet().getSelectedNodes(),
[7389]946 mv.isSelectablePredicate);
[4396]947 return target.isEmpty() ? null : target.iterator().next();
948 }
949
[5370]950 private void selectPrims(Collection<OsmPrimitive> prims, boolean released, boolean area) {
[10382]951 DataSet ds = getLayerManager().getEditDataSet();
[3594]952
953 // not allowed together: do not change dataset selection, return early
[4562]954 // Virtual Ways: if non-empty the cursor is above a virtual node. So don't highlight
955 // anything if about to drag the virtual node (i.e. !released) but continue if the
956 // cursor is only released above a virtual node by accident (i.e. released). See #7018
[6013]957 if (ds == null || (shift && ctrl) || (ctrl && !released) || (virtualManager.hasVirtualWaysToBeConstructed() && !released))
[3594]958 return;
959
960 if (!released) {
961 // Don't replace the selection if the user clicked on a
962 // selected object (it breaks moving of selected groups).
963 // Do it later, on mouse release.
[6013]964 shift |= ds.getSelected().containsAll(prims);
[3594]965 }
966
[2348]967 if (ctrl) {
968 // Ctrl on an item toggles its selection status,
969 // but Ctrl on an *area* just clears those items
970 // out of the selection.
[2402]971 if (area) {
[3594]972 ds.clearSelection(prims);
[2402]973 } else {
[3594]974 ds.toggleSelected(prims);
[2402]975 }
[3594]976 } else if (shift) {
977 // add prims to an existing selection
978 ds.addSelected(prims);
[1750]979 } else {
[3594]980 // clear selection, then select the prims clicked
981 ds.setSelected(prims);
[1750]982 }
[1115]983 }
[1023]984
[7543]985 /**
986 * Returns the current select mode.
987 * @return the select mode
988 * @since 7543
989 */
990 public final Mode getMode() {
991 return mode;
992 }
993
[3702]994 @Override
995 public String getModeHelpText() {
[5735]996 if (mouseDownButton == MouseEvent.BUTTON1 && mouseReleaseTime < mouseDownTime) {
[7543]997 if (mode == Mode.SELECT)
[5735]998 return tr("Release the mouse button to select the objects in the rectangle.");
[7543]999 else if (mode == Mode.MOVE && (System.currentTimeMillis() - mouseDownTime >= initialMoveDelay)) {
[10382]1000 final DataSet ds = getLayerManager().getEditDataSet();
1001 final boolean canMerge = ds != null && !ds.getSelectedNodes().isEmpty();
1002 final String mergeHelp = canMerge ? (' ' + tr("Ctrl to merge with nearest node.")) : "";
[5735]1003 return tr("Release the mouse button to stop moving.") + mergeHelp;
[7543]1004 } else if (mode == Mode.ROTATE)
[5735]1005 return tr("Release the mouse button to stop rotating.");
[7543]1006 else if (mode == Mode.SCALE)
[5735]1007 return tr("Release the mouse button to stop scaling.");
1008 }
[8510]1009 return tr("Move objects by dragging; Shift to add to selection (Ctrl to toggle); Shift-Ctrl to rotate selected; " +
1010 "Alt-Ctrl to scale selected; or change selection");
[1115]1011 }
[1412]1012
[3702]1013 @Override
1014 public boolean layerIsSupported(Layer l) {
[1379]1015 return l instanceof OsmDataLayer;
1016 }
[5152]1017
[5734]1018 /**
1019 * Enable or diable the lasso mode
1020 * @param lassoMode true to enable the lasso mode, false otherwise
1021 */
[5152]1022 public void setLassoMode(boolean lassoMode) {
1023 this.selectionManager.setLassoMode(lassoMode);
1024 this.lassoMode = lassoMode;
1025 }
[6069]1026
[9067]1027 private final transient CycleManager cycleManager = new CycleManager();
1028 private final transient VirtualManager virtualManager = new VirtualManager();
[6069]1029
[5370]1030 private class CycleManager {
1031
1032 private Collection<OsmPrimitive> cycleList = Collections.emptyList();
[8840]1033 private boolean cyclePrims;
1034 private OsmPrimitive cycleStart;
[5394]1035 private boolean waitForMouseUpParameter;
1036 private boolean multipleMatchesParameter;
[5370]1037 /**
[5394]1038 * read preferences
[5370]1039 */
[5394]1040 private void init() {
1041 waitForMouseUpParameter = Main.pref.getBoolean("mappaint.select.waits-for-mouse-up", false);
1042 multipleMatchesParameter = Main.pref.getBoolean("selectaction.cycles.multiple.matches", false);
1043 }
[6069]1044
[5394]1045 /**
[6546]1046 * Determine primitive to be selected and build cycleList
[5394]1047 * @param nearest primitive found by simple method
1048 * @param p point where user clicked
[5443]1049 * @return OsmPrimitive to be selected
[5394]1050 */
[5443]1051 private OsmPrimitive cycleSetup(OsmPrimitive nearest, Point p) {
[5370]1052 OsmPrimitive osm = null;
1053
[5394]1054 if (nearest != null) {
1055 osm = nearest;
[5370]1056
[5394]1057 if (!(alt || multipleMatchesParameter)) {
[6069]1058 // no real cycling, just one element in cycle list
[6992]1059 cycleList = asColl(osm);
[5370]1060
[5394]1061 if (waitForMouseUpParameter) {
[5370]1062 // prefer a selected nearest node or way, if possible
[7389]1063 osm = mv.getNearestNodeOrWay(p, mv.isSelectablePredicate, true);
[5370]1064 }
1065 } else {
[5394]1066 // Alt + left mouse button pressed: we need to build cycle list
[7389]1067 cycleList = mv.getAllNearest(p, mv.isSelectablePredicate);
[5370]1068
1069 if (cycleList.size() > 1) {
1070 cyclePrims = false;
1071
[5394]1072 // find first already selected element in cycle list
[5370]1073 OsmPrimitive old = osm;
1074 for (OsmPrimitive o : cycleList) {
1075 if (o.isSelected()) {
1076 cyclePrims = true;
1077 osm = o;
1078 break;
1079 }
1080 }
1081
1082 // special case: for cycle groups of 2, we can toggle to the
1083 // true nearest primitive on mousePressed right away
[5394]1084 if (cycleList.size() == 2 && !waitForMouseUpParameter) {
[5370]1085 if (!(osm.equals(old) || osm.isNew() || ctrl)) {
1086 cyclePrims = false;
1087 osm = old;
1088 } // else defer toggling to mouseRelease time in those cases:
1089 /*
1090 * osm == old -- the true nearest node is the
1091 * selected one osm is a new node -- do not break
1092 * unglue ways in ALT mode ctrl is pressed -- ctrl
1093 * generally works on mouseReleased
1094 */
1095 }
1096 }
1097 }
1098 }
[5443]1099 return osm;
[5370]1100 }
1101
1102 /**
1103 * Modifies current selection state and returns the next element in a
1104 * selection cycle given by
[5394]1105 * <code>cycleList</code> field
[5370]1106 * @return the next element of cycle list
1107 */
1108 private Collection<OsmPrimitive> cyclePrims() {
[5394]1109 if (cycleList.size() <= 1) {
1110 // no real cycling, just return one-element collection with nearest primitive in it
1111 return cycleList;
1112 }
[9073]1113 // updateKeyModifiers() already called before!
[5370]1114
[10382]1115 DataSet ds = getLayerManager().getEditDataSet();
[5394]1116 OsmPrimitive first = cycleList.iterator().next(), foundInDS = null;
[9062]1117 OsmPrimitive nxt = first;
[5370]1118
[5394]1119 if (cyclePrims && shift) {
1120 for (Iterator<OsmPrimitive> i = cycleList.iterator(); i.hasNext();) {
1121 nxt = i.next();
1122 if (!nxt.isSelected()) {
1123 break; // take first primitive in cycleList not in sel
[5370]1124 }
1125 }
[5394]1126 // if primitives 1,2,3 are under cursor, [Alt-press] [Shift-release] gives 1 -> 12 -> 123
1127 } else {
1128 for (Iterator<OsmPrimitive> i = cycleList.iterator(); i.hasNext();) {
1129 nxt = i.next();
1130 if (nxt.isSelected()) {
1131 foundInDS = nxt;
1132 // first selected primitive in cycleList is found
1133 if (cyclePrims || ctrl) {
[6069]1134 ds.clearSelection(foundInDS); // deselect it
[5394]1135 nxt = i.hasNext() ? i.next() : first;
1136 // return next one in cycle list (last->first)
[5370]1137 }
[5394]1138 break; // take next primitive in cycleList
[5370]1139 }
[5394]1140 }
1141 }
[6069]1142
[5394]1143 // if "no-alt-cycling" is enabled, Ctrl-Click arrives here.
1144 if (ctrl) {
1145 // a member of cycleList was found in the current dataset selection
1146 if (foundInDS != null) {
1147 // mouse was moved to a different selection group w/ a previous sel
1148 if (!cycleList.contains(cycleStart)) {
1149 ds.clearSelection(cycleList);
1150 cycleStart = foundInDS;
1151 } else if (cycleStart.equals(nxt)) {
1152 // loop detected, insert deselect step
1153 ds.addSelected(nxt);
1154 }
[5370]1155 } else {
[5394]1156 // setup for iterating a sel group again or a new, different one..
[9970]1157 nxt = cycleList.contains(cycleStart) ? cycleStart : first;
[5394]1158 cycleStart = nxt;
[5370]1159 }
[5394]1160 } else {
1161 cycleStart = null;
[5370]1162 }
[5394]1163 // return one-element collection with one element to be selected (or added to selection)
[6992]1164 return asColl(nxt);
[5370]1165 }
1166 }
[6069]1167
[5370]1168 private class VirtualManager {
1169
[8840]1170 private Node virtualNode;
[7005]1171 private Collection<WaySegment> virtualWays = new LinkedList<>();
[5394]1172 private int nodeVirtualSize;
1173 private int virtualSnapDistSq2;
1174 private int virtualSpace;
[6069]1175
[5394]1176 private void init() {
1177 nodeVirtualSize = Main.pref.getInteger("mappaint.node.virtual-size", 8);
1178 int virtualSnapDistSq = Main.pref.getInteger("mappaint.node.virtual-snap-distance", 8);
1179 virtualSnapDistSq2 = virtualSnapDistSq*virtualSnapDistSq;
1180 virtualSpace = Main.pref.getInteger("mappaint.node.virtual-space", 70);
1181 }
[6069]1182
[5370]1183 /**
1184 * Calculate a virtual node if there is enough visual space to draw a
1185 * crosshair node and the middle of a way segment is clicked. If the
1186 * user drags the crosshair node, it will be added to all ways in
1187 * <code>virtualWays</code>.
1188 *
[5909]1189 * @param p the point clicked
[5370]1190 * @return whether
1191 * <code>virtualNode</code> and
1192 * <code>virtualWays</code> were setup.
1193 */
[5435]1194 private boolean activateVirtualNodeNearPoint(Point p) {
[5394]1195 if (nodeVirtualSize > 0) {
[5435]1196
[7005]1197 Collection<WaySegment> selVirtualWays = new LinkedList<>();
1198 Pair<Node, Node> vnp = null, wnp = new Pair<>(null, null);
[5370]1199
[7389]1200 for (WaySegment ws : mv.getNearestWaySegments(p, mv.isSelectablePredicate)) {
[10308]1201 Way w = ws.way;
[5370]1202
[10179]1203 wnp.a = w.getNode(ws.lowerIndex);
1204 wnp.b = w.getNode(ws.lowerIndex + 1);
[10827]1205 MapViewPoint p1 = mv.getState().getPointFor(wnp.a);
1206 MapViewPoint p2 = mv.getState().getPointFor(wnp.b);
[5370]1207 if (WireframeMapRenderer.isLargeSegment(p1, p2, virtualSpace)) {
[10827]1208 Point2D pc = new Point2D.Double((p1.getInViewX() + p2.getInViewX()) / 2, (p1.getInViewY() + p2.getInViewY()) / 2);
[5394]1209 if (p.distanceSq(pc) < virtualSnapDistSq2) {
[5370]1210 // Check that only segments on top of each other get added to the
1211 // virtual ways list. Otherwise ways that coincidentally have their
1212 // virtual node at the same spot will be joined which is likely unwanted
1213 Pair.sort(wnp);
1214 if (vnp == null) {
[7005]1215 vnp = new Pair<>(wnp.a, wnp.b);
[5370]1216 virtualNode = new Node(mv.getLatLon(pc.getX(), pc.getY()));
1217 }
1218 if (vnp.equals(wnp)) {
[5435]1219 // if mutiple line segments have the same points,
1220 // add all segments to be splitted to virtualWays list
1221 // if some lines are selected, only their segments will go to virtualWays
[5370]1222 (w.isSelected() ? selVirtualWays : virtualWays).add(ws);
1223 }
1224 }
1225 }
1226 }
1227
1228 if (!selVirtualWays.isEmpty()) {
1229 virtualWays = selVirtualWays;
1230 }
1231 }
1232
1233 return !virtualWays.isEmpty();
1234 }
1235
[5435]1236 private void createMiddleNodeFromVirtual(EastNorth currentEN) {
[12726]1237 DataSet ds = getLayerManager().getEditDataSet();
[7005]1238 Collection<Command> virtualCmds = new LinkedList<>();
[12726]1239 virtualCmds.add(new AddCommand(ds, virtualNode));
[5370]1240 for (WaySegment virtualWay : virtualWays) {
1241 Way w = virtualWay.way;
1242 Way wnew = new Way(w);
1243 wnew.addNode(virtualWay.lowerIndex + 1, virtualNode);
[12726]1244 virtualCmds.add(new ChangeCommand(ds, w, wnew));
[5370]1245 }
[12759]1246 virtualCmds.add(new MoveCommand(ds, virtualNode, startEN, currentEN));
[5370]1247 String text = trn("Add and move a virtual new node to way",
1248 "Add and move a virtual new node to {0} ways", virtualWays.size(),
1249 virtualWays.size());
[12641]1250 MainApplication.undoRedo.add(new SequenceCommand(text, virtualCmds));
[12726]1251 ds.setSelected(Collections.singleton((OsmPrimitive) virtualNode));
[5370]1252 clear();
1253 }
1254
1255 private void clear() {
1256 virtualWays.clear();
1257 virtualNode = null;
1258 }
1259
1260 private boolean hasVirtualNode() {
1261 return virtualNode != null;
1262 }
1263
[5435]1264 private boolean hasVirtualWaysToBeConstructed() {
[5370]1265 return !virtualWays.isEmpty();
1266 }
1267 }
[6992]1268
1269 /**
[9231]1270 * Returns {@code o} as collection of {@code o}'s type.
[9246]1271 * @param <T> object type
[9231]1272 * @param o any object
1273 * @return {@code o} as collection of {@code o}'s type.
[6992]1274 */
1275 protected static <T> Collection<T> asColl(T o) {
[11553]1276 return o == null ? Collections.emptySet() : Collections.singleton(o);
[6992]1277 }
[358]1278}
Note: See TracBrowser for help on using the repository browser.