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

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

fix various Sonar issues:

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