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