]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryManagerActivity.java
Clean up error messaging.
[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                     new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.unzippingFailed, dest)).setNeutralButton("Close", null).show();
177                     Log.e(LOG, "Failed to unzip.", e);
178                 } finally {
179                     localZipFile.delete();
180                 }
181             }
182         }
183     };
184
185     public static Intent getLaunchIntent(Context c) {
186         final Intent intent = new Intent(c, DictionaryManagerActivity.class);
187         intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
188         return intent;
189     }
190
191     @Override
192     public void onCreate(Bundle savedInstanceState) {
193         // This must be first, otherwise the actiona bar doesn't get
194         // styled properly.
195         setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
196
197         super.onCreate(savedInstanceState);
198         Log.d(LOG, "onCreate:" + this);
199
200         application = (DictionaryApplication) getApplication();
201
202         blockAutoLaunch = false;
203
204         // UI init.
205         setContentView(R.layout.dictionary_manager_activity);
206
207         dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
208                 getListView().getContext()).inflate(
209                 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
210
211         downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
212                 getListView().getContext()).inflate(
213                 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
214
215         showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
216                 .findViewById(R.id.hideDownloadable);
217         showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
218             @Override
219             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
220                 onShowDownloadableChanged();
221             }
222         });
223
224         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
225         final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
226         if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
227                 thanksForUpdatingLatestVersion)) {
228             blockAutoLaunch = true;
229             startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
230             prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
231                     .commit();
232         }
233
234         registerReceiver(broadcastReceiver, new IntentFilter(
235                 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
236
237         setMyListAdapater();
238         registerForContextMenu(getListView());
239
240         final File dictDir = application.getDictDir();
241         if (!dictDir.canRead() || !dictDir.canExecute()) {
242             blockAutoLaunch = true;
243
244             AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
245             builder.setTitle(getString(R.string.error));
246             builder.setMessage(getString(
247                     R.string.unableToReadDictionaryDir,
248                     dictDir.getAbsolutePath(),
249                     Environment.getExternalStorageDirectory()));
250             builder.setNeutralButton("Close", null);
251             builder.create().show();
252         }
253
254         onCreateSetupActionBar();
255     }
256
257     private void onCreateSetupActionBar() {
258         ActionBar actionBar = getSupportActionBar();
259         actionBar.setDisplayShowTitleEnabled(false);
260
261         filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
262         filterSearchView.setIconifiedByDefault(false);
263         // filterSearchView.setIconified(false); // puts the magnifying glass in
264         // the
265         // wrong place.
266         filterSearchView.setQueryHint(getString(R.string.searchText));
267         filterSearchView.setSubmitButtonEnabled(false);
268         final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
269                 getResources().getDisplayMetrics());
270         FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
271                 FrameLayout.LayoutParams.WRAP_CONTENT);
272         filterSearchView.setLayoutParams(lp);
273         filterSearchView.setImeOptions(
274                 EditorInfo.IME_ACTION_SEARCH |
275                         EditorInfo.IME_FLAG_NO_EXTRACT_UI |
276                         EditorInfo.IME_FLAG_NO_ENTER_ACTION |
277                         // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
278                         // 11
279                         EditorInfo.IME_MASK_ACTION |
280                         EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
281
282         filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
283             @Override
284             public boolean onQueryTextSubmit(String query) {
285                 return true;
286             }
287
288             @Override
289             public boolean onQueryTextChange(String filterText) {
290                 setMyListAdapater();
291                 return true;
292             }
293         });
294         filterSearchView.setFocusable(true);
295
296         actionBar.setCustomView(filterSearchView);
297         actionBar.setDisplayShowCustomEnabled(true);
298     }
299
300     @Override
301     public void onDestroy() {
302         super.onDestroy();
303         unregisterReceiver(broadcastReceiver);
304     }
305
306     private static int copyStream(final InputStream in, final OutputStream out)
307             throws IOException {
308         int bytesRead;
309         final byte[] bytes = new byte[1024 * 16];
310         while ((bytesRead = in.read(bytes)) != -1) {
311             out.write(bytes, 0, bytesRead);
312         }
313         in.close();
314         out.close();
315         return bytesRead;
316     }
317
318     @Override
319     protected void onStart() {
320         super.onStart();
321         uiHandler = new Handler();
322     }
323
324     @Override
325     protected void onStop() {
326         super.onStop();
327         uiHandler = null;
328     }
329
330     @Override
331     protected void onResume() {
332         super.onResume();
333
334         if (PreferenceActivity.prefsMightHaveChanged) {
335             PreferenceActivity.prefsMightHaveChanged = false;
336             finish();
337             startActivity(getIntent());
338         }
339
340         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
341         showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
342
343         if (!blockAutoLaunch &&
344                 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
345                 prefs.contains(C.DICT_FILE) &&
346                 prefs.contains(C.INDEX_SHORT_NAME)) {
347             Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
348             startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
349                     new File(prefs.getString(C.DICT_FILE, "")),
350                     prefs.getString(C.INDEX_SHORT_NAME, ""),
351                     prefs.getString(C.SEARCH_TOKEN, "")));
352             finish();
353             return;
354         }
355
356         // Remove the active dictionary from the prefs so we won't autolaunch
357         // next time.
358         final Editor editor = prefs.edit();
359         editor.remove(C.DICT_FILE);
360         editor.remove(C.INDEX_SHORT_NAME);
361         editor.remove(C.SEARCH_TOKEN);
362         editor.commit();
363
364         application.backgroundUpdateDictionaries(dictionaryUpdater);
365
366         setMyListAdapater();
367     }
368
369     @Override
370     public boolean onCreateOptionsMenu(final Menu menu) {
371         application.onCreateGlobalOptionsMenu(this, menu);
372         return true;
373     }
374
375     @Override
376     public void onCreateContextMenu(final ContextMenu menu, final View view,
377             final ContextMenuInfo menuInfo) {
378         super.onCreateContextMenu(menu, view, menuInfo);
379         Log.d(LOG, "onCreateContextMenu, " + menuInfo);
380
381         final AdapterContextMenuInfo adapterContextMenuInfo =
382                 (AdapterContextMenuInfo) menuInfo;
383         final int position = adapterContextMenuInfo.position;
384         final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
385
386         if (row.dictionaryInfo == null) {
387             return;
388         }
389
390         if (position > 0 && row.onDevice) {
391             final android.view.MenuItem moveToTopMenuItem =
392                     menu.add(R.string.moveToTop);
393             moveToTopMenuItem.setOnMenuItemClickListener(new
394                     android.view.MenuItem.OnMenuItemClickListener() {
395                         @Override
396                         public boolean onMenuItemClick(android.view.MenuItem item) {
397                             application.moveDictionaryToTop(row.dictionaryInfo);
398                             setMyListAdapater();
399                             return true;
400                         }
401                     });
402         }
403
404         if (row.onDevice) {
405             final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
406             deleteMenuItem
407                     .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
408                         @Override
409                         public boolean onMenuItemClick(android.view.MenuItem item) {
410                             application.deleteDictionary(row.dictionaryInfo);
411                             setMyListAdapater();
412                             return true;
413                         }
414                     });
415         }
416     }
417
418     private void onShowDownloadableChanged() {
419         setMyListAdapater();
420         Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
421         prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
422         prefs.commit();
423     }
424
425     class MyListAdapter extends BaseAdapter {
426
427         List<DictionaryInfo> dictionariesOnDevice;
428         List<DictionaryInfo> downloadableDictionaries;
429
430         class Row {
431             DictionaryInfo dictionaryInfo;
432             boolean onDevice;
433
434             private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
435                 this.dictionaryInfo = dictinoaryInfo;
436                 this.onDevice = onDevice;
437             }
438         }
439
440         private MyListAdapter(final String[] filters) {
441             dictionariesOnDevice = application.getDictionariesOnDevice(filters);
442             if (showDownloadable.isChecked()) {
443                 downloadableDictionaries = application.getDownloadableDictionaries(filters);
444             } else {
445                 downloadableDictionaries = Collections.emptyList();
446             }
447         }
448
449         @Override
450         public int getCount() {
451             return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
452         }
453
454         @Override
455         public Row getItem(int position) {
456             if (position == 0) {
457                 return new Row(null, true);
458             }
459             position -= 1;
460
461             if (position < dictionariesOnDevice.size()) {
462                 return new Row(dictionariesOnDevice.get(position), true);
463             }
464             position -= dictionariesOnDevice.size();
465
466             if (position == 0) {
467                 return new Row(null, false);
468             }
469             position -= 1;
470
471             assert position < downloadableDictionaries.size();
472             return new Row(downloadableDictionaries.get(position), false);
473         }
474
475         @Override
476         public long getItemId(int position) {
477             return position;
478         }
479
480         @Override
481         public View getView(int position, View convertView, ViewGroup parent) {
482             if (convertView instanceof LinearLayout &&
483                     convertView != dictionariesOnDeviceHeaderRow &&
484                     convertView != downloadableDictionariesHeaderRow) {
485                 /*
486                  * This is done to try to avoid leaking memory that used to
487                  * happen on Android 4.0.3
488                  */
489                 ((LinearLayout) convertView).removeAllViews();
490             }
491
492             final Row row = getItem(position);
493
494             if (row.onDevice) {
495                 if (row.dictionaryInfo == null) {
496                     return dictionariesOnDeviceHeaderRow;
497                 }
498                 return createDictionaryRow(row.dictionaryInfo, parent, true);
499             }
500
501             if (row.dictionaryInfo == null) {
502                 return downloadableDictionariesHeaderRow;
503             }
504             return createDictionaryRow(row.dictionaryInfo, parent, false);
505         }
506
507     }
508
509     private void setMyListAdapater() {
510         final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
511                 .toString();
512         final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
513         setListAdapter(new MyListAdapter(filters));
514     }
515
516     private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
517             final ViewGroup parent, final boolean canLaunch) {
518
519         View row = LayoutInflater.from(parent.getContext()).inflate(
520                 R.layout.dictionary_manager_row, parent, false);
521         final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
522         final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
523         name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
524
525         final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
526         final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
527         if (!canLaunch || updateAvailable) {
528             final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
529             downloadButton
530                     .setText(getString(
531                             R.string.downloadButton,
532                             downloadable.zipBytes / 1024.0 / 1024.0));
533             downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
534             downloadButton.setOnClickListener(new OnClickListener() {
535                 @Override
536                 public void onClick(View arg0) {
537                     downloadDictionary(downloadable.downloadUrl);
538                 }
539             });
540         } else {
541             downloadButton.setVisibility(View.INVISIBLE);
542         }
543
544         LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
545         final List<IndexInfo> sortedIndexInfos = application
546                 .sortedIndexInfos(dictionaryInfo.indexInfos);
547         final StringBuilder builder = new StringBuilder();
548         if (updateAvailable) {
549             builder.append(getString(R.string.updateAvailable));
550         }
551         for (IndexInfo indexInfo : sortedIndexInfos) {
552             final View button = application.createButton(buttons.getContext(), dictionaryInfo,
553                     indexInfo);
554             buttons.addView(button);
555
556             if (canLaunch) {
557                 button.setOnClickListener(
558                         new IntentLauncher(buttons.getContext(),
559                                 DictionaryActivity.getLaunchIntent(getApplicationContext(),
560                                         application.getPath(dictionaryInfo.uncompressedFilename),
561                                         indexInfo.shortName, "")));
562
563             } else {
564                 button.setEnabled(false);
565             }
566             if (builder.length() != 0) {
567                 builder.append("; ");
568             }
569             builder.append(getString(R.string.indexInfo, indexInfo.shortName,
570                     indexInfo.mainTokenCount));
571         }
572         details.setText(builder.toString());
573
574         if (canLaunch) {
575             row.setClickable(true);
576             row.setOnClickListener(new IntentLauncher(parent.getContext(),
577                     DictionaryActivity.getLaunchIntent(getApplicationContext(),
578                             application.getPath(dictionaryInfo.uncompressedFilename),
579                             dictionaryInfo.indexInfos.get(0).shortName, "")));
580             row.setFocusable(true);
581             row.setLongClickable(true);
582         }
583         row.setBackgroundResource(android.R.drawable.menuitem_background);
584
585         return row;
586     }
587
588     private void downloadDictionary(final String downloadUrl) {
589         DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
590         Request request = new Request(
591                 Uri.parse(downloadUrl));
592         try {
593             final String destFile = new File(new URL(downloadUrl).getFile())
594                     .getName();
595             Log.d(LOG, "Downloading to: " + destFile);
596
597             request.setDestinationUri(Uri.fromFile(new File(Environment
598                     .getExternalStorageDirectory(), destFile)));
599         } catch (MalformedURLException e) {
600             throw new RuntimeException(e);
601         }
602         downloadManager.enqueue(request);
603     }
604
605 }