aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/SearchActivity.java
blob: 8842603a8b2b814867eb25f33bda09598789bec1 (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
package cgeo.geocaching;

import butterknife.ButterKnife;
import butterknife.InjectView;

import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.activity.ShowcaseViewBuilder;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.connector.capability.ISearchByGeocode;
import cgeo.geocaching.connector.trackable.TrackableConnector;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.GeopointFormatter;
import cgeo.geocaching.search.AutoCompleteAdapter;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.Sensors;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.ui.dialog.CoordinatesInputDialog;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.EditUtils;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;

import rx.functions.Func1;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;

import java.util.Locale;

public class SearchActivity extends AbstractActionBarActivity implements CoordinatesInputDialog.CoordinateUpdate {

    @InjectView(R.id.buttonLatitude) protected Button buttonLatitude;
    @InjectView(R.id.buttonLongitude) protected Button buttonLongitude;
    @InjectView(R.id.search_coordinates) protected Button buttonSearchCoords;

    @InjectView(R.id.address) protected AutoCompleteTextView addressEditText;
    @InjectView(R.id.search_address) protected Button buttonSearchAddress;

    @InjectView(R.id.geocode) protected AutoCompleteTextView geocodeEditText;
    @InjectView(R.id.display_geocode) protected Button buttonSearchGeocode;

    @InjectView(R.id.keyword) protected AutoCompleteTextView keywordEditText;
    @InjectView(R.id.search_keyword) protected Button buttonSearchKeyword;

    @InjectView(R.id.finder) protected AutoCompleteTextView finderNameEditText;
    @InjectView(R.id.search_finder) protected Button buttonSearchFinder;

    @InjectView(R.id.owner) protected AutoCompleteTextView ownerNameEditText;
    @InjectView(R.id.search_owner) protected Button buttonSearchOwner;

    @InjectView(R.id.trackable) protected AutoCompleteTextView trackableEditText;
    @InjectView(R.id.display_trackable) protected Button buttonSearchTrackable;

    private static final String GOOGLE_NOW_SEARCH_ACTION = "com.google.android.gms.actions.SEARCH_ACTION";

    @Override
    public final void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Intent intent = getIntent();

        // search suggestion for a cache
        if (Intents.ACTION_GEOCACHE.equals(intent.getAction())) {
            CacheDetailActivity.startActivity(this, intent.getStringExtra(SearchManager.QUERY));
            finish();
            return;
        }

        // search suggestion for a trackable
        if (Intents.ACTION_TRACKABLE.equals(intent.getAction())) {
            TrackableActivity.startActivity(this, null, intent.getStringExtra(SearchManager.QUERY), null);
            finish();
            return;
        }

        // search query, from search toolbar or from google now
        if (Intent.ACTION_SEARCH.equals(intent.getAction()) || GOOGLE_NOW_SEARCH_ACTION.equals(intent.getAction())) {
            hideKeyboard();
            final String query = intent.getStringExtra(SearchManager.QUERY);
            final boolean keywordSearch = intent.getBooleanExtra(Intents.EXTRA_KEYWORD_SEARCH, true);

            if (instantSearch(query, keywordSearch)) {
                setResult(RESULT_OK);
            } else {
                // send intent back so query string is known
                setResult(RESULT_CANCELED, intent);
            }
            finish();

            return;
        }

        setTheme();
        setContentView(R.layout.search_activity);

        // set title in code, as the activity needs a hard coded title due to the intent filters
        setTitle(res.getString(R.string.search));

        ButterKnife.inject(this);
        init();
    }

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

        init();
    }

    @Override
    public final void onResume() {
        super.onResume();
        init();
    }

    /**
     * Performs a search for query either as geocode, trackable code or keyword
     *
     * @param nonTrimmedQuery
     *            String to search for
     * @param keywordSearch
     *            Set to true if keyword search should be performed if query isn't GC or TB
     * @return true if a search was performed, else false
     */
    private boolean instantSearch(final String nonTrimmedQuery, final boolean keywordSearch) {
        final String query = StringUtils.trim(nonTrimmedQuery);

        // first check if this was a scanned URL
        String geocode = ConnectorFactory.getGeocodeFromURL(query);

        // otherwise see if this is a pure geocode
        if (StringUtils.isEmpty(geocode)) {
            geocode = StringUtils.upperCase(StringUtils.trim(query));
        }

        final IConnector connector = ConnectorFactory.getConnector(geocode);
        if (connector instanceof ISearchByGeocode && geocode != null) {
            CacheDetailActivity.startActivity(this, geocode.toUpperCase(Locale.US));
            return true;
        }

        // Check if the query is a TB code
        TrackableConnector trackableConnector = ConnectorFactory.getTrackableConnector(geocode);

        // check if the query contains a TB code
        if (trackableConnector == ConnectorFactory.UNKNOWN_TRACKABLE_CONNECTOR) {
            final String tbCode = ConnectorFactory.getTrackableFromURL(query);
            if (StringUtils.isNotBlank(tbCode)) {
                trackableConnector = ConnectorFactory.getTrackableConnector(tbCode);
                geocode = tbCode;
            }
        }

        if (trackableConnector != ConnectorFactory.UNKNOWN_TRACKABLE_CONNECTOR && geocode != null) {
            final Intent trackablesIntent = new Intent(this, TrackableActivity.class);
            trackablesIntent.putExtra(Intents.EXTRA_GEOCODE, geocode.toUpperCase(Locale.US));
            startActivity(trackablesIntent);
            return true;
        }

        if (keywordSearch) { // keyword fallback, if desired by caller
            CacheListActivity.startActivityKeyword(this, query.trim());
            return true;
        }

        return false;
    }

    private void init() {
        buttonLatitude.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(final View v) {
                updateCoordinates();
            }
        });
        buttonLongitude.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(final View v) {
                updateCoordinates();
            }
        });

        buttonSearchCoords.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View arg0) {
                findByCoordsFn();
            }
        });

        setSearchAction(addressEditText, buttonSearchAddress, new Runnable() {

            @Override
            public void run() {
                findByAddressFn();
            }
        }, null);

        setSearchAction(geocodeEditText, buttonSearchGeocode, new Runnable() {

            @Override
            public void run() {
                findByGeocodeFn();
            }
        }, new Func1<String, String[]>() {

            @Override
            public String[] call(final String input) {
                return DataStore.getSuggestionsGeocode(input);
            }
        });

        setSearchAction(keywordEditText, buttonSearchKeyword, new Runnable() {

            @Override
            public void run() {
                findByKeywordFn();
            }
        }, new Func1<String, String[]>() {

            @Override
            public String[] call(final String input) {
                return DataStore.getSuggestionsKeyword(input);
            }
        });

        setSearchAction(finderNameEditText, buttonSearchFinder, new Runnable() {

            @Override
            public void run() {
                findByFinderFn();
            }
        }, new Func1<String, String[]>() {

            @Override
            public String[] call(final String input) {
                return DataStore.getSuggestionsFinderName(input);
            }
        });

        setSearchAction(ownerNameEditText, buttonSearchOwner, new Runnable() {

            @Override
            public void run() {
                findByOwnerFn();
            }
        }, new Func1<String, String[]>() {

            @Override
            public String[] call(final String input) {
                return DataStore.getSuggestionsOwnerName(input);
            }
        });

        setSearchAction(trackableEditText, buttonSearchTrackable, new Runnable() {

            @Override
            public void run() {
                findTrackableFn();
            }
        }, new Func1<String, String[]>() {

            @Override
            public String[] call(final String input) {
                return DataStore.getSuggestionsTrackableCode(input);
            }
        });
    }

    private static void setSearchAction(final AutoCompleteTextView editText, final Button button, final @NonNull Runnable runnable, final @Nullable Func1<String, String[]> suggestionFunction) {
        EditUtils.setActionListener(editText, runnable);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View arg0) {
                runnable.run();
            }
        });
        if (suggestionFunction != null) {
            editText.setAdapter(new AutoCompleteAdapter(editText.getContext(), android.R.layout.simple_dropdown_item_1line, suggestionFunction));
        }
    }

    private void updateCoordinates() {
        final CoordinatesInputDialog coordsDialog = CoordinatesInputDialog.getInstance(null, null, Sensors.getInstance().currentGeo());
        coordsDialog.setCancelable(true);
        coordsDialog.show(getSupportFragmentManager(), "wpedit_dialog");
    }

    @Override
    public void updateCoordinates(final Geopoint gp) {
        buttonLatitude.setText(gp.format(GeopointFormatter.Format.LAT_DECMINUTE));
        buttonLongitude.setText(gp.format(GeopointFormatter.Format.LON_DECMINUTE));
    }

    private void findByCoordsFn() {
        final String latText = StringUtils.trim(buttonLatitude.getText().toString());
        final String lonText = StringUtils.trim(buttonLongitude.getText().toString());

        if (StringUtils.isEmpty(latText) || StringUtils.isEmpty(lonText)) {
            final GeoData geo = Sensors.getInstance().currentGeo();
            buttonLatitude.setText(geo.getCoords().format(GeopointFormatter.Format.LAT_DECMINUTE));
            buttonLongitude.setText(geo.getCoords().format(GeopointFormatter.Format.LON_DECMINUTE));
        } else {
            try {
                CacheListActivity.startActivityCoordinates(this, new Geopoint(latText, lonText));
            } catch (final Geopoint.ParseException e) {
                showToast(res.getString(e.resource));
            }
        }
    }

    private void findByKeywordFn() {
        // find caches by coordinates
        final String keyText = StringUtils.trim(keywordEditText.getText().toString());

        if (StringUtils.isBlank(keyText)) {
            Dialogs.message(this, R.string.warn_search_help_title, R.string.warn_search_help_keyword);
            return;
        }

        CacheListActivity.startActivityKeyword(this, keyText);
    }

    private void findByAddressFn() {
        final String addText = StringUtils.trim(addressEditText.getText().toString());

        if (StringUtils.isBlank(addText)) {
            Dialogs.message(this, R.string.warn_search_help_title, R.string.warn_search_help_address);
            return;
        }

        final Intent addressesIntent = new Intent(this, AddressListActivity.class);
        addressesIntent.putExtra(Intents.EXTRA_KEYWORD, addText);
        startActivity(addressesIntent);
    }

    public final void findByFinderFn() {
        final String usernameText = StringUtils.trim(finderNameEditText.getText().toString());

        if (StringUtils.isBlank(usernameText)) {
            Dialogs.message(this, R.string.warn_search_help_title, R.string.warn_search_help_user);
            return;
        }

        CacheListActivity.startActivityFinder(this, usernameText);
    }

    private void findByOwnerFn() {
        findByOwnerFn(ownerNameEditText.getText().toString());
    }

    private void findByOwnerFn(final String userName) {
        final String usernameText = StringUtils.trimToEmpty(userName);

        if (StringUtils.isBlank(usernameText)) {
            Dialogs.message(this, R.string.warn_search_help_title, R.string.warn_search_help_user);
            return;
        }

        CacheListActivity.startActivityOwner(this, usernameText);
    }

    private void findByGeocodeFn() {
        final String geocodeText = StringUtils.trimToEmpty(geocodeEditText.getText().toString());

        if (StringUtils.isBlank(geocodeText) || geocodeText.equalsIgnoreCase("GC")) {
            Dialogs.message(this, R.string.warn_search_help_title, R.string.warn_search_help_gccode);
            return;
        }

        CacheDetailActivity.startActivity(this, geocodeText.toUpperCase(Locale.US));
    }

    private void findTrackableFn() {
        final String trackableText = StringUtils.trimToEmpty(trackableEditText.getText().toString());

        if (StringUtils.isBlank(trackableText) || trackableText.equalsIgnoreCase("TB")) {
            Dialogs.message(this, R.string.warn_search_help_title, R.string.warn_search_help_tb);
            return;
        }

        final Intent trackablesIntent = new Intent(this, TrackableActivity.class);
        trackablesIntent.putExtra(Intents.EXTRA_GEOCODE, trackableText.toUpperCase(Locale.US));
        startActivity(trackablesIntent);
    }

    @Override
    public final boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.search_activity_options, menu);
        presentShowcase();
        return true;
    }

    @Override
    public final boolean onOptionsItemSelected(final MenuItem item) {
        if (item.getItemId() == R.id.menu_search_own_caches) {
            findByOwnerFn(Settings.getUsername());
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public static void startActivityScan(final String scan, final Activity fromActivity) {
        final Intent searchIntent = new Intent(fromActivity, SearchActivity.class);
        searchIntent.setAction(Intent.ACTION_SEARCH).
                putExtra(SearchManager.QUERY, scan).
                putExtra(Intents.EXTRA_KEYWORD_SEARCH, false);
        fromActivity.startActivityForResult(searchIntent, MainActivity.SEARCH_REQUEST_CODE);
    }

    @Override
    public ShowcaseViewBuilder getShowcase() {
        // The showcase doesn't work well with the search activity, because on searching a geocode (or
        // selecting a cache from the search field) we immediately close the activity. That in turn confuses the delayed
        // creation of the showcase bitmap. To avoid someone running into this issue again, this method explicitly overrides
        // the parent method with the same implementation.
        return null;
    }
}