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