altoslib: Switch distance from m/ft to km/miles for large values
[fw/altos] / altosdroid / src / org / altusmetrum / AltosDroid / PreloadMapActivity.java
1 /*
2  * Copyright © 2015 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package org.altusmetrum.AltosDroid;
19
20 import java.util.*;
21 import java.io.*;
22 import java.text.*;
23
24 import org.altusmetrum.AltosDroid.R;
25
26 import android.app.Activity;
27 import android.bluetooth.BluetoothAdapter;
28 import android.bluetooth.BluetoothDevice;
29 import android.content.BroadcastReceiver;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.os.Bundle;
34 import android.view.View;
35 import android.view.Window;
36 import android.view.View.OnClickListener;
37 import android.widget.*;
38 import android.widget.AdapterView.*;
39 import android.location.Location;
40 import android.location.LocationManager;
41 import android.location.LocationListener;
42 import android.location.Criteria;
43
44 import org.altusmetrum.altoslib_10.*;
45
46 /**
47  * This Activity appears as a dialog. It lists any paired devices and
48  * devices detected in the area after discovery. When a device is chosen
49  * by the user, the MAC address of the device is sent back to the parent
50  * Activity in the result Intent.
51  */
52 public class PreloadMapActivity extends Activity implements AltosLaunchSiteListener, AltosMapInterface, AltosMapLoaderListener, LocationListener {
53
54         private ArrayAdapter<AltosLaunchSite> known_sites_adapter;
55
56         private CheckBox        hybrid;
57         private CheckBox        satellite;
58         private CheckBox        roadmap;
59         private CheckBox        terrain;
60
61         private Spinner         known_sites_spinner;
62         private Spinner         min_zoom;
63         private Spinner         max_zoom;
64         private TextView        radius_label;
65         private Spinner         radius;
66
67         private EditText        latitude;
68         private EditText        longitude;
69
70         private ProgressBar     progress;
71
72         /* AltosMapLoaderListener interfaces */
73         public void loader_start(final int max) {
74                 this.runOnUiThread(new Runnable() {
75                                 public void run() {
76                                         progress.setMax(max);
77                                         progress.setProgress(0);
78                                 }
79                         });
80         }
81
82         public void loader_notify(final int cur, final int max, final String name) {
83                 this.runOnUiThread(new Runnable() {
84                                 public void run() {
85                                         progress.setProgress(cur);
86                                 }
87                         });
88         }
89
90         public void loader_done(int max) {
91                 this.runOnUiThread(new Runnable() {
92                                 public void run() {
93                                         progress.setProgress(0);
94                                         finish();
95                                 }
96                         });
97         }
98
99         /* AltosLaunchSiteListener interface */
100         public void notify_launch_sites(final List<AltosLaunchSite> sites) {
101                 this.runOnUiThread(new Runnable() {
102                                 public void run() {
103                                         for (AltosLaunchSite site : sites)
104                                                 known_sites_adapter.add(site);
105                                 }
106                         });
107         }
108
109         AltosMap        map;
110
111         class PreloadMapImage implements AltosImage {
112                 public void flush() {
113                 }
114
115                 public PreloadMapImage(File file) {
116                 }
117         }
118
119         public AltosMapPath new_path() {
120                 return null;
121         }
122
123         public AltosMapLine new_line() {
124                 return null;
125         }
126
127         public AltosImage load_image(File file) throws Exception {
128                 return new PreloadMapImage(file);
129         }
130
131         public AltosMapMark new_mark(double lat, double lon, int state) {
132                 return null;
133         }
134
135         class PreloadMapTile extends AltosMapTile {
136                 public void paint(AltosMapTransform t) {
137                 }
138
139                 public PreloadMapTile(AltosMapCache cache, AltosLatLon upper_left, AltosLatLon center, int zoom, int maptype, int px_size) {
140                         super(cache, upper_left, center, zoom, maptype, px_size, 2);
141                 }
142
143         }
144
145         public AltosMapTile new_tile(AltosMapCache cache, AltosLatLon upper_left, AltosLatLon center, int zoom, int maptype, int px_size) {
146                 return new PreloadMapTile(cache, upper_left, center, zoom, maptype, px_size);
147         }
148
149         public int width() {
150                 return AltosMap.px_size;
151         }
152
153         public int height() {
154                 return AltosMap.px_size;
155         }
156
157         public void repaint() {
158         }
159
160         public void repaint(AltosRectangle damage) {
161         }
162
163         public void set_zoom_label(String label) {
164         }
165
166         public void select_object(AltosLatLon latlon) {
167         }
168
169         public void debug(String format, Object ... arguments) {
170                 AltosDebug.debug(format, arguments);
171         }
172
173         /* LocationProvider interface */
174
175         AltosLaunchSite current_location_site;
176
177         public void onLocationChanged(Location location) {
178                 AltosDebug.debug("location changed");
179                 if (current_location_site == null) {
180                         AltosLaunchSite selected_item = (AltosLaunchSite) known_sites_spinner.getSelectedItem();
181
182                         current_location_site = new AltosLaunchSite("Current Location", location.getLatitude(), location.getLongitude());
183                         known_sites_adapter.insert(current_location_site, 0);
184
185                         if (selected_item != null)
186                                 known_sites_spinner.setSelection(known_sites_adapter.getPosition(selected_item));
187                         else {
188                                 latitude.setText(new StringBuffer(String.format("%12.6f", current_location_site.latitude)));
189                                 longitude.setText(new StringBuffer(String.format("%12.6f", current_location_site.longitude)));
190                         }
191                 } else {
192                         current_location_site.latitude = location.getLatitude();
193                         current_location_site.longitude = location.getLongitude();
194                 }
195         }
196
197         public void onStatusChanged(String provider, int status, Bundle extras) {
198         }
199
200         public void onProviderEnabled(String provider) {
201         }
202
203         public void onProviderDisabled(String provider) {
204         }
205
206         private double text(EditText view) throws ParseException {
207                 return AltosParse.parse_double_locale(view.getEditableText().toString());
208         }
209
210         private double latitude() throws ParseException {
211                 return text(latitude);
212         }
213
214         private double longitude() throws ParseException {
215                 return text(longitude);
216         }
217
218         private int value(Spinner spinner) {
219                 return (Integer) spinner.getSelectedItem();
220         }
221
222         private int min_z() {
223                 return value(min_zoom);
224         }
225
226         private int max_z() {
227                 return value(max_zoom);
228         }
229
230         private double value_distance(Spinner spinner) {
231                 return (Double) spinner.getSelectedItem();
232         }
233
234         private double radius() {
235                 double r = value_distance(radius);
236                 if (AltosPreferences.imperial_units())
237                         r = AltosConvert.miles_to_meters(r);
238                 else
239                         r = r * 1000;
240                 return r;
241         }
242
243         private int bit(CheckBox box, int value) {
244                 if (box.isChecked())
245                         return 1 << value;
246                 return 0;
247         }
248
249         private int types() {
250                 return (bit(hybrid, AltosMap.maptype_hybrid) |
251                         bit(satellite, AltosMap.maptype_satellite) |
252                         bit(roadmap, AltosMap.maptype_roadmap) |
253                         bit(terrain, AltosMap.maptype_terrain));
254         }
255
256         private void load() {
257                 try {
258                         double  lat = latitude();
259                         double  lon = longitude();
260                         int     min = min_z();
261                         int     max = max_z();
262                         double  r = radius();
263                         int     t = types();
264
265                         AltosDebug.debug("PreloadMap load %f %f %d %d %f %d\n",
266                                          lat, lon, min, max, r, t);
267                         new AltosMapLoader(map, this, lat, lon, min, max, r, t);
268                 } catch (ParseException e) {
269                         AltosDebug.debug("PreloadMap load raised exception %s", e.toString());
270                 }
271         }
272
273         private void add_numbers(Spinner spinner, int min, int max, int def) {
274
275                 ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item);
276
277                 int     spinner_def = 0;
278                 int     pos = 0;
279
280                 for (int i = min; i <= max; i++) {
281                         adapter.add(new Integer(i));
282                         if (i == def)
283                                 spinner_def = pos;
284                         pos++;
285                 }
286
287                 spinner.setAdapter(adapter);
288                 spinner.setSelection(spinner_def);
289         }
290
291
292         private void add_distance(Spinner spinner, double[] distances_km, double def_km, double[] distances_mi, double def_mi) {
293
294                 ArrayAdapter<Double> adapter = new ArrayAdapter<Double>(this, android.R.layout.simple_spinner_item);
295
296                 int     spinner_def = 0;
297                 int     pos = 0;
298
299                 double[] distances;
300                 double  def;
301                 if (AltosPreferences.imperial_units()) {
302                         distances = distances_mi;
303                         def = def_mi;
304                 } else {
305                         distances = distances_km;
306                         def = def_km;
307                 }
308
309                 for (int i = 0; i < distances.length; i++) {
310                         adapter.add(distances[i]);
311                         if (distances[i] == def)
312                                 spinner_def = pos;
313                         pos++;
314                 }
315
316                 spinner.setAdapter(adapter);
317                 spinner.setSelection(spinner_def);
318         }
319
320
321
322         class SiteListListener implements OnItemSelectedListener {
323                 public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
324                         AltosLaunchSite site = (AltosLaunchSite) parent.getItemAtPosition(pos);
325                         latitude.setText(new StringBuffer(String.format("%12.6f", site.latitude)));
326                         longitude.setText(new StringBuffer(String.format("%12.6f", site.longitude)));
327                 }
328                 public void onNothingSelected(AdapterView<?> parent) {
329                 }
330
331                 public SiteListListener() {
332                 }
333         }
334
335         double[]        radius_mi = { 1, 2, 5, 10, 20 };
336         double          radius_def_mi = 2;
337         double[]        radius_km = { 1, 2, 5, 10, 20, 30 };
338         double          radius_def_km = 2;
339
340         @Override
341         protected void onCreate(Bundle savedInstanceState) {
342                 super.onCreate(savedInstanceState);
343
344                 // Setup the window
345                 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
346                 setContentView(R.layout.map_preload);
347
348                 // Set result CANCELED incase the user backs out
349                 setResult(Activity.RESULT_CANCELED);
350
351                 // Initialize the button to perform device discovery
352                 Button loadButton = (Button) findViewById(R.id.preload_load);
353                 loadButton.setOnClickListener(new OnClickListener() {
354                         public void onClick(View v) {
355                                 load();
356                         }
357                 });
358
359                 latitude = (EditText) findViewById(R.id.preload_latitude);
360                 longitude = (EditText) findViewById(R.id.preload_longitude);
361
362                 hybrid = (CheckBox) findViewById(R.id.preload_hybrid);
363                 satellite = (CheckBox) findViewById(R.id.preload_satellite);
364                 roadmap = (CheckBox) findViewById(R.id.preload_roadmap);
365                 terrain = (CheckBox) findViewById(R.id.preload_terrain);
366
367                 hybrid.setChecked(true);
368
369                 min_zoom = (Spinner) findViewById(R.id.preload_min_zoom);
370                 add_numbers(min_zoom,
371                             AltosMap.min_zoom - AltosMap.default_zoom,
372                             AltosMap.max_zoom - AltosMap.default_zoom, -2);
373                 max_zoom = (Spinner) findViewById(R.id.preload_max_zoom);
374                 add_numbers(max_zoom,
375                             AltosMap.min_zoom - AltosMap.default_zoom,
376                             AltosMap.max_zoom - AltosMap.default_zoom, 2);
377                 radius_label = (TextView) findViewById(R.id.preload_radius_label);
378                 radius = (Spinner) findViewById(R.id.preload_radius);
379                 if (AltosPreferences.imperial_units())
380                         radius_label.setText("Radius (miles)");
381                 else
382                         radius_label.setText("Radius (km)");
383                 add_distance(radius, radius_km, radius_def_km, radius_mi, radius_def_mi);
384
385                 progress = (ProgressBar) findViewById(R.id.preload_progress);
386
387                 // Initialize array adapters. One for already paired devices and
388                 // one for newly discovered devices
389                 known_sites_spinner = (Spinner) findViewById(R.id.preload_site_list);
390
391                 known_sites_adapter = new ArrayAdapter<AltosLaunchSite>(this, android.R.layout.simple_spinner_item);
392
393                 known_sites_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
394
395                 known_sites_spinner.setAdapter(known_sites_adapter);
396                 known_sites_spinner.setOnItemSelectedListener(new SiteListListener());
397
398                 map = new AltosMap(this);
399
400                 // Listen for GPS and Network position updates
401                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
402
403                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
404
405                 new AltosLaunchSites(this);
406         }
407
408         @Override
409         protected void onDestroy() {
410                 super.onDestroy();
411
412                 // Stop listening for location updates
413                 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
414         }
415 }