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