ab5e433d46d2f0cd4dd650461654b51b2c7ffcdb
[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         private AltosMapLoader  loader;
73
74         long    loader_notify_time;
75
76         /* AltosMapLoaderListener interfaces */
77         public void loader_start(final int max) {
78                 this.runOnUiThread(new Runnable() {
79                                 public void run() {
80                                         progress.setMax(max);
81                                         progress.setProgress(0);
82                                 }
83                         });
84         }
85
86         public void loader_notify(final int cur, final int max, final String name) {
87                 this.runOnUiThread(new Runnable() {
88                                 public void run() {
89                                         progress.setProgress(cur);
90                                 }
91                         });
92         }
93
94         public void loader_done(int max) {
95                 loader = null;
96                 this.runOnUiThread(new Runnable() {
97                                 public void run() {
98                                         progress.setProgress(0);
99                                         finish();
100                                 }
101                         });
102         }
103
104         /* AltosLaunchSiteListener interface */
105         public void notify_launch_sites(final List<AltosLaunchSite> sites) {
106                 this.runOnUiThread(new Runnable() {
107                                 public void run() {
108                                         for (AltosLaunchSite site : sites)
109                                                 known_sites_adapter.add(site);
110                                 }
111                         });
112         }
113
114         AltosMap        map;
115
116         class PreloadMapImage implements AltosImage {
117                 public void flush() {
118                 }
119
120                 public PreloadMapImage(File file) {
121                 }
122         }
123
124         public AltosMapPath new_path() {
125                 return null;
126         }
127
128         public AltosMapLine new_line() {
129                 return null;
130         }
131
132         public AltosImage load_image(File file) throws Exception {
133                 return new PreloadMapImage(file);
134         }
135
136         public AltosMapMark new_mark(double lat, double lon, int state) {
137                 return null;
138         }
139
140         class PreloadMapTile extends AltosMapTile {
141                 public void paint(AltosMapTransform t) {
142                 }
143
144                 public PreloadMapTile(AltosMapCache cache, AltosLatLon upper_left, AltosLatLon center, int zoom, int maptype, int px_size) {
145                         super(cache, upper_left, center, zoom, maptype, px_size, 2);
146                 }
147
148         }
149
150         public AltosMapTile new_tile(AltosMapCache cache, AltosLatLon upper_left, AltosLatLon center, int zoom, int maptype, int px_size) {
151                 return new PreloadMapTile(cache, upper_left, center, zoom, maptype, px_size);
152         }
153
154         public int width() {
155                 return AltosMap.px_size;
156         }
157
158         public int height() {
159                 return AltosMap.px_size;
160         }
161
162         public void repaint() {
163         }
164
165         public void repaint(AltosRectangle damage) {
166         }
167
168         public void set_zoom_label(String label) {
169         }
170
171         public void select_object(AltosLatLon latlon) {
172         }
173
174         public void debug(String format, Object ... arguments) {
175                 AltosDebug.debug(format, arguments);
176         }
177
178         /* LocationProvider interface */
179
180         AltosLaunchSite current_location_site;
181
182         public void onLocationChanged(Location location) {
183                 AltosDebug.debug("location changed");
184                 if (current_location_site == null) {
185                         AltosLaunchSite selected_item = (AltosLaunchSite) known_sites_spinner.getSelectedItem();
186
187                         current_location_site = new AltosLaunchSite("Current Location", location.getLatitude(), location.getLongitude());
188                         known_sites_adapter.insert(current_location_site, 0);
189
190                         if (selected_item != null)
191                                 known_sites_spinner.setSelection(known_sites_adapter.getPosition(selected_item));
192                         else {
193                                 latitude.setText(new StringBuffer(String.format("%12.6f", current_location_site.latitude)));
194                                 longitude.setText(new StringBuffer(String.format("%12.6f", current_location_site.longitude)));
195                         }
196                 } else {
197                         current_location_site.latitude = location.getLatitude();
198                         current_location_site.longitude = location.getLongitude();
199                 }
200         }
201
202         public void onStatusChanged(String provider, int status, Bundle extras) {
203         }
204
205         public void onProviderEnabled(String provider) {
206         }
207
208         public void onProviderDisabled(String provider) {
209         }
210
211         private double text(EditText view) throws ParseException {
212                 return AltosParse.parse_double_locale(view.getEditableText().toString());
213         }
214
215         private double latitude() throws ParseException {
216                 return text(latitude);
217         }
218
219         private double longitude() throws ParseException {
220                 return text(longitude);
221         }
222
223         private int value(Spinner spinner) {
224                 return (Integer) spinner.getSelectedItem();
225         }
226
227         private int min_z() {
228                 return value(min_zoom);
229         }
230
231         private int max_z() {
232                 return value(max_zoom);
233         }
234
235         private double value_distance(Spinner spinner) {
236                 return (Double) spinner.getSelectedItem();
237         }
238
239         private double radius() {
240                 double r = value_distance(radius);
241                 if (AltosPreferences.imperial_units())
242                         r = AltosConvert.miles_to_meters(r);
243                 else
244                         r = r * 1000;
245                 return r;
246         }
247
248         private int bit(CheckBox box, int value) {
249                 if (box.isChecked())
250                         return 1 << value;
251                 return 0;
252         }
253
254         private int types() {
255                 return (bit(hybrid, AltosMap.maptype_hybrid) |
256                         bit(satellite, AltosMap.maptype_satellite) |
257                         bit(roadmap, AltosMap.maptype_roadmap) |
258                         bit(terrain, AltosMap.maptype_terrain));
259         }
260
261         private void load() {
262                 if (loader != null)
263                         return;
264
265                 try {
266                         double  lat = latitude();
267                         double  lon = longitude();
268                         int     min = min_z();
269                         int     max = max_z();
270                         double  r = radius();
271                         int     t = types();
272
273                         AltosDebug.debug("PreloadMap load %f %f %d %d %f %d\n",
274                                          lat, lon, min, max, r, t);
275                         loader = new AltosMapLoader(map, this, lat, lon, min, max, r, t);
276                 } catch (ParseException e) {
277                         AltosDebug.debug("PreloadMap load raised exception %s", e.toString());
278                 }
279         }
280
281         private void add_numbers(Spinner spinner, int min, int max, int def) {
282
283                 ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item);
284
285                 int     spinner_def = 0;
286                 int     pos = 0;
287
288                 for (int i = min; i <= max; i++) {
289                         adapter.add(new Integer(i));
290                         if (i == def)
291                                 spinner_def = pos;
292                         pos++;
293                 }
294
295                 spinner.setAdapter(adapter);
296                 spinner.setSelection(spinner_def);
297         }
298
299
300         private void add_distance(Spinner spinner, double[] distances_km, double def_km, double[] distances_mi, double def_mi) {
301
302                 ArrayAdapter<Double> adapter = new ArrayAdapter<Double>(this, android.R.layout.simple_spinner_item);
303
304                 int     spinner_def = 0;
305                 int     pos = 0;
306
307                 double[] distances;
308                 double  def;
309                 if (AltosPreferences.imperial_units()) {
310                         distances = distances_mi;
311                         def = def_mi;
312                 } else {
313                         distances = distances_km;
314                         def = def_km;
315                 }
316
317                 for (int i = 0; i < distances.length; i++) {
318                         adapter.add(distances[i]);
319                         if (distances[i] == def)
320                                 spinner_def = pos;
321                         pos++;
322                 }
323
324                 spinner.setAdapter(adapter);
325                 spinner.setSelection(spinner_def);
326         }
327
328
329
330         class SiteListListener implements OnItemSelectedListener {
331                 public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
332                         AltosLaunchSite site = (AltosLaunchSite) parent.getItemAtPosition(pos);
333                         latitude.setText(new StringBuffer(String.format("%12.6f", site.latitude)));
334                         longitude.setText(new StringBuffer(String.format("%12.6f", site.longitude)));
335                 }
336                 public void onNothingSelected(AdapterView<?> parent) {
337                 }
338
339                 public SiteListListener() {
340                 }
341         }
342
343         double[]        radius_mi = { 1, 2, 5, 10, 20 };
344         double          radius_def_mi = 2;
345         double[]        radius_km = { 1, 2, 5, 10, 20, 30 };
346         double          radius_def_km = 2;
347
348         @Override
349         protected void onCreate(Bundle savedInstanceState) {
350                 super.onCreate(savedInstanceState);
351
352                 // Setup the window
353                 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
354                 setContentView(R.layout.map_preload);
355
356                 // Set result CANCELED incase the user backs out
357                 setResult(Activity.RESULT_CANCELED);
358
359                 // Initialize the button to perform device discovery
360                 Button loadButton = (Button) findViewById(R.id.preload_load);
361                 loadButton.setOnClickListener(new OnClickListener() {
362                         public void onClick(View v) {
363                                 load();
364                         }
365                 });
366
367                 latitude = (EditText) findViewById(R.id.preload_latitude);
368                 longitude = (EditText) findViewById(R.id.preload_longitude);
369
370                 hybrid = (CheckBox) findViewById(R.id.preload_hybrid);
371                 satellite = (CheckBox) findViewById(R.id.preload_satellite);
372                 roadmap = (CheckBox) findViewById(R.id.preload_roadmap);
373                 terrain = (CheckBox) findViewById(R.id.preload_terrain);
374
375                 hybrid.setChecked(true);
376
377                 min_zoom = (Spinner) findViewById(R.id.preload_min_zoom);
378                 add_numbers(min_zoom,
379                             AltosMap.min_zoom - AltosMap.default_zoom,
380                             AltosMap.max_zoom - AltosMap.default_zoom, -2);
381                 max_zoom = (Spinner) findViewById(R.id.preload_max_zoom);
382                 add_numbers(max_zoom,
383                             AltosMap.min_zoom - AltosMap.default_zoom,
384                             AltosMap.max_zoom - AltosMap.default_zoom, 2);
385                 radius_label = (TextView) findViewById(R.id.preload_radius_label);
386                 radius = (Spinner) findViewById(R.id.preload_radius);
387                 if (AltosPreferences.imperial_units())
388                         radius_label.setText("Radius (miles)");
389                 else
390                         radius_label.setText("Radius (km)");
391                 add_distance(radius, radius_km, radius_def_km, radius_mi, radius_def_mi);
392
393                 progress = (ProgressBar) findViewById(R.id.preload_progress);
394
395                 // Initialize array adapters. One for already paired devices and
396                 // one for newly discovered devices
397                 known_sites_spinner = (Spinner) findViewById(R.id.preload_site_list);
398
399                 known_sites_adapter = new ArrayAdapter<AltosLaunchSite>(this, android.R.layout.simple_spinner_item);
400
401                 known_sites_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
402
403                 known_sites_spinner.setAdapter(known_sites_adapter);
404                 known_sites_spinner.setOnItemSelectedListener(new SiteListListener());
405
406                 map = new AltosMap(this);
407
408                 // Listen for GPS and Network position updates
409                 LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
410
411                 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
412
413                 new AltosLaunchSites(this);
414         }
415
416         @Override
417         protected void onDestroy() {
418                 super.onDestroy();
419
420                 if (loader != null)
421                         loader.abort();
422
423                 // Stop listening for location updates
424                 ((LocationManager) getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
425         }
426 }