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.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.support.v7.widget.Toolbar;
37 import android.util.Log;
38 import android.util.TypedValue;
39 import android.view.ContextMenu;
40 import android.view.ContextMenu.ContextMenuInfo;
41 import android.view.LayoutInflater;
42 import android.view.Menu;
43 import android.view.View;
44 import android.view.View.OnClickListener;
45 import android.view.ViewGroup;
46 import android.view.inputmethod.EditorInfo;
47 import android.view.inputmethod.InputMethodManager;
48 import android.widget.AdapterView.AdapterContextMenuInfo;
49 import android.widget.BaseAdapter;
50 import android.widget.Button;
51 import android.widget.CompoundButton;
52 import android.widget.CompoundButton.OnCheckedChangeListener;
53 import android.widget.FrameLayout;
54 import android.widget.LinearLayout;
55 import android.widget.ListAdapter;
56 import android.widget.ListView;
57 import android.widget.TextView;
58 import android.widget.Toast;
59 import android.widget.ToggleButton;
61 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
62 import com.hughes.android.util.IntentLauncher;
65 import java.io.FileOutputStream;
66 import java.io.IOException;
67 import java.io.InputStream;
68 import java.io.OutputStream;
69 import java.net.MalformedURLException;
71 import java.util.Collections;
72 import java.util.List;
73 import java.util.zip.ZipEntry;
74 import java.util.zip.ZipFile;
77 // Delete, move to top.
79 public class DictionaryManagerActivity extends ActionBarActivity {
81 static final String LOG = "QuickDic";
82 static boolean blockAutoLaunch = false;
84 private ListView listView;
85 private ListView getListView() {
86 if (listView == null) {
87 listView = (ListView)findViewById(android.R.id.list);
91 private void setListAdapter(ListAdapter adapter) {
92 getListView().setAdapter(adapter);
94 private ListAdapter getListAdapter() {
95 return getListView().getAdapter();
98 DictionaryApplication application;
100 SearchView filterSearchView;
101 ToggleButton showDownloadable;
103 LinearLayout dictionariesOnDeviceHeaderRow;
104 LinearLayout downloadableDictionariesHeaderRow;
108 Runnable dictionaryUpdater = new Runnable() {
111 if (uiHandler == null) {
114 uiHandler.post(new Runnable() {
123 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
125 public void onReceive(Context context, Intent intent) {
126 final String action = intent.getAction();
128 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
129 final long downloadId = intent.getLongExtra(
130 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
131 final DownloadManager.Query query = new DownloadManager.Query();
132 query.setFilterById(downloadId);
133 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
134 final Cursor cursor = downloadManager.query(query);
136 if (cursor == null || !cursor.moveToFirst()) {
137 Log.e(LOG, "Couldn't find download.");
141 final String dest = cursor
142 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
143 final int status = cursor
145 .getColumnIndex(DownloadManager.COLUMN_STATUS));
146 if (DownloadManager.STATUS_SUCCESSFUL != status) {
147 final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
149 "Download failed: status=" + status +
150 ", reason=" + reason);
151 String msg = Integer.toString(reason);
153 case DownloadManager.ERROR_FILE_ALREADY_EXISTS: msg = "File exists"; break;
154 case DownloadManager.ERROR_FILE_ERROR: msg = "File error"; break;
155 case DownloadManager.ERROR_INSUFFICIENT_SPACE: msg = "Not enough space"; break;
157 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, reason)).setNeutralButton("Close", null).show();
161 Log.w(LOG, "Download finished: " + dest);
162 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
163 Toast.LENGTH_LONG).show();
166 final File localZipFile = new File(Uri.parse(dest).getPath());
168 ZipFile zipFile = new ZipFile(localZipFile);
169 final ZipEntry zipEntry = zipFile.entries().nextElement();
170 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
171 final InputStream zipIn = zipFile.getInputStream(zipEntry);
172 File targetFile = new File(application.getDictDir(), zipEntry.getName());
173 if (targetFile.exists()) {
174 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
175 targetFile = new File(application.getDictDir(), zipEntry.getName());
177 final OutputStream zipOut = new FileOutputStream(targetFile);
178 copyStream(zipIn, zipOut);
180 application.backgroundUpdateDictionaries(dictionaryUpdater);
181 Toast.makeText(context, getString(R.string.installationFinished, dest),
182 Toast.LENGTH_LONG).show();
183 } catch (Exception e) {
184 String msg = getString(R.string.unzippingFailed, dest);
185 File dir = application.getDictDir();
186 if (!dir.canWrite() || !application.checkFileCreate(dir)) {
187 msg = getString(R.string.notWritable, dir.getAbsolutePath());
189 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
190 Log.e(LOG, "Failed to unzip.", e);
192 localZipFile.delete();
198 public static Intent getLaunchIntent(Context c) {
199 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
200 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
205 public void onCreate(Bundle savedInstanceState) {
206 // This must be first, otherwise the actiona bar doesn't get
208 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
210 super.onCreate(savedInstanceState);
211 Log.d(LOG, "onCreate:" + this);
213 application = (DictionaryApplication) getApplication();
215 blockAutoLaunch = false;
218 setContentView(R.layout.dictionary_manager_activity);
220 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
221 getListView().getContext()).inflate(
222 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
224 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
225 getListView().getContext()).inflate(
226 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
228 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
229 .findViewById(R.id.hideDownloadable);
230 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
232 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
233 onShowDownloadableChanged();
237 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
238 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
239 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
240 thanksForUpdatingLatestVersion)) {
241 blockAutoLaunch = true;
242 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
243 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
247 registerReceiver(broadcastReceiver, new IntentFilter(
248 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
251 registerForContextMenu(getListView());
253 final File dictDir = application.getDictDir();
254 if (!dictDir.canRead() || !dictDir.canExecute()) {
255 blockAutoLaunch = true;
257 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
258 builder.setTitle(getString(R.string.error));
259 builder.setMessage(getString(
260 R.string.unableToReadDictionaryDir,
261 dictDir.getAbsolutePath(),
262 Environment.getExternalStorageDirectory()));
263 builder.setNeutralButton("Close", null);
264 builder.create().show();
267 onCreateSetupActionBar();
270 private void onCreateSetupActionBar() {
271 ActionBar actionBar = getSupportActionBar();
272 actionBar.setDisplayShowTitleEnabled(false);
273 actionBar.setDisplayShowHomeEnabled(false);
274 actionBar.setDisplayHomeAsUpEnabled(false);
276 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
277 filterSearchView.setIconifiedByDefault(false);
278 // filterSearchView.setIconified(false); // puts the magnifying glass in
281 filterSearchView.setQueryHint(getString(R.string.searchText));
282 filterSearchView.setSubmitButtonEnabled(false);
283 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
284 FrameLayout.LayoutParams.WRAP_CONTENT);
285 filterSearchView.setLayoutParams(lp);
286 filterSearchView.setImeOptions(
287 EditorInfo.IME_ACTION_DONE |
288 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
289 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
291 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
293 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
295 public boolean onQueryTextSubmit(String query) {
296 filterSearchView.clearFocus();
301 public boolean onQueryTextChange(String filterText) {
306 filterSearchView.setFocusable(true);
308 actionBar.setCustomView(filterSearchView);
309 actionBar.setDisplayShowCustomEnabled(true);
311 // Avoid wasting space on large left inset
312 Toolbar tb = (Toolbar)filterSearchView.getParent();
313 tb.setContentInsetsRelative(0, 0);
317 public void onDestroy() {
319 unregisterReceiver(broadcastReceiver);
322 private static int copyStream(final InputStream in, final OutputStream out)
325 final byte[] bytes = new byte[1024 * 16];
326 while ((bytesRead = in.read(bytes)) != -1) {
327 out.write(bytes, 0, bytesRead);
335 protected void onStart() {
337 uiHandler = new Handler();
341 protected void onStop() {
347 protected void onResume() {
350 if (PreferenceActivity.prefsMightHaveChanged) {
351 PreferenceActivity.prefsMightHaveChanged = false;
353 startActivity(getIntent());
356 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
357 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
359 if (!blockAutoLaunch &&
360 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
361 prefs.contains(C.DICT_FILE) &&
362 prefs.contains(C.INDEX_SHORT_NAME)) {
363 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
364 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
365 new File(prefs.getString(C.DICT_FILE, "")),
366 prefs.getString(C.INDEX_SHORT_NAME, ""),
367 prefs.getString(C.SEARCH_TOKEN, "")));
372 // Remove the active dictionary from the prefs so we won't autolaunch
374 final Editor editor = prefs.edit();
375 editor.remove(C.DICT_FILE);
376 editor.remove(C.INDEX_SHORT_NAME);
377 editor.remove(C.SEARCH_TOKEN);
380 application.backgroundUpdateDictionaries(dictionaryUpdater);
386 public boolean onCreateOptionsMenu(final Menu menu) {
387 application.onCreateGlobalOptionsMenu(this, menu);
392 public void onCreateContextMenu(final ContextMenu menu, final View view,
393 final ContextMenuInfo menuInfo) {
394 super.onCreateContextMenu(menu, view, menuInfo);
395 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
397 final AdapterContextMenuInfo adapterContextMenuInfo =
398 (AdapterContextMenuInfo) menuInfo;
399 final int position = adapterContextMenuInfo.position;
400 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
402 if (row.dictionaryInfo == null) {
406 if (position > 0 && row.onDevice) {
407 final android.view.MenuItem moveToTopMenuItem =
408 menu.add(R.string.moveToTop);
409 moveToTopMenuItem.setOnMenuItemClickListener(new
410 android.view.MenuItem.OnMenuItemClickListener() {
412 public boolean onMenuItemClick(android.view.MenuItem item) {
413 application.moveDictionaryToTop(row.dictionaryInfo);
421 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
423 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
425 public boolean onMenuItemClick(android.view.MenuItem item) {
426 application.deleteDictionary(row.dictionaryInfo);
434 private void onShowDownloadableChanged() {
436 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
437 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
441 class MyListAdapter extends BaseAdapter {
443 List<DictionaryInfo> dictionariesOnDevice;
444 List<DictionaryInfo> downloadableDictionaries;
447 DictionaryInfo dictionaryInfo;
450 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
451 this.dictionaryInfo = dictinoaryInfo;
452 this.onDevice = onDevice;
456 private MyListAdapter(final String[] filters) {
457 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
458 if (showDownloadable.isChecked()) {
459 downloadableDictionaries = application.getDownloadableDictionaries(filters);
461 downloadableDictionaries = Collections.emptyList();
466 public int getCount() {
467 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
471 public Row getItem(int position) {
473 return new Row(null, true);
477 if (position < dictionariesOnDevice.size()) {
478 return new Row(dictionariesOnDevice.get(position), true);
480 position -= dictionariesOnDevice.size();
483 return new Row(null, false);
487 assert position < downloadableDictionaries.size();
488 return new Row(downloadableDictionaries.get(position), false);
492 public long getItemId(int position) {
497 public View getView(int position, View convertView, ViewGroup parent) {
498 if (convertView instanceof LinearLayout &&
499 convertView != dictionariesOnDeviceHeaderRow &&
500 convertView != downloadableDictionariesHeaderRow) {
502 * This is done to try to avoid leaking memory that used to
503 * happen on Android 4.0.3
505 ((LinearLayout) convertView).removeAllViews();
508 final Row row = getItem(position);
511 if (row.dictionaryInfo == null) {
512 return dictionariesOnDeviceHeaderRow;
514 return createDictionaryRow(row.dictionaryInfo, parent, true);
517 if (row.dictionaryInfo == null) {
518 return downloadableDictionariesHeaderRow;
520 return createDictionaryRow(row.dictionaryInfo, parent, false);
525 private void setMyListAdapater() {
526 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
528 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
529 setListAdapter(new MyListAdapter(filters));
532 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
533 final ViewGroup parent, boolean canLaunch) {
535 View row = LayoutInflater.from(parent.getContext()).inflate(
536 R.layout.dictionary_manager_row, parent, false);
537 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
538 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
539 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
541 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
542 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
543 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
544 boolean broken = false;
545 if (!dictionaryInfo.isValid()) {
549 if (downloadable != null && (!canLaunch || updateAvailable)) {
552 R.string.downloadButton,
553 downloadable.zipBytes / 1024.0 / 1024.0));
554 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
555 downloadButton.setOnClickListener(new OnClickListener() {
557 public void onClick(View arg0) {
558 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
562 downloadButton.setVisibility(View.INVISIBLE);
565 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
566 final List<IndexInfo> sortedIndexInfos = application
567 .sortedIndexInfos(dictionaryInfo.indexInfos);
568 final StringBuilder builder = new StringBuilder();
569 if (updateAvailable) {
570 builder.append(getString(R.string.updateAvailable));
572 for (IndexInfo indexInfo : sortedIndexInfos) {
573 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
575 buttons.addView(button);
578 button.setOnClickListener(
579 new IntentLauncher(buttons.getContext(),
580 DictionaryActivity.getLaunchIntent(getApplicationContext(),
581 application.getPath(dictionaryInfo.uncompressedFilename),
582 indexInfo.shortName, "")));
585 button.setEnabled(false);
587 if (builder.length() != 0) {
588 builder.append("; ");
590 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
591 indexInfo.mainTokenCount));
593 builder.append("; ");
594 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
596 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
597 builder.append("; Cannot be used, redownload, check hardware/file system");
598 // Allow deleting, but cannot open
599 row.setLongClickable(true);
601 details.setText(builder.toString());
604 row.setClickable(true);
605 row.setOnClickListener(new IntentLauncher(parent.getContext(),
606 DictionaryActivity.getLaunchIntent(getApplicationContext(),
607 application.getPath(dictionaryInfo.uncompressedFilename),
608 dictionaryInfo.indexInfos.get(0).shortName, "")));
609 row.setFocusable(true);
610 row.setLongClickable(true);
612 row.setBackgroundResource(android.R.drawable.menuitem_background);
617 private void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
618 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
619 final DownloadManager.Query query = new DownloadManager.Query();
620 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
621 final Cursor cursor = downloadManager.query(query);
623 // Due to a bug, cursor is null instead of empty when
624 // the download manager is disabled.
625 if (cursor == null) {
626 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
627 .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
628 .setNeutralButton("Close", null).show();
632 while (cursor.moveToNext()) {
633 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
636 if (!cursor.isAfterLast()) {
637 downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
640 R.string.downloadButton,
641 bytes / 1024.0 / 1024.0));
646 Request request = new Request(
647 Uri.parse(downloadUrl));
649 final String destFile = new File(new URL(downloadUrl).getFile())
651 Log.d(LOG, "Downloading to: " + destFile);
654 request.setDestinationInExternalFilesDir(getApplicationContext(), null, destFile);
655 } catch (IllegalStateException e) {
656 request.setDestinationUri(Uri.fromFile(new File(Environment
657 .getExternalStorageDirectory(), destFile)));
659 } catch (MalformedURLException e) {
660 throw new RuntimeException(e);
662 downloadManager.enqueue(request);
663 downloadButton.setText("X");