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

Last change on this file since 4934 was 4934, checked in by xeen, 12 years ago

likely fix #7315’s cursor issues and related target-highlight ones

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