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

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

Fix #8128 - NPE while dragging object

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