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