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);
181 application.backgroundUpdateDictionaries(dictionaryUpdater);
182 Toast.makeText(context, getString(R.string.installationFinished, dest),
183 Toast.LENGTH_LONG).show();
184 } catch (Exception e) {
185 String msg = getString(R.string.unzippingFailed, dest);
186 File dir = application.getDictDir();
187 if (!dir.canWrite() || !application.checkFileCreate(dir)) {
188 msg = getString(R.string.notWritable, dir.getAbsolutePath());
190 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
191 Log.e(LOG, "Failed to unzip.", e);
193 localZipFile.delete();
199 public static Intent getLaunchIntent(Context c) {
200 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
201 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
206 public void onCreate(Bundle savedInstanceState) {
207 // This must be first, otherwise the actiona bar doesn't get
209 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
211 super.onCreate(savedInstanceState);
212 Log.d(LOG, "onCreate:" + this);
214 application = (DictionaryApplication) getApplication();
216 blockAutoLaunch = false;
219 setContentView(R.layout.dictionary_manager_activity);
221 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
222 getListView().getContext()).inflate(
223 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
225 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
226 getListView().getContext()).inflate(
227 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
229 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
230 .findViewById(R.id.hideDownloadable);
231 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
233 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
234 onShowDownloadableChanged();
238 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
239 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
240 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
241 thanksForUpdatingLatestVersion)) {
242 blockAutoLaunch = true;
243 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
244 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
248 registerReceiver(broadcastReceiver, new IntentFilter(
249 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
252 registerForContextMenu(getListView());
254 final File dictDir = application.getDictDir();
255 if (!dictDir.canRead() || !dictDir.canExecute()) {
256 blockAutoLaunch = true;
258 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
259 builder.setTitle(getString(R.string.error));
260 builder.setMessage(getString(
261 R.string.unableToReadDictionaryDir,
262 dictDir.getAbsolutePath(),
263 Environment.getExternalStorageDirectory()));
264 builder.setNeutralButton("Close", null);
265 builder.create().show();
268 onCreateSetupActionBar();
271 private void onCreateSetupActionBar() {
272 ActionBar actionBar = getSupportActionBar();
273 actionBar.setDisplayShowTitleEnabled(false);
274 actionBar.setDisplayShowHomeEnabled(false);
275 actionBar.setDisplayHomeAsUpEnabled(false);
277 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
278 filterSearchView.setIconifiedByDefault(false);
279 // filterSearchView.setIconified(false); // puts the magnifying glass in
282 filterSearchView.setQueryHint(getString(R.string.searchText));
283 filterSearchView.setSubmitButtonEnabled(false);
284 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
285 FrameLayout.LayoutParams.WRAP_CONTENT);
286 filterSearchView.setLayoutParams(lp);
287 filterSearchView.setImeOptions(
288 EditorInfo.IME_ACTION_DONE |
289 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
290 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
292 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
294 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
296 public boolean onQueryTextSubmit(String query) {
297 filterSearchView.clearFocus();
302 public boolean onQueryTextChange(String filterText) {
307 filterSearchView.setFocusable(true);
309 actionBar.setCustomView(filterSearchView);
310 actionBar.setDisplayShowCustomEnabled(true);
312 // Avoid wasting space on large left inset
313 Toolbar tb = (Toolbar)filterSearchView.getParent();
314 tb.setContentInsetsRelative(0, 0);
318 public void onDestroy() {
320 unregisterReceiver(broadcastReceiver);
323 private static int copyStream(final InputStream in, final OutputStream out)
326 final byte[] bytes = new byte[1024 * 16];
327 while ((bytesRead = in.read(bytes)) != -1) {
328 out.write(bytes, 0, bytesRead);
336 protected void onStart() {
338 uiHandler = new Handler();
342 protected void onStop() {
348 protected void onResume() {
351 if (PreferenceActivity.prefsMightHaveChanged) {
352 PreferenceActivity.prefsMightHaveChanged = false;
354 startActivity(getIntent());
357 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
358 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
360 if (!blockAutoLaunch &&
361 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
362 prefs.contains(C.DICT_FILE) &&
363 prefs.contains(C.INDEX_SHORT_NAME)) {
364 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
365 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
366 new File(prefs.getString(C.DICT_FILE, "")),
367 prefs.getString(C.INDEX_SHORT_NAME, ""),
368 prefs.getString(C.SEARCH_TOKEN, "")));
373 // Remove the active dictionary from the prefs so we won't autolaunch
375 final Editor editor = prefs.edit();
376 editor.remove(C.DICT_FILE);
377 editor.remove(C.INDEX_SHORT_NAME);
378 editor.remove(C.SEARCH_TOKEN);
381 application.backgroundUpdateDictionaries(dictionaryUpdater);
387 public boolean onCreateOptionsMenu(final Menu menu) {
388 application.onCreateGlobalOptionsMenu(this, menu);
393 public void onCreateContextMenu(final ContextMenu menu, final View view,
394 final ContextMenuInfo menuInfo) {
395 super.onCreateContextMenu(menu, view, menuInfo);
396 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
398 final AdapterContextMenuInfo adapterContextMenuInfo =
399 (AdapterContextMenuInfo) menuInfo;
400 final int position = adapterContextMenuInfo.position;
401 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
403 if (row.dictionaryInfo == null) {
407 if (position > 0 && row.onDevice) {
408 final android.view.MenuItem moveToTopMenuItem =
409 menu.add(R.string.moveToTop);
410 moveToTopMenuItem.setOnMenuItemClickListener(new
411 android.view.MenuItem.OnMenuItemClickListener() {
413 public boolean onMenuItemClick(android.view.MenuItem item) {
414 application.moveDictionaryToTop(row.dictionaryInfo);
422 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
424 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
426 public boolean onMenuItemClick(android.view.MenuItem item) {
427 application.deleteDictionary(row.dictionaryInfo);
435 private void onShowDownloadableChanged() {
437 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
438 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
442 class MyListAdapter extends BaseAdapter {
444 List<DictionaryInfo> dictionariesOnDevice;
445 List<DictionaryInfo> downloadableDictionaries;
448 DictionaryInfo dictionaryInfo;
451 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
452 this.dictionaryInfo = dictinoaryInfo;
453 this.onDevice = onDevice;
457 private MyListAdapter(final String[] filters) {
458 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
459 if (showDownloadable.isChecked()) {
460 downloadableDictionaries = application.getDownloadableDictionaries(filters);
462 downloadableDictionaries = Collections.emptyList();
467 public int getCount() {
468 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
472 public Row getItem(int position) {
474 return new Row(null, true);
478 if (position < dictionariesOnDevice.size()) {
479 return new Row(dictionariesOnDevice.get(position), true);
481 position -= dictionariesOnDevice.size();
484 return new Row(null, false);
488 assert position < downloadableDictionaries.size();
489 return new Row(downloadableDictionaries.get(position), false);
493 public long getItemId(int position) {
498 public View getView(int position, View convertView, ViewGroup parent) {
499 if (convertView instanceof LinearLayout &&
500 convertView != dictionariesOnDeviceHeaderRow &&
501 convertView != downloadableDictionariesHeaderRow) {
503 * This is done to try to avoid leaking memory that used to
504 * happen on Android 4.0.3
506 ((LinearLayout) convertView).removeAllViews();
509 final Row row = getItem(position);
512 if (row.dictionaryInfo == null) {
513 return dictionariesOnDeviceHeaderRow;
515 return createDictionaryRow(row.dictionaryInfo, parent, true);
518 if (row.dictionaryInfo == null) {
519 return downloadableDictionariesHeaderRow;
521 return createDictionaryRow(row.dictionaryInfo, parent, false);
526 private void setMyListAdapater() {
527 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
529 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
530 setListAdapter(new MyListAdapter(filters));
533 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
534 final ViewGroup parent, boolean canLaunch) {
536 View row = LayoutInflater.from(parent.getContext()).inflate(
537 R.layout.dictionary_manager_row, parent, false);
538 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
539 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
540 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
542 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
543 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
544 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
545 boolean broken = false;
546 if (!dictionaryInfo.isValid()) {
550 if (downloadable != null && (!canLaunch || updateAvailable)) {
553 R.string.downloadButton,
554 downloadable.zipBytes / 1024.0 / 1024.0));
555 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
556 downloadButton.setOnClickListener(new OnClickListener() {
558 public void onClick(View arg0) {
559 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
563 downloadButton.setVisibility(View.INVISIBLE);
566 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
567 final List<IndexInfo> sortedIndexInfos = application
568 .sortedIndexInfos(dictionaryInfo.indexInfos);
569 final StringBuilder builder = new StringBuilder();
570 if (updateAvailable) {
571 builder.append(getString(R.string.updateAvailable));
573 for (IndexInfo indexInfo : sortedIndexInfos) {
574 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
576 buttons.addView(button);
579 button.setOnClickListener(
580 new IntentLauncher(buttons.getContext(),
581 DictionaryActivity.getLaunchIntent(getApplicationContext(),
582 application.getPath(dictionaryInfo.uncompressedFilename),
583 indexInfo.shortName, "")));
586 button.setEnabled(false);
588 if (builder.length() != 0) {
589 builder.append("; ");
591 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
592 indexInfo.mainTokenCount));
594 builder.append("; ");
595 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
597 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
598 builder.append("; Cannot be used, redownload, check hardware/file system");
599 // Allow deleting, but cannot open
600 row.setLongClickable(true);
602 details.setText(builder.toString());
605 row.setClickable(true);
606 row.setOnClickListener(new IntentLauncher(parent.getContext(),
607 DictionaryActivity.getLaunchIntent(getApplicationContext(),
608 application.getPath(dictionaryInfo.uncompressedFilename),
609 dictionaryInfo.indexInfos.get(0).shortName, "")));
610 row.setFocusable(true);
611 row.setLongClickable(true);
613 row.setBackgroundResource(android.R.drawable.menuitem_background);
618 private void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
619 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
620 final DownloadManager.Query query = new DownloadManager.Query();
621 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
622 final Cursor cursor = downloadManager.query(query);
624 // Due to a bug, cursor is null instead of empty when
625 // the download manager is disabled.
626 if (cursor == null) {
627 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
628 .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
629 .setNeutralButton("Close", null).show();
633 while (cursor.moveToNext()) {
634 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
637 if (!cursor.isAfterLast()) {
638 downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
641 R.string.downloadButton,
642 bytes / 1024.0 / 1024.0));
647 Request request = new Request(
648 Uri.parse(downloadUrl));
650 final String destFile = new File(new URL(downloadUrl).getFile())
652 Log.d(LOG, "Downloading to: " + destFile);
655 request.setDestinationInExternalFilesDir(getApplicationContext(), null, destFile);
656 } catch (IllegalStateException e) {
657 request.setDestinationUri(Uri.fromFile(new File(Environment
658 .getExternalStorageDirectory(), destFile)));
660 } catch (MalformedURLException e) {
661 throw new RuntimeException(e);
663 downloadManager.enqueue(request);
664 downloadButton.setText("X");