summaryrefslogtreecommitdiff
path: root/navit/android/src/org/navitproject/navit/NavitAddressSearchActivity.java
blob: 3c0c489d153346714a8bdc0440c268898948104c (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
/*
 * Navit, a modular navigation system.
 * Copyright (C) 2005-2008 Navit Team
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 */

package org.navitproject.navit;

import static org.navitproject.navit.NavitAppConfig.getTstring;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;


public class NavitAddressSearchActivity extends Activity {
    static final class NavitAddress {
        NavitAddress(int type, float latitude, float longitude, String address) {
            mResultType = type;
            mLat = latitude;
            mLon = longitude;
            mAddr = address;
        }

        final int mResultType;
        final float mLat;
        final float mLon;
        final String mAddr;
    }

    private static final String TAG                         = "NavitAddress";
    private static final int    ADDRESS_RESULT_PROGRESS_MAX = 10;

    private List<NavitAddress> mAddressesFound = null;
    private List<NavitAddress> mAddressesShown = null;
    private String             mAddressString               = "";
    private boolean            mPartialSearch               = false;
    private String             mCountry;
    private ImageButton        mCountryButton;
    private ProgressDialog mSearchResultsWait = null;
    private int mSearchResultsTowns = 0;
    private int mSearchResultsStreets = 0;
    private int mSearchResultsStreetsHn = 0;
    private long mSearchHandle = 0;

    // TODO remember settings
    private static String sLastAddressSearchString = "";
    private static Boolean sLastAddressPartialMatch = false;
    private static String sLastCountry = "";

    private int getDrawableID(String resourceName) {
        int drawableId = 0;
        try {
            Class<?> res = R.drawable.class;
            Field field = res.getField(resourceName);
            drawableId = field.getInt(null);
        } catch (Exception e) {
            Log.e(TAG, "Failure to get drawable id.", e);
        }
        return drawableId;
    }

    private void setCountryButtonImage() {
        // We have all images stored as drawable_nodpi resources which allows native code to manipulate them
        // without interference with android builtin choosing and scaling system. But that makes us to
        // reinvent the wheel here to show an image in android native interface.
        int[] flagIconSizes = {24,32,48,64,96};
        int exactSize;
        int nearestSize;
        exactSize = (int)(Navit.sMetrics.density * 24.0 - .5);
        nearestSize = flagIconSizes[0];
        for (int size: flagIconSizes) {
            nearestSize = size;
            if (exactSize <= size) {
                break;
            }
        }
        mCountryButton.setImageResource(getDrawableID("country_" + mCountry + "_" + nearestSize + "_" + nearestSize));
    }


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

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String searchString = extras.getString(("search_string"));
            if (searchString != null) {
                mPartialSearch = true;
                mAddressString = searchString;
                executeSearch();
                return;
            }
        }

        mPartialSearch = sLastAddressPartialMatch;
        mAddressString = sLastAddressSearchString;

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
        LinearLayout panel = new LinearLayout(this);
        panel.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        panel.setOrientation(LinearLayout.VERTICAL);

        // address: label and text field
        SharedPreferences settings = getSharedPreferences(NavitAppConfig.NAVIT_PREFS, MODE_PRIVATE);
        mCountry = settings.getString(("DefaultCountry"), null);

        if (mCountry == null) {
            Locale defaultLocale = Locale.getDefault();
            mCountry = defaultLocale.getCountry().toLowerCase(defaultLocale);
            SharedPreferences.Editor editSettings = settings.edit();
            editSettings.putString("DefaultCountry", mCountry);
            editSettings.apply();
        }

        mCountryButton = new ImageButton(this);

        setCountryButtonImage();

        mCountryButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                requestCountryDialog();
            }
        });

        // address: label and text field
        TextView addrView = new TextView(this);
        addrView.setText(getTstring(R.string.address_enter_destination)); // TRANS
        addrView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f);
        addrView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        addrView.setPadding(4, 4, 4, 4);

        // partial match checkbox
        final CheckBox checkboxPartialMatch = new CheckBox(this);
        checkboxPartialMatch.setText(getTstring(R.string.address_partial_match)); // TRANS
        checkboxPartialMatch.setChecked(sLastAddressPartialMatch);
        checkboxPartialMatch.setGravity(Gravity.CENTER);

        final EditText address_string = new EditText(this);
        address_string.setText(sLastAddressSearchString);
        address_string.setSelectAllOnFocus(true);

        // search button
        final Button btnSearch = new Button(this);
        btnSearch.setText(getTstring(R.string.address_search_button)); // TRANS
        btnSearch.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        btnSearch.setGravity(Gravity.CENTER);
        btnSearch.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mPartialSearch = checkboxPartialMatch.isChecked();
                mAddressString = address_string.getText().toString();
                sLastAddressPartialMatch = mPartialSearch;
                sLastAddressSearchString = mAddressString;
                executeSearch();
            }
        });

        ListView lastAddresses = new ListView(this);
        NavitAppConfig navitConfig = (NavitAppConfig) getApplicationContext();

        final List<NavitAddress> addresses = navitConfig.getLastAddresses();
        int addressCount = addresses.size();
        if (addressCount > 0) {
            String[] strAddresses = new String[addressCount];
            for (int addrIndex = 0; addrIndex < addressCount; addrIndex++) {
                strAddresses[addrIndex] = addresses.get(addrIndex).mAddr;
            }
            ArrayAdapter<String> addressList =
                    new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, strAddresses);
            lastAddresses.setAdapter(addressList);
            lastAddresses.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    NavitAddress addressSelected = addresses.get(arg2);
                    Intent resultIntent = new Intent();

                    resultIntent.putExtra("lat", addressSelected.mLat);
                    resultIntent.putExtra("lon", addressSelected.mLon);
                    resultIntent.putExtra("q", addressSelected.mAddr);

                    setResult(Activity.RESULT_OK, resultIntent);
                    finish();
                }
            });
        }

        String title = getString(R.string.address_search_title);
        this.setTitle(title);

        LinearLayout searchSettingsLayout = new LinearLayout(this);
        searchSettingsLayout.setOrientation(LinearLayout.HORIZONTAL);

        searchSettingsLayout.addView(mCountryButton);
        searchSettingsLayout.addView(checkboxPartialMatch);
        panel.addView(addrView);
        panel.addView(address_string);
        panel.addView(searchSettingsLayout);
        panel.addView(btnSearch);
        panel.addView(lastAddresses);

        setContentView(panel);
    }

    private void requestCountryDialog() {
        final String[][] all_countries = NavitGraphics.getAllCountries();

        Comparator<String[]> countryComparator = new Comparator<String[]>() {
            public int compare(String[] object1, String[] object2) {
                return object1[1].compareTo(object2[1]);
            }
        };

        Arrays.sort(all_countries, countryComparator);

        AlertDialog.Builder mapModeChooser = new AlertDialog.Builder(this);
        // ToDo also show icons and country code
        String[] countryName = new String[all_countries.length];

        for (int countryIndex = 0; countryIndex < all_countries.length; countryIndex++) {
            countryName[countryIndex] = all_countries[countryIndex][1];
        }

        mapModeChooser.setItems(countryName, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                SharedPreferences settings = getSharedPreferences(NavitAppConfig.NAVIT_PREFS, MODE_PRIVATE);
                mCountry = all_countries[item][0];
                SharedPreferences.Editor editSettings = settings.edit();
                editSettings.putString("DefaultCountry", mCountry);
                editSettings.apply();
                setCountryButtonImage();
            }
        });

        AlertDialog d = mapModeChooser.create();
        d.getListView().setFastScrollEnabled(true);
        d.show();
    }

    //start a search on the map
    void receiveAddress(int type, float latitude, float longitude, String address) {
        Log.d(TAG, "(" + latitude + ", " + longitude + ") " + address);

        switch (type) {
            case 0:
                mSearchResultsTowns++;
                break;
            case 1:
                mSearchResultsStreets++;
                break;
            case 2:
                mSearchResultsStreetsHn++;
                break;
            default:
                Log.e(TAG,"Unexpected value: " + type);
        }
        mSearchResultsWait.setMessage(getTstring(R.string.address_search_towns) + ":"
                + mSearchResultsTowns + " "
                + getTstring(R.string.address_search_streets) + ":" + mSearchResultsStreets + "/"
                + mSearchResultsStreetsHn);

        mSearchResultsWait.setProgress(mAddressesFound.size() % (ADDRESS_RESULT_PROGRESS_MAX + 1));

        mAddressesFound.add(new NavitAddress(type, latitude, longitude, address));
    }

    void finishAddressSearch() {
        if (mAddressesFound.isEmpty()) {
            // TRANS
            Toast.makeText(getApplicationContext(),
                    getString(R.string.address_search_not_found) + "\n" + mAddressString, Toast.LENGTH_LONG).show();
            setResult(Activity.RESULT_CANCELED);
            finish();
        }
        ListView addressesFound = new ListView(this);
        addressesFound.setFastScrollEnabled(true);
        ArrayAdapter<String> addressList =
                new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);

        mAddressesShown = new ArrayList<>();

        for (NavitAddress currentAddress : mAddressesFound) {
            if (currentAddress.mResultType != 0 || mSearchResultsStreets == 0) {
                addressList.add(currentAddress.mAddr);
                mAddressesShown.add(currentAddress);
            }
        }

        addressesFound.setAdapter(addressList);

        addressesFound.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                NavitAddress addressSelected = mAddressesShown.get(arg2);
                Intent resultIntent = new Intent();

                resultIntent.putExtra("lat", addressSelected.mLat);
                resultIntent.putExtra("lon", addressSelected.mLon);
                resultIntent.putExtra("q", addressSelected.mAddr);

                setResult(Activity.RESULT_OK, resultIntent);
                finish();
            }
        });

        setContentView(addressesFound);
        mSearchResultsWait.dismiss();
    }

    native long callbackStartAddressSearch(int partialMatch, String country, String s);

    native void callbackCancelAddressSearch(long handle);

    @Override
    protected Dialog onCreateDialog(int id) {
        mSearchResultsWait = new ProgressDialog(this);
        mSearchResultsWait.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mSearchResultsWait.setTitle("Loading search results");
        mSearchResultsWait.setMessage("--");
        mSearchResultsWait.setCancelable(true);
        mSearchResultsWait.setProgress(0);
        mSearchResultsWait.setMax(10);

        mAddressesFound = new ArrayList<>();
        mSearchResultsTowns = 0;
        mSearchResultsStreets = 0;
        mSearchResultsStreetsHn = 0;

        mSearchHandle = callbackStartAddressSearch(mPartialSearch ? 1 : 0, mCountry, mAddressString);

        mSearchResultsWait.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                callbackCancelAddressSearch(mSearchHandle);
                mSearchHandle = 0;
                mSearchResultsWait.dismiss();
            }
        });
        return mSearchResultsWait;
    }

    private void executeSearch() {
        showDialog(0);
    }
}