aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/cgeopoint.java
blob: bd2ec6f4f168a3fd1db23265d816facac6bf810d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
package cgeo.geocaching;

import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.apps.cache.navi.NavigationAppFactory;
import cgeo.geocaching.geopoint.DistanceParser;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.geopoint.GeopointFormatter;
import cgeo.geocaching.ui.Formatter;
import cgeo.geocaching.utils.IObserver;
import cgeo.geocaching.utils.Log;

import org.apache.commons.lang3.StringUtils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.List;

public class cgeopoint extends AbstractActivity implements IObserver<IGeoData> {
    private static final int MENU_DEFAULT_NAVIGATION = 2;
    private static final int MENU_NAVIGATE = 0;
    private static final int MENU_CACHES_AROUND = 5;
    private static final int MENU_CLEAR_HISTORY = 6;

    private static class DestinationHistoryAdapter extends ArrayAdapter<Destination> {
        private LayoutInflater inflater = null;

        public DestinationHistoryAdapter(Context context,
                List<Destination> objects) {
            super(context, 0, objects);
        }

        @Override
        public View getView(final int position, final View convertView, final ViewGroup parent) {

            Destination loc = getItem(position);

            View v = convertView;

            if (v == null) {
                v = getInflater().inflate(R.layout.simple_way_point,
                        null);
            }
            TextView longitude = (TextView) v
                    .findViewById(R.id.simple_way_point_longitude);
            TextView latitude = (TextView) v
                    .findViewById(R.id.simple_way_point_latitude);
            TextView date = (TextView) v.findViewById(R.id.date);

            String lonString = loc.getCoords().format(GeopointFormatter.Format.LON_DECMINUTE);
            String latString = loc.getCoords().format(GeopointFormatter.Format.LAT_DECMINUTE);

            longitude.setText(lonString);
            latitude.setText(latString);
            date.setText(Formatter.formatShortDateTime(getContext(), loc.getDate()));

            return v;
        }

        private LayoutInflater getInflater() {
            if (inflater == null) {
                inflater = ((Activity) getContext()).getLayoutInflater();
            }

            return inflater;
        }
    }

    private Button latButton = null;
    private Button lonButton = null;
    private boolean changed = false;
    private List<Destination> historyOfSearchedLocations;
    private DestinationHistoryAdapter destionationHistoryAdapter;
    private ListView historyListView;
    private TextView historyFooter;

    private static final int CONTEXT_MENU_NAVIGATE = 1;
    private static final int CONTEXT_MENU_DELETE_WAYPOINT = 2;
    private static final int CONTEXT_MENU_EDIT_WAYPOINT = 3;

    private int contextMenuItemPosition;

    String distanceUnit = "";

    public cgeopoint() {
        super("c:geo-navigate-any");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTheme();
        setContentView(R.layout.point);
        setTitle(res.getString(R.string.search_destination));

        createHistoryView();

        init();
    }

    private void createHistoryView() {
        historyListView = (ListView) findViewById(R.id.historyList);

        final View pointControls = getLayoutInflater().inflate(
                R.layout.point_controls, null);
        historyListView.addHeaderView(pointControls, null, false);

        if (getHistoryOfSearchedLocations().isEmpty()) {
            historyListView.addFooterView(getEmptyHistoryFooter(), null, false);
        }

        historyListView.setAdapter(getDestionationHistoryAdapter());
        historyListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                final Object selection = arg0.getItemAtPosition(arg2);
                if (selection instanceof Destination) {
                    navigateTo(((Destination) selection).getCoords());
                }
            }
        });

        historyListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v,
                                            ContextMenuInfo menuInfo) {
                menu.add(Menu.NONE, CONTEXT_MENU_NAVIGATE, Menu.NONE, res.getString(R.string.cache_menu_navigate));
                menu.add(Menu.NONE, CONTEXT_MENU_EDIT_WAYPOINT, Menu.NONE, R.string.waypoint_edit);
                menu.add(Menu.NONE, CONTEXT_MENU_DELETE_WAYPOINT, Menu.NONE, R.string.waypoint_delete);
            }
        });
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        final int position = (null != menuInfo) ? menuInfo.position : contextMenuItemPosition;
        Object destination = historyListView.getItemAtPosition(position);

        switch (item.getItemId()) {
            case CONTEXT_MENU_NAVIGATE:
                contextMenuItemPosition = position;
                if (destination instanceof Destination) {
                    NavigationAppFactory.showNavigationMenu(this, null, null, ((Destination) destination).getCoords());
                    return true;
                }
                break;

            case CONTEXT_MENU_DELETE_WAYPOINT:
                if (destination instanceof Destination) {
                    removeFromHistory((Destination) destination);
                }
                return true;

            case CONTEXT_MENU_EDIT_WAYPOINT:
                if (destination instanceof Destination) {
                    final Geopoint gp = ((Destination) destination).getCoords();
                    latButton.setText(gp.format(GeopointFormatter.Format.LAT_DECMINUTE));
                    lonButton.setText(gp.format(GeopointFormatter.Format.LON_DECMINUTE));
                }
                return true;
            default:
        }

        return super.onContextItemSelected(item);
    }

    private TextView getEmptyHistoryFooter() {
        if (historyFooter == null) {
            historyFooter = (TextView) getLayoutInflater().inflate(
                    R.layout.caches_footer, null);
            historyFooter.setText(R.string.search_history_empty);
        }
        return historyFooter;
    }

    private DestinationHistoryAdapter getDestionationHistoryAdapter() {
        if (destionationHistoryAdapter == null) {
            destionationHistoryAdapter = new DestinationHistoryAdapter(this,
                    getHistoryOfSearchedLocations());
        }
        return destionationHistoryAdapter;
    }

    private List<Destination> getHistoryOfSearchedLocations() {
        if (historyOfSearchedLocations == null) {
            // Load from database
            historyOfSearchedLocations = app.getHistoryOfSearchedLocations();
        }

        return historyOfSearchedLocations;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        init();
    }

    @Override
    public void onResume() {
        super.onResume();
        app.addGeoObserver(this);
        init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onPause() {
        app.deleteGeoObserver(this);
        super.onPause();
    }

    private void init() {
        latButton = (Button) findViewById(R.id.buttonLatitude);
        lonButton = (Button) findViewById(R.id.buttonLongitude);

        latButton.setOnClickListener(new coordDialogListener());
        lonButton.setOnClickListener(new coordDialogListener());

        final Geopoint coords = Settings.getAnyCoordinates();
        if (coords != null) {
            latButton.setText(coords.format(GeopointFormatter.Format.LAT_DECMINUTE));
            lonButton.setText(coords.format(GeopointFormatter.Format.LON_DECMINUTE));
        }

        Button buttonCurrent = (Button) findViewById(R.id.current);
        buttonCurrent.setOnClickListener(new currentListener());

        getDestionationHistoryAdapter().notifyDataSetChanged();
        disableSuggestions((EditText) findViewById(R.id.distance));

        initializeDistanceUnitSelector();
    }

    private void initializeDistanceUnitSelector() {

        Spinner distanceUnitSelector = (Spinner) findViewById(R.id.distanceUnit);

        if (StringUtils.isBlank(distanceUnit)) {
            if (Settings.isUseMetricUnits()) {
                distanceUnitSelector.setSelection(0); // m
                distanceUnit = res.getStringArray(R.array.distance_units)[0];
            } else {
                distanceUnitSelector.setSelection(2); // ft
                distanceUnit = res.getStringArray(R.array.distance_units)[2];
            }
        }

        distanceUnitSelector.setOnItemSelectedListener(new changeDistanceUnit(this));
    }

    private class coordDialogListener implements View.OnClickListener {

        public void onClick(View arg0) {
            Geopoint gp = null;
            if (latButton.getText().length() > 0 && lonButton.getText().length() > 0) {
                gp = new Geopoint(latButton.getText().toString() + " " + lonButton.getText().toString());
            }
            cgeocoords coordsDialog = new cgeocoords(cgeopoint.this, null, gp, app.currentGeo());
            coordsDialog.setCancelable(true);
            coordsDialog.setOnCoordinateUpdate(new cgeocoords.CoordinateUpdate() {
                @Override
                public void update(Geopoint gp) {
                    latButton.setText(gp.format(GeopointFormatter.Format.LAT_DECMINUTE));
                    lonButton.setText(gp.format(GeopointFormatter.Format.LON_DECMINUTE));
                    changed = true;
                }
            });
            coordsDialog.show();
        }
    }

    private class changeDistanceUnit implements OnItemSelectedListener {

        private changeDistanceUnit(cgeopoint unitView) {
            this.unitView = unitView;
        }

        private cgeopoint unitView;

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            unitView.distanceUnit = (String) arg0.getItemAtPosition(arg2);
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_DEFAULT_NAVIGATION, 0, NavigationAppFactory.getDefaultNavigationApplication().getName()).setIcon(R.drawable.ic_menu_compass); // default navigation tool

        menu.add(0, MENU_NAVIGATE, 0, res.getString(R.string.cache_menu_navigate)).setIcon(R.drawable.ic_menu_mapmode);

        menu.add(0, MENU_CACHES_AROUND, 0, res.getString(R.string.cache_menu_around)).setIcon(R.drawable.ic_menu_rotate); // caches around

        menu.add(0, MENU_CLEAR_HISTORY, 0, res.getString(R.string.search_clear_history)).setIcon(R.drawable.ic_menu_delete); // clear history

        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        try {
            boolean visible = getDestination() != null;
            menu.findItem(MENU_NAVIGATE).setVisible(visible);
            menu.findItem(MENU_DEFAULT_NAVIGATION).setVisible(visible);
            menu.findItem(MENU_CACHES_AROUND).setVisible(visible);

            menu.findItem(MENU_CLEAR_HISTORY).setEnabled(!getHistoryOfSearchedLocations().isEmpty());
        } catch (Exception e) {
            // nothing
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        final int menuItem = item.getItemId();

        final Geopoint coords = getDestination();

        if (coords != null) {
            addToHistory(coords);
        }

        switch (menuItem) {
            case MENU_DEFAULT_NAVIGATION:
                navigateTo();
                return true;

            case MENU_CACHES_AROUND:
                cachesAround();
                return true;

            case MENU_CLEAR_HISTORY:
                clearHistory();
                return true;

            case MENU_NAVIGATE:
                NavigationAppFactory.showNavigationMenu(this, null, null, coords);
                return true;
            default:
                return false;
        }
    }

    private void addToHistory(final Geopoint coords) {
        // Add locations to history
        final Destination loc = new Destination(coords);

        if (!getHistoryOfSearchedLocations().contains(loc)) {
            getHistoryOfSearchedLocations().add(0, loc);

            // Save location
            app.saveSearchedDestination(loc);

            // Ensure to remove the footer
            historyListView.removeFooterView(getEmptyHistoryFooter());
        }
    }

    private void removeFromHistory(Destination destination) {
        if (getHistoryOfSearchedLocations().contains(destination)) {
            getHistoryOfSearchedLocations().remove(destination);

            // Save
            app.removeSearchedDestinations(destination);

            if (getHistoryOfSearchedLocations().isEmpty()) {
                if (historyListView.getFooterViewsCount() == 0) {
                    historyListView.addFooterView(getEmptyHistoryFooter());
                }
            }

            getDestionationHistoryAdapter().notifyDataSetChanged();

            showToast(res.getString(R.string.search_remove_destination));
        }
    }

    private void clearHistory() {
        if (!getHistoryOfSearchedLocations().isEmpty()) {
            getHistoryOfSearchedLocations().clear();

            // Save
            app.clearSearchedDestinations();

            if (historyListView.getFooterViewsCount() == 0) {
                historyListView.addFooterView(getEmptyHistoryFooter());
            }

            getDestionationHistoryAdapter().notifyDataSetChanged();

            showToast(res.getString(R.string.search_history_cleared));
        }
    }

    private void navigateTo() {
        navigateTo(getDestination());
    }

    private void navigateTo(Geopoint geopoint) {
        NavigationAppFactory.startDefaultNavigationApplication(1, this, geopoint);
    }

    private void cachesAround() {
        final Geopoint coords = getDestination();

        if (coords == null) {
            showToast(res.getString(R.string.err_location_unknown));
            return;
        }

        cgeocaches.startActivityCoordinates(this, coords);

        finish();
    }

    @Override
    public void update(final IGeoData geo) {
        try {
            latButton.setHint(geo.getCoords().format(GeopointFormatter.Format.LAT_DECMINUTE_RAW));
            lonButton.setHint(geo.getCoords().format(GeopointFormatter.Format.LON_DECMINUTE_RAW));
        } catch (final Exception e) {
            Log.w("Failed to update location.");
        }
    }

    private class currentListener implements View.OnClickListener {

        public void onClick(View arg0) {
            final Geopoint coords = app.currentGeo().getCoords();
            if (coords == null) {
                showToast(res.getString(R.string.err_point_unknown_position));
                return;
            }

            latButton.setText(coords.format(GeopointFormatter.Format.LAT_DECMINUTE));
            lonButton.setText(coords.format(GeopointFormatter.Format.LON_DECMINUTE));

            changed = false;
        }
    }

    private Geopoint getDestination() {
        Geopoint result;
        Geopoint coords;

        String bearingText = ((EditText) findViewById(R.id.bearing)).getText().toString();
        // combine distance from EditText and distanceUnit saved from Spinner
        String distanceText = ((EditText) findViewById(R.id.distance)).getText().toString() + distanceUnit;
        String latText = latButton.getText().toString();
        String lonText = lonButton.getText().toString();

        if (StringUtils.isBlank(bearingText) && StringUtils.isBlank(distanceText)
                && StringUtils.isBlank(latText) && StringUtils.isBlank(lonText)) {
            showToast(res.getString(R.string.err_point_no_position_given));
            return null;
        }

        if (StringUtils.isNotBlank(latText) && StringUtils.isNotBlank(lonText)) {
            try {
                coords = new Geopoint(latText, lonText);
            } catch (Geopoint.ParseException e) {
                showToast(res.getString(e.resource));
                return null;
            }
        } else {
            if (app.currentGeo().getCoords() == null) {
                showToast(res.getString(R.string.err_point_curr_position_unavailable));
                return null;
            }

            coords = app.currentGeo().getCoords();
        }

        if (StringUtils.isNotBlank(bearingText) && StringUtils.isNotBlank(distanceText)) {
            // bearing & distance
            double bearing;
            try {
                bearing = Double.parseDouble(bearingText);
            } catch (NumberFormatException e) {
                helpDialog(res.getString(R.string.err_point_bear_and_dist_title), res.getString(R.string.err_point_bear_and_dist));
                return null;
            }

            double distance;
            try {
                distance = DistanceParser.parseDistance(distanceText, Settings.isUseMetricUnits());
            } catch (NumberFormatException e) {
                showToast(res.getString(R.string.err_parse_dist));
                return null;
            }

            final Geopoint coordsDst = coords.project(bearing, distance);

            if (coordsDst == null) {
                showToast(res.getString(R.string.err_point_location_error));
                return null;
            }

            result = coordsDst;
        } else if (coords != null) {
            result = coords;
        } else {
            return null;
        }

        saveCoords(result);

        return result;
    }

    private void saveCoords(final Geopoint coords) {
        if (!changed) {
            return;
        }
        Settings.setAnyCoordinates(coords);
    }
}