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.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.widget.AdapterView.AdapterContextMenuInfo;
41 import android.widget.BaseAdapter;
42 import android.widget.Button;
43 import android.widget.CompoundButton;
44 import android.widget.ListView;
45 import android.widget.Toast;
46 import android.widget.CompoundButton.OnCheckedChangeListener;
47 import android.widget.LinearLayout;
48 import android.widget.TextView;
49 import android.widget.ToggleButton;
51 import com.actionbarsherlock.app.SherlockListActivity;
52 import com.actionbarsherlock.view.Menu;
53 import com.actionbarsherlock.view.MenuInflater;
54 import com.actionbarsherlock.widget.SearchView;
55 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
56 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
57 import com.hughes.android.util.IntentLauncher;
60 import java.io.FileOutputStream;
61 import java.io.IOException;
62 import java.io.InputStream;
63 import java.io.OutputStream;
64 import java.net.MalformedURLException;
66 import java.util.Collections;
67 import java.util.List;
68 import java.util.zip.ZipEntry;
69 import java.util.zip.ZipFile;
72 // Delete, move to top.
74 public class DictionaryManagerActivity extends SherlockListActivity {
76 static final String LOG = "QuickDic";
77 static boolean blockAutoLaunch = false;
79 DictionaryApplication application;
81 SearchView filterSearchView;
82 ToggleButton showDownloadable;
84 LinearLayout dictionariesOnDeviceHeaderRow;
85 LinearLayout downloadableDictionariesHeaderRow;
89 Runnable dictionaryUpdater = new Runnable() {
92 if (uiHandler == null) {
95 uiHandler.post(new Runnable() {
104 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
106 public void onReceive(Context context, Intent intent) {
107 final String action = intent.getAction();
109 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
110 final long downloadId = intent.getLongExtra(
111 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
112 final DownloadManager.Query query = new DownloadManager.Query();
113 query.setFilterById(downloadId);
114 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
115 final Cursor cursor = downloadManager.query(query);
117 if (!cursor.moveToFirst()) {
118 Log.e(LOG, "Couldn't find download.");
122 final String dest = cursor
123 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
124 final int status = cursor
126 .getColumnIndex(DownloadManager.COLUMN_STATUS));
127 if (DownloadManager.STATUS_SUCCESSFUL != status) {
129 "Download failed: status=" + status +
130 ", reason=" + cursor.getString(cursor
131 .getColumnIndex(DownloadManager.COLUMN_REASON)));
132 Toast.makeText(context, getString(R.string.downloadFailed, dest),
133 Toast.LENGTH_LONG).show();
137 Log.w(LOG, "Download finished: " + dest);
138 final File localZipFile = new File(Uri.parse(dest).getPath());
141 ZipFile zipFile = new ZipFile(localZipFile);
142 final ZipEntry zipEntry = zipFile.entries().nextElement();
143 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
144 final InputStream zipIn = zipFile.getInputStream(zipEntry);
145 final OutputStream zipOut = new FileOutputStream(
146 new File(application.getDictDir(), zipEntry.getName()));
147 copyStream(zipIn, zipOut);
149 application.backgroundUpdateDictionaries(dictionaryUpdater);
150 Toast.makeText(context, getString(R.string.downloadFinished, dest),
151 Toast.LENGTH_LONG).show();
152 } catch (Exception e) {
153 Toast.makeText(context, getString(R.string.downloadFailed, dest),
154 Toast.LENGTH_LONG).show();
155 Log.e(LOG, "Failed to unzip.", e);
157 localZipFile.delete();
163 public static Intent getLaunchIntent() {
164 final Intent intent = new Intent();
165 intent.setClassName(DictionaryManagerActivity.class.getPackage().getName(),
166 DictionaryManagerActivity.class.getName());
167 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
172 public void onCreate(Bundle savedInstanceState) {
173 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
175 super.onCreate(savedInstanceState);
176 Log.d(LOG, "onCreate:" + this);
178 application = (DictionaryApplication) getApplication();
180 blockAutoLaunch = false;
183 setContentView(R.layout.dictionary_manager_activity);
185 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
186 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
188 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
189 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
191 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow.findViewById(R.id.hideDownloadable);
192 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
194 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
195 onShowLocalChanged();
199 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
200 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
201 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
202 thanksForUpdatingLatestVersion)) {
203 blockAutoLaunch = true;
204 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent());
205 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
210 registerReceiver(broadcastReceiver, new IntentFilter(
211 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
214 registerForContextMenu(getListView());
216 final File dictDir = application.getDictDir();
217 if (!dictDir.canRead() || !dictDir.canExecute()) {
218 blockAutoLaunch = true;
220 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
221 builder.setTitle(getString(R.string.error));
222 builder.setMessage(getString(
223 R.string.unableToReadDictionaryDir,
224 dictDir.getAbsolutePath(),
225 Environment.getExternalStorageDirectory()));
226 builder.create().show();
231 public void onDestroy() {
233 unregisterReceiver(broadcastReceiver);
236 private static int copyStream(final InputStream in, final OutputStream out)
239 final byte[] bytes = new byte[1024 * 16];
240 while ((bytesRead = in.read(bytes)) != -1) {
241 out.write(bytes, 0, bytesRead);
249 protected void onStart() {
251 uiHandler = new Handler();
255 protected void onStop() {
261 protected void onResume() {
264 if (PreferenceActivity.prefsMightHaveChanged) {
265 PreferenceActivity.prefsMightHaveChanged = false;
267 startActivity(getIntent());
270 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
271 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, false));
273 if (!blockAutoLaunch &&
274 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
275 prefs.contains(C.DICT_FILE) &&
276 prefs.contains(C.INDEX_SHORT_NAME)) {
277 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
278 startActivity(DictionaryActivity.getLaunchIntent(
279 new File(prefs.getString(C.DICT_FILE, "")), prefs.getString(C.INDEX_SHORT_NAME, ""),
280 prefs.getString(C.SEARCH_TOKEN, "")));
285 // Remove the active dictionary from the prefs so we won't autolaunch
287 final Editor editor = prefs.edit();
288 editor.remove(C.DICT_FILE);
289 editor.remove(C.INDEX_SHORT_NAME);
290 editor.remove(C.SEARCH_TOKEN);
293 application.backgroundUpdateDictionaries(dictionaryUpdater);
299 public boolean onCreateOptionsMenu(final Menu menu) {
300 MenuInflater inflater = getSupportMenuInflater();
301 inflater.inflate(R.menu.dictionary_manager_options_menu, menu);
303 filterSearchView = (SearchView) menu.findItem(R.id.filterText).getActionView();
304 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
306 public boolean onQueryTextSubmit(String query) {
311 public boolean onQueryTextChange(String filterText) {
316 filterSearchView.setIconifiedByDefault(false);
318 application.onCreateGlobalOptionsMenu(this, menu);
323 public void onCreateContextMenu(final ContextMenu menu, final View view,
324 final ContextMenuInfo menuInfo) {
325 super.onCreateContextMenu(menu, view, menuInfo);
326 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
328 final AdapterContextMenuInfo adapterContextMenuInfo =
329 (AdapterContextMenuInfo) menuInfo;
330 final int position = adapterContextMenuInfo.position;
331 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
333 if (row.dictionaryInfo == null) {
337 if (position > 0 && row.onDevice) {
338 final android.view.MenuItem moveToTopMenuItem =
339 menu.add(R.string.moveToTop);
340 moveToTopMenuItem.setOnMenuItemClickListener(new
341 android.view.MenuItem.OnMenuItemClickListener() {
343 public boolean onMenuItemClick(android.view.MenuItem item) {
344 application.moveDictionaryToTop(row.dictionaryInfo);
352 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
354 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
356 public boolean onMenuItemClick(android.view.MenuItem item) {
357 application.deleteDictionary(row.dictionaryInfo);
365 private void onShowLocalChanged() {
367 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
368 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
372 // private void onClick(int index) {
373 // final DictionaryInfo dictionaryInfo = adapter.getItem(index);
374 // final DictionaryInfo downloadable =
375 // application.getDownloadable(dictionaryInfo.uncompressedFilename);
377 // (!application.isDictionaryOnDevice(dictionaryInfo.uncompressedFilename)
378 // && downloadable != null) {
379 // final Intent intent = getDownloadIntent(downloadable);
380 // startActivity(intent);
382 // final Intent intent =
383 // DictionaryActivity.getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
385 // startActivity(intent);
390 class MyListAdapter extends BaseAdapter {
392 List<DictionaryInfo> dictionariesOnDevice;
393 List<DictionaryInfo> downloadableDictionaries;
396 DictionaryInfo dictionaryInfo;
399 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
400 this.dictionaryInfo = dictinoaryInfo;
401 this.onDevice = onDevice;
406 private MyListAdapter(final String[] filters) {
407 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
408 if (showDownloadable.isChecked()) {
409 downloadableDictionaries = application.getDownloadableDictionaries(filters);
411 downloadableDictionaries = Collections.emptyList();
416 public int getCount() {
417 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
421 public Row getItem(int position) {
423 return new Row(null, true);
427 if (position < dictionariesOnDevice.size()) {
428 return new Row(dictionariesOnDevice.get(position), true);
430 position -= dictionariesOnDevice.size();
433 return new Row(null, false);
437 assert position < downloadableDictionaries.size();
438 return new Row(downloadableDictionaries.get(position), false);
442 public long getItemId(int position) {
447 public View getView(int position, View convertView, ViewGroup parent) {
448 if (convertView instanceof LinearLayout &&
449 convertView != dictionariesOnDeviceHeaderRow &&
450 convertView != downloadableDictionariesHeaderRow) {
451 /* This is done to try to avoid leaking memory that used to
452 * happen on Android 4.0.3 */
453 ((LinearLayout)convertView).removeAllViews();
456 final Row row = getItem(position);
459 if (row.dictionaryInfo == null) {
460 return dictionariesOnDeviceHeaderRow;
462 return createDictionaryRow(row.dictionaryInfo, parent, true);
465 if (row.dictionaryInfo == null) {
466 return downloadableDictionariesHeaderRow;
468 return createDictionaryRow(row.dictionaryInfo, parent, false);
473 private void setListAdapater() {
474 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery().toString();
475 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
476 setListAdapter(new MyListAdapter(filters));
479 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
480 final ViewGroup parent, final boolean canLaunch) {
482 View row = LayoutInflater.from(parent.getContext()).inflate(
483 R.layout.dictionary_manager_row, parent, false);
484 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
485 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
486 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
488 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
489 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
490 if (!canLaunch || updateAvailable) {
491 downloadButton.setText(getString(R.string.downloadButton, application.getDownloadable(dictionaryInfo.uncompressedFilename).zipBytes / 1024.0 / 1024.0));
492 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
493 downloadButton.setOnClickListener(new OnClickListener() {
495 public void onClick(View arg0) {
496 downloadDictionary(dictionaryInfo);
500 downloadButton.setVisibility(View.INVISIBLE);
503 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
504 final List<IndexInfo> sortedIndexInfos = application.sortedIndexInfos(dictionaryInfo.indexInfos);
505 final StringBuilder builder = new StringBuilder();
506 if (updateAvailable) {
507 builder.append(getString(R.string.updateButton));
509 for (IndexInfo indexInfo : sortedIndexInfos) {
510 final View button = application.createButton(buttons.getContext(), dictionaryInfo, indexInfo);
511 buttons.addView(button);
514 button.setOnClickListener(
515 new IntentLauncher(buttons.getContext(),
516 DictionaryActivity.getLaunchIntent(
517 application.getPath(dictionaryInfo.uncompressedFilename),
518 indexInfo.shortName, "")));
521 button.setEnabled(false);
523 if (builder.length() != 0) {
524 builder.append("; ");
526 builder.append(getString(R.string.indexInfo, indexInfo.shortName, indexInfo.mainTokenCount));
528 details.setText(builder.toString());
530 row.setClickable(true);
531 row.setFocusable(true);
532 row.setLongClickable(true);
533 row.setBackgroundResource(android.R.drawable.menuitem_background);
538 private void downloadDictionary(final DictionaryInfo dictionaryInfo) {
539 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
540 Request request = new Request(
541 Uri.parse(dictionaryInfo.downloadUrl));
543 final String destFile = new File(new URL(dictionaryInfo.downloadUrl).getFile()).getName();
544 Log.d(LOG, "Downloading to: " + destFile);
546 request.setDestinationUri(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), destFile)));
547 } catch (MalformedURLException e) {
548 throw new RuntimeException(e);
550 downloadManager.enqueue(request);