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

Last change on this file since 5394 was 5394, checked in by akks, 12 years ago

see #7888, smaller refactoring or SelectAction (cycling) (behavior should not change)

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