1 // Copyright 2011 Google Inc. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 package com.hughes.android.dictionary;
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.ContentResolver;
22 import android.content.Context;
23 import android.content.Intent;
24 import android.content.IntentFilter;
25 import android.content.SharedPreferences;
26 import android.content.SharedPreferences.Editor;
27 import android.database.Cursor;
28 import android.net.Uri;
29 import android.os.Bundle;
30 import android.os.Environment;
31 import android.os.Handler;
32 import android.preference.PreferenceManager;
33 import android.support.v7.app.ActionBar;
34 import android.support.v7.app.ActionBarActivity;
35 import android.support.v7.widget.SearchView;
36 import android.support.v7.widget.SearchView.OnQueryTextListener;
37 import android.support.v7.widget.Toolbar;
38 import android.text.InputType;
39 import android.util.Log;
40 import android.util.TypedValue;
41 import android.view.ContextMenu;
42 import android.view.ContextMenu.ContextMenuInfo;
43 import android.view.LayoutInflater;
44 import android.view.Menu;
45 import android.view.View;
46 import android.view.View.OnClickListener;
47 import android.view.ViewGroup;
48 import android.view.inputmethod.EditorInfo;
49 import android.view.inputmethod.InputMethodManager;
50 import android.widget.AdapterView.AdapterContextMenuInfo;
51 import android.widget.BaseAdapter;
52 import android.widget.Button;
53 import android.widget.CompoundButton;
54 import android.widget.CompoundButton.OnCheckedChangeListener;
55 import android.widget.FrameLayout;
56 import android.widget.LinearLayout;
57 import android.widget.ListAdapter;
58 import android.widget.ListView;
59 import android.widget.TextView;
60 import android.widget.Toast;
61 import android.widget.ToggleButton;
63 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
64 import com.hughes.android.util.IntentLauncher;
67 import java.io.FileInputStream;
68 import java.io.FileOutputStream;
69 import java.io.IOException;
70 import java.io.InputStream;
71 import java.io.OutputStream;
72 import java.net.MalformedURLException;
74 import java.util.Collections;
75 import java.util.HashSet;
76 import java.util.List;
78 import java.util.zip.ZipEntry;
79 import java.util.zip.ZipFile;
80 import java.util.zip.ZipInputStream;
83 // Delete, move to top.
85 public class DictionaryManagerActivity extends ActionBarActivity {
87 static final String LOG = "QuickDic";
88 static boolean blockAutoLaunch = false;
90 private ListView listView;
91 private ListView getListView() {
92 if (listView == null) {
93 listView = (ListView)findViewById(android.R.id.list);
97 private void setListAdapter(ListAdapter adapter) {
98 getListView().setAdapter(adapter);
100 private ListAdapter getListAdapter() {
101 return getListView().getAdapter();
104 // For DownloadManager bug workaround
105 private Set<Long> finishedDownloadIds = new HashSet<Long>();
107 DictionaryApplication application;
109 SearchView filterSearchView;
110 ToggleButton showDownloadable;
112 LinearLayout dictionariesOnDeviceHeaderRow;
113 LinearLayout downloadableDictionariesHeaderRow;
117 Runnable dictionaryUpdater = new Runnable() {
120 if (uiHandler == null) {
123 uiHandler.post(new Runnable() {
132 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
134 public synchronized void onReceive(Context context, Intent intent) {
135 final String action = intent.getAction();
137 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
138 final long downloadId = intent.getLongExtra(
139 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
140 if (finishedDownloadIds.contains(downloadId)) return; // ignore double notifications
141 final DownloadManager.Query query = new DownloadManager.Query();
142 query.setFilterById(downloadId);
143 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
144 final Cursor cursor = downloadManager.query(query);
146 if (cursor == null || !cursor.moveToFirst()) {
147 Log.e(LOG, "Couldn't find download.");
151 final String dest = cursor
152 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
153 final int status = cursor
155 .getColumnIndex(DownloadManager.COLUMN_STATUS));
156 if (DownloadManager.STATUS_SUCCESSFUL != status) {
157 final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
159 "Download failed: status=" + status +
160 ", reason=" + reason);
161 String msg = Integer.toString(reason);
163 case DownloadManager.ERROR_FILE_ALREADY_EXISTS: msg = "File exists"; break;
164 case DownloadManager.ERROR_FILE_ERROR: msg = "File error"; break;
165 case DownloadManager.ERROR_INSUFFICIENT_SPACE: msg = "Not enough space"; break;
167 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, msg)).setNeutralButton("Close", null).show();
171 Log.w(LOG, "Download finished: " + dest + " Id: " + downloadId);
172 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
173 Toast.LENGTH_LONG).show();
176 final Uri zipUri = Uri.parse(dest);
177 File localZipFile = null;
178 InputStream zipFileStream = null;
179 ZipInputStream zipFile = null;
180 OutputStream zipOut = null;
182 if (zipUri.getScheme().equals("content")) {
183 zipFileStream = context.getContentResolver().openInputStream(zipUri);
186 localZipFile = new File(zipUri.getPath());
187 zipFileStream = new FileInputStream(localZipFile);
189 zipFile = new ZipInputStream(zipFileStream);
190 final ZipEntry zipEntry = zipFile.getNextEntry();
191 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
192 File targetFile = new File(application.getDictDir(), zipEntry.getName());
193 if (targetFile.exists()) {
194 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
195 targetFile = new File(application.getDictDir(), zipEntry.getName());
197 zipOut = new FileOutputStream(targetFile);
198 copyStream(zipFile, zipOut);
199 application.backgroundUpdateDictionaries(dictionaryUpdater);
200 Toast.makeText(context, getString(R.string.installationFinished, dest),
201 Toast.LENGTH_LONG).show();
202 finishedDownloadIds.add(downloadId);
203 Log.w(LOG, "Unzipping finished: " + dest + " Id: " + downloadId);
204 } catch (Exception e) {
205 String msg = getString(R.string.unzippingFailed, dest);
206 File dir = application.getDictDir();
207 if (!dir.canWrite() || !application.checkFileCreate(dir)) {
208 msg = getString(R.string.notWritable, dir.getAbsolutePath());
210 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
211 Log.e(LOG, "Failed to unzip.", e);
213 try { if (zipOut != null) zipOut.close(); } catch (IOException e) {}
214 try { if (zipFile != null) zipFile.close(); } catch (IOException e) {}
215 try { if (zipFileStream != null) zipFileStream.close(); } catch (IOException e) {}
216 if (localZipFile != null) localZipFile.delete();
222 public static Intent getLaunchIntent(Context c) {
223 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
224 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
229 public void onCreate(Bundle savedInstanceState) {
230 // This must be first, otherwise the actiona bar doesn't get
232 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
234 super.onCreate(savedInstanceState);
235 Log.d(LOG, "onCreate:" + this);
237 application = (DictionaryApplication) getApplication();
239 blockAutoLaunch = false;
242 setContentView(R.layout.dictionary_manager_activity);
244 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
245 getListView().getContext()).inflate(
246 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
248 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
249 getListView().getContext()).inflate(
250 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
252 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
253 .findViewById(R.id.hideDownloadable);
254 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
256 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
257 onShowDownloadableChanged();
261 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
262 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
263 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
264 thanksForUpdatingLatestVersion)) {
265 blockAutoLaunch = true;
266 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
267 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
271 registerReceiver(broadcastReceiver, new IntentFilter(
272 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
275 registerForContextMenu(getListView());
277 final File dictDir = application.getDictDir();
278 if (!dictDir.canRead() || !dictDir.canExecute()) {
279 blockAutoLaunch = true;
281 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
282 builder.setTitle(getString(R.string.error));
283 builder.setMessage(getString(
284 R.string.unableToReadDictionaryDir,
285 dictDir.getAbsolutePath(),
286 Environment.getExternalStorageDirectory()));
287 builder.setNeutralButton("Close", null);
288 builder.create().show();
291 onCreateSetupActionBar();
294 private void onCreateSetupActionBar() {
295 ActionBar actionBar = getSupportActionBar();
296 actionBar.setDisplayShowTitleEnabled(false);
297 actionBar.setDisplayShowHomeEnabled(false);
298 actionBar.setDisplayHomeAsUpEnabled(false);
300 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
301 filterSearchView.setIconifiedByDefault(false);
302 // filterSearchView.setIconified(false); // puts the magnifying glass in
305 filterSearchView.setQueryHint(getString(R.string.searchText));
306 filterSearchView.setSubmitButtonEnabled(false);
307 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
308 FrameLayout.LayoutParams.WRAP_CONTENT);
309 filterSearchView.setLayoutParams(lp);
310 filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT);
311 filterSearchView.setImeOptions(
312 EditorInfo.IME_ACTION_DONE |
313 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
314 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
316 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
318 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
320 public boolean onQueryTextSubmit(String query) {
321 filterSearchView.clearFocus();
326 public boolean onQueryTextChange(String filterText) {
331 filterSearchView.setFocusable(true);
333 actionBar.setCustomView(filterSearchView);
334 actionBar.setDisplayShowCustomEnabled(true);
336 // Avoid wasting space on large left inset
337 Toolbar tb = (Toolbar)filterSearchView.getParent();
338 tb.setContentInsetsRelative(0, 0);
342 public void onDestroy() {
344 unregisterReceiver(broadcastReceiver);
347 private static int copyStream(final InputStream in, final OutputStream out)
350 final byte[] bytes = new byte[1024 * 16];
351 while ((bytesRead = in.read(bytes)) != -1) {
352 out.write(bytes, 0, bytesRead);
360 protected void onStart() {
362 uiHandler = new Handler();
366 protected void onStop() {
372 protected void onResume() {
375 if (PreferenceActivity.prefsMightHaveChanged) {
376 PreferenceActivity.prefsMightHaveChanged = false;
378 startActivity(getIntent());
381 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
382 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
384 if (!blockAutoLaunch &&
385 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
386 prefs.contains(C.DICT_FILE) &&
387 prefs.contains(C.INDEX_SHORT_NAME)) {
388 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
389 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
390 new File(prefs.getString(C.DICT_FILE, "")),
391 prefs.getString(C.INDEX_SHORT_NAME, ""),
392 prefs.getString(C.SEARCH_TOKEN, "")));
397 // Remove the active dictionary from the prefs so we won't autolaunch
399 final Editor editor = prefs.edit();
400 editor.remove(C.DICT_FILE);
401 editor.remove(C.INDEX_SHORT_NAME);
402 editor.remove(C.SEARCH_TOKEN);
405 application.backgroundUpdateDictionaries(dictionaryUpdater);
411 public boolean onCreateOptionsMenu(final Menu menu) {
412 application.onCreateGlobalOptionsMenu(this, menu);
417 public void onCreateContextMenu(final ContextMenu menu, final View view,
418 final ContextMenuInfo menuInfo) {
419 super.onCreateContextMenu(menu, view, menuInfo);
420 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
422 final AdapterContextMenuInfo adapterContextMenuInfo =
423 (AdapterContextMenuInfo) menuInfo;
424 final int position = adapterContextMenuInfo.position;
425 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
427 if (row.dictionaryInfo == null) {
431 if (position > 0 && row.onDevice) {
432 final android.view.MenuItem moveToTopMenuItem =
433 menu.add(R.string.moveToTop);
434 moveToTopMenuItem.setOnMenuItemClickListener(new
435 android.view.MenuItem.OnMenuItemClickListener() {
437 public boolean onMenuItemClick(android.view.MenuItem item) {
438 application.moveDictionaryToTop(row.dictionaryInfo);
446 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
448 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
450 public boolean onMenuItemClick(android.view.MenuItem item) {
451 application.deleteDictionary(row.dictionaryInfo);
459 private void onShowDownloadableChanged() {
461 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
462 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
466 class MyListAdapter extends BaseAdapter {
468 List<DictionaryInfo> dictionariesOnDevice;
469 List<DictionaryInfo> downloadableDictionaries;
472 DictionaryInfo dictionaryInfo;
475 private Row(DictionaryInfo dictionaryInfo, boolean onDevice) {
476 this.dictionaryInfo = dictionaryInfo;
477 this.onDevice = onDevice;
481 private MyListAdapter(final String[] filters) {
482 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
483 if (showDownloadable.isChecked()) {
484 downloadableDictionaries = application.getDownloadableDictionaries(filters);
486 downloadableDictionaries = Collections.emptyList();
491 public int getCount() {
492 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
496 public Row getItem(int position) {
498 return new Row(null, true);
502 if (position < dictionariesOnDevice.size()) {
503 return new Row(dictionariesOnDevice.get(position), true);
505 position -= dictionariesOnDevice.size();
508 return new Row(null, false);
512 assert position < downloadableDictionaries.size();
513 return new Row(downloadableDictionaries.get(position), false);
517 public long getItemId(int position) {
522 public View getView(int position, View convertView, ViewGroup parent) {
523 if (convertView instanceof LinearLayout &&
524 convertView != dictionariesOnDeviceHeaderRow &&
525 convertView != downloadableDictionariesHeaderRow) {
527 * This is done to try to avoid leaking memory that used to
528 * happen on Android 4.0.3
530 ((LinearLayout) convertView).removeAllViews();
533 final Row row = getItem(position);
536 if (row.dictionaryInfo == null) {
537 return dictionariesOnDeviceHeaderRow;
539 return createDictionaryRow(row.dictionaryInfo, parent, true);
542 if (row.dictionaryInfo == null) {
543 return downloadableDictionariesHeaderRow;
545 return createDictionaryRow(row.dictionaryInfo, parent, false);
550 private void setMyListAdapater() {
551 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
553 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
554 setListAdapter(new MyListAdapter(filters));
557 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
558 final ViewGroup parent, boolean canLaunch) {
560 View row = LayoutInflater.from(parent.getContext()).inflate(
561 R.layout.dictionary_manager_row, parent, false);
562 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
563 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
564 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
566 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
567 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
568 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
569 boolean broken = false;
570 if (!dictionaryInfo.isValid()) {
574 if (downloadable != null && (!canLaunch || updateAvailable)) {
577 R.string.downloadButton,
578 downloadable.zipBytes / 1024.0 / 1024.0));
579 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
580 downloadButton.setOnClickListener(new OnClickListener() {
582 public void onClick(View arg0) {
583 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
587 downloadButton.setVisibility(View.INVISIBLE);
590 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
591 final List<IndexInfo> sortedIndexInfos = application
592 .sortedIndexInfos(dictionaryInfo.indexInfos);
593 final StringBuilder builder = new StringBuilder();
594 if (updateAvailable) {
595 builder.append(getString(R.string.updateAvailable));
597 for (IndexInfo indexInfo : sortedIndexInfos) {
598 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
600 buttons.addView(button);
603 button.setOnClickListener(
604 new IntentLauncher(buttons.getContext(),
605 DictionaryActivity.getLaunchIntent(getApplicationContext(),
606 application.getPath(dictionaryInfo.uncompressedFilename),
607 indexInfo.shortName, "")));
610 button.setEnabled(false);
612 if (builder.length() != 0) {
613 builder.append("; ");
615 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
616 indexInfo.mainTokenCount));
618 builder.append("; ");
619 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
621 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
622 builder.append("; Cannot be used, redownload, check hardware/file system");
623 // Allow deleting, but cannot open
624 row.setLongClickable(true);
626 details.setText(builder.toString());
629 row.setClickable(true);
630 row.setOnClickListener(new IntentLauncher(parent.getContext(),
631 DictionaryActivity.getLaunchIntent(getApplicationContext(),
632 application.getPath(dictionaryInfo.uncompressedFilename),
633 dictionaryInfo.indexInfos.get(0).shortName, "")));
634 row.setFocusable(true);
635 row.setLongClickable(true);
637 row.setBackgroundResource(android.R.drawable.menuitem_background);
642 private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
645 destFile = new File(new URL(downloadUrl).getPath()).getName();
646 } catch (MalformedURLException e) {
647 throw new RuntimeException("Invalid download URL!", e);
649 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
650 final DownloadManager.Query query = new DownloadManager.Query();
651 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
652 final Cursor cursor = downloadManager.query(query);
654 // Due to a bug, cursor is null instead of empty when
655 // the download manager is disabled.
656 if (cursor == null) {
657 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
658 .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
659 .setNeutralButton("Close", null).show();
663 while (cursor.moveToNext()) {
664 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
666 if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE))))
669 if (!cursor.isAfterLast()) {
670 downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
673 R.string.downloadButton,
674 bytes / 1024.0 / 1024.0));
679 Request request = new Request(
680 Uri.parse(downloadUrl));
682 Log.d(LOG, "Downloading to: " + destFile);
683 request.setTitle(destFile);
685 File destFilePath = new File(application.getDictDir(), destFile);
686 destFilePath.delete();
688 request.setDestinationUri(Uri.fromFile(destFilePath));
689 } catch (Exception e) {
693 downloadManager.enqueue(request);
694 } catch (SecurityException e) {
695 request = new Request(Uri.parse(downloadUrl));
696 request.setTitle(destFile);
697 downloadManager.enqueue(request);
699 Log.w(LOG, "Download started: " + destFile);
700 downloadButton.setText("X");