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

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

add AbstractOsmDataLayer, MainLayerManager.getActiveData, Main.getInProgressISelection

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