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

Last change on this file since 13277 was 13277, checked in by stoecker, 6 years ago

see #15734 - fix icon detection

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