]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryManagerActivity.java
Fix crash if unknown dictionaries exist.
[Dictionary.git] / src / com / hughes / android / dictionary / DictionaryManagerActivity.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package com.hughes.android.dictionary;
16
17 import android.app.AlertDialog;
18 import android.app.DownloadManager;
19 import android.app.DownloadManager.Request;
20 import android.content.BroadcastReceiver;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.IntentFilter;
24 import android.content.SharedPreferences;
25 import android.content.SharedPreferences.Editor;
26 import android.database.Cursor;
27 import android.net.Uri;
28 import android.os.Bundle;
29 import android.os.Environment;
30 import android.os.Handler;
31 import android.preference.PreferenceManager;
32 import android.support.v7.app.ActionBar;
33 import android.support.v7.app.ActionBarActivity;
34 import android.support.v7.widget.SearchView;
35 import android.support.v7.widget.SearchView.OnQueryTextListener;
36 import android.util.Log;
37 import android.util.TypedValue;
38 import android.view.ContextMenu;
39 import android.view.ContextMenu.ContextMenuInfo;
40 import android.view.LayoutInflater;
41 import android.view.Menu;
42 import android.view.View;
43 import android.view.View.OnClickListener;
44 import android.view.ViewGroup;
45 import android.view.inputmethod.EditorInfo;
46 import android.widget.AdapterView.AdapterContextMenuInfo;
47 import android.widget.BaseAdapter;
48 import android.widget.Button;
49 import android.widget.CompoundButton;
50 import android.widget.CompoundButton.OnCheckedChangeListener;
51 import android.widget.FrameLayout;
52 import android.widget.LinearLayout;
53 import android.widget.ListAdapter;
54 import android.widget.ListView;
55 import android.widget.TextView;
56 import android.widget.Toast;
57 import android.widget.ToggleButton;
58
59 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
60 import com.hughes.android.util.IntentLauncher;
61
62 import java.io.File;
63 import java.io.FileOutputStream;
64 import java.io.IOException;
65 import java.io.InputStream;
66 import java.io.OutputStream;
67 import java.net.MalformedURLException;
68 import java.net.URL;
69 import java.util.Collections;
70 import java.util.List;
71 import java.util.zip.ZipEntry;
72 import java.util.zip.ZipFile;
73
74 // Right-click:
75 //  Delete, move to top.
76
77 public class DictionaryManagerActivity extends ActionBarActivity {
78
79     static final String LOG = "QuickDic";
80     static boolean blockAutoLaunch = false;
81
82     private ListView listView;
83     private ListView getListView() {
84         if (listView == null) {
85             listView = (ListView)findViewById(android.R.id.list);
86         }
87         return listView;
88     }
89     private void setListAdapter(ListAdapter adapter) {
90         getListView().setAdapter(adapter);
91     }
92     private ListAdapter getListAdapter() {
93         return getListView().getAdapter();
94     }
95
96     DictionaryApplication application;
97
98     SearchView filterSearchView;
99     ToggleButton showDownloadable;
100
101     LinearLayout dictionariesOnDeviceHeaderRow;
102     LinearLayout downloadableDictionariesHeaderRow;
103
104     Handler uiHandler;
105
106     Runnable dictionaryUpdater = new Runnable() {
107         @Override
108         public void run() {
109             if (uiHandler == null) {
110                 return;
111             }
112             uiHandler.post(new Runnable() {
113                 @Override
114                 public void run() {
115                     setMyListAdapater();
116                 }
117             });
118         }
119     };
120
121     final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
122         @Override
123         public void onReceive(Context context, Intent intent) {
124             final String action = intent.getAction();
125
126             if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
127                 final long downloadId = intent.getLongExtra(
128                         DownloadManager.EXTRA_DOWNLOAD_ID, 0);
129                 final DownloadManager.Query query = new DownloadManager.Query();
130                 query.setFilterById(downloadId);
131                 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
132                 final Cursor cursor = downloadManager.query(query);
133
134                 if (!cursor.moveToFirst()) {
135                     Log.e(LOG, "Couldn't find download.");
136                     return;
137                 }
138
139                 final String dest = cursor
140                         .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
141                 final int status = cursor
142                         .getInt(cursor
143                                 .getColumnIndex(DownloadManager.COLUMN_STATUS));
144                 if (DownloadManager.STATUS_SUCCESSFUL != status) {
145                     Log.w(LOG,
146                             "Download failed: status=" + status +
147                                     ", reason=" + cursor.getString(cursor
148                                             .getColumnIndex(DownloadManager.COLUMN_REASON)));
149                     new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, dest)).setNeutralButton("Close", null).show();
150                     return;
151                 }
152
153                 Log.w(LOG, "Download finished: " + dest);
154                 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
155                         Toast.LENGTH_LONG).show();
156                 
157                 
158                 final File localZipFile = new File(Uri.parse(dest).getPath());
159                 try {
160                     ZipFile zipFile = new ZipFile(localZipFile);
161                     final ZipEntry zipEntry = zipFile.entries().nextElement();
162                     Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
163                     final InputStream zipIn = zipFile.getInputStream(zipEntry);
164                     File targetFile = new File(application.getDictDir(), zipEntry.getName());
165                     if (targetFile.exists()) {
166                         targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
167                         targetFile = new File(application.getDictDir(), zipEntry.getName());
168                     }
169                     final OutputStream zipOut = new FileOutputStream(targetFile);
170                     copyStream(zipIn, zipOut);
171                     zipFile.close();
172                     application.backgroundUpdateDictionaries(dictionaryUpdater);
173                     Toast.makeText(context, getString(R.string.installationFinished, dest),
174                             Toast.LENGTH_LONG).show();
175                 } catch (Exception e) {
176                     String msg = getString(R.string.unzippingFailed, dest);
177                     File dir = application.getDictDir();
178                     if (!dir.canWrite() || !application.checkFileCreate(dir)) {
179                         msg = getString(R.string.notWritable, dir.getAbsolutePath());
180                     }
181                     new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
182                     Log.e(LOG, "Failed to unzip.", e);
183                 } finally {
184                     localZipFile.delete();
185                 }
186             }
187         }
188     };
189
190     public static Intent getLaunchIntent(Context c) {
191         final Intent intent = new Intent(c, DictionaryManagerActivity.class);
192         intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
193         return intent;
194     }
195
196     @Override
197     public void onCreate(Bundle savedInstanceState) {
198         // This must be first, otherwise the actiona bar doesn't get
199         // styled properly.
200         setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
201
202         super.onCreate(savedInstanceState);
203         Log.d(LOG, "onCreate:" + this);
204
205         application = (DictionaryApplication) getApplication();
206
207         blockAutoLaunch = false;
208
209         // UI init.
210         setContentView(R.layout.dictionary_manager_activity);
211
212         dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
213                 getListView().getContext()).inflate(
214                 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
215
216         downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
217                 getListView().getContext()).inflate(
218                 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
219
220         showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
221                 .findViewById(R.id.hideDownloadable);
222         showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
223             @Override
224             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
225                 onShowDownloadableChanged();
226             }
227         });
228
229         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
230         final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
231         if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
232                 thanksForUpdatingLatestVersion)) {
233             blockAutoLaunch = true;
234             startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
235             prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
236                     .commit();
237         }
238
239         registerReceiver(broadcastReceiver, new IntentFilter(
240                 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
241
242         setMyListAdapater();
243         registerForContextMenu(getListView());
244
245         final File dictDir = application.getDictDir();
246         if (!dictDir.canRead() || !dictDir.canExecute()) {
247             blockAutoLaunch = true;
248
249             AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
250             builder.setTitle(getString(R.string.error));
251             builder.setMessage(getString(
252                     R.string.unableToReadDictionaryDir,
253                     dictDir.getAbsolutePath(),
254                     Environment.getExternalStorageDirectory()));
255             builder.setNeutralButton("Close", null);
256             builder.create().show();
257         }
258
259         onCreateSetupActionBar();
260     }
261
262     private void onCreateSetupActionBar() {
263         ActionBar actionBar = getSupportActionBar();
264         actionBar.setDisplayShowTitleEnabled(false);
265
266         filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
267         filterSearchView.setIconifiedByDefault(false);
268         // filterSearchView.setIconified(false); // puts the magnifying glass in
269         // the
270         // wrong place.
271         filterSearchView.setQueryHint(getString(R.string.searchText));
272         filterSearchView.setSubmitButtonEnabled(false);
273         final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
274                 getResources().getDisplayMetrics());
275         FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
276                 FrameLayout.LayoutParams.WRAP_CONTENT);
277         filterSearchView.setLayoutParams(lp);
278         filterSearchView.setImeOptions(
279                 EditorInfo.IME_ACTION_SEARCH |
280                         EditorInfo.IME_FLAG_NO_EXTRACT_UI |
281                         EditorInfo.IME_FLAG_NO_ENTER_ACTION |
282                         // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
283                         // 11
284                         EditorInfo.IME_MASK_ACTION |
285                         EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
286
287         filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
288             @Override
289             public boolean onQueryTextSubmit(String query) {
290                 return true;
291             }
292
293             @Override
294             public boolean onQueryTextChange(String filterText) {
295                 setMyListAdapater();
296                 return true;
297             }
298         });
299         filterSearchView.setFocusable(true);
300
301         actionBar.setCustomView(filterSearchView);
302         actionBar.setDisplayShowCustomEnabled(true);
303     }
304
305     @Override
306     public void onDestroy() {
307         super.onDestroy();
308         unregisterReceiver(broadcastReceiver);
309     }
310
311     private static int copyStream(final InputStream in, final OutputStream out)
312             throws IOException {
313         int bytesRead;
314         final byte[] bytes = new byte[1024 * 16];
315         while ((bytesRead = in.read(bytes)) != -1) {
316             out.write(bytes, 0, bytesRead);
317         }
318         in.close();
319         out.close();
320         return bytesRead;
321     }
322
323     @Override
324     protected void onStart() {
325         super.onStart();
326         uiHandler = new Handler();
327     }
328
329     @Override
330     protected void onStop() {
331         super.onStop();
332         uiHandler = null;
333     }
334
335     @Override
336     protected void onResume() {
337         super.onResume();
338
339         if (PreferenceActivity.prefsMightHaveChanged) {
340             PreferenceActivity.prefsMightHaveChanged = false;
341             finish();
342             startActivity(getIntent());
343         }
344
345         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
346         showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
347
348         if (!blockAutoLaunch &&
349                 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
350                 prefs.contains(C.DICT_FILE) &&
351                 prefs.contains(C.INDEX_SHORT_NAME)) {
352             Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
353             startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
354                     new File(prefs.getString(C.DICT_FILE, "")),
355                     prefs.getString(C.INDEX_SHORT_NAME, ""),
356                     prefs.getString(C.SEARCH_TOKEN, "")));
357             finish();
358             return;
359         }
360
361         // Remove the active dictionary from the prefs so we won't autolaunch
362         // next time.
363         final Editor editor = prefs.edit();
364         editor.remove(C.DICT_FILE);
365         editor.remove(C.INDEX_SHORT_NAME);
366         editor.remove(C.SEARCH_TOKEN);
367         editor.commit();
368
369         application.backgroundUpdateDictionaries(dictionaryUpdater);
370
371         setMyListAdapater();
372     }
373
374     @Override
375     public boolean onCreateOptionsMenu(final Menu menu) {
376         application.onCreateGlobalOptionsMenu(this, menu);
377         return true;
378     }
379
380     @Override
381     public void onCreateContextMenu(final ContextMenu menu, final View view,
382             final ContextMenuInfo menuInfo) {
383         super.onCreateContextMenu(menu, view, menuInfo);
384         Log.d(LOG, "onCreateContextMenu, " + menuInfo);
385
386         final AdapterContextMenuInfo adapterContextMenuInfo =
387                 (AdapterContextMenuInfo) menuInfo;
388         final int position = adapterContextMenuInfo.position;
389         final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
390
391         if (row.dictionaryInfo == null) {
392             return;
393         }
394
395         if (position > 0 && row.onDevice) {
396             final android.view.MenuItem moveToTopMenuItem =
397                     menu.add(R.string.moveToTop);
398             moveToTopMenuItem.setOnMenuItemClickListener(new
399                     android.view.MenuItem.OnMenuItemClickListener() {
400                         @Override
401                         public boolean onMenuItemClick(android.view.MenuItem item) {
402                             application.moveDictionaryToTop(row.dictionaryInfo);
403                             setMyListAdapater();
404                             return true;
405                         }
406                     });
407         }
408
409         if (row.onDevice) {
410             final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
411             deleteMenuItem
412                     .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
413                         @Override
414                         public boolean onMenuItemClick(android.view.MenuItem item) {
415                             application.deleteDictionary(row.dictionaryInfo);
416                             setMyListAdapater();
417                             return true;
418                         }
419                     });
420         }
421     }
422
423     private void onShowDownloadableChanged() {
424         setMyListAdapater();
425         Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
426         prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
427         prefs.commit();
428     }
429
430     class MyListAdapter extends BaseAdapter {
431
432         List<DictionaryInfo> dictionariesOnDevice;
433         List<DictionaryInfo> downloadableDictionaries;
434
435         class Row {
436             DictionaryInfo dictionaryInfo;
437             boolean onDevice;
438
439             private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
440                 this.dictionaryInfo = dictinoaryInfo;
441                 this.onDevice = onDevice;
442             }
443         }
444
445         private MyListAdapter(final String[] filters) {
446             dictionariesOnDevice = application.getDictionariesOnDevice(filters);
447             if (showDownloadable.isChecked()) {
448                 downloadableDictionaries = application.getDownloadableDictionaries(filters);
449             } else {
450                 downloadableDictionaries = Collections.emptyList();
451             }
452         }
453
454         @Override
455         public int getCount() {
456             return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
457         }
458
459         @Override
460         public Row getItem(int position) {
461             if (position == 0) {
462                 return new Row(null, true);
463             }
464             position -= 1;
465
466             if (position < dictionariesOnDevice.size()) {
467                 return new Row(dictionariesOnDevice.get(position), true);
468             }
469             position -= dictionariesOnDevice.size();
470
471             if (position == 0) {
472                 return new Row(null, false);
473             }
474             position -= 1;
475
476             assert position < downloadableDictionaries.size();
477             return new Row(downloadableDictionaries.get(position), false);
478         }
479
480         @Override
481         public long getItemId(int position) {
482             return position;
483         }
484
485         @Override
486         public View getView(int position, View convertView, ViewGroup parent) {
487             if (convertView instanceof LinearLayout &&
488                     convertView != dictionariesOnDeviceHeaderRow &&
489                     convertView != downloadableDictionariesHeaderRow) {
490                 /*
491                  * This is done to try to avoid leaking memory that used to
492                  * happen on Android 4.0.3
493                  */
494                 ((LinearLayout) convertView).removeAllViews();
495             }
496
497             final Row row = getItem(position);
498
499             if (row.onDevice) {
500                 if (row.dictionaryInfo == null) {
501                     return dictionariesOnDeviceHeaderRow;
502                 }
503                 return createDictionaryRow(row.dictionaryInfo, parent, true);
504             }
505
506             if (row.dictionaryInfo == null) {
507                 return downloadableDictionariesHeaderRow;
508             }
509             return createDictionaryRow(row.dictionaryInfo, parent, false);
510         }
511
512     }
513
514     private void setMyListAdapater() {
515         final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
516                 .toString();
517         final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
518         setListAdapter(new MyListAdapter(filters));
519     }
520
521     private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
522             final ViewGroup parent, final boolean canLaunch) {
523
524         View row = LayoutInflater.from(parent.getContext()).inflate(
525                 R.layout.dictionary_manager_row, parent, false);
526         final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
527         final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
528         name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
529
530         final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
531         final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
532         final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
533         if (!canLaunch || updateAvailable) {
534             downloadButton
535                     .setText(getString(
536                             R.string.downloadButton,
537                             downloadable.zipBytes / 1024.0 / 1024.0));
538             downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
539             downloadButton.setOnClickListener(new OnClickListener() {
540                 @Override
541                 public void onClick(View arg0) {
542                     downloadDictionary(downloadable.downloadUrl);
543                 }
544             });
545         } else {
546             downloadButton.setVisibility(View.INVISIBLE);
547         }
548
549         LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
550         final List<IndexInfo> sortedIndexInfos = application
551                 .sortedIndexInfos(dictionaryInfo.indexInfos);
552         final StringBuilder builder = new StringBuilder();
553         if (updateAvailable) {
554             builder.append(getString(R.string.updateAvailable));
555         }
556         for (IndexInfo indexInfo : sortedIndexInfos) {
557             final View button = application.createButton(buttons.getContext(), dictionaryInfo,
558                     indexInfo);
559             buttons.addView(button);
560
561             if (canLaunch) {
562                 button.setOnClickListener(
563                         new IntentLauncher(buttons.getContext(),
564                                 DictionaryActivity.getLaunchIntent(getApplicationContext(),
565                                         application.getPath(dictionaryInfo.uncompressedFilename),
566                                         indexInfo.shortName, "")));
567
568             } else {
569                 button.setEnabled(false);
570             }
571             if (builder.length() != 0) {
572                 builder.append("; ");
573             }
574             builder.append(getString(R.string.indexInfo, indexInfo.shortName,
575                     indexInfo.mainTokenCount));
576         }
577         if (downloadable != null) {
578             builder.append("; ");
579             builder.append(getString(R.string.downloadButton, downloadable.uncompressedBytes / 1024.0 / 1024.0));
580         }
581         details.setText(builder.toString());
582
583         if (canLaunch) {
584             row.setClickable(true);
585             row.setOnClickListener(new IntentLauncher(parent.getContext(),
586                     DictionaryActivity.getLaunchIntent(getApplicationContext(),
587                             application.getPath(dictionaryInfo.uncompressedFilename),
588                             dictionaryInfo.indexInfos.get(0).shortName, "")));
589             row.setFocusable(true);
590             row.setLongClickable(true);
591         }
592         row.setBackgroundResource(android.R.drawable.menuitem_background);
593
594         return row;
595     }
596
597     private void downloadDictionary(final String downloadUrl) {
598         DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
599         Request request = new Request(
600                 Uri.parse(downloadUrl));
601         try {
602             final String destFile = new File(new URL(downloadUrl).getFile())
603                     .getName();
604             Log.d(LOG, "Downloading to: " + destFile);
605
606             request.setDestinationUri(Uri.fromFile(new File(Environment
607                     .getExternalStorageDirectory(), destFile)));
608         } catch (MalformedURLException e) {
609             throw new RuntimeException(e);
610         }
611         downloadManager.enqueue(request);
612     }
613
614 }