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.v4.view.MenuItemCompat;
34 import android.support.v7.app.ActionBar;
35 import android.support.v7.app.ActionBarActivity;
36 import android.support.v7.widget.SearchView;
37 import android.support.v7.widget.SearchView.OnQueryTextListener;
38 import android.support.v7.widget.Toolbar;
39 import android.text.InputType;
40 import android.util.Log;
41 import android.util.TypedValue;
42 import android.view.ContextMenu;
43 import android.view.ContextMenu.ContextMenuInfo;
44 import android.view.LayoutInflater;
45 import android.view.Menu;
46 import android.view.MenuItem;
47 import android.view.View;
48 import android.view.View.OnClickListener;
49 import android.view.ViewGroup;
50 import android.view.inputmethod.EditorInfo;
51 import android.view.inputmethod.InputMethodManager;
52 import android.widget.AdapterView.AdapterContextMenuInfo;
53 import android.widget.BaseAdapter;
54 import android.widget.Button;
55 import android.widget.CompoundButton;
56 import android.widget.CompoundButton.OnCheckedChangeListener;
57 import android.widget.FrameLayout;
58 import android.widget.LinearLayout;
59 import android.widget.ListAdapter;
60 import android.widget.ListView;
61 import android.widget.TextView;
62 import android.widget.Toast;
63 import android.widget.ToggleButton;
65 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
66 import com.hughes.android.util.IntentLauncher;
69 import java.io.FileInputStream;
70 import java.io.FileOutputStream;
71 import java.io.IOException;
72 import java.io.InputStream;
73 import java.io.OutputStream;
74 import java.net.MalformedURLException;
76 import java.util.Collections;
77 import java.util.HashSet;
78 import java.util.List;
80 import java.util.zip.ZipEntry;
81 import java.util.zip.ZipFile;
82 import java.util.zip.ZipInputStream;
85 // Delete, move to top.
87 public class DictionaryManagerActivity extends ActionBarActivity {
89 static final String LOG = "QuickDic";
90 static boolean blockAutoLaunch = false;
92 private ListView listView;
93 private ListView getListView() {
94 if (listView == null) {
95 listView = (ListView)findViewById(android.R.id.list);
99 private void setListAdapter(ListAdapter adapter) {
100 getListView().setAdapter(adapter);
102 private ListAdapter getListAdapter() {
103 return getListView().getAdapter();
106 // For DownloadManager bug workaround
107 private Set<Long> finishedDownloadIds = new HashSet<Long>();
109 DictionaryApplication application;
111 SearchView filterSearchView;
112 ToggleButton showDownloadable;
114 LinearLayout dictionariesOnDeviceHeaderRow;
115 LinearLayout downloadableDictionariesHeaderRow;
119 Runnable dictionaryUpdater = new Runnable() {
122 if (uiHandler == null) {
125 uiHandler.post(new Runnable() {
134 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
136 public synchronized void onReceive(Context context, Intent intent) {
137 final String action = intent.getAction();
139 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
140 final long downloadId = intent.getLongExtra(
141 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
142 if (finishedDownloadIds.contains(downloadId)) return; // ignore double notifications
143 final DownloadManager.Query query = new DownloadManager.Query();
144 query.setFilterById(downloadId);
145 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
146 final Cursor cursor = downloadManager.query(query);
148 if (cursor == null || !cursor.moveToFirst()) {
149 Log.e(LOG, "Couldn't find download.");
153 final String dest = cursor
154 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
155 final int status = cursor
157 .getColumnIndex(DownloadManager.COLUMN_STATUS));
158 if (DownloadManager.STATUS_SUCCESSFUL != status) {
159 final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
161 "Download failed: status=" + status +
162 ", reason=" + reason);
163 String msg = Integer.toString(reason);
165 case DownloadManager.ERROR_FILE_ALREADY_EXISTS: msg = "File exists"; break;
166 case DownloadManager.ERROR_FILE_ERROR: msg = "File error"; break;
167 case DownloadManager.ERROR_INSUFFICIENT_SPACE: msg = "Not enough space"; break;
169 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, msg)).setNeutralButton("Close", null).show();
173 Log.w(LOG, "Download finished: " + dest + " Id: " + downloadId);
174 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
175 Toast.LENGTH_LONG).show();
178 final Uri zipUri = Uri.parse(dest);
179 File localZipFile = null;
180 InputStream zipFileStream = null;
181 ZipInputStream zipFile = null;
182 OutputStream zipOut = null;
184 if (zipUri.getScheme().equals("content")) {
185 zipFileStream = context.getContentResolver().openInputStream(zipUri);
188 localZipFile = new File(zipUri.getPath());
189 zipFileStream = new FileInputStream(localZipFile);
191 zipFile = new ZipInputStream(zipFileStream);
192 final ZipEntry zipEntry = zipFile.getNextEntry();
193 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
194 File targetFile = new File(application.getDictDir(), zipEntry.getName());
195 if (targetFile.exists()) {
196 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
197 targetFile = new File(application.getDictDir(), zipEntry.getName());
199 zipOut = new FileOutputStream(targetFile);
200 copyStream(zipFile, zipOut);
201 application.backgroundUpdateDictionaries(dictionaryUpdater);
202 Toast.makeText(context, getString(R.string.installationFinished, dest),
203 Toast.LENGTH_LONG).show();
204 finishedDownloadIds.add(downloadId);
205 Log.w(LOG, "Unzipping finished: " + dest + " Id: " + downloadId);
206 } catch (Exception e) {
207 String msg = getString(R.string.unzippingFailed, dest);
208 File dir = application.getDictDir();
209 if (!dir.canWrite() || !application.checkFileCreate(dir)) {
210 msg = getString(R.string.notWritable, dir.getAbsolutePath());
212 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
213 Log.e(LOG, "Failed to unzip.", e);
215 try { if (zipOut != null) zipOut.close(); } catch (IOException e) {}
216 try { if (zipFile != null) zipFile.close(); } catch (IOException e) {}
217 try { if (zipFileStream != null) zipFileStream.close(); } catch (IOException e) {}
218 if (localZipFile != null) localZipFile.delete();
224 public static Intent getLaunchIntent(Context c) {
225 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
226 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
231 public void onCreate(Bundle savedInstanceState) {
232 // This must be first, otherwise the actiona bar doesn't get
234 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
236 super.onCreate(savedInstanceState);
237 Log.d(LOG, "onCreate:" + this);
239 application = (DictionaryApplication) getApplication();
241 blockAutoLaunch = false;
244 setContentView(R.layout.dictionary_manager_activity);
246 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
247 getListView().getContext()).inflate(
248 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
250 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
251 getListView().getContext()).inflate(
252 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
254 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
255 .findViewById(R.id.hideDownloadable);
256 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
258 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
259 onShowDownloadableChanged();
263 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
264 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
265 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
266 thanksForUpdatingLatestVersion)) {
267 blockAutoLaunch = true;
268 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
269 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
273 registerReceiver(broadcastReceiver, new IntentFilter(
274 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
277 registerForContextMenu(getListView());
279 final File dictDir = application.getDictDir();
280 if (!dictDir.canRead() || !dictDir.canExecute()) {
281 blockAutoLaunch = true;
283 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
284 builder.setTitle(getString(R.string.error));
285 builder.setMessage(getString(
286 R.string.unableToReadDictionaryDir,
287 dictDir.getAbsolutePath(),
288 Environment.getExternalStorageDirectory()));
289 builder.setNeutralButton("Close", null);
290 builder.create().show();
293 onCreateSetupActionBar();
296 private void onCreateSetupActionBar() {
297 ActionBar actionBar = getSupportActionBar();
298 actionBar.setDisplayShowTitleEnabled(false);
299 actionBar.setDisplayShowHomeEnabled(false);
300 actionBar.setDisplayHomeAsUpEnabled(false);
302 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
303 filterSearchView.setIconifiedByDefault(false);
304 // filterSearchView.setIconified(false); // puts the magnifying glass in
307 filterSearchView.setQueryHint(getString(R.string.searchText));
308 filterSearchView.setSubmitButtonEnabled(false);
309 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
310 FrameLayout.LayoutParams.WRAP_CONTENT);
311 filterSearchView.setLayoutParams(lp);
312 filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT);
313 filterSearchView.setImeOptions(
314 EditorInfo.IME_ACTION_DONE |
315 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
316 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
318 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
320 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
322 public boolean onQueryTextSubmit(String query) {
323 filterSearchView.clearFocus();
328 public boolean onQueryTextChange(String filterText) {
333 filterSearchView.setFocusable(true);
335 actionBar.setCustomView(filterSearchView);
336 actionBar.setDisplayShowCustomEnabled(true);
338 // Avoid wasting space on large left inset
339 Toolbar tb = (Toolbar)filterSearchView.getParent();
340 tb.setContentInsetsRelative(0, 0);
344 public void onDestroy() {
346 unregisterReceiver(broadcastReceiver);
349 private static int copyStream(final InputStream in, final OutputStream out)
352 final byte[] bytes = new byte[1024 * 16];
353 while ((bytesRead = in.read(bytes)) != -1) {
354 out.write(bytes, 0, bytesRead);
362 protected void onStart() {
364 uiHandler = new Handler();
368 protected void onStop() {
374 protected void onResume() {
377 if (PreferenceActivity.prefsMightHaveChanged) {
378 PreferenceActivity.prefsMightHaveChanged = false;
380 startActivity(getIntent());
383 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
384 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
386 if (!blockAutoLaunch &&
387 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
388 prefs.contains(C.DICT_FILE) &&
389 prefs.contains(C.INDEX_SHORT_NAME)) {
390 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
391 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
392 new File(prefs.getString(C.DICT_FILE, "")),
393 prefs.getString(C.INDEX_SHORT_NAME, ""),
394 prefs.getString(C.SEARCH_TOKEN, "")));
399 // Remove the active dictionary from the prefs so we won't autolaunch
401 final Editor editor = prefs.edit();
402 editor.remove(C.DICT_FILE);
403 editor.remove(C.INDEX_SHORT_NAME);
404 editor.remove(C.SEARCH_TOKEN);
407 application.backgroundUpdateDictionaries(dictionaryUpdater);
413 public boolean onCreateOptionsMenu(final Menu menu) {
414 final MenuItem sort = menu.add(getString(R.string.sortDicts));
415 MenuItemCompat.setShowAsAction(sort, MenuItem.SHOW_AS_ACTION_NEVER);
416 sort.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
417 public boolean onMenuItemClick(final MenuItem menuItem) {
418 application.sortDictionaries();
424 application.onCreateGlobalOptionsMenu(this, menu);
429 public void onCreateContextMenu(final ContextMenu menu, final View view,
430 final ContextMenuInfo menuInfo) {
431 super.onCreateContextMenu(menu, view, menuInfo);
432 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
434 final AdapterContextMenuInfo adapterContextMenuInfo =
435 (AdapterContextMenuInfo) menuInfo;
436 final int position = adapterContextMenuInfo.position;
437 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
439 if (row.dictionaryInfo == null) {
443 if (position > 0 && row.onDevice) {
444 final android.view.MenuItem moveToTopMenuItem =
445 menu.add(R.string.moveToTop);
446 moveToTopMenuItem.setOnMenuItemClickListener(new
447 android.view.MenuItem.OnMenuItemClickListener() {
449 public boolean onMenuItemClick(android.view.MenuItem item) {
450 application.moveDictionaryToTop(row.dictionaryInfo);
458 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
460 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
462 public boolean onMenuItemClick(android.view.MenuItem item) {
463 application.deleteDictionary(row.dictionaryInfo);
471 private void onShowDownloadableChanged() {
473 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
474 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
478 class MyListAdapter extends BaseAdapter {
480 List<DictionaryInfo> dictionariesOnDevice;
481 List<DictionaryInfo> downloadableDictionaries;
484 DictionaryInfo dictionaryInfo;
487 private Row(DictionaryInfo dictionaryInfo, boolean onDevice) {
488 this.dictionaryInfo = dictionaryInfo;
489 this.onDevice = onDevice;
493 private MyListAdapter(final String[] filters) {
494 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
495 if (showDownloadable.isChecked()) {
496 downloadableDictionaries = application.getDownloadableDictionaries(filters);
498 downloadableDictionaries = Collections.emptyList();
503 public int getCount() {
504 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
508 public Row getItem(int position) {
510 return new Row(null, true);
514 if (position < dictionariesOnDevice.size()) {
515 return new Row(dictionariesOnDevice.get(position), true);
517 position -= dictionariesOnDevice.size();
520 return new Row(null, false);
524 assert position < downloadableDictionaries.size();
525 return new Row(downloadableDictionaries.get(position), false);
529 public long getItemId(int position) {
534 public View getView(int position, View convertView, ViewGroup parent) {
535 if (convertView instanceof LinearLayout &&
536 convertView != dictionariesOnDeviceHeaderRow &&
537 convertView != downloadableDictionariesHeaderRow) {
539 * This is done to try to avoid leaking memory that used to
540 * happen on Android 4.0.3
542 ((LinearLayout) convertView).removeAllViews();
545 final Row row = getItem(position);
548 if (row.dictionaryInfo == null) {
549 return dictionariesOnDeviceHeaderRow;
551 return createDictionaryRow(row.dictionaryInfo, parent, true);
554 if (row.dictionaryInfo == null) {
555 return downloadableDictionariesHeaderRow;
557 return createDictionaryRow(row.dictionaryInfo, parent, false);
562 private void setMyListAdapater() {
563 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
565 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
566 setListAdapter(new MyListAdapter(filters));
569 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
570 final ViewGroup parent, boolean canLaunch) {
572 View row = LayoutInflater.from(parent.getContext()).inflate(
573 R.layout.dictionary_manager_row, parent, false);
574 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
575 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
576 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
578 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
579 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
580 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
581 boolean broken = false;
582 if (!dictionaryInfo.isValid()) {
586 if (downloadable != null && (!canLaunch || updateAvailable)) {
589 R.string.downloadButton,
590 downloadable.zipBytes / 1024.0 / 1024.0));
591 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
592 downloadButton.setOnClickListener(new OnClickListener() {
594 public void onClick(View arg0) {
595 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
599 downloadButton.setVisibility(View.INVISIBLE);
602 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
603 final List<IndexInfo> sortedIndexInfos = application
604 .sortedIndexInfos(dictionaryInfo.indexInfos);
605 final StringBuilder builder = new StringBuilder();
606 if (updateAvailable) {
607 builder.append(getString(R.string.updateAvailable));
609 for (IndexInfo indexInfo : sortedIndexInfos) {
610 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
612 buttons.addView(button);
615 button.setOnClickListener(
616 new IntentLauncher(buttons.getContext(),
617 DictionaryActivity.getLaunchIntent(getApplicationContext(),
618 application.getPath(dictionaryInfo.uncompressedFilename),
619 indexInfo.shortName, "")));
622 button.setEnabled(false);
624 if (builder.length() != 0) {
625 builder.append("; ");
627 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
628 indexInfo.mainTokenCount));
630 builder.append("; ");
631 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
633 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
634 builder.append("; Cannot be used, redownload, check hardware/file system");
635 // Allow deleting, but cannot open
636 row.setLongClickable(true);
638 details.setText(builder.toString());
641 row.setClickable(true);
642 row.setOnClickListener(new IntentLauncher(parent.getContext(),
643 DictionaryActivity.getLaunchIntent(getApplicationContext(),
644 application.getPath(dictionaryInfo.uncompressedFilename),
645 dictionaryInfo.indexInfos.get(0).shortName, "")));
646 row.setFocusable(true);
647 row.setLongClickable(true);
649 row.setBackgroundResource(android.R.drawable.menuitem_background);
654 private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
657 destFile = new File(new URL(downloadUrl).getPath()).getName();
658 } catch (MalformedURLException e) {
659 throw new RuntimeException("Invalid download URL!", e);
661 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
662 final DownloadManager.Query query = new DownloadManager.Query();
663 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
664 final Cursor cursor = downloadManager.query(query);
666 // Due to a bug, cursor is null instead of empty when
667 // the download manager is disabled.
668 if (cursor == null) {
669 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
670 .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
671 .setNeutralButton("Close", null).show();
675 while (cursor.moveToNext()) {
676 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
678 if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE))))
681 if (!cursor.isAfterLast()) {
682 downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
685 R.string.downloadButton,
686 bytes / 1024.0 / 1024.0));
691 Request request = new Request(
692 Uri.parse(downloadUrl));
694 Log.d(LOG, "Downloading to: " + destFile);
695 request.setTitle(destFile);
697 File destFilePath = new File(application.getDictDir(), destFile);
698 destFilePath.delete();
700 request.setDestinationUri(Uri.fromFile(destFilePath));
701 } catch (Exception e) {
705 downloadManager.enqueue(request);
706 } catch (SecurityException e) {
707 request = new Request(Uri.parse(downloadUrl));
708 request.setTitle(destFile);
709 downloadManager.enqueue(request);
711 Log.w(LOG, "Download started: " + destFile);
712 downloadButton.setText("X");