]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryManagerActivity.java
Using external storage dir properly, better notifications when missing.
[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.Dialog;
19 import android.app.DownloadManager;
20 import android.app.DownloadManager.Request;
21 import android.content.BroadcastReceiver;
22 import android.content.Context;
23 import android.content.Intent;
24 import android.content.IntentFilter;
25 import android.content.SharedPreferences;
26 import android.content.SharedPreferences.Editor;
27 import android.database.Cursor;
28 import android.net.Uri;
29 import android.os.Bundle;
30 import android.os.Environment;
31 import android.os.Handler;
32 import android.preference.PreferenceManager;
33 import android.util.Log;
34 import android.view.ContextMenu;
35 import android.view.ContextMenu.ContextMenuInfo;
36 import android.view.LayoutInflater;
37 import android.view.View;
38 import android.view.View.OnClickListener;
39 import android.view.ViewGroup;
40 import android.widget.AdapterView.AdapterContextMenuInfo;
41 import android.widget.BaseAdapter;
42 import android.widget.Button;
43 import android.widget.CompoundButton;
44 import android.widget.ListView;
45 import android.widget.Toast;
46 import android.widget.CompoundButton.OnCheckedChangeListener;
47 import android.widget.LinearLayout;
48 import android.widget.TextView;
49 import android.widget.ToggleButton;
50
51 import com.actionbarsherlock.app.SherlockListActivity;
52 import com.actionbarsherlock.view.Menu;
53 import com.actionbarsherlock.view.MenuInflater;
54 import com.actionbarsherlock.widget.SearchView;
55 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
56 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
57 import com.hughes.android.util.IntentLauncher;
58
59 import java.io.File;
60 import java.io.FileOutputStream;
61 import java.io.IOException;
62 import java.io.InputStream;
63 import java.io.OutputStream;
64 import java.net.MalformedURLException;
65 import java.net.URL;
66 import java.util.Collections;
67 import java.util.List;
68 import java.util.zip.ZipEntry;
69 import java.util.zip.ZipFile;
70
71 // Right-click:
72 //  Delete, move to top.
73
74 public class DictionaryManagerActivity extends SherlockListActivity {
75
76     static final String LOG = "QuickDic";
77     static boolean blockAutoLaunch = false;
78
79     DictionaryApplication application;
80
81     SearchView filterSearchView;
82     ToggleButton showDownloadable;
83
84     LinearLayout dictionariesOnDeviceHeaderRow;
85     LinearLayout downloadableDictionariesHeaderRow;
86
87     Handler uiHandler;
88     
89     Runnable dictionaryUpdater = new Runnable() {
90         @Override
91         public void run() {
92             if (uiHandler == null) {
93                 return;
94             }
95             uiHandler.post(new Runnable() {
96                 @Override
97                 public void run() {
98                     setListAdapater();
99                 }
100             });
101         }
102     };
103     
104     final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
105         @Override
106         public void onReceive(Context context, Intent intent) {
107             final String action = intent.getAction();
108
109             if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
110                 final long downloadId = intent.getLongExtra(
111                         DownloadManager.EXTRA_DOWNLOAD_ID, 0);
112                 final DownloadManager.Query query = new DownloadManager.Query();
113                 query.setFilterById(downloadId);
114                 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
115                 final Cursor cursor = downloadManager.query(query);
116
117                 if (!cursor.moveToFirst()) {
118                     Log.e(LOG, "Couldn't find download.");
119                     return;
120                 }
121
122                 final String dest = cursor
123                         .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
124                 final int status = cursor
125                         .getInt(cursor
126                                 .getColumnIndex(DownloadManager.COLUMN_STATUS));
127                 if (DownloadManager.STATUS_SUCCESSFUL != status) {
128                     Log.w(LOG,
129                             "Download failed: status=" + status +
130                                     ", reason=" + cursor.getString(cursor
131                                             .getColumnIndex(DownloadManager.COLUMN_REASON)));
132                     Toast.makeText(context, getString(R.string.downloadFailed, dest),
133                             Toast.LENGTH_LONG).show();
134                     return;
135                 }
136
137                 Log.w(LOG, "Download finished: " + dest);
138                 final File localZipFile = new File(Uri.parse(dest).getPath());
139
140                 try {
141                     ZipFile zipFile = new ZipFile(localZipFile);
142                     final ZipEntry zipEntry = zipFile.entries().nextElement();
143                     Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
144                     final InputStream zipIn = zipFile.getInputStream(zipEntry);
145                     final OutputStream zipOut = new FileOutputStream(
146                             new File(application.getDictDir(), zipEntry.getName()));
147                     copyStream(zipIn, zipOut);
148                     zipFile.close();
149                     application.backgroundUpdateDictionaries(dictionaryUpdater);
150                     Toast.makeText(context, getString(R.string.downloadFinished, dest),
151                             Toast.LENGTH_LONG).show();
152                 } catch (Exception e) {
153                     Toast.makeText(context, getString(R.string.downloadFailed, dest),
154                             Toast.LENGTH_LONG).show();
155                     Log.e(LOG, "Failed to unzip.", e);
156                 } finally {
157                     localZipFile.delete();
158                 }
159             }
160         }
161     };
162
163     public static Intent getLaunchIntent() {
164         final Intent intent = new Intent();
165         intent.setClassName(DictionaryManagerActivity.class.getPackage().getName(),
166                 DictionaryManagerActivity.class.getName());
167         intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
168         return intent;
169     }
170
171     @Override
172     public void onCreate(Bundle savedInstanceState) {
173         setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
174
175         super.onCreate(savedInstanceState);
176         Log.d(LOG, "onCreate:" + this);
177
178         application = (DictionaryApplication) getApplication();
179         
180         blockAutoLaunch = false;
181         
182         // UI init.
183         setContentView(R.layout.dictionary_manager_activity);
184
185         dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
186                 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
187
188         downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
189                 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
190
191         showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow.findViewById(R.id.hideDownloadable);
192         showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
193             @Override
194             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
195                 onShowLocalChanged();
196             }
197         });
198
199         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
200         final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
201         if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
202                 thanksForUpdatingLatestVersion)) {
203             blockAutoLaunch = true;
204             startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent());
205             prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
206                     .commit();
207         }
208         
209          
210         registerReceiver(broadcastReceiver, new IntentFilter(
211                 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
212         
213         setListAdapater();
214         registerForContextMenu(getListView());
215         
216         final File dictDir = application.getDictDir();
217         if (!dictDir.canRead() || !dictDir.canExecute()) {
218             blockAutoLaunch = true;
219             
220             AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
221             builder.setTitle(getString(R.string.error));
222             builder.setMessage(getString(
223                     R.string.unableToReadDictionaryDir, 
224                     dictDir.getAbsolutePath(), 
225                     Environment.getExternalStorageDirectory()));
226             builder.create().show();
227         }
228     }
229     
230     @Override
231     public void onDestroy() {
232         super.onDestroy();
233         unregisterReceiver(broadcastReceiver);
234     }
235     
236     private static int copyStream(final InputStream in, final OutputStream out)
237             throws IOException {
238         int bytesRead;
239         final byte[] bytes = new byte[1024 * 16];
240         while ((bytesRead = in.read(bytes)) != -1) {
241             out.write(bytes, 0, bytesRead);
242         }
243         in.close();
244         out.close();
245         return bytesRead;
246     }
247
248     @Override
249     protected void onStart() {
250         super.onStart();
251         uiHandler = new Handler();
252     }
253
254     @Override
255     protected void onStop() {
256         super.onStop();
257         uiHandler = null;
258     }
259
260     @Override
261     protected void onResume() {
262         super.onResume();
263
264         if (PreferenceActivity.prefsMightHaveChanged) {
265             PreferenceActivity.prefsMightHaveChanged = false;
266             finish();
267             startActivity(getIntent());
268         }
269
270         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
271         showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, false));
272
273         if (!blockAutoLaunch &&
274                 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
275                 prefs.contains(C.DICT_FILE) &&
276                 prefs.contains(C.INDEX_SHORT_NAME)) {
277             Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
278             startActivity(DictionaryActivity.getLaunchIntent(
279                     new File(prefs.getString(C.DICT_FILE, "")), prefs.getString(C.INDEX_SHORT_NAME, ""),
280                     prefs.getString(C.SEARCH_TOKEN, "")));
281             finish();
282             return;
283         }
284         
285         // Remove the active dictionary from the prefs so we won't autolaunch
286         // next time.
287         final Editor editor = prefs.edit();
288         editor.remove(C.DICT_FILE);
289         editor.remove(C.INDEX_SHORT_NAME);
290         editor.remove(C.SEARCH_TOKEN);
291         editor.commit();
292
293         application.backgroundUpdateDictionaries(dictionaryUpdater);
294
295         setListAdapater();
296     }
297
298     @Override
299     public boolean onCreateOptionsMenu(final Menu menu) {
300         MenuInflater inflater = getSupportMenuInflater();
301         inflater.inflate(R.menu.dictionary_manager_options_menu, menu);
302         
303         filterSearchView = (SearchView) menu.findItem(R.id.filterText).getActionView();
304         filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
305             @Override
306             public boolean onQueryTextSubmit(String query) {
307                 return true;
308             }
309             
310             @Override
311             public boolean onQueryTextChange(String filterText) {
312                 setListAdapater();
313                 return true;
314             }
315         });
316         filterSearchView.setIconifiedByDefault(false);
317
318         application.onCreateGlobalOptionsMenu(this, menu);
319         return true;
320     }
321
322     @Override
323     public void onCreateContextMenu(final ContextMenu menu, final View view,
324             final ContextMenuInfo menuInfo) {
325         super.onCreateContextMenu(menu, view, menuInfo);
326         Log.d(LOG, "onCreateContextMenu, " + menuInfo);
327
328         final AdapterContextMenuInfo adapterContextMenuInfo =
329                 (AdapterContextMenuInfo) menuInfo;
330         final int position = adapterContextMenuInfo.position;
331         final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
332         
333         if (row.dictionaryInfo == null) {
334             return;
335         }
336
337         if (position > 0 && row.onDevice) {
338             final android.view.MenuItem moveToTopMenuItem =
339                     menu.add(R.string.moveToTop);
340             moveToTopMenuItem.setOnMenuItemClickListener(new
341                     android.view.MenuItem.OnMenuItemClickListener() {
342                         @Override
343                         public boolean onMenuItemClick(android.view.MenuItem item) {
344                             application.moveDictionaryToTop(row.dictionaryInfo);
345                             setListAdapater();
346                             return true;
347                         }
348                     });
349         }
350
351         if (row.onDevice) {
352             final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
353             deleteMenuItem
354                     .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
355                         @Override
356                         public boolean onMenuItemClick(android.view.MenuItem item) {
357                             application.deleteDictionary(row.dictionaryInfo);
358                             setListAdapater();
359                             return true;
360                         }
361                 });
362         }
363     }
364
365     private void onShowLocalChanged() {
366         setListAdapater();
367         Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
368         prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
369         prefs.commit();
370     }
371
372     // private void onClick(int index) {
373     // final DictionaryInfo dictionaryInfo = adapter.getItem(index);
374     // final DictionaryInfo downloadable =
375     // application.getDownloadable(dictionaryInfo.uncompressedFilename);
376     // if
377     // (!application.isDictionaryOnDevice(dictionaryInfo.uncompressedFilename)
378     // && downloadable != null) {
379     // final Intent intent = getDownloadIntent(downloadable);
380     // startActivity(intent);
381     // } else {
382     // final Intent intent =
383     // DictionaryActivity.getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
384     // 0, "");
385     // startActivity(intent);
386     // }
387     // }
388     
389     
390     class MyListAdapter extends BaseAdapter {
391
392         List<DictionaryInfo> dictionariesOnDevice;
393         List<DictionaryInfo> downloadableDictionaries;
394         
395         class Row {
396             DictionaryInfo dictionaryInfo;
397             boolean onDevice;
398             
399             private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
400                 this.dictionaryInfo = dictinoaryInfo;
401                 this.onDevice = onDevice;
402             }
403         }
404
405         
406         private MyListAdapter(final String[] filters) {
407             dictionariesOnDevice = application.getDictionariesOnDevice(filters);
408             if (showDownloadable.isChecked()) {
409                 downloadableDictionaries = application.getDownloadableDictionaries(filters);
410             } else {
411                 downloadableDictionaries = Collections.emptyList();
412             }
413         }
414
415         @Override
416         public int getCount() {
417             return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
418         }
419
420         @Override
421         public Row getItem(int position) {
422             if (position == 0) {
423                 return new Row(null, true);
424             }
425             position -= 1;
426             
427             if (position < dictionariesOnDevice.size()) {
428                 return new Row(dictionariesOnDevice.get(position), true);
429             }
430             position -= dictionariesOnDevice.size();
431             
432             if (position == 0) {
433                 return new Row(null, false);
434             }
435             position -= 1;
436             
437             assert position < downloadableDictionaries.size();
438             return new Row(downloadableDictionaries.get(position), false);
439         }
440
441         @Override
442         public long getItemId(int position) {
443             return position;
444         }
445
446         @Override
447         public View getView(int position, View convertView, ViewGroup parent) {
448             if (convertView instanceof LinearLayout && 
449                     convertView != dictionariesOnDeviceHeaderRow && 
450                     convertView != downloadableDictionariesHeaderRow) {
451                 /* This is done to try to avoid leaking memory that used to 
452                  * happen on Android 4.0.3 */
453                 ((LinearLayout)convertView).removeAllViews();
454             }
455             
456             final Row row = getItem(position);
457             
458             if (row.onDevice) {
459                 if (row.dictionaryInfo == null) {
460                     return dictionariesOnDeviceHeaderRow;
461                 }
462                 return createDictionaryRow(row.dictionaryInfo, parent, true);
463             }
464             
465             if (row.dictionaryInfo == null) {
466                 return downloadableDictionariesHeaderRow;
467             }
468             return createDictionaryRow(row.dictionaryInfo, parent, false);
469         }
470         
471     }
472     
473     private void setListAdapater() {
474         final String filter = filterSearchView == null ? "" : filterSearchView.getQuery().toString();
475         final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
476         setListAdapter(new MyListAdapter(filters));
477     }
478
479     private View createDictionaryRow(final DictionaryInfo dictionaryInfo, 
480             final ViewGroup parent, final boolean canLaunch) {
481         
482         View row = LayoutInflater.from(parent.getContext()).inflate(
483                 R.layout.dictionary_manager_row, parent, false);
484         final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
485         final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
486         name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
487
488         final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
489         final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
490         if (!canLaunch || updateAvailable) {
491             downloadButton.setText(getString(R.string.downloadButton, application.getDownloadable(dictionaryInfo.uncompressedFilename).zipBytes / 1024.0 / 1024.0));
492             downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
493             downloadButton.setOnClickListener(new OnClickListener() {
494                 @Override
495                 public void onClick(View arg0) {
496                     downloadDictionary(dictionaryInfo);
497                 }
498             });
499         } else {
500             downloadButton.setVisibility(View.INVISIBLE);
501         }
502
503         LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
504         final List<IndexInfo> sortedIndexInfos = application.sortedIndexInfos(dictionaryInfo.indexInfos);
505         final StringBuilder builder = new StringBuilder();
506         if (updateAvailable) {
507             builder.append(getString(R.string.updateButton));
508         }
509         for (IndexInfo indexInfo : sortedIndexInfos) {
510             final View button = application.createButton(buttons.getContext(), dictionaryInfo, indexInfo);
511             buttons.addView(button);
512             
513             if (canLaunch) {
514                 button.setOnClickListener(
515                         new IntentLauncher(buttons.getContext(), 
516                         DictionaryActivity.getLaunchIntent(
517                                 application.getPath(dictionaryInfo.uncompressedFilename), 
518                                 indexInfo.shortName, "")));
519
520             } else {
521                 button.setEnabled(false);
522             }
523             if (builder.length() != 0) {
524                 builder.append("; ");
525             }
526             builder.append(getString(R.string.indexInfo, indexInfo.shortName, indexInfo.mainTokenCount));
527         }
528         details.setText(builder.toString());
529         
530         row.setClickable(true);
531         row.setFocusable(true);
532         row.setLongClickable(true);
533         row.setBackgroundResource(android.R.drawable.menuitem_background);
534         
535         return row;
536     }
537     
538     private void downloadDictionary(final DictionaryInfo dictionaryInfo) {
539         DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
540         Request request = new Request(
541                 Uri.parse(dictionaryInfo.downloadUrl));
542         try {
543             final String destFile = new File(new URL(dictionaryInfo.downloadUrl).getFile()).getName(); 
544             Log.d(LOG, "Downloading to: " + destFile);
545             
546             request.setDestinationUri(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), destFile)));
547         } catch (MalformedURLException e) {
548             throw new RuntimeException(e);
549         }
550         downloadManager.enqueue(request);
551     }
552
553 }