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