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

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

see #5710 - code refactor to ease a potential fix

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