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.Dialog;
19 import android.app.DownloadManager;
20 import android.app.DownloadManager.Request;
21 import android.content.BroadcastReceiver;
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.util.Log;
34 import android.util.TypedValue;
35 import android.view.ContextMenu;
36 import android.view.ContextMenu.ContextMenuInfo;
37 import android.view.LayoutInflater;
38 import android.view.View;
39 import android.view.View.OnClickListener;
40 import android.view.View.OnLongClickListener;
41 import android.view.inputmethod.EditorInfo;
42 import android.view.ViewGroup;
43 import android.widget.AdapterView.AdapterContextMenuInfo;
44 import android.widget.BaseAdapter;
45 import android.widget.Button;
46 import android.widget.CompoundButton;
47 import android.widget.FrameLayout;
48 import android.widget.ImageView;
49 import android.widget.ListView;
50 import android.widget.Toast;
51 import android.widget.CompoundButton.OnCheckedChangeListener;
52 import android.widget.LinearLayout;
53 import android.widget.TextView;
54 import android.widget.ToggleButton;
56 import com.actionbarsherlock.app.ActionBar;
57 import com.actionbarsherlock.app.SherlockListActivity;
58 import com.actionbarsherlock.view.Menu;
59 import com.actionbarsherlock.view.MenuInflater;
60 import com.actionbarsherlock.widget.SearchView;
61 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
62 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
63 import com.hughes.android.util.IntentLauncher;
66 import java.io.FileOutputStream;
67 import java.io.IOException;
68 import java.io.InputStream;
69 import java.io.OutputStream;
70 import java.net.MalformedURLException;
72 import java.util.Collections;
73 import java.util.List;
74 import java.util.zip.ZipEntry;
75 import java.util.zip.ZipFile;
78 // Delete, move to top.
80 public class DictionaryManagerActivity extends SherlockListActivity {
82 static final String LOG = "QuickDic";
83 static boolean blockAutoLaunch = false;
85 DictionaryApplication application;
87 SearchView filterSearchView;
88 ToggleButton showDownloadable;
90 LinearLayout dictionariesOnDeviceHeaderRow;
91 LinearLayout downloadableDictionariesHeaderRow;
95 Runnable dictionaryUpdater = new Runnable() {
98 if (uiHandler == null) {
101 uiHandler.post(new Runnable() {
110 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
112 public void onReceive(Context context, Intent intent) {
113 final String action = intent.getAction();
115 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
116 final long downloadId = intent.getLongExtra(
117 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
118 final DownloadManager.Query query = new DownloadManager.Query();
119 query.setFilterById(downloadId);
120 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
121 final Cursor cursor = downloadManager.query(query);
123 if (!cursor.moveToFirst()) {
124 Log.e(LOG, "Couldn't find download.");
128 final String dest = cursor
129 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
130 final int status = cursor
132 .getColumnIndex(DownloadManager.COLUMN_STATUS));
133 if (DownloadManager.STATUS_SUCCESSFUL != status) {
135 "Download failed: status=" + status +
136 ", reason=" + cursor.getString(cursor
137 .getColumnIndex(DownloadManager.COLUMN_REASON)));
138 Toast.makeText(context, getString(R.string.downloadFailed, dest),
139 Toast.LENGTH_LONG).show();
143 Log.w(LOG, "Download finished: " + dest);
144 final File localZipFile = new File(Uri.parse(dest).getPath());
147 ZipFile zipFile = new ZipFile(localZipFile);
148 final ZipEntry zipEntry = zipFile.entries().nextElement();
149 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
150 final InputStream zipIn = zipFile.getInputStream(zipEntry);
151 final OutputStream zipOut = new FileOutputStream(
152 new File(application.getDictDir(), zipEntry.getName()));
153 copyStream(zipIn, zipOut);
155 application.backgroundUpdateDictionaries(dictionaryUpdater);
156 Toast.makeText(context, getString(R.string.downloadFinished, dest),
157 Toast.LENGTH_LONG).show();
158 } catch (Exception e) {
159 Toast.makeText(context, getString(R.string.downloadFailed, dest),
160 Toast.LENGTH_LONG).show();
161 Log.e(LOG, "Failed to unzip.", e);
163 localZipFile.delete();
169 public static Intent getLaunchIntent() {
170 final Intent intent = new Intent();
171 intent.setClassName(DictionaryManagerActivity.class.getPackage().getName(),
172 DictionaryManagerActivity.class.getName());
173 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
178 public void onCreate(Bundle savedInstanceState) {
179 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
181 super.onCreate(savedInstanceState);
182 Log.d(LOG, "onCreate:" + this);
184 application = (DictionaryApplication) getApplication();
186 blockAutoLaunch = false;
189 setContentView(R.layout.dictionary_manager_activity);
191 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
192 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
194 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
195 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
197 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow.findViewById(R.id.hideDownloadable);
198 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
200 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
201 onShowLocalChanged();
205 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
206 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
207 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
208 thanksForUpdatingLatestVersion)) {
209 blockAutoLaunch = true;
210 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent());
211 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
216 registerReceiver(broadcastReceiver, new IntentFilter(
217 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
220 registerForContextMenu(getListView());
222 final File dictDir = application.getDictDir();
223 if (!dictDir.canRead() || !dictDir.canExecute()) {
224 blockAutoLaunch = true;
226 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
227 builder.setTitle(getString(R.string.error));
228 builder.setMessage(getString(
229 R.string.unableToReadDictionaryDir,
230 dictDir.getAbsolutePath(),
231 Environment.getExternalStorageDirectory()));
232 builder.create().show();
235 onCreateSetupActionBar();
238 private void onCreateSetupActionBar() {
239 ActionBar actionBar = getSupportActionBar();
240 actionBar.setDisplayShowTitleEnabled(false);
242 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
243 filterSearchView.setIconifiedByDefault(false);
244 // filterSearchView.setIconified(false); // puts the magnifying glass in the
246 filterSearchView.setQueryHint(getString(R.string.searchText));
247 filterSearchView.setSubmitButtonEnabled(false);
248 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
249 getResources().getDisplayMetrics());
250 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
251 FrameLayout.LayoutParams.WRAP_CONTENT);
252 filterSearchView.setLayoutParams(lp);
253 filterSearchView.setImeOptions(
254 EditorInfo.IME_ACTION_SEARCH |
255 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
256 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
257 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
259 EditorInfo.IME_MASK_ACTION |
260 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
262 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
264 public boolean onQueryTextSubmit(String query) {
269 public boolean onQueryTextChange(String filterText) {
274 filterSearchView.setFocusable(true);
276 actionBar.setCustomView(filterSearchView);
277 actionBar.setDisplayShowCustomEnabled(true);
282 public void onDestroy() {
284 unregisterReceiver(broadcastReceiver);
287 private static int copyStream(final InputStream in, final OutputStream out)
290 final byte[] bytes = new byte[1024 * 16];
291 while ((bytesRead = in.read(bytes)) != -1) {
292 out.write(bytes, 0, bytesRead);
300 protected void onStart() {
302 uiHandler = new Handler();
306 protected void onStop() {
312 protected void onResume() {
315 if (PreferenceActivity.prefsMightHaveChanged) {
316 PreferenceActivity.prefsMightHaveChanged = false;
318 startActivity(getIntent());
321 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
322 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, false));
324 if (!blockAutoLaunch &&
325 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
326 prefs.contains(C.DICT_FILE) &&
327 prefs.contains(C.INDEX_SHORT_NAME)) {
328 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
329 startActivity(DictionaryActivity.getLaunchIntent(
330 new File(prefs.getString(C.DICT_FILE, "")), prefs.getString(C.INDEX_SHORT_NAME, ""),
331 prefs.getString(C.SEARCH_TOKEN, "")));
336 // Remove the active dictionary from the prefs so we won't autolaunch
338 final Editor editor = prefs.edit();
339 editor.remove(C.DICT_FILE);
340 editor.remove(C.INDEX_SHORT_NAME);
341 editor.remove(C.SEARCH_TOKEN);
344 application.backgroundUpdateDictionaries(dictionaryUpdater);
350 public boolean onCreateOptionsMenu(final Menu menu) {
351 // MenuInflater inflater = getSupportMenuInflater();
352 // inflater.inflate(R.menu.dictionary_manager_options_menu, menu);
354 // filterSearchView = (SearchView) menu.findItem(R.id.filterText).getActionView();
355 // filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
357 // public boolean onQueryTextSubmit(String query) {
362 // public boolean onQueryTextChange(String filterText) {
363 // setListAdapater();
367 // filterSearchView.setIconifiedByDefault(false);
369 application.onCreateGlobalOptionsMenu(this, menu);
374 public void onCreateContextMenu(final ContextMenu menu, final View view,
375 final ContextMenuInfo menuInfo) {
376 super.onCreateContextMenu(menu, view, menuInfo);
377 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
379 final AdapterContextMenuInfo adapterContextMenuInfo =
380 (AdapterContextMenuInfo) menuInfo;
381 final int position = adapterContextMenuInfo.position;
382 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
384 if (row.dictionaryInfo == null) {
388 if (position > 0 && row.onDevice) {
389 final android.view.MenuItem moveToTopMenuItem =
390 menu.add(R.string.moveToTop);
391 moveToTopMenuItem.setOnMenuItemClickListener(new
392 android.view.MenuItem.OnMenuItemClickListener() {
394 public boolean onMenuItemClick(android.view.MenuItem item) {
395 application.moveDictionaryToTop(row.dictionaryInfo);
403 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
405 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
407 public boolean onMenuItemClick(android.view.MenuItem item) {
408 application.deleteDictionary(row.dictionaryInfo);
416 private void onShowLocalChanged() {
418 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
419 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
424 // private void onClick(int index) {
425 // final DictionaryInfo dictionaryInfo = adapter.getItem(index);
426 // final DictionaryInfo downloadable =
427 // application.getDownloadable(dictionaryInfo.uncompressedFilename);
428 // if (!application.isDictionaryOnDevice(dictionaryInfo.uncompressedFilename)
429 // && downloadable != null) {
430 // final Intent intent = getDownloadIntent(downloadable);
431 // startActivity(intent);
433 // final Intent intent =
434 // DictionaryActivity.getLaunchIntent(
435 // application.getPath(dictionaryInfo.uncompressedFilename),
437 // startActivity(intent);
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;
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) {
502 /* This is done to try to avoid leaking memory that used to
503 * happen on Android 4.0.3 */
504 ((LinearLayout)convertView).removeAllViews();
507 final Row row = getItem(position);
510 if (row.dictionaryInfo == null) {
511 return dictionariesOnDeviceHeaderRow;
513 return createDictionaryRow(row.dictionaryInfo, parent, true);
516 if (row.dictionaryInfo == null) {
517 return downloadableDictionariesHeaderRow;
519 return createDictionaryRow(row.dictionaryInfo, parent, false);
524 private void setListAdapater() {
525 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery().toString();
526 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
527 setListAdapter(new MyListAdapter(filters));
530 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
531 final ViewGroup parent, final boolean canLaunch) {
533 View row = LayoutInflater.from(parent.getContext()).inflate(
534 R.layout.dictionary_manager_row, parent, false);
535 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
536 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
537 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
539 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
540 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
541 if (!canLaunch || updateAvailable) {
542 downloadButton.setText(getString(R.string.downloadButton, application.getDownloadable(dictionaryInfo.uncompressedFilename).zipBytes / 1024.0 / 1024.0));
543 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
544 downloadButton.setOnClickListener(new OnClickListener() {
546 public void onClick(View arg0) {
547 downloadDictionary(dictionaryInfo);
551 downloadButton.setVisibility(View.INVISIBLE);
554 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
555 final List<IndexInfo> sortedIndexInfos = application.sortedIndexInfos(dictionaryInfo.indexInfos);
556 final StringBuilder builder = new StringBuilder();
557 if (updateAvailable) {
558 builder.append(getString(R.string.updateButton));
560 for (IndexInfo indexInfo : sortedIndexInfos) {
561 final View button = application.createButton(buttons.getContext(), dictionaryInfo, indexInfo);
562 buttons.addView(button);
565 button.setOnClickListener(
566 new IntentLauncher(buttons.getContext(),
567 DictionaryActivity.getLaunchIntent(
568 application.getPath(dictionaryInfo.uncompressedFilename),
569 indexInfo.shortName, "")));
572 button.setEnabled(false);
574 if (builder.length() != 0) {
575 builder.append("; ");
577 builder.append(getString(R.string.indexInfo, indexInfo.shortName, indexInfo.mainTokenCount));
579 details.setText(builder.toString());
582 row.setClickable(true);
583 row.setOnClickListener(new IntentLauncher(parent.getContext(),
584 DictionaryActivity.getLaunchIntent(
585 application.getPath(dictionaryInfo.uncompressedFilename),
586 dictionaryInfo.indexInfos.get(0).shortName, "")));
587 row.setFocusable(true);
588 row.setLongClickable(true);
590 row.setBackgroundResource(android.R.drawable.menuitem_background);
595 private void downloadDictionary(final DictionaryInfo dictionaryInfo) {
596 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
597 Request request = new Request(
598 Uri.parse(dictionaryInfo.downloadUrl));
600 final String destFile = new File(new URL(dictionaryInfo.downloadUrl).getFile()).getName();
601 Log.d(LOG, "Downloading to: " + destFile);
603 request.setDestinationUri(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), destFile)));
604 } catch (MalformedURLException e) {
605 throw new RuntimeException(e);
607 downloadManager.enqueue(request);