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