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

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

fix #2447 - Unnessary changes of a target node by dragging another node onto it

  • Property svn:eol-style set to native
File size: 45.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.ActionEvent;
15import java.awt.event.ActionListener;
16import java.awt.event.InputEvent;
17import java.awt.event.KeyEvent;
18import java.awt.event.MouseEvent;
19import java.awt.geom.Point2D;
20import java.util.Collection;
21import java.util.Collections;
22import java.util.HashSet;
23import java.util.Iterator;
24import java.util.LinkedList;
25import java.util.Set;
26
27import javax.swing.JOptionPane;
28
29import org.openstreetmap.josm.Main;
30import org.openstreetmap.josm.actions.MergeNodesAction;
31import org.openstreetmap.josm.command.AddCommand;
32import org.openstreetmap.josm.command.ChangeCommand;
33import org.openstreetmap.josm.command.Command;
34import org.openstreetmap.josm.command.MoveCommand;
35import org.openstreetmap.josm.command.RotateCommand;
36import org.openstreetmap.josm.command.ScaleCommand;
37import org.openstreetmap.josm.command.SequenceCommand;
38import org.openstreetmap.josm.data.coor.EastNorth;
39import org.openstreetmap.josm.data.osm.DataSet;
40import org.openstreetmap.josm.data.osm.Node;
41import org.openstreetmap.josm.data.osm.OsmPrimitive;
42import org.openstreetmap.josm.data.osm.Way;
43import org.openstreetmap.josm.data.osm.WaySegment;
44import org.openstreetmap.josm.data.osm.visitor.AllNodesVisitor;
45import org.openstreetmap.josm.data.osm.visitor.paint.WireframeMapRenderer;
46import org.openstreetmap.josm.gui.ExtendedDialog;
47import org.openstreetmap.josm.gui.MapFrame;
48import org.openstreetmap.josm.gui.MapView;
49import org.openstreetmap.josm.gui.NavigatableComponent;
50import org.openstreetmap.josm.gui.SelectionManager;
51import org.openstreetmap.josm.gui.SelectionManager.SelectionEnded;
52import org.openstreetmap.josm.gui.layer.Layer;
53import org.openstreetmap.josm.gui.layer.OsmDataLayer;
54import org.openstreetmap.josm.gui.util.GuiHelper;
55import org.openstreetmap.josm.tools.ImageProvider;
56import org.openstreetmap.josm.tools.Pair;
57import org.openstreetmap.josm.tools.PlatformHookOsx;
58import org.openstreetmap.josm.tools.Shortcut;
59
60/**
61 * Move is an action that can move all kind of OsmPrimitives (except keys for now).
62 *
63 * If an selected object is under the mouse when dragging, move all selected objects.
64 * If an unselected object is under the mouse when dragging, it becomes selected
65 * and will be moved.
66 * If no object is under the mouse, move all selected objects (if any)
67 *
68 * @author imi
69 */
70public class SelectAction extends MapMode implements AWTEventListener, SelectionEnded {
71 // "select" means the selection rectangle and "move" means either dragging
72 // or select if no mouse movement occurs (i.e. just clicking)
73 enum Mode { move, rotate, scale, select }
74
75 // contains all possible cases the cursor can be in the SelectAction
76 static private enum SelectActionCursor {
77 rect("normal", "selection"),
78 rect_add("normal", "select_add"),
79 rect_rm("normal", "select_remove"),
80 way("normal", "select_way"),
81 way_add("normal", "select_way_add"),
82 way_rm("normal", "select_way_remove"),
83 node("normal", "select_node"),
84 node_add("normal", "select_node_add"),
85 node_rm("normal", "select_node_remove"),
86 virtual_node("normal", "addnode"),
87 scale("scale", null),
88 rotate("rotate", null),
89 merge("crosshair", null),
90 lasso("normal", "rope"),
91 merge_to_node("crosshair", "joinnode"),
92 move(Cursor.MOVE_CURSOR);
93
94 private final Cursor c;
95 private SelectActionCursor(String main, String sub) {
96 c = ImageProvider.getCursor(main, sub);
97 }
98 private SelectActionCursor(int systemCursor) {
99 c = Cursor.getPredefinedCursor(systemCursor);
100 }
101 public Cursor cursor() {
102 return c;
103 }
104 }
105
106 private boolean lassoMode = false;
107
108 // Cache previous mouse event (needed when only the modifier keys are
109 // pressed but the mouse isn't moved)
110 private MouseEvent oldEvent = null;
111
112 private Mode mode = null;
113 private SelectionManager selectionManager;
114 private boolean cancelDrawMode = false;
115 private boolean drawTargetHighlight;
116 private boolean didMouseDrag = false;
117 /**
118 * The component this SelectAction is associated with.
119 */
120 private final MapView mv;
121 /**
122 * The old cursor before the user pressed the mouse button.
123 */
124 private Point startingDraggingPos;
125 /**
126 * point where user pressed the mouse to start movement
127 */
128 EastNorth startEN;
129 /**
130 * The last known position of the mouse.
131 */
132 private Point lastMousePos;
133 /**
134 * The time of the user mouse down event.
135 */
136 private long mouseDownTime = 0;
137 /**
138 * The pressed button of the user mouse down event.
139 */
140 private int mouseDownButton = 0;
141 /**
142 * The time of the user mouse down event.
143 */
144 private long mouseReleaseTime = 0;
145 /**
146 * The time which needs to pass between click and release before something
147 * counts as a move, in milliseconds
148 */
149 private int initialMoveDelay;
150 /**
151 * The screen distance which needs to be travelled before something
152 * counts as a move, in pixels
153 */
154 private int initialMoveThreshold;
155 private boolean initialMoveThresholdExceeded = false;
156
157 /**
158 * elements that have been highlighted in the previous iteration. Used
159 * to remove the highlight from them again as otherwise the whole data
160 * set would have to be checked.
161 */
162 private Set<OsmPrimitive> oldHighlights = new HashSet<OsmPrimitive>();
163
164 /**
165 * Create a new SelectAction
166 * @param mapFrame The MapFrame this action belongs to.
167 */
168 public SelectAction(MapFrame mapFrame) {
169 super(tr("Select"), "move/move", tr("Select, move, scale and rotate objects"),
170 Shortcut.registerShortcut("mapmode:select", tr("Mode: {0}", tr("Select")), KeyEvent.VK_S, Shortcut.DIRECT),
171 mapFrame,
172 ImageProvider.getCursor("normal", "selection"));
173 mv = mapFrame.mapView;
174 putValue("help", ht("/Action/Select"));
175 selectionManager = new SelectionManager(this, false, mv);
176 initialMoveDelay = Main.pref.getInteger("edit.initial-move-delay", 200);
177 initialMoveThreshold = Main.pref.getInteger("edit.initial-move-threshold", 5);
178 }
179
180 @Override
181 public void enterMode() {
182 super.enterMode();
183 mv.addMouseListener(this);
184 mv.addMouseMotionListener(this);
185 mv.setVirtualNodesEnabled(Main.pref.getInteger("mappaint.node.virtual-size", 8) != 0);
186 drawTargetHighlight = Main.pref.getBoolean("draw.target-highlight", true);
187 cycleManager.init();
188 virtualManager.init();
189 // This is required to update the cursors when ctrl/shift/alt is pressed
190 try {
191 Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
192 } catch (SecurityException ex) {}
193 }
194
195 @Override
196 public void exitMode() {
197 super.exitMode();
198 selectionManager.unregister(mv);
199 mv.removeMouseListener(this);
200 mv.removeMouseMotionListener(this);
201 mv.setVirtualNodesEnabled(false);
202 try {
203 Toolkit.getDefaultToolkit().removeAWTEventListener(this);
204 } catch (SecurityException ex) {}
205 removeHighlighting();
206 }
207
208 int previousModifiers;
209
210 /**
211 * This is called whenever the keyboard modifier status changes
212 */
213 @Override
214 public void eventDispatched(AWTEvent e) {
215 if(oldEvent == null)
216 return;
217 // We don't have a mouse event, so we pass the old mouse event but the
218 // new modifiers.
219 int modif = ((InputEvent) e).getModifiers();
220 if (previousModifiers == modif)
221 return;
222 previousModifiers = modif;
223 if(giveUserFeedback(oldEvent, ((InputEvent) e).getModifiers())) {
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 = MapView.asColl(
247 mv.getNearestNodeOrWay(e.getPoint(), OsmPrimitive.isSelectablePredicate, true));
248
249 updateKeyModifiers(modifiers);
250 determineMapMode(!c.isEmpty());
251
252 HashSet<OsmPrimitive> newHighlights = new HashSet<OsmPrimitive>();
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 != null && 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 ? "_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<OsmPrimitive>();
361 return true;
362 }
363
364 private boolean repaintIfRequired(HashSet<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(), OsmPrimitive.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(MapView.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(NavigatableComponent.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 // start working with rectangle or lasso
457 selectionManager.register(mv, lassoMode);
458 selectionManager.mousePressed(e);
459 break;
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.platform instanceof PlatformHookOsx) && (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 return;
498
499 // do not count anything as a move if it lasts less than 100 milliseconds.
500 if ((mode == Mode.move) && (System.currentTimeMillis() - mouseDownTime < initialMoveDelay))
501 return;
502
503 if (mode != Mode.rotate && mode != Mode.scale) // button is pressed in rotate mode
504 {
505 if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) == 0)
506 return;
507 }
508
509 if (mode == Mode.move) {
510 // If ctrl is pressed we are in merge mode. Look for a nearby node,
511 // highlight it and adjust the cursor accordingly.
512 final boolean canMerge = ctrl && !getCurrentDataSet().getSelectedNodes().isEmpty();
513 final OsmPrimitive p = canMerge ? (OsmPrimitive)findNodeToMergeTo(e.getPoint()) : null;
514 boolean needsRepaint = removeHighlighting();
515 if(p != null) {
516 p.setHighlighted(true);
517 oldHighlights.add(p);
518 needsRepaint = true;
519 }
520 mv.setNewCursor(getCursor(MapView.asColl(p)), this);
521 // also update the stored mouse event, so we can display the correct cursor
522 // when dragging a node onto another one and then press CTRL to merge
523 oldEvent = e;
524 if(needsRepaint) {
525 mv.repaint();
526 }
527 }
528
529 if (startingDraggingPos == null) {
530 startingDraggingPos = new Point(e.getX(), e.getY());
531 }
532
533 if( lastMousePos == null ) {
534 lastMousePos = e.getPoint();
535 return;
536 }
537
538 if (!initialMoveThresholdExceeded) {
539 int dp = (int) lastMousePos.distance(e.getX(), e.getY());
540 if (dp < initialMoveThreshold)
541 return; // ignore small drags
542 initialMoveThresholdExceeded = true; //no more ingnoring uintil nex mouse press
543 }
544 if (e.getPoint().equals(lastMousePos))
545 return;
546
547 EastNorth currentEN = mv.getEastNorth(e.getX(), e.getY());
548
549 if (virtualManager.hasVirtualWaysToBeConstructed()) {
550 virtualManager.createMiddleNodeFromVirtual(currentEN);
551 } else {
552 if (!updateCommandWhileDragging(currentEN)) return;
553 }
554
555 mv.repaint();
556 if (mode != Mode.scale) {
557 lastMousePos = e.getPoint();
558 }
559
560 didMouseDrag = true;
561 }
562
563
564
565 @Override
566 public void mouseExited(MouseEvent e) {
567 if(removeHighlighting()) {
568 mv.repaint();
569 }
570 }
571
572
573 @Override
574 public void mouseReleased(MouseEvent e) {
575 if (!mv.isActiveLayerVisible())
576 return;
577
578 startingDraggingPos = null;
579 mouseReleaseTime = System.currentTimeMillis();
580
581 if (mode == Mode.select) {
582 selectionManager.unregister(mv);
583
584 // Select Draw Tool if no selection has been made
585 if (getCurrentDataSet().getSelected().isEmpty() && !cancelDrawMode) {
586 Main.map.selectDrawTool(true);
587 updateStatusLine();
588 return;
589 }
590 }
591
592 if (mode == Mode.move && e.getButton() == MouseEvent.BUTTON1) {
593 if (!didMouseDrag) {
594 // only built in move mode
595 virtualManager.clear();
596 // do nothing if the click was to short too be recognized as a drag,
597 // but the release position is farther than 10px away from the press position
598 if (lastMousePos == null || lastMousePos.distanceSq(e.getPoint()) < 100) {
599 updateKeyModifiers(e);
600 selectPrims(cycleManager.cyclePrims(), true, false);
601
602 // If the user double-clicked a node, change to draw mode
603 Collection<OsmPrimitive> c = getCurrentDataSet().getSelected();
604 if (e.getClickCount() >= 2 && c.size() == 1 && c.iterator().next() instanceof Node) {
605 // We need to do it like this as otherwise drawAction will see a double
606 // click and switch back to SelectMode
607 Main.worker.execute(new Runnable() {
608 @Override
609 public void run() {
610 Main.map.selectDrawTool(true);
611 }
612 });
613 return;
614 }
615 }
616 } else {
617 confirmOrUndoMovement(e);
618 }
619 }
620
621 mode = null;
622
623 // simply remove any highlights if the middle click popup is active because
624 // the highlights don't depend on the cursor position there. If something was
625 // selected beforehand this would put us into move mode as well, which breaks
626 // the cycling through primitives on top of each other (see #6739).
627 if(e.getButton() == MouseEvent.BUTTON2) {
628 removeHighlighting();
629 } else {
630 giveUserFeedback(e);
631 }
632 updateStatusLine();
633 }
634
635 @Override
636 public void selectionEnded(Rectangle r, MouseEvent e) {
637 updateKeyModifiers(e);
638 selectPrims(selectionManager.getSelectedObjects(alt), true, true);
639 }
640
641 /**
642 * sets the mapmode according to key modifiers and if there are any
643 * selectables nearby. Everything has to be pre-determined for this
644 * function; its main purpose is to centralize what the modifiers do.
645 * @param hasSelectionNearby
646 */
647 private void determineMapMode(boolean hasSelectionNearby) {
648 if (shift && ctrl) {
649 mode = Mode.rotate;
650 } else if (alt && ctrl) {
651 mode = Mode.scale;
652 } else if (hasSelectionNearby || dragInProgress()) {
653 mode = Mode.move;
654 } else {
655 mode = Mode.select;
656 }
657 }
658
659 /** returns true whenever elements have been grabbed and moved (i.e. the initial
660 * thresholds have been exceeded) and is still in progress (i.e. mouse button
661 * still pressed)
662 */
663 final private boolean dragInProgress() {
664 return didMouseDrag && startingDraggingPos != null;
665 }
666
667
668 /**
669 * Create or update data modification command while dragging mouse - implementation of
670 * continuous moving, scaling and rotation
671 * @param currentEN - mouse position
672 * @return status of action (<code>true</code> when action was performed)
673 */
674 private boolean updateCommandWhileDragging(EastNorth currentEN) {
675 // Currently we support only transformations which do not affect relations.
676 // So don't add them in the first place to make handling easier
677 Collection<OsmPrimitive> selection = getCurrentDataSet().getSelectedNodesAndWays();
678 if (selection.isEmpty()) { // if nothing was selected to drag, just select nearest node/way to the cursor
679 OsmPrimitive nearestPrimitive = mv.getNearestNodeOrWay(mv.getPoint(startEN), OsmPrimitive.isSelectablePredicate, true);
680 getCurrentDataSet().setSelected(nearestPrimitive);
681 }
682
683 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
684 // for these transformations, having only one node makes no sense - quit silently
685 if (affectedNodes.size() < 2 && (mode == Mode.rotate || mode == Mode.scale)) {
686 return false;
687 }
688 Command c = getLastCommand();
689 if (mode == Mode.move) {
690 if (startEN == null) return false; // fix #8128
691 getCurrentDataSet().beginUpdate();
692 if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
693 ((MoveCommand) c).saveCheckpoint();
694 ((MoveCommand) c).applyVectorTo(currentEN);
695 } else {
696 Main.main.undoRedo.add(
697 c = new MoveCommand(selection, startEN, currentEN));
698 }
699 for (Node n : affectedNodes) {
700 if (n.getCoor().isOutSideWorld()) {
701 // Revert move
702 ((MoveCommand) c).resetToCheckpoint();
703 getCurrentDataSet().endUpdate();
704 JOptionPane.showMessageDialog(
705 Main.parent,
706 tr("Cannot move objects outside of the world."),
707 tr("Warning"),
708 JOptionPane.WARNING_MESSAGE);
709 mv.setNewCursor(cursor, this);
710 return false;
711 }
712 }
713 } else {
714 startEN = currentEN; // drag can continue after scaling/rotation
715
716 if (mode != Mode.rotate && mode != Mode.scale) {
717 return false;
718 }
719
720 getCurrentDataSet().beginUpdate();
721
722 if (mode == Mode.rotate) {
723 if (c instanceof RotateCommand && affectedNodes.equals(((RotateCommand) c).getTransformedNodes())) {
724 ((RotateCommand) c).handleEvent(currentEN);
725 } else {
726 Main.main.undoRedo.add(new RotateCommand(selection, currentEN));
727 }
728 } else if (mode == Mode.scale) {
729 if (c instanceof ScaleCommand && affectedNodes.equals(((ScaleCommand) c).getTransformedNodes())) {
730 ((ScaleCommand) c).handleEvent(currentEN);
731 } else {
732 Main.main.undoRedo.add(new ScaleCommand(selection, currentEN));
733 }
734 }
735
736 Collection<Way> ways = getCurrentDataSet().getSelectedWays();
737 if (doesImpactStatusLine(affectedNodes, ways)) {
738 Main.map.statusLine.setDist(ways);
739 }
740 }
741 getCurrentDataSet().endUpdate();
742 return true;
743 }
744
745 private boolean doesImpactStatusLine(Collection<Node> affectedNodes, Collection<Way> selectedWays) {
746 for (Way w : selectedWays) {
747 for (Node n : w.getNodes()) {
748 if (affectedNodes.contains(n)) {
749 return true;
750 }
751 }
752 }
753 return false;
754 }
755
756 /**
757 * Adapt last move command (if it is suitable) to work with next drag, started at point startEN
758 */
759 private void useLastMoveCommandIfPossible() {
760 Command c = getLastCommand();
761 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(getCurrentDataSet().getSelected());
762 if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
763 // old command was created with different base point of movement, we need to recalculate it
764 ((MoveCommand) c).changeStartPoint(startEN);
765 }
766 }
767
768 /**
769 * Obtain command in undoRedo stack to "continue" when dragging
770 */
771 private Command getLastCommand() {
772 Command c = !Main.main.undoRedo.commands.isEmpty()
773 ? Main.main.undoRedo.commands.getLast() : null;
774 if (c instanceof SequenceCommand) {
775 c = ((SequenceCommand) c).getLastCommand();
776 }
777 return c;
778 }
779
780 /**
781 * Present warning in case of large and possibly unwanted movements and undo
782 * unwanted movements.
783 *
784 * @param e the mouse event causing the action (mouse released)
785 */
786 private void confirmOrUndoMovement(MouseEvent e) {
787 int max = Main.pref.getInteger("warn.move.maxelements", 20), limit = max;
788 for (OsmPrimitive osm : getCurrentDataSet().getSelected()) {
789 if (osm instanceof Way) {
790 limit -= ((Way) osm).getNodes().size();
791 }
792 if ((limit -= 1) < 0) {
793 break;
794 }
795 }
796 if (limit < 0) {
797 ExtendedDialog ed = new ExtendedDialog(
798 Main.parent,
799 tr("Move elements"),
800 new String[]{tr("Move them"), tr("Undo move")});
801 ed.setButtonIcons(new String[]{"reorder.png", "cancel.png"});
802 ed.setContent(tr("You moved more than {0} elements. " + "Moving a large number of elements is often an error.\n" + "Really move them?", max));
803 ed.setCancelButton(2);
804 ed.toggleEnable("movedManyElements");
805 ed.showDialog();
806
807 if (ed.getValue() != 1) {
808 Main.main.undoRedo.undo();
809 }
810 } else {
811 // if small number of elements were moved,
812 updateKeyModifiers(e);
813 if (ctrl) mergePrims(e.getPoint());
814 }
815 getCurrentDataSet().fireSelectionChanged();
816 }
817
818 /**
819 * Merges the selected nodes to the one closest to the given mouse position if the control
820 * key is pressed. If there is no such node, no action will be done and no error will be
821 * reported. If there is, it will execute the merge and add it to the undo buffer.
822 */
823 final private void mergePrims(Point p) {
824 Collection<Node> selNodes = getCurrentDataSet().getSelectedNodes();
825 if (selNodes.isEmpty())
826 return;
827
828 Node target = findNodeToMergeTo(p);
829 if (target == null)
830 return;
831
832 Collection<Node> nodesToMerge = new LinkedList<Node>(selNodes);
833 nodesToMerge.add(target);
834 MergeNodesAction.doMergeNodes(Main.main.getEditLayer(), nodesToMerge, target);
835 }
836
837 /**
838 * Tries to find a node to merge to when in move-merge mode for the current mouse
839 * position. Either returns the node or null, if no suitable one is nearby.
840 */
841 final private Node findNodeToMergeTo(Point p) {
842 Collection<Node> target = mv.getNearestNodes(p,
843 getCurrentDataSet().getSelectedNodes(),
844 OsmPrimitive.isSelectablePredicate);
845 return target.isEmpty() ? null : target.iterator().next();
846 }
847
848 private void selectPrims(Collection<OsmPrimitive> prims, boolean released, boolean area) {
849 DataSet ds = getCurrentDataSet();
850
851 // not allowed together: do not change dataset selection, return early
852 // Virtual Ways: if non-empty the cursor is above a virtual node. So don't highlight
853 // anything if about to drag the virtual node (i.e. !released) but continue if the
854 // cursor is only released above a virtual node by accident (i.e. released). See #7018
855 if (ds == null || (shift && ctrl) || (ctrl && !released) || (virtualManager.hasVirtualWaysToBeConstructed() && !released))
856 return;
857
858 if (!released) {
859 // Don't replace the selection if the user clicked on a
860 // selected object (it breaks moving of selected groups).
861 // Do it later, on mouse release.
862 shift |= ds.getSelected().containsAll(prims);
863 }
864
865 if (ctrl) {
866 // Ctrl on an item toggles its selection status,
867 // but Ctrl on an *area* just clears those items
868 // out of the selection.
869 if (area) {
870 ds.clearSelection(prims);
871 } else {
872 ds.toggleSelected(prims);
873 }
874 } else if (shift) {
875 // add prims to an existing selection
876 ds.addSelected(prims);
877 } else {
878 // clear selection, then select the prims clicked
879 ds.setSelected(prims);
880 }
881 }
882
883 @Override
884 public String getModeHelpText() {
885 if (mouseDownButton == MouseEvent.BUTTON1 && mouseReleaseTime < mouseDownTime) {
886 if (mode == Mode.select)
887 return tr("Release the mouse button to select the objects in the rectangle.");
888 else if (mode == Mode.move && (System.currentTimeMillis() - mouseDownTime >= initialMoveDelay)) {
889 final boolean canMerge = getCurrentDataSet()!=null && !getCurrentDataSet().getSelectedNodes().isEmpty();
890 final String mergeHelp = canMerge ? (" " + tr("Ctrl to merge with nearest node.")) : "";
891 return tr("Release the mouse button to stop moving.") + mergeHelp;
892 } else if (mode == Mode.rotate)
893 return tr("Release the mouse button to stop rotating.");
894 else if (mode == Mode.scale)
895 return tr("Release the mouse button to stop scaling.");
896 }
897 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");
898 }
899
900 @Override
901 public boolean layerIsSupported(Layer l) {
902 return l instanceof OsmDataLayer;
903 }
904
905 /**
906 * Enable or diable the lasso mode
907 * @param lassoMode true to enable the lasso mode, false otherwise
908 */
909 public void setLassoMode(boolean lassoMode) {
910 this.selectionManager.setLassoMode(lassoMode);
911 this.lassoMode = lassoMode;
912 }
913
914 CycleManager cycleManager = new CycleManager();
915 VirtualManager virtualManager = new VirtualManager();
916
917 private class CycleManager {
918
919 private Collection<OsmPrimitive> cycleList = Collections.emptyList();
920 private boolean cyclePrims = false;
921 private OsmPrimitive cycleStart = null;
922 private boolean waitForMouseUpParameter;
923 private boolean multipleMatchesParameter;
924 /**
925 * read preferences
926 */
927 private void init() {
928 waitForMouseUpParameter = Main.pref.getBoolean("mappaint.select.waits-for-mouse-up", false);
929 multipleMatchesParameter = Main.pref.getBoolean("selectaction.cycles.multiple.matches", false);
930 }
931
932 /**
933 * Determine prmitive to be selected and build cycleList
934 * @param nearest primitive found by simple method
935 * @param p point where user clicked
936 * @return OsmPrimitive to be selected
937 */
938 private OsmPrimitive cycleSetup(OsmPrimitive nearest, Point p) {
939 OsmPrimitive osm = null;
940
941 if (nearest != null) {
942 osm = nearest;
943
944 // Point p = e.getPoint();
945// updateKeyModifiers(e); // cycleSetup called only after updateModifiers !
946
947 if (!(alt || multipleMatchesParameter)) {
948 // no real cycling, just one element in cycle list
949 cycleList = MapView.asColl(osm);
950
951 if (waitForMouseUpParameter) {
952 // prefer a selected nearest node or way, if possible
953 osm = mv.getNearestNodeOrWay(p, OsmPrimitive.isSelectablePredicate, true);
954 }
955 } else {
956 // Alt + left mouse button pressed: we need to build cycle list
957 cycleList = mv.getAllNearest(p, OsmPrimitive.isSelectablePredicate);
958
959 if (cycleList.size() > 1) {
960 cyclePrims = false;
961
962 // find first already selected element in cycle list
963 OsmPrimitive old = osm;
964 for (OsmPrimitive o : cycleList) {
965 if (o.isSelected()) {
966 cyclePrims = true;
967 osm = o;
968 break;
969 }
970 }
971
972 // special case: for cycle groups of 2, we can toggle to the
973 // true nearest primitive on mousePressed right away
974 if (cycleList.size() == 2 && !waitForMouseUpParameter) {
975 if (!(osm.equals(old) || osm.isNew() || ctrl)) {
976 cyclePrims = false;
977 osm = old;
978 } // else defer toggling to mouseRelease time in those cases:
979 /*
980 * osm == old -- the true nearest node is the
981 * selected one osm is a new node -- do not break
982 * unglue ways in ALT mode ctrl is pressed -- ctrl
983 * generally works on mouseReleased
984 */
985 }
986 }
987 }
988 }
989 return osm;
990 }
991
992 /**
993 * Modifies current selection state and returns the next element in a
994 * selection cycle given by
995 * <code>cycleList</code> field
996 * @return the next element of cycle list
997 */
998 private Collection<OsmPrimitive> cyclePrims() {
999 OsmPrimitive nxt = null;
1000
1001 if (cycleList.size() <= 1) {
1002 // no real cycling, just return one-element collection with nearest primitive in it
1003 return cycleList;
1004 }
1005// updateKeyModifiers(e); // already called before !
1006
1007 DataSet ds = getCurrentDataSet();
1008 OsmPrimitive first = cycleList.iterator().next(), foundInDS = null;
1009 nxt = first;
1010
1011 if (cyclePrims && shift) {
1012 for (Iterator<OsmPrimitive> i = cycleList.iterator(); i.hasNext();) {
1013 nxt = i.next();
1014 if (!nxt.isSelected()) {
1015 break; // take first primitive in cycleList not in sel
1016 }
1017 }
1018 // if primitives 1,2,3 are under cursor, [Alt-press] [Shift-release] gives 1 -> 12 -> 123
1019 } else {
1020 for (Iterator<OsmPrimitive> i = cycleList.iterator(); i.hasNext();) {
1021 nxt = i.next();
1022 if (nxt.isSelected()) {
1023 foundInDS = nxt;
1024 // first selected primitive in cycleList is found
1025 if (cyclePrims || ctrl) {
1026 ds.clearSelection(foundInDS); // deselect it
1027 nxt = i.hasNext() ? i.next() : first;
1028 // return next one in cycle list (last->first)
1029 }
1030 break; // take next primitive in cycleList
1031 }
1032 }
1033 }
1034
1035 // if "no-alt-cycling" is enabled, Ctrl-Click arrives here.
1036 if (ctrl) {
1037 // a member of cycleList was found in the current dataset selection
1038 if (foundInDS != null) {
1039 // mouse was moved to a different selection group w/ a previous sel
1040 if (!cycleList.contains(cycleStart)) {
1041 ds.clearSelection(cycleList);
1042 cycleStart = foundInDS;
1043 } else if (cycleStart.equals(nxt)) {
1044 // loop detected, insert deselect step
1045 ds.addSelected(nxt);
1046 }
1047 } else {
1048 // setup for iterating a sel group again or a new, different one..
1049 nxt = (cycleList.contains(cycleStart)) ? cycleStart : first;
1050 cycleStart = nxt;
1051 }
1052 } else {
1053 cycleStart = null;
1054 }
1055 // return one-element collection with one element to be selected (or added to selection)
1056 return MapView.asColl(nxt);
1057 }
1058 }
1059
1060 private class VirtualManager {
1061
1062 private Node virtualNode = null;
1063 private Collection<WaySegment> virtualWays = new LinkedList<WaySegment>();
1064 private int nodeVirtualSize;
1065 private int virtualSnapDistSq2;
1066 private int virtualSpace;
1067
1068 private void init() {
1069 nodeVirtualSize = Main.pref.getInteger("mappaint.node.virtual-size", 8);
1070 int virtualSnapDistSq = Main.pref.getInteger("mappaint.node.virtual-snap-distance", 8);
1071 virtualSnapDistSq2 = virtualSnapDistSq*virtualSnapDistSq;
1072 virtualSpace = Main.pref.getInteger("mappaint.node.virtual-space", 70);
1073 }
1074
1075 /**
1076 * Calculate a virtual node if there is enough visual space to draw a
1077 * crosshair node and the middle of a way segment is clicked. If the
1078 * user drags the crosshair node, it will be added to all ways in
1079 * <code>virtualWays</code>.
1080 *
1081 * @param p the point clicked
1082 * @return whether
1083 * <code>virtualNode</code> and
1084 * <code>virtualWays</code> were setup.
1085 */
1086 private boolean activateVirtualNodeNearPoint(Point p) {
1087 if (nodeVirtualSize > 0) {
1088
1089 Collection<WaySegment> selVirtualWays = new LinkedList<WaySegment>();
1090 Pair<Node, Node> vnp = null, wnp = new Pair<Node, Node>(null, null);
1091
1092 Way w = null;
1093 for (WaySegment ws : mv.getNearestWaySegments(p, OsmPrimitive.isSelectablePredicate)) {
1094 w = ws.way;
1095
1096 Point2D p1 = mv.getPoint2D(wnp.a = w.getNode(ws.lowerIndex));
1097 Point2D p2 = mv.getPoint2D(wnp.b = w.getNode(ws.lowerIndex + 1));
1098 if (WireframeMapRenderer.isLargeSegment(p1, p2, virtualSpace)) {
1099 Point2D pc = new Point2D.Double((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2);
1100 if (p.distanceSq(pc) < virtualSnapDistSq2) {
1101 // Check that only segments on top of each other get added to the
1102 // virtual ways list. Otherwise ways that coincidentally have their
1103 // virtual node at the same spot will be joined which is likely unwanted
1104 Pair.sort(wnp);
1105 if (vnp == null) {
1106 vnp = new Pair<Node, Node>(wnp.a, wnp.b);
1107 virtualNode = new Node(mv.getLatLon(pc.getX(), pc.getY()));
1108 }
1109 if (vnp.equals(wnp)) {
1110 // if mutiple line segments have the same points,
1111 // add all segments to be splitted to virtualWays list
1112 // if some lines are selected, only their segments will go to virtualWays
1113 (w.isSelected() ? selVirtualWays : virtualWays).add(ws);
1114 }
1115 }
1116 }
1117 }
1118
1119 if (!selVirtualWays.isEmpty()) {
1120 virtualWays = selVirtualWays;
1121 }
1122 }
1123
1124 return !virtualWays.isEmpty();
1125 }
1126
1127 private void createMiddleNodeFromVirtual(EastNorth currentEN) {
1128 Collection<Command> virtualCmds = new LinkedList<Command>();
1129 virtualCmds.add(new AddCommand(virtualNode));
1130 for (WaySegment virtualWay : virtualWays) {
1131 Way w = virtualWay.way;
1132 Way wnew = new Way(w);
1133 wnew.addNode(virtualWay.lowerIndex + 1, virtualNode);
1134 virtualCmds.add(new ChangeCommand(w, wnew));
1135 }
1136 virtualCmds.add(new MoveCommand(virtualNode, startEN, currentEN));
1137 String text = trn("Add and move a virtual new node to way",
1138 "Add and move a virtual new node to {0} ways", virtualWays.size(),
1139 virtualWays.size());
1140 Main.main.undoRedo.add(new SequenceCommand(text, virtualCmds));
1141 getCurrentDataSet().setSelected(Collections.singleton((OsmPrimitive) virtualNode));
1142 clear();
1143 }
1144
1145 private void clear() {
1146 virtualWays.clear();
1147 virtualNode = null;
1148 }
1149
1150 private boolean hasVirtualNode() {
1151 return virtualNode != null;
1152 }
1153
1154 private boolean hasVirtualWaysToBeConstructed() {
1155 return !virtualWays.isEmpty();
1156 }
1157 }
1158}
Note: See TracBrowser for help on using the repository browser.