source: josm/src/org/openstreetmap/josm/actions/DownloadAction.java@ 94

Last change on this file since 94 was 94, checked in by imi, 18 years ago
  • changed Add Way mode, so that ways can be modified
  • added Command Stack dialog (list the undo buffer)
  • fixed Exception in download gps data
File size: 12.9 KB
Line 
1package org.openstreetmap.josm.actions;
2
3import java.awt.Dimension;
4import java.awt.GridBagLayout;
5import java.awt.GridLayout;
6import java.awt.event.ActionEvent;
7import java.awt.event.ActionListener;
8import java.awt.event.InputEvent;
9import java.awt.event.KeyAdapter;
10import java.awt.event.KeyEvent;
11import java.awt.event.KeyListener;
12import java.io.IOException;
13import java.util.Collection;
14import java.util.HashMap;
15
16import javax.swing.DefaultListModel;
17import javax.swing.JButton;
18import javax.swing.JCheckBox;
19import javax.swing.JLabel;
20import javax.swing.JOptionPane;
21import javax.swing.JPanel;
22import javax.swing.JScrollPane;
23import javax.swing.JTextField;
24import javax.swing.KeyStroke;
25import javax.swing.SwingUtilities;
26import javax.swing.event.ListSelectionEvent;
27import javax.swing.event.ListSelectionListener;
28
29import org.jdom.JDOMException;
30import org.openstreetmap.josm.Main;
31import org.openstreetmap.josm.data.Bounds;
32import org.openstreetmap.josm.data.coor.LatLon;
33import org.openstreetmap.josm.data.osm.DataSet;
34import org.openstreetmap.josm.gui.BookmarkList;
35import org.openstreetmap.josm.gui.MapFrame;
36import org.openstreetmap.josm.gui.MapView;
37import org.openstreetmap.josm.gui.PleaseWaitRunnable;
38import org.openstreetmap.josm.gui.WorldChooser;
39import org.openstreetmap.josm.gui.BookmarkList.Bookmark;
40import org.openstreetmap.josm.gui.layer.Layer;
41import org.openstreetmap.josm.gui.layer.OsmDataLayer;
42import org.openstreetmap.josm.gui.layer.RawGpsDataLayer;
43import org.openstreetmap.josm.gui.layer.RawGpsDataLayer.GpsPoint;
44import org.openstreetmap.josm.io.OsmServerReader;
45import org.openstreetmap.josm.tools.GBC;
46import org.xml.sax.SAXException;
47
48/**
49 * Action that opens a connection to the osm server and download map data.
50 *
51 * An dialog is displayed asking the user to specify a rectangle to grab.
52 * The url and account settings from the preferences are used.
53 *
54 * @author imi
55 */
56public class DownloadAction extends JosmAction {
57
58 /**
59 * Open the download dialog and download the data.
60 * Run in the worker thread.
61 */
62 private final class DownloadOsmTask extends PleaseWaitRunnable {
63 private final OsmServerReader reader;
64 private DataSet dataSet;
65
66 private DownloadOsmTask(OsmServerReader reader) {
67 super("Downloading data");
68 this.reader = reader;
69 reader.setProgressInformation(currentAction, progress);
70 }
71
72 @Override public void realRun() throws IOException, SAXException {
73 dataSet = reader.parseOsm();
74 if (dataSet == null)
75 return;
76 if (dataSet.nodes.isEmpty())
77 JOptionPane.showMessageDialog(Main.main, "No data imported.");
78 }
79
80 @Override protected void finish() {
81 if (dataSet == null)
82 return; // user cancelled download or error occoured
83 Layer layer = new OsmDataLayer(dataSet, "Data Layer", false);
84 if (Main.main.getMapFrame() == null)
85 Main.main.setMapFrame(new MapFrame(layer));
86 else
87 Main.main.getMapFrame().mapView.addLayer(layer);
88 }
89
90 @Override protected void cancel() {
91 reader.cancel();
92 }
93 }
94
95
96 private final class DownloadGpsTask extends PleaseWaitRunnable {
97 private final OsmServerReader reader;
98 private Collection<Collection<GpsPoint>> rawData;
99
100 private DownloadGpsTask(OsmServerReader reader) {
101 super("Downloading GPS data");
102 this.reader = reader;
103 reader.setProgressInformation(currentAction, progress);
104 }
105
106 @Override public void realRun() throws IOException, JDOMException {
107 rawData = reader.parseRawGps();
108 }
109
110 @Override protected void finish() {
111 if (rawData == null)
112 return;
113 String name = latlon[0].getText() + " " + latlon[1].getText() + " x " + latlon[2].getText() + " " + latlon[3].getText();
114 Layer layer = new RawGpsDataLayer(rawData, name);
115 if (Main.main.getMapFrame() == null)
116 Main.main.setMapFrame(new MapFrame(layer));
117 else
118 Main.main.getMapFrame().mapView.addLayer(layer);
119 }
120
121 @Override protected void cancel() {
122 }
123 }
124
125
126 /**
127 * minlat, minlon, maxlat, maxlon
128 */
129 JTextField[] latlon = new JTextField[]{
130 new JTextField(9),
131 new JTextField(9),
132 new JTextField(9),
133 new JTextField(9)};
134 JCheckBox rawGps = new JCheckBox("Open as raw gps data", false);
135
136 public DownloadAction() {
137 super("Download from OSM", "download", "Download map data from the OSM server.", "Ctrl-Shift-D",
138 KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK));
139 // TODO remove when bug in Java6 is fixed
140 for (JTextField f : latlon)
141 f.setMinimumSize(new Dimension(100,new JTextField().getMinimumSize().height));
142 }
143
144 public void actionPerformed(ActionEvent e) {
145 String osmDataServer = Main.pref.get("osm-server.url");
146 //TODO: Remove this in later versions (temporary only)
147 if (osmDataServer.endsWith("/0.2") || osmDataServer.endsWith("/0.2/")) {
148 int answer = JOptionPane.showConfirmDialog(Main.main,
149 "You seem to have an outdated server entry in your preferences.\n" +
150 "\n" +
151 "As of JOSM Release 1.2, you must no longer specify the API version in\n" +
152 "the osm url. For the OSM standard server, use http://www.openstreetmap.org/api" +
153 "\n" +
154 "Fix settings and continue?", "Outdated server url detected.", JOptionPane.YES_NO_OPTION);
155 if (answer != JOptionPane.YES_OPTION)
156 return;
157 int cutPos = osmDataServer.endsWith("/0.2") ? 4 : 5;
158 Main.pref.put("osm-server.url", osmDataServer.substring(0, osmDataServer.length()-cutPos));
159 }
160
161 JPanel dlg = new JPanel(new GridBagLayout());
162
163 // World image
164 WorldChooser wc = new WorldChooser();
165 dlg.add(wc, GBC.eop());
166 wc.setToolTipText("Move and zoom the image like the main map. Select an area to download by dragging.");
167
168 // Bounding box edits
169 dlg.add(new JLabel("Bounding box"), GBC.eol());
170 dlg.add(new JLabel("min lat"), GBC.std().insets(10,0,5,0));
171 dlg.add(latlon[0], GBC.std());
172 dlg.add(new JLabel("min lon"), GBC.std().insets(10,0,5,0));
173 dlg.add(latlon[1], GBC.eol());
174 dlg.add(new JLabel("max lat"), GBC.std().insets(10,0,5,0));
175 dlg.add(latlon[2], GBC.std());
176 dlg.add(new JLabel("max lon"), GBC.std().insets(10,0,5,0));
177 dlg.add(latlon[3], GBC.eol());
178 if (Main.main.getMapFrame() != null) {
179 MapView mv = Main.main.getMapFrame().mapView;
180 setEditBounds(new Bounds(
181 mv.getLatLon(0, mv.getHeight()),
182 mv.getLatLon(mv.getWidth(), 0)));
183 rawGps.setSelected(mv.getActiveLayer() instanceof RawGpsDataLayer);
184 }
185 dlg.add(rawGps, GBC.eop());
186
187 // OSM url edit
188 dlg.add(new JLabel("URL from www.openstreetmap.org"), GBC.eol());
189 final JTextField osmUrl = new JTextField();
190 dlg.add(osmUrl, GBC.eop().fill(GBC.HORIZONTAL));
191 final KeyListener osmUrlRefresher = new KeyAdapter(){
192 @Override public void keyTyped(KeyEvent e) {
193 SwingUtilities.invokeLater(new Runnable() {
194 public void run() {
195 try {
196 double latMin = Double.parseDouble(latlon[0].getText());
197 double lonMin = Double.parseDouble(latlon[1].getText());
198 double latMax = Double.parseDouble(latlon[2].getText());
199 double lonMax = Double.parseDouble(latlon[3].getText());
200 double lat = (latMax+latMin)/2;
201 double lon = (lonMax+lonMin)/2;
202 // convert to mercator (for calculation of zoom only)
203 latMin = Math.log(Math.tan(Math.PI/4.0+latMin/180.0*Math.PI/2.0))*180.0/Math.PI;
204 latMax = Math.log(Math.tan(Math.PI/4.0+latMax/180.0*Math.PI/2.0))*180.0/Math.PI;
205 double size = Math.max(Math.abs(latMax-latMin), Math.abs(lonMax-lonMin));
206 int zoom = 0;
207 while (zoom <= 20) {
208 if (size >= 180)
209 break;
210 size *= 2;
211 zoom++;
212 }
213 osmUrl.setText("http://www.openstreetmap.org/index.html?lat="+lat+"&lon="+lon+"&zoom="+zoom);
214 } catch (NumberFormatException x) {
215 osmUrl.setText("");
216 }
217 osmUrl.setCaretPosition(0);
218 }
219 });
220 }
221 };
222 for (JTextField f : latlon)
223 f.addKeyListener(osmUrlRefresher);
224 SwingUtilities.invokeLater(new Runnable() {public void run() {osmUrlRefresher.keyTyped(null);}});
225 osmUrl.addKeyListener(new KeyAdapter(){
226 @Override public void keyTyped(KeyEvent e) {
227 SwingUtilities.invokeLater(new Runnable() {
228 public void run() {
229 Bounds b = osmurl2bounds(osmUrl.getText());
230 if (b != null)
231 setEditBounds(b);
232 else
233 for (JTextField f : latlon)
234 f.setText("");
235 }
236 });
237 }
238 });
239
240 // Bookmarks
241 dlg.add(new JLabel("Bookmarks"), GBC.eol());
242 final BookmarkList bookmarks = new BookmarkList();
243 bookmarks.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
244 public void valueChanged(ListSelectionEvent e) {
245 Bookmark b = (Bookmark)bookmarks.getSelectedValue();
246 for (int i = 0; i < 4; ++i) {
247 latlon[i].setText(b == null ? "" : ""+b.latlon[i]);
248 latlon[i].setCaretPosition(0);
249 }
250 rawGps.setSelected(b == null ? false : b.rawgps);
251 osmUrlRefresher.keyTyped(null);
252 }
253 });
254 wc.addListMarker(bookmarks);
255 dlg.add(new JScrollPane(bookmarks), GBC.eol().fill());
256
257 JPanel buttons = new JPanel(new GridLayout(1,2));
258 JButton add = new JButton("Add");
259 add.addActionListener(new ActionListener(){
260 public void actionPerformed(ActionEvent e) {
261 Bookmark b = readBookmark();
262 if (b == null) {
263 JOptionPane.showMessageDialog(Main.main, "Please enter the desired coordinates first.");
264 return;
265 }
266 b.name = JOptionPane.showInputDialog(Main.main, "Please enter a name for the location.");
267 if (b.name != null && !b.name.equals("")) {
268 ((DefaultListModel)bookmarks.getModel()).addElement(b);
269 bookmarks.save();
270 }
271 }
272 });
273 buttons.add(add);
274 JButton remove = new JButton("Remove");
275 remove.addActionListener(new ActionListener(){
276 public void actionPerformed(ActionEvent e) {
277 Object sel = bookmarks.getSelectedValue();
278 if (sel == null) {
279 JOptionPane.showMessageDialog(Main.main, "Select a bookmark first.");
280 return;
281 }
282 ((DefaultListModel)bookmarks.getModel()).removeElement(sel);
283 bookmarks.save();
284 }
285 });
286 buttons.add(remove);
287 dlg.add(buttons, GBC.eop().fill(GBC.HORIZONTAL));
288
289 Dimension d = dlg.getPreferredSize();
290 wc.setPreferredSize(new Dimension(d.width, d.width/2));
291 wc.addInputFields(latlon, osmUrl, osmUrlRefresher);
292
293 // Finally: the dialog
294 Bookmark b;
295 do {
296 int r = JOptionPane.showConfirmDialog(Main.main, dlg, "Choose an area",
297 JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
298 if (r != JOptionPane.OK_OPTION)
299 return;
300 b = readBookmark();
301 if (b == null)
302 JOptionPane.showMessageDialog(Main.main, "Please enter the desired coordinates or click on a bookmark.");
303 } while (b == null);
304
305 double minlon = b.latlon[0];
306 double minlat = b.latlon[1];
307 double maxlon = b.latlon[2];
308 double maxlat = b.latlon[3];
309 download(rawGps.isSelected(), minlon, minlat, maxlon, maxlat);
310 }
311
312 /**
313 * Read a bookmark from the current set edit fields. If one of the fields is
314 * empty or contain illegal chars, <code>null</code> is returned.
315 * The name of the bookmark is <code>null</code>.
316 * @return A bookmark containing information from the edit fields and rawgps
317 * checkbox.
318 */
319 Bookmark readBookmark() {
320 try {
321 Bookmark b = new Bookmark();
322 for (int i = 0; i < 4; ++i) {
323 if (latlon[i].getText().equals(""))
324 return null;
325 b.latlon[i] = Double.parseDouble(latlon[i].getText());
326 }
327 b.rawgps = rawGps.isSelected();
328 return b;
329 } catch (NumberFormatException x) {
330 return null;
331 }
332 }
333
334
335 public static Bounds osmurl2bounds(String url) {
336 int i = url.indexOf('?');
337 if (i == -1)
338 return null;
339 String[] args = url.substring(i+1).split("&");
340 HashMap<String, Double> map = new HashMap<String, Double>();
341 for (String arg : args) {
342 int eq = arg.indexOf('=');
343 if (eq != -1) {
344 try {
345 map.put(arg.substring(0, eq), Double.parseDouble(arg.substring(eq + 1)));
346 } catch (NumberFormatException e) {
347 }
348 }
349 }
350 try {
351 double size = 180.0 / Math.pow(2, map.get("zoom"));
352 return new Bounds(
353 new LatLon(map.get("lat") - size/2, map.get("lon") - size),
354 new LatLon(map.get("lat") + size/2, map.get("lon") + size));
355 } catch (Exception x) { // NPE or IAE
356 return null;
357 }
358 }
359
360 /**
361 * Set the four edit fields to the given bounds coordinates.
362 */
363 private void setEditBounds(Bounds b) {
364 LatLon bottomLeft = b.min;
365 LatLon topRight = b.max;
366 if (bottomLeft.isOutSideWorld())
367 bottomLeft = new LatLon(-89.999, -179.999); // do not use the Projection constants, since this looks better.
368 if (topRight.isOutSideWorld())
369 topRight = new LatLon(89.999, 179.999);
370 latlon[0].setText(""+bottomLeft.lat());
371 latlon[1].setText(""+bottomLeft.lon());
372 latlon[2].setText(""+topRight.lat());
373 latlon[3].setText(""+topRight.lon());
374 for (JTextField f : latlon)
375 f.setCaretPosition(0);
376 }
377
378 /**
379 * Do the download for the given area.
380 */
381 public void download(boolean rawGps, double minlat, double minlon, double maxlat, double maxlon) {
382 OsmServerReader reader = new OsmServerReader(minlat, minlon, maxlat, maxlon);
383 PleaseWaitRunnable task = rawGps ? new DownloadGpsTask(reader) : new DownloadOsmTask(reader);
384 Main.worker.execute(task);
385 task.pleaseWaitDlg.setVisible(true);
386 }
387}
Note: See TracBrowser for help on using the repository browser.