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

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

fix #8116 - Update status line message when mouse button is released in select mode

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