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

Last change on this file since 6679 was 6679, checked in by stoecker, 10 years ago

see #9110 - fix singular forms, even if they are useless

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