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

Last change on this file was 19556, checked in by GerdP, 3 days ago

fix #24687: JOSM doesn't warn about many moved nodes when rotating or scaling several objects

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