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

Last change on this file since 17374 was 17374, checked in by GerdP, 3 years ago

see #20167: [patch] Improve code readability by replacing indexed loops with foreach
Patch by gaben, slightly modified
I removed the changes for

  • GpxImageCorrelation.java, they introduce a TODO
  • ConnectivityRelations.java (no improvement in readability)
  • Property svn:eol-style set to native
File size: 52.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.List;
20import java.util.Optional;
21
22import javax.swing.JOptionPane;
23
24import org.openstreetmap.josm.actions.MergeNodesAction;
25import org.openstreetmap.josm.command.AddCommand;
26import org.openstreetmap.josm.command.ChangeNodesCommand;
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.SystemOfMeasurement;
33import org.openstreetmap.josm.data.UndoRedoHandler;
34import org.openstreetmap.josm.data.coor.EastNorth;
35import org.openstreetmap.josm.data.osm.DataSet;
36import org.openstreetmap.josm.data.osm.Node;
37import org.openstreetmap.josm.data.osm.OsmData;
38import org.openstreetmap.josm.data.osm.OsmPrimitive;
39import org.openstreetmap.josm.data.osm.Way;
40import org.openstreetmap.josm.data.osm.WaySegment;
41import org.openstreetmap.josm.data.osm.visitor.AllNodesVisitor;
42import org.openstreetmap.josm.data.osm.visitor.paint.WireframeMapRenderer;
43import org.openstreetmap.josm.gui.ExtendedDialog;
44import org.openstreetmap.josm.gui.MainApplication;
45import org.openstreetmap.josm.gui.MapFrame;
46import org.openstreetmap.josm.gui.MapView;
47import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
48import org.openstreetmap.josm.gui.SelectionManager;
49import org.openstreetmap.josm.gui.SelectionManager.SelectionEnded;
50import org.openstreetmap.josm.gui.layer.Layer;
51import org.openstreetmap.josm.gui.layer.OsmDataLayer;
52import org.openstreetmap.josm.gui.util.GuiHelper;
53import org.openstreetmap.josm.gui.util.KeyPressReleaseListener;
54import org.openstreetmap.josm.gui.util.ModifierExListener;
55import org.openstreetmap.josm.spi.preferences.Config;
56import org.openstreetmap.josm.tools.ImageProvider;
57import org.openstreetmap.josm.tools.Logging;
58import org.openstreetmap.josm.tools.Pair;
59import org.openstreetmap.josm.tools.PlatformManager;
60import org.openstreetmap.josm.tools.Shortcut;
61
62/**
63 * Move is an action that can move all kind of OsmPrimitives (except keys for now).
64 *
65 * If an selected object is under the mouse when dragging, move all selected objects.
66 * If an unselected object is under the mouse when dragging, it becomes selected
67 * and will be moved.
68 * If no object is under the mouse, move all selected objects (if any)
69 *
70 * On Mac OS X, Ctrl + mouse button 1 simulates right click (map move), so the
71 * feature "selection remove" is disabled on this platform.
72 */
73public class SelectAction extends MapMode implements ModifierExListener, KeyPressReleaseListener, SelectionEnded {
74
75 private static final String NORMAL = /* ICON(cursor/)*/ "normal";
76
77 /**
78 * Select action mode.
79 * @since 7543
80 */
81 public enum Mode {
82 /** "MOVE" means either dragging or select if no mouse movement occurs (i.e. just clicking) */
83 MOVE,
84 /** "ROTATE" allows to apply a rotation transformation on the selected object (see {@link RotateCommand}) */
85 ROTATE,
86 /** "SCALE" allows to apply a scaling transformation on the selected object (see {@link ScaleCommand}) */
87 SCALE,
88 /** "SELECT" means the selection rectangle */
89 SELECT
90 }
91
92 // contains all possible cases the cursor can be in the SelectAction
93 enum SelectActionCursor {
94
95 rect(NORMAL, /* ICON(cursor/modifier/)*/ "selection"),
96 rect_add(NORMAL, /* ICON(cursor/modifier/)*/ "select_add"),
97 rect_rm(NORMAL, /* ICON(cursor/modifier/)*/ "select_remove"),
98 way(NORMAL, /* ICON(cursor/modifier/)*/ "select_way"),
99 way_add(NORMAL, /* ICON(cursor/modifier/)*/ "select_way_add"),
100 way_rm(NORMAL, /* ICON(cursor/modifier/)*/ "select_way_remove"),
101 node(NORMAL, /* ICON(cursor/modifier/)*/ "select_node"),
102 node_add(NORMAL, /* ICON(cursor/modifier/)*/ "select_node_add"),
103 node_rm(NORMAL, /* ICON(cursor/modifier/)*/ "select_node_remove"),
104 virtual_node(NORMAL, /* ICON(cursor/modifier/)*/ "addnode"),
105 scale(/* ICON(cursor/)*/ "scale", null),
106 rotate(/* ICON(cursor/)*/ "rotate", null),
107 merge(/* ICON(cursor/)*/ "crosshair", null),
108 lasso(NORMAL, /* ICON(cursor/modifier/)*/ "rope"),
109 merge_to_node(/* ICON(cursor/)*/ "crosshair", /* ICON(cursor/modifier/)*/"joinnode"),
110 move(Cursor.MOVE_CURSOR);
111
112 @SuppressWarnings("ImmutableEnumChecker")
113 private final Cursor c;
114 SelectActionCursor(String main, String sub) {
115 c = ImageProvider.getCursor(main, sub);
116 }
117
118 SelectActionCursor(int systemCursor) {
119 c = Cursor.getPredefinedCursor(systemCursor);
120 }
121
122 /**
123 * Returns the action cursor.
124 * @return the cursor
125 */
126 public Cursor cursor() {
127 return c;
128 }
129 }
130
131 private boolean lassoMode;
132 private boolean repeatedKeySwitchLassoOption;
133
134 // Cache previous mouse event (needed when only the modifier keys are
135 // pressed but the mouse isn't moved)
136 private MouseEvent oldEvent;
137
138 private Mode mode;
139 private final transient SelectionManager selectionManager;
140 private boolean cancelDrawMode;
141 private boolean drawTargetHighlight;
142 private boolean didMouseDrag;
143 /**
144 * The component this SelectAction is associated with.
145 */
146 private final MapView mv;
147 /**
148 * The old cursor before the user pressed the mouse button.
149 */
150 private Point startingDraggingPos;
151 /**
152 * point where user pressed the mouse to start movement
153 */
154 private EastNorth startEN;
155 /**
156 * The last known position of the mouse.
157 */
158 private Point lastMousePos;
159 /**
160 * The time of the user mouse down event.
161 */
162 private long mouseDownTime;
163 /**
164 * The pressed button of the user mouse down event.
165 */
166 private int mouseDownButton;
167 /**
168 * The time of the user mouse down event.
169 */
170 private long mouseReleaseTime;
171 /**
172 * The time which needs to pass between click and release before something
173 * counts as a move, in milliseconds
174 */
175 private int initialMoveDelay;
176 /**
177 * The screen distance which needs to be travelled before something
178 * counts as a move, in pixels
179 */
180 private int initialMoveThreshold;
181 private boolean initialMoveThresholdExceeded;
182
183 /**
184 * elements that have been highlighted in the previous iteration. Used
185 * to remove the highlight from them again as otherwise the whole data
186 * set would have to be checked.
187 */
188 private transient Optional<OsmPrimitive> currentHighlight = Optional.empty();
189
190 /**
191 * Create a new SelectAction
192 * @param mapFrame The MapFrame this action belongs to.
193 */
194 public SelectAction(MapFrame mapFrame) {
195 super(tr("Select mode"), "move/move", tr("Select, move, scale and rotate objects"),
196 Shortcut.registerShortcut("mapmode:select", tr("Mode: {0}", tr("Select mode")), KeyEvent.VK_S, Shortcut.DIRECT),
197 ImageProvider.getCursor("normal", "selection"));
198 mv = mapFrame.mapView;
199 setHelpId(ht("/Action/Select"));
200 selectionManager = new SelectionManager(this, false, mv);
201 }
202
203 @Override
204 public void enterMode() {
205 super.enterMode();
206 mv.addMouseListener(this);
207 mv.addMouseMotionListener(this);
208 mv.setVirtualNodesEnabled(Config.getPref().getInt("mappaint.node.virtual-size", 8) != 0);
209 drawTargetHighlight = Config.getPref().getBoolean("draw.target-highlight", true);
210 initialMoveDelay = Config.getPref().getInt("edit.initial-move-delay", 200);
211 initialMoveThreshold = Config.getPref().getInt("edit.initial-move-threshold", 5);
212 repeatedKeySwitchLassoOption = Config.getPref().getBoolean("mappaint.select.toggle-lasso-on-repeated-S", true);
213 cycleManager.init();
214 virtualManager.init();
215 // This is required to update the cursors when ctrl/shift/alt is pressed
216 MapFrame map = MainApplication.getMap();
217 map.keyDetector.addModifierExListener(this);
218 map.keyDetector.addKeyListener(this);
219 }
220
221 @Override
222 public void exitMode() {
223 super.exitMode();
224 cycleManager.cycleStart = null;
225 cycleManager.cycleList = asColl(null);
226 selectionManager.unregister(mv);
227 mv.removeMouseListener(this);
228 mv.removeMouseMotionListener(this);
229 mv.setVirtualNodesEnabled(false);
230 MapFrame map = MainApplication.getMap();
231 map.keyDetector.removeModifierExListener(this);
232 map.keyDetector.removeKeyListener(this);
233 removeHighlighting();
234 }
235
236 @Override
237 public void modifiersExChanged(int modifiers) {
238 if (!MainApplication.isDisplayingMapView() || oldEvent == null) return;
239 if (giveUserFeedback(oldEvent, modifiers)) {
240 mv.repaint();
241 }
242 }
243
244 /**
245 * handles adding highlights and updating the cursor for the given mouse event.
246 * Please note that the highlighting for merging while moving is handled via mouseDragged.
247 * @param e {@code MouseEvent} which should be used as base for the feedback
248 * @return {@code true} if repaint is required
249 */
250 private boolean giveUserFeedback(MouseEvent e) {
251 return giveUserFeedback(e, e.getModifiersEx());
252 }
253
254 /**
255 * handles adding highlights and updating the cursor for the given mouse event.
256 * Please note that the highlighting for merging while moving is handled via mouseDragged.
257 * @param e {@code MouseEvent} which should be used as base for the feedback
258 * @param modifiers define custom keyboard extended modifiers if the ones from MouseEvent are outdated or similar
259 * @return {@code true} if repaint is required
260 */
261 private boolean giveUserFeedback(MouseEvent e, int modifiers) {
262 Optional<OsmPrimitive> c = Optional.ofNullable(
263 mv.getNearestNodeOrWay(e.getPoint(), mv.isSelectablePredicate, true));
264
265 updateKeyModifiersEx(modifiers);
266 determineMapMode(c.isPresent());
267
268 Optional<OsmPrimitive> newHighlight = Optional.empty();
269
270 virtualManager.clear();
271 if (mode == Mode.MOVE && !dragInProgress() && virtualManager.activateVirtualNodeNearPoint(e.getPoint())) {
272 DataSet ds = getLayerManager().getActiveDataSet();
273 if (ds != null && drawTargetHighlight) {
274 ds.setHighlightedVirtualNodes(virtualManager.virtualWays);
275 }
276 mv.setNewCursor(SelectActionCursor.virtual_node.cursor(), this);
277 // don't highlight anything else if a virtual node will be
278 return repaintIfRequired(newHighlight);
279 }
280
281 mv.setNewCursor(getCursor(c.orElse(null)), this);
282
283 // return early if there can't be any highlights
284 if (!drawTargetHighlight || (mode != Mode.MOVE && mode != Mode.SELECT) || !c.isPresent())
285 return repaintIfRequired(newHighlight);
286
287 // CTRL toggles selection, but if while dragging CTRL means merge
288 final boolean isToggleMode = ctrl && !dragInProgress();
289 if (c.isPresent() && (isToggleMode || !c.get().isSelected())) {
290 // only highlight primitives that will change the selection
291 // when clicked. I.e. don't highlight selected elements unless
292 // we are in toggle mode.
293 newHighlight = c;
294 }
295 return repaintIfRequired(newHighlight);
296 }
297
298 /**
299 * works out which cursor should be displayed for most of SelectAction's
300 * features. The only exception is the "move" cursor when actually dragging
301 * primitives.
302 * @param nearbyStuff primitives near the cursor
303 * @return the cursor that should be displayed
304 */
305 private Cursor getCursor(OsmPrimitive nearbyStuff) {
306 String c = "rect";
307 switch(mode) {
308 case MOVE:
309 if (virtualManager.hasVirtualNode()) {
310 c = "virtual_node";
311 break;
312 }
313 final OsmPrimitive osm = nearbyStuff;
314
315 if (dragInProgress()) {
316 // only consider merge if ctrl is pressed and there are nodes in
317 // the selection that could be merged
318 if (!ctrl || getLayerManager().getEditDataSet().getSelectedNodes().isEmpty()) {
319 c = "move";
320 break;
321 }
322 // only show merge to node cursor if nearby node and that node is currently
323 // not being dragged
324 final boolean hasTarget = osm instanceof Node && !osm.isSelected();
325 c = hasTarget ? "merge_to_node" : "merge";
326 break;
327 }
328
329 c = (osm instanceof Node) ? "node" : c;
330 c = (osm instanceof Way) ? "way" : c;
331 if (shift) {
332 c += "_add";
333 } else if (ctrl) {
334 c += osm == null || osm.isSelected() ? "_rm" : "_add";
335 }
336 break;
337 case ROTATE:
338 c = "rotate";
339 break;
340 case SCALE:
341 c = "scale";
342 break;
343 case SELECT:
344 if (lassoMode) {
345 c = "lasso";
346 } else {
347 c = "rect" + (shift ? "_add" : (ctrl && !PlatformManager.isPlatformOsx() ? "_rm" : ""));
348 }
349 break;
350 }
351 return SelectActionCursor.valueOf(c).cursor();
352 }
353
354 /**
355 * Removes all existing highlights.
356 * @return true if a repaint is required
357 */
358 private boolean removeHighlighting() {
359 boolean needsRepaint = false;
360 OsmData<?, ?, ?, ?> ds = getLayerManager().getActiveData();
361 if (ds != null && !ds.getHighlightedVirtualNodes().isEmpty()) {
362 needsRepaint = true;
363 ds.clearHighlightedVirtualNodes();
364 }
365 if (!currentHighlight.isPresent()) {
366 return needsRepaint;
367 } else {
368 currentHighlight.get().setHighlighted(false);
369 }
370 currentHighlight = Optional.empty();
371 return true;
372 }
373
374 private boolean repaintIfRequired(Optional<OsmPrimitive> newHighlight) {
375 if (!drawTargetHighlight || currentHighlight.equals(newHighlight))
376 return false;
377 currentHighlight.ifPresent(osm -> osm.setHighlighted(false));
378 newHighlight.ifPresent(osm -> osm.setHighlighted(true));
379 currentHighlight = newHighlight;
380 return true;
381 }
382
383 /**
384 * Look, whether any object is selected. If not, select the nearest node.
385 * If there are no nodes in the dataset, do nothing.
386 *
387 * If the user did not press the left mouse button, do nothing.
388 *
389 * Also remember the starting position of the movement and change the mouse
390 * cursor to movement.
391 */
392 @Override
393 public void mousePressed(MouseEvent e) {
394 mouseDownButton = e.getButton();
395 // return early
396 if (!mv.isActiveLayerVisible() || !(Boolean) this.getValue("active") || mouseDownButton != MouseEvent.BUTTON1)
397 return;
398
399 // left-button mouse click only is processed here
400
401 // request focus in order to enable the expected keyboard shortcuts
402 mv.requestFocus();
403
404 // update which modifiers are pressed (shift, alt, ctrl)
405 updateKeyModifiers(e);
406
407 // We don't want to change to draw tool if the user tries to (de)select
408 // stuff but accidentally clicks in an empty area when selection is empty
409 cancelDrawMode = shift || ctrl;
410 didMouseDrag = false;
411 initialMoveThresholdExceeded = false;
412 mouseDownTime = System.currentTimeMillis();
413 lastMousePos = e.getPoint();
414 startEN = mv.getEastNorth(lastMousePos.x, lastMousePos.y);
415
416 // primitives under cursor are stored in c collection
417
418 OsmPrimitive nearestPrimitive = mv.getNearestNodeOrWay(e.getPoint(), mv.isSelectablePredicate, true);
419
420 determineMapMode(nearestPrimitive != null);
421
422 switch(mode) {
423 case ROTATE:
424 case SCALE:
425 // if nothing was selected, select primitive under cursor for scaling or rotating
426 DataSet ds = getLayerManager().getEditDataSet();
427 if (ds.selectionEmpty()) {
428 ds.setSelected(asColl(nearestPrimitive));
429 }
430
431 // Mode.select redraws when selectPrims is called
432 // Mode.move redraws when mouseDragged is called
433 // Mode.rotate redraws here
434 // Mode.scale redraws here
435 break;
436 case MOVE:
437 // also include case when some primitive is under cursor and no shift+ctrl / alt+ctrl is pressed
438 // so this is not movement, but selection on primitive under cursor
439 if (!cancelDrawMode && nearestPrimitive instanceof Way) {
440 virtualManager.activateVirtualNodeNearPoint(e.getPoint());
441 }
442 OsmPrimitive toSelect = cycleManager.cycleSetup(nearestPrimitive, e.getPoint());
443 selectPrims(asColl(toSelect), false, false);
444 useLastMoveCommandIfPossible();
445 // Schedule a timer to update status line "initialMoveDelay+1" ms in the future
446 GuiHelper.scheduleTimer(initialMoveDelay+1, evt -> updateStatusLine(), false);
447 break;
448 case SELECT:
449 default:
450 if (!(ctrl && PlatformManager.isPlatformOsx())) {
451 // start working with rectangle or lasso
452 selectionManager.register(mv, lassoMode);
453 selectionManager.mousePressed(e);
454 break;
455 }
456 }
457 if (giveUserFeedback(e)) {
458 mv.repaint();
459 }
460 updateStatusLine();
461 }
462
463 @Override
464 public void mouseMoved(MouseEvent e) {
465 // Mac OSX simulates with ctrl + mouse 1 the second mouse button hence no dragging events get fired.
466 if (PlatformManager.isPlatformOsx() && (mode == Mode.ROTATE || mode == Mode.SCALE)) {
467 mouseDragged(e);
468 return;
469 }
470 oldEvent = e;
471 if (giveUserFeedback(e)) {
472 mv.repaint();
473 }
474 }
475
476 /**
477 * If the left mouse button is pressed, move all currently selected
478 * objects (if one of them is under the mouse) or the current one under the
479 * mouse (which will become selected).
480 */
481 @Override
482 public void mouseDragged(MouseEvent e) {
483 if (!mv.isActiveLayerVisible())
484 return;
485
486 // Swing sends random mouseDragged events when closing dialogs by double-clicking their top-left icon on Windows
487 // Ignore such false events to prevent issues like #7078
488 if (mouseDownButton == MouseEvent.BUTTON1 && mouseReleaseTime > mouseDownTime)
489 return;
490
491 cancelDrawMode = true;
492 if (mode == Mode.SELECT) {
493 // Unregisters selectionManager if ctrl has been pressed after mouse click on Mac OS X in order to move the map
494 if (ctrl && PlatformManager.isPlatformOsx()) {
495 selectionManager.unregister(mv);
496 // Make sure correct cursor is displayed
497 mv.setNewCursor(Cursor.MOVE_CURSOR, this);
498 }
499 return;
500 }
501
502 // do not count anything as a move if it lasts less than 100 milliseconds.
503 if ((mode == Mode.MOVE) && (System.currentTimeMillis() - mouseDownTime < initialMoveDelay))
504 return;
505
506 if (mode != Mode.ROTATE && mode != Mode.SCALE && (e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) == 0) {
507 // button is pressed in rotate mode
508 return;
509 }
510
511 if (mode == Mode.MOVE) {
512 // If ctrl is pressed we are in merge mode. Look for a nearby node,
513 // highlight it and adjust the cursor accordingly.
514 final boolean canMerge = ctrl && !getLayerManager().getEditDataSet().getSelectedNodes().isEmpty();
515 final OsmPrimitive p = canMerge ? findNodeToMergeTo(e.getPoint()) : null;
516 boolean needsRepaint = removeHighlighting();
517 if (p != null) {
518 p.setHighlighted(true);
519 currentHighlight = Optional.of(p);
520 needsRepaint = true;
521 }
522 mv.setNewCursor(getCursor(p), this);
523 // also update the stored mouse event, so we can display the correct cursor
524 // when dragging a node onto another one and then press CTRL to merge
525 oldEvent = e;
526 if (needsRepaint) {
527 mv.repaint();
528 }
529 }
530
531 if (startingDraggingPos == null) {
532 startingDraggingPos = new Point(e.getX(), e.getY());
533 }
534
535 if (lastMousePos == null) {
536 lastMousePos = e.getPoint();
537 return;
538 }
539
540 if (!initialMoveThresholdExceeded) {
541 int dp = (int) lastMousePos.distance(e.getX(), e.getY());
542 if (dp < initialMoveThreshold)
543 return; // ignore small drags
544 initialMoveThresholdExceeded = true; //no more ignoring until next mouse press
545 }
546 if (e.getPoint().equals(lastMousePos))
547 return;
548
549 EastNorth currentEN = mv.getEastNorth(e.getX(), e.getY());
550
551 if (virtualManager.hasVirtualWaysToBeConstructed()) {
552 virtualManager.createMiddleNodeFromVirtual(currentEN);
553 } else {
554 if (!updateCommandWhileDragging(currentEN)) return;
555 }
556
557 mv.repaint();
558 if (mode != Mode.SCALE) {
559 lastMousePos = e.getPoint();
560 }
561
562 didMouseDrag = true;
563 }
564
565 @Override
566 public void mouseExited(MouseEvent e) {
567 if (removeHighlighting()) {
568 mv.repaint();
569 }
570 }
571
572 @Override
573 public void mouseReleased(MouseEvent e) {
574 if (!mv.isActiveLayerVisible())
575 return;
576
577 startingDraggingPos = null;
578 mouseReleaseTime = System.currentTimeMillis();
579 MapFrame map = MainApplication.getMap();
580
581 if (mode == Mode.SELECT) {
582 if (e.getButton() != MouseEvent.BUTTON1) {
583 return;
584 }
585 selectionManager.endSelecting(e);
586 selectionManager.unregister(mv);
587
588 // Select Draw Tool if no selection has been made
589 if (!cancelDrawMode && getLayerManager().getActiveDataSet().selectionEmpty()) {
590 map.selectDrawTool(true);
591 updateStatusLine();
592 return;
593 }
594 }
595
596 if (mode == Mode.MOVE && e.getButton() == MouseEvent.BUTTON1) {
597 DataSet ds = getLayerManager().getEditDataSet();
598 if (!didMouseDrag) {
599 // only built in move mode
600 virtualManager.clear();
601 // do nothing if the click was to short too be recognized as a drag,
602 // but the release position is farther than 10px away from the press position
603 if (lastMousePos == null || lastMousePos.distanceSq(e.getPoint()) < 100) {
604 updateKeyModifiers(e);
605 selectPrims(cycleManager.cyclePrims(), true, false);
606
607 // If the user double-clicked a node, change to draw mode
608 Collection<OsmPrimitive> c = ds.getSelected();
609 if (e.getClickCount() >= 2 && c.size() == 1 && c.iterator().next() instanceof Node) {
610 // We need to do it like this as otherwise drawAction will see a double
611 // click and switch back to SelectMode
612 MainApplication.worker.execute(() -> map.selectDrawTool(true));
613 return;
614 }
615 }
616 } else {
617 confirmOrUndoMovement(e);
618 }
619 }
620
621 mode = null;
622
623 // simply remove any highlights if the middle click popup is active because
624 // the highlights don't depend on the cursor position there. If something was
625 // selected beforehand this would put us into move mode as well, which breaks
626 // the cycling through primitives on top of each other (see #6739).
627 if (e.getButton() == MouseEvent.BUTTON2) {
628 removeHighlighting();
629 } else {
630 giveUserFeedback(e);
631 }
632 updateStatusLine();
633 }
634
635 @Override
636 public void selectionEnded(Rectangle r, MouseEvent e) {
637 updateKeyModifiers(e);
638 selectPrims(selectionManager.getSelectedObjects(alt), true, true);
639 }
640
641 @Override
642 public void doKeyPressed(KeyEvent e) {
643 if (!repeatedKeySwitchLassoOption || !MainApplication.isDisplayingMapView() || !getShortcut().isEvent(e))
644 return;
645 if (Logging.isDebugEnabled()) {
646 Logging.debug("{0} consuming event {1}", getClass().getName(), e);
647 }
648 e.consume();
649 MapFrame map = MainApplication.getMap();
650 if (!lassoMode) {
651 map.selectMapMode(map.mapModeSelectLasso);
652 } else {
653 map.selectMapMode(map.mapModeSelect);
654 }
655 }
656
657 @Override
658 public void doKeyReleased(KeyEvent e) {
659 // Do nothing
660 }
661
662 /**
663 * sets the mapmode according to key modifiers and if there are any
664 * selectables nearby. Everything has to be pre-determined for this
665 * function; its main purpose is to centralize what the modifiers do.
666 * @param hasSelectionNearby {@code true} if some primitves are selectable nearby
667 */
668 private void determineMapMode(boolean hasSelectionNearby) {
669 if (getLayerManager().getEditDataSet() != null) {
670 if (shift && ctrl) {
671 mode = Mode.ROTATE;
672 } else if (alt && ctrl) {
673 mode = Mode.SCALE;
674 } else if (hasSelectionNearby || dragInProgress()) {
675 mode = Mode.MOVE;
676 } else {
677 mode = Mode.SELECT;
678 }
679 } else {
680 mode = Mode.SELECT;
681 }
682 }
683
684 /**
685 * Determines whenever elements have been grabbed and moved (i.e. the initial
686 * thresholds have been exceeded) and is still in progress (i.e. mouse button still pressed)
687 * @return true if a drag is in progress
688 */
689 private boolean dragInProgress() {
690 return didMouseDrag && startingDraggingPos != null;
691 }
692
693 /**
694 * Create or update data modification command while dragging mouse - implementation of
695 * continuous moving, scaling and rotation
696 * @param currentEN - mouse position
697 * @return status of action (<code>true</code> when action was performed)
698 */
699 private boolean updateCommandWhileDragging(EastNorth currentEN) {
700 // Currently we support only transformations which do not affect relations.
701 // So don't add them in the first place to make handling easier
702 DataSet ds = getLayerManager().getEditDataSet();
703 Collection<OsmPrimitive> selection = ds.getSelectedNodesAndWays();
704 if (selection.isEmpty()) { // if nothing was selected to drag, just select nearest node/way to the cursor
705 ds.setSelected(mv.getNearestNodeOrWay(mv.getPoint(startEN), mv.isSelectablePredicate, true));
706 }
707
708 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
709 // for these transformations, having only one node makes no sense - quit silently
710 if (affectedNodes.size() < 2 && (mode == Mode.ROTATE || mode == Mode.SCALE)) {
711 return false;
712 }
713 Command c = getLastCommandInDataset(ds);
714 if (mode == Mode.MOVE) {
715 if (startEN == null) return false; // fix #8128
716 return ds.update(() -> {
717 MoveCommand moveCmd = null;
718 if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
719 moveCmd = (MoveCommand) c;
720 moveCmd.saveCheckpoint();
721 moveCmd.applyVectorTo(currentEN);
722 } else if (!selection.isEmpty()) {
723 moveCmd = new MoveCommand(selection, startEN, currentEN);
724 UndoRedoHandler.getInstance().add(moveCmd);
725 }
726 for (Node n : affectedNodes) {
727 if (n.isOutSideWorld()) {
728 // Revert move
729 if (moveCmd != null) {
730 moveCmd.resetToCheckpoint();
731 }
732 // TODO: We might use a simple notification in the lower left corner.
733 JOptionPane.showMessageDialog(
734 MainApplication.getMainFrame(),
735 tr("Cannot move objects outside of the world."),
736 tr("Warning"),
737 JOptionPane.WARNING_MESSAGE);
738 mv.setNewCursor(cursor, this);
739 return false;
740 }
741 }
742 return true;
743 });
744 } else {
745 startEN = currentEN; // drag can continue after scaling/rotation
746
747 if (mode != Mode.ROTATE && mode != Mode.SCALE) {
748 return false;
749 }
750
751 return ds.update(() -> {
752 if (mode == Mode.ROTATE) {
753 if (c instanceof RotateCommand && affectedNodes.equals(((RotateCommand) c).getTransformedNodes())) {
754 ((RotateCommand) c).handleEvent(currentEN);
755 } else {
756 UndoRedoHandler.getInstance().add(new RotateCommand(selection, currentEN));
757 }
758 } else if (mode == Mode.SCALE) {
759 if (c instanceof ScaleCommand && affectedNodes.equals(((ScaleCommand) c).getTransformedNodes())) {
760 ((ScaleCommand) c).handleEvent(currentEN);
761 } else {
762 UndoRedoHandler.getInstance().add(new ScaleCommand(selection, currentEN));
763 }
764 }
765
766 Collection<Way> ways = ds.getSelectedWays();
767 if (doesImpactStatusLine(affectedNodes, ways)) {
768 MainApplication.getMap().statusLine.setDist(ways);
769 }
770 return true;
771 });
772 }
773 }
774
775 private static boolean doesImpactStatusLine(Collection<Node> affectedNodes, Collection<Way> selectedWays) {
776 return selectedWays.stream()
777 .flatMap(w -> w.getNodes().stream())
778 .anyMatch(affectedNodes::contains);
779 }
780
781 /**
782 * Adapt last move command (if it is suitable) to work with next drag, started at point startEN
783 */
784 private void useLastMoveCommandIfPossible() {
785 DataSet dataSet = getLayerManager().getEditDataSet();
786 if (dataSet == null) {
787 // It may happen that there is no edit layer.
788 return;
789 }
790 Command c = getLastCommandInDataset(dataSet);
791 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(dataSet.getSelected());
792 if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
793 // old command was created with different base point of movement, we need to recalculate it
794 ((MoveCommand) c).changeStartPoint(startEN);
795 }
796 }
797
798 /**
799 * Obtain command in undoRedo stack to "continue" when dragging
800 * @param ds The data set the command needs to be in.
801 * @return last command
802 */
803 private static Command getLastCommandInDataset(DataSet ds) {
804 Command lastCommand = UndoRedoHandler.getInstance().getLastCommand();
805 if (lastCommand instanceof SequenceCommand) {
806 lastCommand = ((SequenceCommand) lastCommand).getLastCommand();
807 }
808 if (lastCommand != null && ds.equals(lastCommand.getAffectedDataSet())) {
809 return lastCommand;
810 } else {
811 return null;
812 }
813 }
814
815 /**
816 * Present warning in the following cases and undo unwanted movements: <ul>
817 * <li>large and possibly unwanted movements</li>
818 * <li>movement of node with attached ways that are hidden by filters</li>
819 * </ul>
820 *
821 * @param e the mouse event causing the action (mouse released)
822 */
823 private void confirmOrUndoMovement(MouseEvent e) {
824 if (movesHiddenWay()) {
825 final ConfirmMoveDialog ed = new ConfirmMoveDialog();
826 ed.setContent(tr("Are you sure that you want to move elements with attached ways that are hidden by filters?"));
827 ed.toggleEnable("movedHiddenElements");
828 showConfirmMoveDialog(ed);
829 }
830 final Command lastCommand = UndoRedoHandler.getInstance().getLastCommand();
831 if (lastCommand == null) {
832 Logging.warn("No command found in undo/redo history, skipping confirmOrUndoMovement");
833 return;
834 }
835 final int moveCount = lastCommand.getParticipatingPrimitives().size();
836 if (lastCommand instanceof MoveCommand) {
837 final double moveDistance = ((MoveCommand) lastCommand).getDistance(n -> !n.isNew());
838 if (Double.isFinite(moveDistance) && moveDistance > Config.getPref().getInt("warn.move.maxdistance", 200)) {
839 final ConfirmMoveDialog ed = new ConfirmMoveDialog();
840 ed.setContent(trn(
841 "You moved {0} element by a distance of {1}. "
842 + "Moving elements by a large distance is often an error.\n" + "Really move them?",
843 "You moved {0} elements by a distance of {1}. "
844 + "Moving elements by a large distance is often an error.\n" + "Really move them?",
845 moveCount, moveCount, SystemOfMeasurement.getSystemOfMeasurement().getDistText(moveDistance)));
846 ed.toggleEnable("movedLargeDistance");
847 showConfirmMoveDialog(ed);
848 }
849 }
850 int max = Config.getPref().getInt("warn.move.maxelements", 20);
851 if (moveCount > max) {
852 final ConfirmMoveDialog ed = new ConfirmMoveDialog();
853 ed.setContent(
854 /* for correct i18n of plural forms - see #9110 */
855 trn("You moved more than {0} element. " + "Moving a large number of elements is often an error.\n" + "Really move them?",
856 "You moved more than {0} elements. " + "Moving a large number of elements is often an error.\n" + "Really move them?",
857 max, max));
858 ed.toggleEnable("movedManyElements");
859 showConfirmMoveDialog(ed);
860 } else {
861 // if small number of elements were moved,
862 updateKeyModifiers(e);
863 if (ctrl) mergePrims(e.getPoint());
864 }
865 }
866
867 private void showConfirmMoveDialog(ConfirmMoveDialog ed) {
868 if (ed.showDialog().getValue() != 1) {
869 UndoRedoHandler.getInstance().undo();
870 }
871 }
872
873 static class ConfirmMoveDialog extends ExtendedDialog {
874 ConfirmMoveDialog() {
875 super(MainApplication.getMainFrame(),
876 tr("Move elements"),
877 tr("Move them"), tr("Undo move"));
878 setButtonIcons("reorder", "cancel");
879 setCancelButton(2);
880 }
881 }
882
883 private boolean movesHiddenWay() {
884 DataSet ds = getLayerManager().getEditDataSet();
885 final Collection<Node> elementsToTest = new HashSet<>(ds.getSelectedNodes());
886 for (Way osm : ds.getSelectedWays()) {
887 elementsToTest.addAll(osm.getNodes());
888 }
889 return elementsToTest.stream()
890 .flatMap(n -> n.referrers(Way.class))
891 .anyMatch(Way::isDisabledAndHidden);
892 }
893
894 /**
895 * Merges the selected nodes to the one closest to the given mouse position if the control
896 * key is pressed. If there is no such node, no action will be done and no error will be
897 * reported. If there is, it will execute the merge and add it to the undo buffer.
898 * @param p mouse position
899 */
900 private void mergePrims(Point p) {
901 DataSet ds = getLayerManager().getEditDataSet();
902 Collection<Node> selNodes = ds.getSelectedNodes();
903 if (selNodes.isEmpty())
904 return;
905
906 Node target = findNodeToMergeTo(p);
907 if (target == null)
908 return;
909
910 if (selNodes.size() == 1) {
911 // Move all selected primitive to preserve shape #10748
912 Collection<OsmPrimitive> selection = ds.getSelectedNodesAndWays();
913 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
914 Command c = getLastCommandInDataset(ds);
915 ds.update(() -> {
916 if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand) c).getParticipatingPrimitives())) {
917 Node selectedNode = selNodes.iterator().next();
918 EastNorth selectedEN = selectedNode.getEastNorth();
919 EastNorth targetEN = target.getEastNorth();
920 ((MoveCommand) c).moveAgain(targetEN.getX() - selectedEN.getX(),
921 targetEN.getY() - selectedEN.getY());
922 }
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 (OsmPrimitive osmPrimitive : cycleList) {
1127 nxt = osmPrimitive;
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 List<Node> modNodes = w.getNodes();
1251 modNodes.add(virtualWay.lowerIndex + 1, virtualNode);
1252 virtualCmds.add(new ChangeNodesCommand(ds, w, modNodes));
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.