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

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

convention - An open curly brace should be located at the end of a line

  • Property svn:eol-style set to native
File size: 48.7 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 Set<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 && (e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) == 0) {
512 // button is pressed in rotate mode
513 return;
514 }
515
516 if (mode == Mode.MOVE) {
517 // If ctrl is pressed we are in merge mode. Look for a nearby node,
518 // highlight it and adjust the cursor accordingly.
519 final boolean canMerge = ctrl && !getCurrentDataSet().getSelectedNodes().isEmpty();
520 final OsmPrimitive p = canMerge ? findNodeToMergeTo(e.getPoint()) : null;
521 boolean needsRepaint = removeHighlighting();
522 if(p != null) {
523 p.setHighlighted(true);
524 oldHighlights.add(p);
525 needsRepaint = true;
526 }
527 mv.setNewCursor(getCursor(asColl(p)), this);
528 // also update the stored mouse event, so we can display the correct cursor
529 // when dragging a node onto another one and then press CTRL to merge
530 oldEvent = e;
531 if(needsRepaint) {
532 mv.repaint();
533 }
534 }
535
536 if (startingDraggingPos == null) {
537 startingDraggingPos = new Point(e.getX(), e.getY());
538 }
539
540 if( lastMousePos == null ) {
541 lastMousePos = e.getPoint();
542 return;
543 }
544
545 if (!initialMoveThresholdExceeded) {
546 int dp = (int) lastMousePos.distance(e.getX(), e.getY());
547 if (dp < initialMoveThreshold)
548 return; // ignore small drags
549 initialMoveThresholdExceeded = true; //no more ingnoring uintil nex mouse press
550 }
551 if (e.getPoint().equals(lastMousePos))
552 return;
553
554 EastNorth currentEN = mv.getEastNorth(e.getX(), e.getY());
555
556 if (virtualManager.hasVirtualWaysToBeConstructed()) {
557 virtualManager.createMiddleNodeFromVirtual(currentEN);
558 } else {
559 if (!updateCommandWhileDragging(currentEN)) return;
560 }
561
562 mv.repaint();
563 if (mode != Mode.SCALE) {
564 lastMousePos = e.getPoint();
565 }
566
567 didMouseDrag = true;
568 }
569
570 @Override
571 public void mouseExited(MouseEvent e) {
572 if(removeHighlighting()) {
573 mv.repaint();
574 }
575 }
576
577 @Override
578 public void mouseReleased(MouseEvent e) {
579 if (!mv.isActiveLayerVisible())
580 return;
581
582 startingDraggingPos = null;
583 mouseReleaseTime = System.currentTimeMillis();
584
585 if (mode == Mode.SELECT) {
586 selectionManager.unregister(mv);
587
588 // Select Draw Tool if no selection has been made
589 if (getCurrentDataSet().getSelected().isEmpty() && !cancelDrawMode) {
590 Main.map.selectDrawTool(true);
591 updateStatusLine();
592 return;
593 }
594 }
595
596 if (mode == Mode.MOVE && e.getButton() == MouseEvent.BUTTON1) {
597 if (!didMouseDrag) {
598 // only built in move mode
599 virtualManager.clear();
600 // do nothing if the click was to short too be recognized as a drag,
601 // but the release position is farther than 10px away from the press position
602 if (lastMousePos == null || lastMousePos.distanceSq(e.getPoint()) < 100) {
603 updateKeyModifiers(e);
604 selectPrims(cycleManager.cyclePrims(), true, false);
605
606 // If the user double-clicked a node, change to draw mode
607 Collection<OsmPrimitive> c = getCurrentDataSet().getSelected();
608 if (e.getClickCount() >= 2 && c.size() == 1 && c.iterator().next() instanceof Node) {
609 // We need to do it like this as otherwise drawAction will see a double
610 // click and switch back to SelectMode
611 Main.worker.execute(new Runnable() {
612 @Override
613 public void run() {
614 Main.map.selectDrawTool(true);
615 }
616 });
617 return;
618 }
619 }
620 } else {
621 confirmOrUndoMovement(e);
622 }
623 }
624
625 mode = null;
626
627 // simply remove any highlights if the middle click popup is active because
628 // the highlights don't depend on the cursor position there. If something was
629 // selected beforehand this would put us into move mode as well, which breaks
630 // the cycling through primitives on top of each other (see #6739).
631 if(e.getButton() == MouseEvent.BUTTON2) {
632 removeHighlighting();
633 } else {
634 giveUserFeedback(e);
635 }
636 updateStatusLine();
637 }
638
639 @Override
640 public void selectionEnded(Rectangle r, MouseEvent e) {
641 updateKeyModifiers(e);
642 selectPrims(selectionManager.getSelectedObjects(alt), true, true);
643 }
644
645 @Override
646 public void doKeyPressed(KeyEvent e) {
647 if (!Main.isDisplayingMapView() ||
648 !repeatedKeySwitchLassoOption || !getShortcut().isEvent(e)) return;
649 e.consume();
650 if (!lassoMode) {
651 Main.map.selectMapMode(Main.map.mapModeSelectLasso);
652 } else {
653 Main.map.selectMapMode(Main.map.mapModeSelect);
654 }
655 }
656
657 @Override
658 public void doKeyReleased(KeyEvent e) {
659 }
660
661 /**
662 * sets the mapmode according to key modifiers and if there are any
663 * selectables nearby. Everything has to be pre-determined for this
664 * function; its main purpose is to centralize what the modifiers do.
665 * @param hasSelectionNearby
666 */
667 private void determineMapMode(boolean hasSelectionNearby) {
668 if (shift && ctrl) {
669 mode = Mode.ROTATE;
670 } else if (alt && ctrl) {
671 mode = Mode.SCALE;
672 } else if (hasSelectionNearby || dragInProgress()) {
673 mode = Mode.MOVE;
674 } else {
675 mode = Mode.SELECT;
676 }
677 }
678
679 /** returns true whenever elements have been grabbed and moved (i.e. the initial
680 * thresholds have been exceeded) and is still in progress (i.e. mouse button
681 * still pressed)
682 */
683 private final boolean dragInProgress() {
684 return didMouseDrag && startingDraggingPos != null;
685 }
686
687 /**
688 * Create or update data modification command while dragging mouse - implementation of
689 * continuous moving, scaling and rotation
690 * @param currentEN - mouse position
691 * @return status of action (<code>true</code> when action was performed)
692 */
693 private boolean updateCommandWhileDragging(EastNorth currentEN) {
694 // Currently we support only transformations which do not affect relations.
695 // So don't add them in the first place to make handling easier
696 Collection<OsmPrimitive> selection = getCurrentDataSet().getSelectedNodesAndWays();
697 if (selection.isEmpty()) { // if nothing was selected to drag, just select nearest node/way to the cursor
698 OsmPrimitive nearestPrimitive = mv.getNearestNodeOrWay(mv.getPoint(startEN), mv.isSelectablePredicate, true);
699 getCurrentDataSet().setSelected(nearestPrimitive);
700 }
701
702 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
703 // for these transformations, having only one node makes no sense - quit silently
704 if (affectedNodes.size() < 2 && (mode == Mode.ROTATE || mode == Mode.SCALE)) {
705 return false;
706 }
707 Command c = getLastCommand();
708 if (mode == Mode.MOVE) {
709 if (startEN == null) return false; // fix #8128
710 getCurrentDataSet().beginUpdate();
711 if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
712 ((MoveCommand) c).saveCheckpoint();
713 ((MoveCommand) c).applyVectorTo(currentEN);
714 } else {
715 Main.main.undoRedo.add(
716 c = new MoveCommand(selection, startEN, currentEN));
717 }
718 for (Node n : affectedNodes) {
719 LatLon ll = n.getCoor();
720 if (ll != null && ll.isOutSideWorld()) {
721 // Revert move
722 ((MoveCommand) c).resetToCheckpoint();
723 getCurrentDataSet().endUpdate();
724 JOptionPane.showMessageDialog(
725 Main.parent,
726 tr("Cannot move objects outside of the world."),
727 tr("Warning"),
728 JOptionPane.WARNING_MESSAGE);
729 mv.setNewCursor(cursor, this);
730 return false;
731 }
732 }
733 } else {
734 startEN = currentEN; // drag can continue after scaling/rotation
735
736 if (mode != Mode.ROTATE && mode != Mode.SCALE) {
737 return false;
738 }
739
740 getCurrentDataSet().beginUpdate();
741
742 if (mode == Mode.ROTATE) {
743 if (c instanceof RotateCommand && affectedNodes.equals(((RotateCommand) c).getTransformedNodes())) {
744 ((RotateCommand) c).handleEvent(currentEN);
745 } else {
746 Main.main.undoRedo.add(new RotateCommand(selection, currentEN));
747 }
748 } else if (mode == Mode.SCALE) {
749 if (c instanceof ScaleCommand && affectedNodes.equals(((ScaleCommand) c).getTransformedNodes())) {
750 ((ScaleCommand) c).handleEvent(currentEN);
751 } else {
752 Main.main.undoRedo.add(new ScaleCommand(selection, currentEN));
753 }
754 }
755
756 Collection<Way> ways = getCurrentDataSet().getSelectedWays();
757 if (doesImpactStatusLine(affectedNodes, ways)) {
758 Main.map.statusLine.setDist(ways);
759 }
760 }
761 getCurrentDataSet().endUpdate();
762 return true;
763 }
764
765 private boolean doesImpactStatusLine(Collection<Node> affectedNodes, Collection<Way> selectedWays) {
766 for (Way w : selectedWays) {
767 for (Node n : w.getNodes()) {
768 if (affectedNodes.contains(n)) {
769 return true;
770 }
771 }
772 }
773 return false;
774 }
775
776 /**
777 * Adapt last move command (if it is suitable) to work with next drag, started at point startEN
778 */
779 private void useLastMoveCommandIfPossible() {
780 Command c = getLastCommand();
781 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(getCurrentDataSet().getSelected());
782 if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
783 // old command was created with different base point of movement, we need to recalculate it
784 ((MoveCommand) c).changeStartPoint(startEN);
785 }
786 }
787
788 /**
789 * Obtain command in undoRedo stack to "continue" when dragging
790 */
791 private Command getLastCommand() {
792 Command c = !Main.main.undoRedo.commands.isEmpty()
793 ? Main.main.undoRedo.commands.getLast() : null;
794 if (c instanceof SequenceCommand) {
795 c = ((SequenceCommand) c).getLastCommand();
796 }
797 return c;
798 }
799
800 /**
801 * Present warning in case of large and possibly unwanted movements and undo
802 * unwanted movements.
803 *
804 * @param e the mouse event causing the action (mouse released)
805 */
806 private void confirmOrUndoMovement(MouseEvent e) {
807 int max = Main.pref.getInteger("warn.move.maxelements", 20), limit = max;
808 for (OsmPrimitive osm : getCurrentDataSet().getSelected()) {
809 if (osm instanceof Way) {
810 limit -= ((Way) osm).getNodes().size();
811 }
812 if ((limit -= 1) < 0) {
813 break;
814 }
815 }
816 if (limit < 0) {
817 ExtendedDialog ed = new ExtendedDialog(
818 Main.parent,
819 tr("Move elements"),
820 new String[]{tr("Move them"), tr("Undo move")});
821 ed.setButtonIcons(new String[]{"reorder", "cancel"});
822 ed.setContent(
823 /* for correct i18n of plural forms - see #9110 */
824 trn(
825 "You moved more than {0} element. " + "Moving a large number of elements is often an error.\n" + "Really move them?",
826 "You moved more than {0} elements. " + "Moving a large number of elements is often an error.\n" + "Really move them?",
827 max, max));
828 ed.setCancelButton(2);
829 ed.toggleEnable("movedManyElements");
830 ed.showDialog();
831
832 if (ed.getValue() != 1) {
833 Main.main.undoRedo.undo();
834 }
835 } else {
836 // if small number of elements were moved,
837 updateKeyModifiers(e);
838 if (ctrl) mergePrims(e.getPoint());
839 }
840 getCurrentDataSet().fireSelectionChanged();
841 }
842
843 /**
844 * Merges the selected nodes to the one closest to the given mouse position if the control
845 * key is pressed. If there is no such node, no action will be done and no error will be
846 * reported. If there is, it will execute the merge and add it to the undo buffer.
847 */
848 private final void mergePrims(Point p) {
849 Collection<Node> selNodes = getCurrentDataSet().getSelectedNodes();
850 if (selNodes.isEmpty())
851 return;
852
853 Node target = findNodeToMergeTo(p);
854 if (target == null)
855 return;
856
857 if (selNodes.size() == 1) {
858 // Move all selected primitive to preserve shape #10748
859 Collection<OsmPrimitive> selection =
860 getCurrentDataSet().getSelectedNodesAndWays();
861 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
862 Command c = getLastCommand();
863 getCurrentDataSet().beginUpdate();
864 if (c instanceof MoveCommand
865 && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
866 Node selectedNode = selNodes.iterator().next();
867 EastNorth selectedEN = selectedNode.getEastNorth();
868 EastNorth targetEN = target.getEastNorth();
869 ((MoveCommand) c).moveAgain(targetEN.getX() - selectedEN.getX(),
870 targetEN.getY() - selectedEN.getY());
871 }
872 getCurrentDataSet().endUpdate();
873 }
874
875 Collection<Node> nodesToMerge = new LinkedList<>(selNodes);
876 nodesToMerge.add(target);
877 mergeNodes(Main.main.getEditLayer(), nodesToMerge, target);
878 }
879
880 /**
881 * Merge nodes using {@code MergeNodesAction}.
882 * Can be overridden for testing purpose.
883 * @param layer layer the reference data layer. Must not be null
884 * @param nodes the collection of nodes. Ignored if null
885 * @param targetLocationNode this node's location will be used for the target node
886 */
887 public void mergeNodes(OsmDataLayer layer, Collection<Node> nodes,
888 Node targetLocationNode) {
889 MergeNodesAction.doMergeNodes(layer, nodes, targetLocationNode);
890 }
891
892 /**
893 * Tries to find a node to merge to when in move-merge mode for the current mouse
894 * position. Either returns the node or null, if no suitable one is nearby.
895 */
896 private final Node findNodeToMergeTo(Point p) {
897 Collection<Node> target = mv.getNearestNodes(p,
898 getCurrentDataSet().getSelectedNodes(),
899 mv.isSelectablePredicate);
900 return target.isEmpty() ? null : target.iterator().next();
901 }
902
903 private void selectPrims(Collection<OsmPrimitive> prims, boolean released, boolean area) {
904 DataSet ds = getCurrentDataSet();
905
906 // not allowed together: do not change dataset selection, return early
907 // Virtual Ways: if non-empty the cursor is above a virtual node. So don't highlight
908 // anything if about to drag the virtual node (i.e. !released) but continue if the
909 // cursor is only released above a virtual node by accident (i.e. released). See #7018
910 if (ds == null || (shift && ctrl) || (ctrl && !released) || (virtualManager.hasVirtualWaysToBeConstructed() && !released))
911 return;
912
913 if (!released) {
914 // Don't replace the selection if the user clicked on a
915 // selected object (it breaks moving of selected groups).
916 // Do it later, on mouse release.
917 shift |= ds.getSelected().containsAll(prims);
918 }
919
920 if (ctrl) {
921 // Ctrl on an item toggles its selection status,
922 // but Ctrl on an *area* just clears those items
923 // out of the selection.
924 if (area) {
925 ds.clearSelection(prims);
926 } else {
927 ds.toggleSelected(prims);
928 }
929 } else if (shift) {
930 // add prims to an existing selection
931 ds.addSelected(prims);
932 } else {
933 // clear selection, then select the prims clicked
934 ds.setSelected(prims);
935 }
936 }
937
938 /**
939 * Returns the current select mode.
940 * @return the select mode
941 * @since 7543
942 */
943 public final Mode getMode() {
944 return mode;
945 }
946
947 @Override
948 public String getModeHelpText() {
949 if (mouseDownButton == MouseEvent.BUTTON1 && mouseReleaseTime < mouseDownTime) {
950 if (mode == Mode.SELECT)
951 return tr("Release the mouse button to select the objects in the rectangle.");
952 else if (mode == Mode.MOVE && (System.currentTimeMillis() - mouseDownTime >= initialMoveDelay)) {
953 final boolean canMerge = getCurrentDataSet()!=null && !getCurrentDataSet().getSelectedNodes().isEmpty();
954 final String mergeHelp = canMerge ? " " + tr("Ctrl to merge with nearest node.") : "";
955 return tr("Release the mouse button to stop moving.") + mergeHelp;
956 } else if (mode == Mode.ROTATE)
957 return tr("Release the mouse button to stop rotating.");
958 else if (mode == Mode.SCALE)
959 return tr("Release the mouse button to stop scaling.");
960 }
961 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");
962 }
963
964 @Override
965 public boolean layerIsSupported(Layer l) {
966 return l instanceof OsmDataLayer;
967 }
968
969 /**
970 * Enable or diable the lasso mode
971 * @param lassoMode true to enable the lasso mode, false otherwise
972 */
973 public void setLassoMode(boolean lassoMode) {
974 this.selectionManager.setLassoMode(lassoMode);
975 this.lassoMode = lassoMode;
976 }
977
978 private transient CycleManager cycleManager = new CycleManager();
979 private transient VirtualManager virtualManager = new VirtualManager();
980
981 private class CycleManager {
982
983 private Collection<OsmPrimitive> cycleList = Collections.emptyList();
984 private boolean cyclePrims = false;
985 private OsmPrimitive cycleStart = null;
986 private boolean waitForMouseUpParameter;
987 private boolean multipleMatchesParameter;
988 /**
989 * read preferences
990 */
991 private void init() {
992 waitForMouseUpParameter = Main.pref.getBoolean("mappaint.select.waits-for-mouse-up", false);
993 multipleMatchesParameter = Main.pref.getBoolean("selectaction.cycles.multiple.matches", false);
994 }
995
996 /**
997 * Determine primitive to be selected and build cycleList
998 * @param nearest primitive found by simple method
999 * @param p point where user clicked
1000 * @return OsmPrimitive to be selected
1001 */
1002 private OsmPrimitive cycleSetup(OsmPrimitive nearest, Point p) {
1003 OsmPrimitive osm = null;
1004
1005 if (nearest != null) {
1006 osm = nearest;
1007
1008 if (!(alt || multipleMatchesParameter)) {
1009 // no real cycling, just one element in cycle list
1010 cycleList = asColl(osm);
1011
1012 if (waitForMouseUpParameter) {
1013 // prefer a selected nearest node or way, if possible
1014 osm = mv.getNearestNodeOrWay(p, mv.isSelectablePredicate, true);
1015 }
1016 } else {
1017 // Alt + left mouse button pressed: we need to build cycle list
1018 cycleList = mv.getAllNearest(p, mv.isSelectablePredicate);
1019
1020 if (cycleList.size() > 1) {
1021 cyclePrims = false;
1022
1023 // find first already selected element in cycle list
1024 OsmPrimitive old = osm;
1025 for (OsmPrimitive o : cycleList) {
1026 if (o.isSelected()) {
1027 cyclePrims = true;
1028 osm = o;
1029 break;
1030 }
1031 }
1032
1033 // special case: for cycle groups of 2, we can toggle to the
1034 // true nearest primitive on mousePressed right away
1035 if (cycleList.size() == 2 && !waitForMouseUpParameter) {
1036 if (!(osm.equals(old) || osm.isNew() || ctrl)) {
1037 cyclePrims = false;
1038 osm = old;
1039 } // else defer toggling to mouseRelease time in those cases:
1040 /*
1041 * osm == old -- the true nearest node is the
1042 * selected one osm is a new node -- do not break
1043 * unglue ways in ALT mode ctrl is pressed -- ctrl
1044 * generally works on mouseReleased
1045 */
1046 }
1047 }
1048 }
1049 }
1050 return osm;
1051 }
1052
1053 /**
1054 * Modifies current selection state and returns the next element in a
1055 * selection cycle given by
1056 * <code>cycleList</code> field
1057 * @return the next element of cycle list
1058 */
1059 private Collection<OsmPrimitive> cyclePrims() {
1060 OsmPrimitive nxt = null;
1061
1062 if (cycleList.size() <= 1) {
1063 // no real cycling, just return one-element collection with nearest primitive in it
1064 return cycleList;
1065 }
1066// updateKeyModifiers(e); // already called before !
1067
1068 DataSet ds = getCurrentDataSet();
1069 OsmPrimitive first = cycleList.iterator().next(), foundInDS = null;
1070 nxt = first;
1071
1072 if (cyclePrims && shift) {
1073 for (Iterator<OsmPrimitive> i = cycleList.iterator(); i.hasNext();) {
1074 nxt = i.next();
1075 if (!nxt.isSelected()) {
1076 break; // take first primitive in cycleList not in sel
1077 }
1078 }
1079 // if primitives 1,2,3 are under cursor, [Alt-press] [Shift-release] gives 1 -> 12 -> 123
1080 } else {
1081 for (Iterator<OsmPrimitive> i = cycleList.iterator(); i.hasNext();) {
1082 nxt = i.next();
1083 if (nxt.isSelected()) {
1084 foundInDS = nxt;
1085 // first selected primitive in cycleList is found
1086 if (cyclePrims || ctrl) {
1087 ds.clearSelection(foundInDS); // deselect it
1088 nxt = i.hasNext() ? i.next() : first;
1089 // return next one in cycle list (last->first)
1090 }
1091 break; // take next primitive in cycleList
1092 }
1093 }
1094 }
1095
1096 // if "no-alt-cycling" is enabled, Ctrl-Click arrives here.
1097 if (ctrl) {
1098 // a member of cycleList was found in the current dataset selection
1099 if (foundInDS != null) {
1100 // mouse was moved to a different selection group w/ a previous sel
1101 if (!cycleList.contains(cycleStart)) {
1102 ds.clearSelection(cycleList);
1103 cycleStart = foundInDS;
1104 } else if (cycleStart.equals(nxt)) {
1105 // loop detected, insert deselect step
1106 ds.addSelected(nxt);
1107 }
1108 } else {
1109 // setup for iterating a sel group again or a new, different one..
1110 nxt = (cycleList.contains(cycleStart)) ? cycleStart : first;
1111 cycleStart = nxt;
1112 }
1113 } else {
1114 cycleStart = null;
1115 }
1116 // return one-element collection with one element to be selected (or added to selection)
1117 return asColl(nxt);
1118 }
1119 }
1120
1121 private class VirtualManager {
1122
1123 private Node virtualNode = null;
1124 private Collection<WaySegment> virtualWays = new LinkedList<>();
1125 private int nodeVirtualSize;
1126 private int virtualSnapDistSq2;
1127 private int virtualSpace;
1128
1129 private void init() {
1130 nodeVirtualSize = Main.pref.getInteger("mappaint.node.virtual-size", 8);
1131 int virtualSnapDistSq = Main.pref.getInteger("mappaint.node.virtual-snap-distance", 8);
1132 virtualSnapDistSq2 = virtualSnapDistSq*virtualSnapDistSq;
1133 virtualSpace = Main.pref.getInteger("mappaint.node.virtual-space", 70);
1134 }
1135
1136 /**
1137 * Calculate a virtual node if there is enough visual space to draw a
1138 * crosshair node and the middle of a way segment is clicked. If the
1139 * user drags the crosshair node, it will be added to all ways in
1140 * <code>virtualWays</code>.
1141 *
1142 * @param p the point clicked
1143 * @return whether
1144 * <code>virtualNode</code> and
1145 * <code>virtualWays</code> were setup.
1146 */
1147 private boolean activateVirtualNodeNearPoint(Point p) {
1148 if (nodeVirtualSize > 0) {
1149
1150 Collection<WaySegment> selVirtualWays = new LinkedList<>();
1151 Pair<Node, Node> vnp = null, wnp = new Pair<>(null, null);
1152
1153 Way w = null;
1154 for (WaySegment ws : mv.getNearestWaySegments(p, mv.isSelectablePredicate)) {
1155 w = ws.way;
1156
1157 Point2D p1 = mv.getPoint2D(wnp.a = w.getNode(ws.lowerIndex));
1158 Point2D p2 = mv.getPoint2D(wnp.b = w.getNode(ws.lowerIndex + 1));
1159 if (WireframeMapRenderer.isLargeSegment(p1, p2, virtualSpace)) {
1160 Point2D pc = new Point2D.Double((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2);
1161 if (p.distanceSq(pc) < virtualSnapDistSq2) {
1162 // Check that only segments on top of each other get added to the
1163 // virtual ways list. Otherwise ways that coincidentally have their
1164 // virtual node at the same spot will be joined which is likely unwanted
1165 Pair.sort(wnp);
1166 if (vnp == null) {
1167 vnp = new Pair<>(wnp.a, wnp.b);
1168 virtualNode = new Node(mv.getLatLon(pc.getX(), pc.getY()));
1169 }
1170 if (vnp.equals(wnp)) {
1171 // if mutiple line segments have the same points,
1172 // add all segments to be splitted to virtualWays list
1173 // if some lines are selected, only their segments will go to virtualWays
1174 (w.isSelected() ? selVirtualWays : virtualWays).add(ws);
1175 }
1176 }
1177 }
1178 }
1179
1180 if (!selVirtualWays.isEmpty()) {
1181 virtualWays = selVirtualWays;
1182 }
1183 }
1184
1185 return !virtualWays.isEmpty();
1186 }
1187
1188 private void createMiddleNodeFromVirtual(EastNorth currentEN) {
1189 Collection<Command> virtualCmds = new LinkedList<>();
1190 virtualCmds.add(new AddCommand(virtualNode));
1191 for (WaySegment virtualWay : virtualWays) {
1192 Way w = virtualWay.way;
1193 Way wnew = new Way(w);
1194 wnew.addNode(virtualWay.lowerIndex + 1, virtualNode);
1195 virtualCmds.add(new ChangeCommand(w, wnew));
1196 }
1197 virtualCmds.add(new MoveCommand(virtualNode, startEN, currentEN));
1198 String text = trn("Add and move a virtual new node to way",
1199 "Add and move a virtual new node to {0} ways", virtualWays.size(),
1200 virtualWays.size());
1201 Main.main.undoRedo.add(new SequenceCommand(text, virtualCmds));
1202 getCurrentDataSet().setSelected(Collections.singleton((OsmPrimitive) virtualNode));
1203 clear();
1204 }
1205
1206 private void clear() {
1207 virtualWays.clear();
1208 virtualNode = null;
1209 }
1210
1211 private boolean hasVirtualNode() {
1212 return virtualNode != null;
1213 }
1214
1215 private boolean hasVirtualWaysToBeConstructed() {
1216 return !virtualWays.isEmpty();
1217 }
1218 }
1219
1220 /**
1221 * @return o as collection of o's type.
1222 */
1223 protected static <T> Collection<T> asColl(T o) {
1224 if (o == null)
1225 return Collections.emptySet();
1226 return Collections.singleton(o);
1227 }
1228}
Note: See TracBrowser for help on using the repository browser.