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.util.Log;
33 import android.util.TypedValue;
34 import android.view.ContextMenu;
35 import android.view.ContextMenu.ContextMenuInfo;
36 import android.view.LayoutInflater;
37 import android.view.View;
38 import android.view.View.OnClickListener;
39 import android.view.ViewGroup;
40 import android.view.inputmethod.EditorInfo;
41 import android.widget.AdapterView.AdapterContextMenuInfo;
42 import android.widget.BaseAdapter;
43 import android.widget.Button;
44 import android.widget.CompoundButton;
45 import android.widget.CompoundButton.OnCheckedChangeListener;
46 import android.widget.FrameLayout;
47 import android.widget.LinearLayout;
48 import android.widget.TextView;
49 import android.widget.Toast;
50 import android.widget.ToggleButton;
52 import com.actionbarsherlock.app.ActionBar;
53 import com.actionbarsherlock.app.SherlockListActivity;
54 import com.actionbarsherlock.view.Menu;
55 import com.actionbarsherlock.widget.SearchView;
56 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
57 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
58 import com.hughes.android.util.IntentLauncher;
61 import java.io.FileOutputStream;
62 import java.io.IOException;
63 import java.io.InputStream;
64 import java.io.OutputStream;
65 import java.net.MalformedURLException;
67 import java.util.Collections;
68 import java.util.List;
69 import java.util.zip.ZipEntry;
70 import java.util.zip.ZipFile;
73 // Delete, move to top.
75 public class DictionaryManagerActivity extends SherlockListActivity {
77 static final String LOG = "QuickDic";
78 static boolean blockAutoLaunch = false;
80 DictionaryApplication application;
82 SearchView filterSearchView;
83 ToggleButton showDownloadable;
85 LinearLayout dictionariesOnDeviceHeaderRow;
86 LinearLayout downloadableDictionariesHeaderRow;
90 Runnable dictionaryUpdater = new Runnable() {
93 if (uiHandler == null) {
96 uiHandler.post(new Runnable() {
105 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
107 public void onReceive(Context context, Intent intent) {
108 final String action = intent.getAction();
110 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
111 final long downloadId = intent.getLongExtra(
112 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
113 final DownloadManager.Query query = new DownloadManager.Query();
114 query.setFilterById(downloadId);
115 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
116 final Cursor cursor = downloadManager.query(query);
118 if (!cursor.moveToFirst()) {
119 Log.e(LOG, "Couldn't find download.");
123 final String dest = cursor
124 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
125 final int status = cursor
127 .getColumnIndex(DownloadManager.COLUMN_STATUS));
128 if (DownloadManager.STATUS_SUCCESSFUL != status) {
130 "Download failed: status=" + status +
131 ", reason=" + cursor.getString(cursor
132 .getColumnIndex(DownloadManager.COLUMN_REASON)));
133 Toast.makeText(context, getString(R.string.downloadFailed, dest),
134 Toast.LENGTH_LONG).show();
138 Log.w(LOG, "Download finished: " + dest);
139 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
140 Toast.LENGTH_LONG).show();
143 final File localZipFile = new File(Uri.parse(dest).getPath());
145 ZipFile zipFile = new ZipFile(localZipFile);
146 final ZipEntry zipEntry = zipFile.entries().nextElement();
147 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
148 final InputStream zipIn = zipFile.getInputStream(zipEntry);
149 File targetFile = new File(application.getDictDir(), zipEntry.getName());
150 if (targetFile.exists()) {
151 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
152 targetFile = new File(application.getDictDir(), zipEntry.getName());
154 final OutputStream zipOut = new FileOutputStream(targetFile);
155 copyStream(zipIn, zipOut);
157 application.backgroundUpdateDictionaries(dictionaryUpdater);
158 Toast.makeText(context, getString(R.string.installationFinished, dest),
159 Toast.LENGTH_LONG).show();
160 } catch (Exception e) {
161 Toast.makeText(context, getString(R.string.unzippingFailed, dest),
162 Toast.LENGTH_LONG).show();
163 Log.e(LOG, "Failed to unzip.", e);
165 localZipFile.delete();
171 public static Intent getLaunchIntent() {
172 final Intent intent = new Intent();
173 intent.setClassName(DictionaryManagerActivity.class.getPackage().getName(),
174 DictionaryManagerActivity.class.getName());
175 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
180 public void onCreate(Bundle savedInstanceState) {
181 // This must be first, otherwise the actiona bar doesn't get
183 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
185 super.onCreate(savedInstanceState);
186 Log.d(LOG, "onCreate:" + this);
188 application = (DictionaryApplication) getApplication();
190 blockAutoLaunch = false;
193 setContentView(R.layout.dictionary_manager_activity);
195 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
196 getListView().getContext()).inflate(
197 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
199 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
200 getListView().getContext()).inflate(
201 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
203 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
204 .findViewById(R.id.hideDownloadable);
205 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
207 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
208 onShowDownloadableChanged();
212 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
213 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
214 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
215 thanksForUpdatingLatestVersion)) {
216 blockAutoLaunch = true;
217 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent());
218 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
222 registerReceiver(broadcastReceiver, new IntentFilter(
223 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
226 registerForContextMenu(getListView());
228 final File dictDir = application.getDictDir();
229 if (!dictDir.canRead() || !dictDir.canExecute()) {
230 blockAutoLaunch = true;
232 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
233 builder.setTitle(getString(R.string.error));
234 builder.setMessage(getString(
235 R.string.unableToReadDictionaryDir,
236 dictDir.getAbsolutePath(),
237 Environment.getExternalStorageDirectory()));
238 builder.create().show();
241 onCreateSetupActionBar();
244 private void onCreateSetupActionBar() {
245 ActionBar actionBar = getSupportActionBar();
246 actionBar.setDisplayShowTitleEnabled(false);
248 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
249 filterSearchView.setIconifiedByDefault(false);
250 // filterSearchView.setIconified(false); // puts the magnifying glass in
253 filterSearchView.setQueryHint(getString(R.string.searchText));
254 filterSearchView.setSubmitButtonEnabled(false);
255 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
256 getResources().getDisplayMetrics());
257 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
258 FrameLayout.LayoutParams.WRAP_CONTENT);
259 filterSearchView.setLayoutParams(lp);
260 filterSearchView.setImeOptions(
261 EditorInfo.IME_ACTION_SEARCH |
262 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
263 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
264 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
266 EditorInfo.IME_MASK_ACTION |
267 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
269 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
271 public boolean onQueryTextSubmit(String query) {
276 public boolean onQueryTextChange(String filterText) {
281 filterSearchView.setFocusable(true);
283 actionBar.setCustomView(filterSearchView);
284 actionBar.setDisplayShowCustomEnabled(true);
288 public void onDestroy() {
290 unregisterReceiver(broadcastReceiver);
293 private static int copyStream(final InputStream in, final OutputStream out)
296 final byte[] bytes = new byte[1024 * 16];
297 while ((bytesRead = in.read(bytes)) != -1) {
298 out.write(bytes, 0, bytesRead);
306 protected void onStart() {
308 uiHandler = new Handler();
312 protected void onStop() {
318 protected void onResume() {
321 if (PreferenceActivity.prefsMightHaveChanged) {
322 PreferenceActivity.prefsMightHaveChanged = false;
324 startActivity(getIntent());
327 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
328 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
330 if (!blockAutoLaunch &&
331 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
332 prefs.contains(C.DICT_FILE) &&
333 prefs.contains(C.INDEX_SHORT_NAME)) {
334 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
335 startActivity(DictionaryActivity.getLaunchIntent(
336 new File(prefs.getString(C.DICT_FILE, "")),
337 prefs.getString(C.INDEX_SHORT_NAME, ""),
338 prefs.getString(C.SEARCH_TOKEN, "")));
343 // Remove the active dictionary from the prefs so we won't autolaunch
345 final Editor editor = prefs.edit();
346 editor.remove(C.DICT_FILE);
347 editor.remove(C.INDEX_SHORT_NAME);
348 editor.remove(C.SEARCH_TOKEN);
351 application.backgroundUpdateDictionaries(dictionaryUpdater);
357 public boolean onCreateOptionsMenu(final Menu menu) {
358 application.onCreateGlobalOptionsMenu(this, menu);
363 public void onCreateContextMenu(final ContextMenu menu, final View view,
364 final ContextMenuInfo menuInfo) {
365 super.onCreateContextMenu(menu, view, menuInfo);
366 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
368 final AdapterContextMenuInfo adapterContextMenuInfo =
369 (AdapterContextMenuInfo) menuInfo;
370 final int position = adapterContextMenuInfo.position;
371 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
373 if (row.dictionaryInfo == null) {
377 if (position > 0 && row.onDevice) {
378 final android.view.MenuItem moveToTopMenuItem =
379 menu.add(R.string.moveToTop);
380 moveToTopMenuItem.setOnMenuItemClickListener(new
381 android.view.MenuItem.OnMenuItemClickListener() {
383 public boolean onMenuItemClick(android.view.MenuItem item) {
384 application.moveDictionaryToTop(row.dictionaryInfo);
392 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
394 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
396 public boolean onMenuItemClick(android.view.MenuItem item) {
397 application.deleteDictionary(row.dictionaryInfo);
405 private void onShowDownloadableChanged() {
407 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
408 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
412 class MyListAdapter extends BaseAdapter {
414 List<DictionaryInfo> dictionariesOnDevice;
415 List<DictionaryInfo> downloadableDictionaries;
418 DictionaryInfo dictionaryInfo;
421 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
422 this.dictionaryInfo = dictinoaryInfo;
423 this.onDevice = onDevice;
427 private MyListAdapter(final String[] filters) {
428 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
429 if (showDownloadable.isChecked()) {
430 downloadableDictionaries = application.getDownloadableDictionaries(filters);
432 downloadableDictionaries = Collections.emptyList();
437 public int getCount() {
438 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
442 public Row getItem(int position) {
444 return new Row(null, true);
448 if (position < dictionariesOnDevice.size()) {
449 return new Row(dictionariesOnDevice.get(position), true);
451 position -= dictionariesOnDevice.size();
454 return new Row(null, false);
458 assert position < downloadableDictionaries.size();
459 return new Row(downloadableDictionaries.get(position), false);
463 public long getItemId(int position) {
468 public View getView(int position, View convertView, ViewGroup parent) {
469 if (convertView instanceof LinearLayout &&
470 convertView != dictionariesOnDeviceHeaderRow &&
471 convertView != downloadableDictionariesHeaderRow) {
473 * This is done to try to avoid leaking memory that used to
474 * happen on Android 4.0.3
476 ((LinearLayout) convertView).removeAllViews();
479 final Row row = getItem(position);
482 if (row.dictionaryInfo == null) {
483 return dictionariesOnDeviceHeaderRow;
485 return createDictionaryRow(row.dictionaryInfo, parent, true);
488 if (row.dictionaryInfo == null) {
489 return downloadableDictionariesHeaderRow;
491 return createDictionaryRow(row.dictionaryInfo, parent, false);
496 private void setMyListAdapater() {
497 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
499 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
500 setListAdapter(new MyListAdapter(filters));
503 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
504 final ViewGroup parent, final boolean canLaunch) {
506 View row = LayoutInflater.from(parent.getContext()).inflate(
507 R.layout.dictionary_manager_row, parent, false);
508 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
509 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
510 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
512 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
513 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
514 if (!canLaunch || updateAvailable) {
515 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
518 R.string.downloadButton,
519 downloadable.zipBytes / 1024.0 / 1024.0));
520 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
521 downloadButton.setOnClickListener(new OnClickListener() {
523 public void onClick(View arg0) {
524 downloadDictionary(downloadable.downloadUrl);
528 downloadButton.setVisibility(View.INVISIBLE);
531 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
532 final List<IndexInfo> sortedIndexInfos = application
533 .sortedIndexInfos(dictionaryInfo.indexInfos);
534 final StringBuilder builder = new StringBuilder();
535 if (updateAvailable) {
536 builder.append(getString(R.string.updateAvailable));
538 for (IndexInfo indexInfo : sortedIndexInfos) {
539 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
541 buttons.addView(button);
544 button.setOnClickListener(
545 new IntentLauncher(buttons.getContext(),
546 DictionaryActivity.getLaunchIntent(
547 application.getPath(dictionaryInfo.uncompressedFilename),
548 indexInfo.shortName, "")));
551 button.setEnabled(false);
553 if (builder.length() != 0) {
554 builder.append("; ");
556 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
557 indexInfo.mainTokenCount));
559 details.setText(builder.toString());
562 row.setClickable(true);
563 row.setOnClickListener(new IntentLauncher(parent.getContext(),
564 DictionaryActivity.getLaunchIntent(
565 application.getPath(dictionaryInfo.uncompressedFilename),
566 dictionaryInfo.indexInfos.get(0).shortName, "")));
567 row.setFocusable(true);
568 row.setLongClickable(true);
570 row.setBackgroundResource(android.R.drawable.menuitem_background);
575 private void downloadDictionary(final String downloadUrl) {
576 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
577 Request request = new Request(
578 Uri.parse(downloadUrl));
580 final String destFile = new File(new URL(downloadUrl).getFile())
582 Log.d(LOG, "Downloading to: " + destFile);
584 request.setDestinationUri(Uri.fromFile(new File(Environment
585 .getExternalStorageDirectory(), destFile)));
586 } catch (MalformedURLException e) {
587 throw new RuntimeException(e);
589 downloadManager.enqueue(request);