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

Last change on this file since 8061 was 8061, checked in by bastiK, 9 years ago

see #11096 - strip .png

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