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

Last change on this file since 86 was 86, checked in by imi, 18 years ago
  • added conflicts and resolve conflict dialog

This is one of those "changed everything" checkpoint.

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