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

Last change on this file since 1412 was 1412, checked in by stoecker, 15 years ago

close #2179

  • Property svn:eol-style set to native
File size: 16.5 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.actions.mapmode;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Cursor;
7import java.awt.Point;
8import java.awt.Rectangle;
9import java.awt.event.ActionEvent;
10import java.awt.event.KeyEvent;
11import java.awt.event.MouseEvent;
12import java.util.ArrayList;
13import java.util.Collection;
14import java.util.Collections;
15import java.util.LinkedList;
16import java.util.List;
17
18import javax.swing.JOptionPane;
19
20import org.openstreetmap.josm.Main;
21import org.openstreetmap.josm.actions.MergeNodesAction;
22import org.openstreetmap.josm.command.AddCommand;
23import org.openstreetmap.josm.command.ChangeCommand;
24import org.openstreetmap.josm.command.Command;
25import org.openstreetmap.josm.command.MoveCommand;
26import org.openstreetmap.josm.command.RotateCommand;
27import org.openstreetmap.josm.command.SequenceCommand;
28import org.openstreetmap.josm.data.coor.EastNorth;
29import org.openstreetmap.josm.data.osm.DataSet;
30import org.openstreetmap.josm.data.osm.Node;
31import org.openstreetmap.josm.data.osm.OsmPrimitive;
32import org.openstreetmap.josm.data.osm.Way;
33import org.openstreetmap.josm.data.osm.WaySegment;
34import org.openstreetmap.josm.data.osm.visitor.AllNodesVisitor;
35import org.openstreetmap.josm.data.osm.visitor.SimplePaintVisitor;
36import org.openstreetmap.josm.gui.MapFrame;
37import org.openstreetmap.josm.gui.MapView;
38import org.openstreetmap.josm.gui.SelectionManager;
39import org.openstreetmap.josm.gui.SelectionManager.SelectionEnded;
40import org.openstreetmap.josm.gui.layer.Layer;
41import org.openstreetmap.josm.gui.layer.OsmDataLayer;
42import org.openstreetmap.josm.tools.ImageProvider;
43import org.openstreetmap.josm.tools.Shortcut;
44
45/**
46 * Move is an action that can move all kind of OsmPrimitives (except keys for now).
47 *
48 * If an selected object is under the mouse when dragging, move all selected objects.
49 * If an unselected object is under the mouse when dragging, it becomes selected
50 * and will be moved.
51 * If no object is under the mouse, move all selected objects (if any)
52 *
53 * @author imi
54 */
55public class SelectAction extends MapMode implements SelectionEnded {
56
57 enum Mode { move, rotate, select }
58 private Mode mode = null;
59 private long mouseDownTime = 0;
60 private boolean didMove = false;
61 private boolean cancelDrawMode = false;
62 Node virtualNode = null;
63 WaySegment virtualWay = null;
64 SequenceCommand virtualCmds = null;
65
66 /**
67 * The old cursor before the user pressed the mouse button.
68 */
69 private Cursor oldCursor;
70 /**
71 * The position of the mouse before the user moves a node.
72 */
73 private Point mousePos;
74 private SelectionManager selectionManager;
75
76 /**
77 * The time which needs to pass between click and release before something
78 * counts as a move, in milliseconds
79 */
80 private int initialMoveDelay;
81
82 /**
83 * The screen distance which needs to be travelled before something
84 * counts as a move, in pixels
85 */
86 private int initialMoveThreshold;
87 private boolean initialMoveThresholdExceeded = false;
88 /**
89 * Create a new SelectAction
90 * @param mapFrame The MapFrame this action belongs to.
91 */
92 public SelectAction(MapFrame mapFrame) {
93 super(tr("Select"), "move/move", tr("Select, move and rotate objects"),
94 Shortcut.registerShortcut("mapmode:select", tr("Mode: {0}", tr("Select")), KeyEvent.VK_S, Shortcut.GROUP_EDIT),
95 mapFrame,
96 getCursor("normal", "selection", Cursor.DEFAULT_CURSOR));
97 putValue("help", "Action/Move/Move");
98 selectionManager = new SelectionManager(this, false, mapFrame.mapView);
99 initialMoveDelay = Main.pref.getInteger("edit.initial-move-delay",200);
100 initialMoveThreshold = Main.pref.getInteger("edit.initial-move-threshold",5);
101 }
102
103 private static Cursor getCursor(String name, String mod, int def) {
104 try {
105 return ImageProvider.getCursor(name, mod);
106 } catch (Exception e) {
107 }
108 return Cursor.getPredefinedCursor(def);
109 }
110
111 private void setCursor(Cursor c) {
112 if (oldCursor == null) {
113 oldCursor = Main.map.mapView.getCursor();
114 Main.map.mapView.setCursor(c);
115 }
116 }
117
118 private void restoreCursor() {
119 if (oldCursor != null) {
120 Main.map.mapView.setCursor(oldCursor);
121 oldCursor = null;
122 }
123 }
124
125 @Override public void enterMode() {
126 super.enterMode();
127 Main.map.mapView.addMouseListener(this);
128 Main.map.mapView.addMouseMotionListener(this);
129 Main.map.mapView.enableVirtualNodes(
130 Main.pref.getInteger("mappaint.node.virtual-size", 8) != 0);
131 }
132
133 @Override public void exitMode() {
134 super.exitMode();
135 selectionManager.unregister(Main.map.mapView);
136 Main.map.mapView.removeMouseListener(this);
137 Main.map.mapView.removeMouseMotionListener(this);
138 Main.map.mapView.enableVirtualNodes(false);
139 }
140
141 /**
142 * If the left mouse button is pressed, move all currently selected
143 * objects (if one of them is under the mouse) or the current one under the
144 * mouse (which will become selected).
145 */
146 @Override public void mouseDragged(MouseEvent e) {
147 cancelDrawMode = true;
148 if (mode == Mode.select) return;
149
150 // do not count anything as a move if it lasts less than 100 milliseconds.
151 if ((mode == Mode.move) && (System.currentTimeMillis() - mouseDownTime < initialMoveDelay)) return;
152
153 if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) == 0)
154 return;
155
156 if (mode == Mode.move) {
157 setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
158 }
159
160 if (mousePos == null) {
161 mousePos = e.getPoint();
162 return;
163 }
164
165 if (!initialMoveThresholdExceeded) {
166 int dxp = mousePos.x - e.getX();
167 int dyp = mousePos.y - e.getY();
168 int dp = (int) Math.sqrt(dxp*dxp+dyp*dyp);
169 if (dp < initialMoveThreshold) return;
170 initialMoveThresholdExceeded = true;
171 }
172
173 EastNorth mouseEN = Main.map.mapView.getEastNorth(e.getX(), e.getY());
174 EastNorth mouseStartEN = Main.map.mapView.getEastNorth(mousePos.x, mousePos.y);
175 double dx = mouseEN.east() - mouseStartEN.east();
176 double dy = mouseEN.north() - mouseStartEN.north();
177 if (dx == 0 && dy == 0)
178 return;
179
180 if (virtualWay != null) {
181 Collection<Command> virtualCmds = new LinkedList<Command>();
182 virtualCmds.add(new AddCommand(virtualNode));
183 Way w = virtualWay.way;
184 Way wnew = new Way(w);
185 wnew.addNode(virtualWay.lowerIndex+1, virtualNode);
186 virtualCmds.add(new ChangeCommand(w, wnew));
187 virtualCmds.add(new MoveCommand(virtualNode, dx, dy));
188 Main.main.undoRedo.add(new SequenceCommand(tr("Add and move a virtual new node to way"), virtualCmds));
189 selectPrims(Collections.singleton((OsmPrimitive)virtualNode), false, false);
190 virtualWay = null;
191 virtualNode = null;
192 } else {
193 // Currently we support moving and rotating, which do not affect relations.
194 // So don't add them in the first place to make handling easier
195 Collection<OsmPrimitive> selection = Main.ds.getSelectedPhysical();
196 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
197
198 // when rotating, having only one node makes no sense - quit silently
199 if (mode == Mode.rotate && affectedNodes.size() < 2)
200 return;
201
202 Command c = !Main.main.undoRedo.commands.isEmpty()
203 ? Main.main.undoRedo.commands.getLast() : null;
204 if (c instanceof SequenceCommand)
205 c = ((SequenceCommand)c).getLastCommand();
206
207 if (mode == Mode.move) {
208 if (c instanceof MoveCommand && affectedNodes.equals(((MoveCommand)c).objects))
209 ((MoveCommand)c).moveAgain(dx,dy);
210 else
211 Main.main.undoRedo.add(
212 c = new MoveCommand(selection, dx, dy));
213
214 for (Node n : affectedNodes) {
215 if (n.coor.isOutSideWorld()) {
216 // Revert move
217 ((MoveCommand) c).moveAgain(-dx, -dy);
218
219 JOptionPane.showMessageDialog(Main.parent,
220 tr("Cannot move objects outside of the world."));
221 return;
222 }
223 }
224 } else if (mode == Mode.rotate) {
225 if (c instanceof RotateCommand && affectedNodes.equals(((RotateCommand)c).objects))
226 ((RotateCommand)c).rotateAgain(mouseStartEN, mouseEN);
227 else
228 Main.main.undoRedo.add(new RotateCommand(selection, mouseStartEN, mouseEN));
229 }
230 }
231
232 Main.map.mapView.repaint();
233 mousePos = e.getPoint();
234
235 didMove = true;
236 }
237
238 private Collection<OsmPrimitive> getNearestCollectionVirtual(Point p) {
239 MapView c = Main.map.mapView;
240 int snapDistance = Main.pref.getInteger("mappaint.node.virtual-snap-distance", 8);
241 snapDistance *= snapDistance;
242 OsmPrimitive osm = c.getNearestNode(p);
243 virtualWay = null;
244 virtualNode = null;
245
246 if (osm == null)
247 {
248 WaySegment nearestWaySeg = c.getNearestWaySegment(p);
249 if (nearestWaySeg != null)
250 {
251 osm = nearestWaySeg.way;
252 if(Main.pref.getInteger("mappaint.node.virtual-size", 8) > 0)
253 {
254 Way w = (Way)osm;
255 Point p1 = c.getPoint(w.nodes.get(nearestWaySeg.lowerIndex).eastNorth);
256 Point p2 = c.getPoint(w.nodes.get(nearestWaySeg.lowerIndex+1).eastNorth);
257 if(SimplePaintVisitor.isLargeSegment(p1, p2, Main.pref.getInteger("mappaint.node.virtual-space", 70)))
258 {
259 Point pc = new Point((p1.x+p2.x)/2, (p1.y+p2.y)/2);
260 if (p.distanceSq(pc) < snapDistance)
261 {
262 virtualWay = nearestWaySeg;
263 virtualNode = new Node(Main.map.mapView.getLatLon(pc.x, pc.y));
264 osm = w;
265 }
266 }
267 }
268 }
269 }
270 if (osm == null)
271 return Collections.emptySet();
272 return Collections.singleton(osm);
273 }
274
275 /**
276 * Look, whether any object is selected. If not, select the nearest node.
277 * If there are no nodes in the dataset, do nothing.
278 *
279 * If the user did not press the left mouse button, do nothing.
280 *
281 * Also remember the starting position of the movement and change the mouse
282 * cursor to movement.
283 */
284 @Override public void mousePressed(MouseEvent e) {
285 cancelDrawMode = false;
286 if (! (Boolean)this.getValue("active")) return;
287 if (e.getButton() != MouseEvent.BUTTON1)
288 return;
289 boolean ctrl = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0;
290 // boolean alt = (e.getModifiers() & ActionEvent.ALT_MASK) != 0;
291 boolean shift = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
292
293 mouseDownTime = System.currentTimeMillis();
294 didMove = false;
295 initialMoveThresholdExceeded = false;
296
297 Collection<OsmPrimitive> osmColl = getNearestCollectionVirtual(e.getPoint());
298
299 if (ctrl && shift) {
300 if (Main.ds.getSelected().isEmpty()) selectPrims(osmColl, true, false);
301 mode = Mode.rotate;
302 setCursor(ImageProvider.getCursor("rotate", null));
303 } else if (!osmColl.isEmpty()) {
304 // Don't replace the selection now if the user clicked on a
305 // selected object (this would break moving of selected groups).
306 // We'll do that later in mouseReleased if the user didn't try to
307 // move.
308 selectPrims(osmColl,
309 shift || Main.ds.getSelected().containsAll(osmColl),
310 ctrl);
311 mode = Mode.move;
312 } else {
313 mode = Mode.select;
314 oldCursor = Main.map.mapView.getCursor();
315 selectionManager.register(Main.map.mapView);
316 selectionManager.mousePressed(e);
317 }
318 if(mode != Mode.move || shift || ctrl)
319 {
320 virtualNode = null;
321 virtualWay = null;
322 }
323
324 updateStatusLine();
325 Main.map.mapView.repaint();
326
327 mousePos = e.getPoint();
328 }
329
330 /**
331 * Restore the old mouse cursor.
332 */
333 @Override public void mouseReleased(MouseEvent e) {
334 if (mode == Mode.select) {
335 selectionManager.unregister(Main.map.mapView);
336
337 // Select Draw Tool if no selection has been made
338 if(Main.ds.getSelected().size() == 0 && !cancelDrawMode) {
339 Main.map.selectDrawTool(true);
340 return;
341 }
342 }
343 restoreCursor();
344
345 if (mode == Mode.move) {
346 boolean ctrl = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0;
347 boolean shift = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
348 if (!didMove) {
349 selectPrims(
350 Main.map.mapView.getNearestCollection(e.getPoint()),
351 shift, ctrl);
352
353 // If the user double-clicked a node, change to draw mode
354 List<OsmPrimitive> sel = new ArrayList<OsmPrimitive>(Main.ds.getSelected());
355 if(e.getClickCount() >=2 && sel.size() == 1 && sel.get(0) instanceof Node) {
356 // We need to do it like this as otherwise drawAction will see a double
357 // click and switch back to SelectMode
358 Main.worker.execute(new Runnable(){
359 public void run() {
360 Main.map.selectDrawTool(true);
361 }
362 });
363 return;
364 }
365 } else {
366 Collection<OsmPrimitive> selection = Main.ds.getSelected();
367 if (ctrl) {
368 Collection<Node> affectedNodes = AllNodesVisitor.getAllNodes(selection);
369 Collection<Node> nn = Main.map.mapView.getNearestNodes(e.getPoint(), affectedNodes);
370 if (nn != null) {
371 Node n = nn.iterator().next();
372 LinkedList<Node> selNodes = new LinkedList<Node>();
373 for (OsmPrimitive osm : selection)
374 if (osm instanceof Node)
375 selNodes.add((Node)osm);
376 if (selNodes.size() > 0) {
377 selNodes.add(n);
378 MergeNodesAction.mergeNodes(selNodes, n);
379 }
380 }
381 }
382 DataSet.fireSelectionChanged(selection);
383 }
384 }
385
386 updateStatusLine();
387 mode = null;
388 updateStatusLine();
389 }
390
391 public void selectionEnded(Rectangle r, boolean alt, boolean shift, boolean ctrl) {
392 selectPrims(selectionManager.getObjectsInRectangle(r, alt), shift, ctrl);
393 }
394
395 public void selectPrims(Collection<OsmPrimitive> selectionList, boolean shift, boolean ctrl) {
396 if (shift && ctrl)
397 return; // not allowed together
398
399 Collection<OsmPrimitive> curSel;
400 if (!ctrl && !shift)
401 curSel = new LinkedList<OsmPrimitive>(); // new selection will replace the old.
402 else
403 curSel = Main.ds.getSelected();
404
405 for (OsmPrimitive osm : selectionList)
406 if (ctrl)
407 curSel.remove(osm);
408 else
409 curSel.add(osm);
410 Main.ds.setSelected(curSel);
411 Main.map.mapView.repaint();
412 }
413
414 @Override public String getModeHelpText() {
415 if (mode == Mode.select) {
416 return tr("Release the mouse button to select the objects in the rectangle.");
417 } else if (mode == Mode.move) {
418 return tr("Release the mouse button to stop moving. Ctrl to merge with nearest node.");
419 } else if (mode == Mode.rotate) {
420 return tr("Release the mouse button to stop rotating.");
421 } else {
422 return tr("Move objects by dragging; Shift to add to selection (Ctrl to remove); Shift-Ctrl to rotate selected; or change selection");
423 }
424 }
425
426 @Override public boolean layerIsSupported(Layer l) {
427 return l instanceof OsmDataLayer;
428 }
429}
Note: See TracBrowser for help on using the repository browser.