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

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

checkstyle: enable relevant whitespace checks and fix them

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