]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/function/DownloadOsmFunction.java
76c69da7f928aa3099e383c5603a06de11997025
[GpsPrune.git] / tim / prune / function / DownloadOsmFunction.java
1 package tim.prune.function;
2
3 import java.awt.BorderLayout;
4 import java.awt.Component;
5 import java.awt.FlowLayout;
6 import java.awt.GridLayout;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
9 import java.io.File;
10 import java.io.FileOutputStream;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.net.MalformedURLException;
14 import java.net.URL;
15 import java.text.NumberFormat;
16
17 import javax.swing.BorderFactory;
18 import javax.swing.BoxLayout;
19 import javax.swing.JButton;
20 import javax.swing.JDialog;
21 import javax.swing.JFileChooser;
22 import javax.swing.JLabel;
23 import javax.swing.JOptionPane;
24 import javax.swing.JPanel;
25 import javax.swing.JProgressBar;
26
27 import tim.prune.App;
28 import tim.prune.GenericFunction;
29 import tim.prune.I18nManager;
30 import tim.prune.data.DoubleRange;
31
32 /**
33  * Class to allow the download of OSM data (using the XAPI)
34  * for the area covered by the data
35  */
36 public class DownloadOsmFunction extends GenericFunction implements Runnable
37 {
38         private JDialog _dialog = null;
39         private JLabel[] _latLonLabels = null;
40         private JProgressBar _progressBar = null;
41         private JButton _okButton = null;
42         private JFileChooser _fileChooser = null;
43         private File _selectedFile = null;
44         private boolean _cancelled = false;
45         /** Number formatter */
46         private final NumberFormat FORMAT_TWO_DP = NumberFormat.getNumberInstance();
47
48
49         /**
50          * Constructor
51          * @param inApp application object for callback
52          */
53         public DownloadOsmFunction(App inApp)
54         {
55                 super(inApp);
56                 FORMAT_TWO_DP.setMaximumFractionDigits(2);
57                 FORMAT_TWO_DP.setMinimumFractionDigits(2);
58         }
59
60         /** Get the name key */
61         public String getNameKey() {
62                 return "function.downloadosm";
63         }
64
65         /**
66          * Begin the function
67          */
68         public void begin()
69         {
70                 // Make dialog window
71                 if (_dialog == null)
72                 {
73                         _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), true);
74                         _dialog.setLocationRelativeTo(_parentFrame);
75                         _dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
76                         _dialog.getContentPane().add(makeDialogComponents());
77                         _dialog.pack();
78                         _fileChooser = new JFileChooser();
79                         _fileChooser.setSelectedFile(new File("data.osm"));
80                 }
81                 initDialog();
82                 _dialog.setVisible(true);
83         }
84
85
86         /**
87          * Create dialog components
88          * @return Panel containing all gui elements in dialog
89          */
90         private Component makeDialogComponents()
91         {
92                 JPanel dialogPanel = new JPanel();
93                 dialogPanel.setLayout(new BorderLayout(0, 10));
94                 dialogPanel.add(new JLabel(I18nManager.getText("dialog.downloadosm.desc")), BorderLayout.NORTH);
95                 // grid of labels to show lat/long extent
96                 JPanel gridPanel = new JPanel();
97                 gridPanel.setLayout(new GridLayout(3, 3));
98                 _latLonLabels = new JLabel[4];
99                 for (int i=0; i<4; i++) {
100                         _latLonLabels[i] = new JLabel("0");
101                 }
102                 int lNum = 0;
103                 for (int i=0; i<4; i++) {
104                         gridPanel.add(new JLabel(" "));
105                         gridPanel.add(_latLonLabels[lNum++]);
106                 }
107                 // layout main panel
108                 JPanel mainPanel = new JPanel();
109                 mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
110                 mainPanel.add(gridPanel);
111                 _progressBar = new JProgressBar();
112                 _progressBar.setIndeterminate(true);
113                 mainPanel.add(_progressBar);
114                 dialogPanel.add(mainPanel, BorderLayout.CENTER);
115                 // button panel at bottom
116                 JPanel buttonPanel = new JPanel();
117                 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
118                 _okButton = new JButton(I18nManager.getText("button.ok"));
119                 ActionListener okListener = new ActionListener() {
120                         public void actionPerformed(ActionEvent e) {
121                                 finish();
122                         }
123                 };
124                 _okButton.addActionListener(okListener);
125                 buttonPanel.add(_okButton);
126                 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
127                 cancelButton.addActionListener(new ActionListener() {
128                         public void actionPerformed(ActionEvent e) {
129                                 _cancelled = true;
130                                 _dialog.dispose();
131                         }
132                 });
133                 buttonPanel.add(cancelButton);
134                 dialogPanel.add(buttonPanel, BorderLayout.SOUTH);
135                 dialogPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 15));
136                 return dialogPanel;
137         }
138
139         /**
140          * Initialise the values of the labels in the dialog
141          */
142         private void initDialog()
143         {
144                 // Get range of data
145                 String[] lats = expandRange(_app.getTrackInfo().getTrack().getLatRange());
146                 String[] lons = expandRange(_app.getTrackInfo().getTrack().getLonRange());
147                 _latLonLabels[0].setText(lats[1]); // max lat
148                 _latLonLabels[1].setText(lons[0]); // min lon
149                 _latLonLabels[2].setText(lons[1]); // max lon
150                 _latLonLabels[3].setText(lats[0]); // min lat
151                 _okButton.setEnabled(true);
152                 _progressBar.setVisible(false);
153                 _cancelled = false;
154         }
155
156         /**
157          * Expand the given range to reasonable limits
158          * @param inRange range of lat/long values
159          * @return expanded range as pair of Strings
160          */
161         private String[] expandRange(DoubleRange inRange)
162         {
163                 double mid = (inRange.getMaximum() + inRange.getMinimum()) / 2.0;
164                 double range = inRange.getRange();
165                 double max = 0.0, min = 0.0;
166                 // Expand range to at least 0.02 degree
167                 if (range < 0.02)
168                 {
169                         min = mid - 0.01;
170                         max = mid + 0.01;
171                 }
172                 else {
173                         // expand by 10% in both directions
174                         min = mid - range * 0.55;
175                         max = mid + range * 0.55;
176                 }
177                 // Round min down to 0.01 degree
178                 int minCents = (int) (100 * min);
179                 // Round max upwards likewise
180                 int maxCents = (int) (100 * max + 1);
181                 final String[] answer = new String[] {FORMAT_TWO_DP.format(minCents/100.0),
182                         FORMAT_TWO_DP.format(maxCents/100.0)};
183                 return answer;
184         }
185
186         /**
187          * Finish the dialog when OK pressed
188          */
189         private void finish()
190         {
191                 if (!_okButton.isEnabled()) return;
192                 _selectedFile = selectOsmFile();
193                 if (_selectedFile != null)
194                 {
195                         // Show progress bar
196                         _okButton.setEnabled(false);
197                         _progressBar.setVisible(true);
198                         new Thread(this).start();
199                 }
200                 else
201                         _dialog.dispose();
202         }
203
204         /**
205          * Select a file to save the OSM data to
206          * @return selected file or null if cancelled
207          */
208         private File selectOsmFile()
209         {
210                 File saveFile = null;
211                 boolean chooseAgain = false;
212                 do
213                 {
214                         chooseAgain = false;
215                         if (_fileChooser.showSaveDialog(_dialog) == JFileChooser.APPROVE_OPTION)
216                         {
217                                 // OK pressed and file chosen
218                                 File file = _fileChooser.getSelectedFile();
219                                 // Check if file exists and if necessary prompt for overwrite
220                                 Object[] buttonTexts = {I18nManager.getText("button.overwrite"), I18nManager.getText("button.cancel")};
221                                 if (!file.exists() || JOptionPane.showOptionDialog(_dialog,
222                                                 I18nManager.getText("dialog.save.overwrite.text"),
223                                                 I18nManager.getText("dialog.save.overwrite.title"), JOptionPane.YES_NO_OPTION,
224                                                 JOptionPane.WARNING_MESSAGE, null, buttonTexts, buttonTexts[1])
225                                         == JOptionPane.YES_OPTION)
226                                 {
227                                         // new file or overwrite confirmed
228                                         saveFile = file;
229                                 }
230                                 else
231                                 {
232                                         // file exists and overwrite cancelled - select again
233                                         chooseAgain = true;
234                                 }
235                         }
236                 } while (chooseAgain);
237                 return saveFile;
238         }
239
240
241         /**
242          * Do the actual download - launched to run in another thread
243          */
244         public void run()
245         {
246                 final String url = "http://www.overpass-api.de/api/xapi?map?bbox=" +
247                         _latLonLabels[1].getText() + "," + _latLonLabels[3].getText() + "," +
248                         _latLonLabels[2].getText() + "," + _latLonLabels[0].getText();
249
250                 byte[] buffer = new byte[1024];
251                 InputStream inStream = null;
252                 FileOutputStream outStream = null;
253                 int numBytesRead = 0;
254                 try
255                 {
256                         inStream = new URL(url).openStream();
257                         outStream = new FileOutputStream(_selectedFile);
258                         // Loop and copy bytes to file
259                         while ((numBytesRead = inStream.read(buffer)) > -1 && !_cancelled)
260                         {
261                                 outStream.write(buffer, 0, numBytesRead);
262                         }
263                 }
264                 catch (MalformedURLException mue) {}
265                 catch (IOException ioe) {
266                         _app.showErrorMessageNoLookup(getNameKey(), ioe.getClass().getName() + " - " + ioe.getMessage());
267                 }
268                 // clean up streams
269                 finally {
270                         try {inStream.close();} catch (Exception e) {}
271                         try {outStream.close();} catch (Exception e) {}
272                 }
273                 // close dialog
274                 _dialog.dispose();
275         }
276 }