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.DownloadManager;
18 import android.app.DownloadManager.Request;
19 import android.content.BroadcastReceiver;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
23 import android.content.SharedPreferences;
24 import android.content.SharedPreferences.Editor;
25 import android.database.Cursor;
26 import android.net.Uri;
27 import android.os.Bundle;
28 import android.os.Environment;
29 import android.os.Handler;
30 import android.preference.PreferenceManager;
31 import android.util.Log;
32 import android.view.ContextMenu;
33 import android.view.ContextMenu.ContextMenuInfo;
34 import android.view.LayoutInflater;
35 import android.view.View;
36 import android.view.View.OnClickListener;
37 import android.view.ViewGroup;
38 import android.widget.AdapterView.AdapterContextMenuInfo;
39 import android.widget.BaseAdapter;
40 import android.widget.Button;
41 import android.widget.CompoundButton;
42 import android.widget.Toast;
43 import android.widget.CompoundButton.OnCheckedChangeListener;
44 import android.widget.LinearLayout;
45 import android.widget.TextView;
46 import android.widget.ToggleButton;
48 import com.actionbarsherlock.app.SherlockListActivity;
49 import com.actionbarsherlock.view.Menu;
50 import com.actionbarsherlock.view.MenuInflater;
51 import com.actionbarsherlock.widget.SearchView;
52 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
53 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
54 import com.hughes.android.util.IntentLauncher;
57 import java.io.FileOutputStream;
58 import java.io.IOException;
59 import java.io.InputStream;
60 import java.io.OutputStream;
61 import java.net.MalformedURLException;
63 import java.util.Collections;
64 import java.util.List;
65 import java.util.zip.ZipEntry;
66 import java.util.zip.ZipFile;
69 // Delete, move to top.
71 public class DictionaryManagerActivity extends SherlockListActivity {
73 static final String LOG = "QuickDic";
74 static boolean blockAutoLaunch = false;
76 DictionaryApplication application;
78 SearchView filterSearchView;
79 ToggleButton showDownloadable;
81 LinearLayout dictionariesOnDeviceHeaderRow;
82 LinearLayout downloadableDictionariesHeaderRow;
86 Runnable dictionaryUpdater = new Runnable() {
89 if (uiHandler == null) {
92 uiHandler.post(new Runnable() {
101 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
103 public void onReceive(Context context, Intent intent) {
104 final String action = intent.getAction();
106 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
107 final long downloadId = intent.getLongExtra(
108 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
109 final DownloadManager.Query query = new DownloadManager.Query();
110 query.setFilterById(downloadId);
111 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
112 final Cursor cursor = downloadManager.query(query);
114 if (!cursor.moveToFirst()) {
115 Log.e(LOG, "Couldn't find download.");
119 final String dest = cursor
120 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
121 final int status = cursor
123 .getColumnIndex(DownloadManager.COLUMN_STATUS));
124 if (DownloadManager.STATUS_SUCCESSFUL != status) {
126 "Download failed: status=" + status +
127 ", reason=" + cursor.getString(cursor
128 .getColumnIndex(DownloadManager.COLUMN_REASON)));
129 Toast.makeText(context, getString(R.string.downloadFailed, dest),
130 Toast.LENGTH_LONG).show();
134 Log.w(LOG, "Download finished: " + dest);
135 final File localZipFile = new File(Uri.parse(dest).getPath());
138 ZipFile zipFile = new ZipFile(localZipFile);
139 final ZipEntry zipEntry = zipFile.entries().nextElement();
140 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
141 final InputStream zipIn = zipFile.getInputStream(zipEntry);
142 final OutputStream zipOut = new FileOutputStream(
143 new File(application.getDictDir(), zipEntry.getName()));
144 copyStream(zipIn, zipOut);
146 application.backgroundUpdateDictionaries(dictionaryUpdater);
147 Toast.makeText(context, getString(R.string.downloadFinished, dest),
148 Toast.LENGTH_LONG).show();
149 } catch (Exception e) {
150 Toast.makeText(context, getString(R.string.downloadFailed, dest),
151 Toast.LENGTH_LONG).show();
152 Log.e(LOG, "Failed to unzip.", e);
154 localZipFile.delete();
160 public static Intent getLaunchIntent() {
161 final Intent intent = new Intent();
162 intent.setClassName(DictionaryManagerActivity.class.getPackage().getName(),
163 DictionaryManagerActivity.class.getName());
164 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
168 public void onCreate(Bundle savedInstanceState) {
169 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
171 super.onCreate(savedInstanceState);
172 Log.d(LOG, "onCreate:" + this);
174 application = (DictionaryApplication) getApplication();
177 setContentView(R.layout.dictionary_manager_activity);
179 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
180 R.layout.dictionaries_on_device_header_row, getListView(), false);
182 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
183 R.layout.downloadable_dictionaries_header_row, getListView(), false);
185 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow.findViewById(R.id.hideDownloadable);
186 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
188 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
189 onShowLocalChanged();
193 blockAutoLaunch = false;
194 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
195 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
196 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
197 thanksForUpdatingLatestVersion)) {
198 blockAutoLaunch = true;
199 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent());
200 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
205 registerReceiver(broadcastReceiver, new IntentFilter(
206 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
209 registerForContextMenu(getListView());
213 public void onDestroy() {
214 unregisterReceiver(broadcastReceiver);
217 private static int copyStream(final InputStream in, final OutputStream out)
220 final byte[] bytes = new byte[1024 * 16];
221 while ((bytesRead = in.read(bytes)) != -1) {
222 out.write(bytes, 0, bytesRead);
230 protected void onStart() {
232 uiHandler = new Handler();
236 protected void onStop() {
242 protected void onResume() {
245 if (PreferenceActivity.prefsMightHaveChanged) {
246 PreferenceActivity.prefsMightHaveChanged = false;
248 startActivity(getIntent());
251 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
252 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, false));
254 if (!blockAutoLaunch &&
255 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
256 prefs.contains(C.DICT_FILE) &&
257 prefs.contains(C.INDEX_SHORT_NAME)) {
258 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
259 startActivity(DictionaryActivity.getLaunchIntent(
260 new File(prefs.getString(C.DICT_FILE, "")), prefs.getString(C.INDEX_SHORT_NAME, ""),
261 prefs.getString(C.SEARCH_TOKEN, "")));
266 // Remove the active dictionary from the prefs so we won't autolaunch
268 final Editor editor = prefs.edit();
269 editor.remove(C.DICT_FILE);
270 editor.remove(C.INDEX_SHORT_NAME);
271 editor.remove(C.SEARCH_TOKEN);
274 application.backgroundUpdateDictionaries(dictionaryUpdater);
280 public boolean onCreateOptionsMenu(final Menu menu) {
281 MenuInflater inflater = getSupportMenuInflater();
282 inflater.inflate(R.menu.dictionary_manager_options_menu, menu);
284 filterSearchView = (SearchView) menu.findItem(R.id.filterText).getActionView();
285 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
287 public boolean onQueryTextSubmit(String query) {
292 public boolean onQueryTextChange(String filterText) {
297 filterSearchView.setIconifiedByDefault(false);
299 application.onCreateGlobalOptionsMenu(this, menu);
304 public void onCreateContextMenu(final ContextMenu menu, final View view,
305 final ContextMenuInfo menuInfo) {
306 super.onCreateContextMenu(menu, view, menuInfo);
307 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
309 final AdapterContextMenuInfo adapterContextMenuInfo =
310 (AdapterContextMenuInfo) menuInfo;
311 final int position = adapterContextMenuInfo.position;
312 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
314 if (row.dictionaryInfo == null) {
318 if (position > 0 && row.onDevice) {
319 final android.view.MenuItem moveToTopMenuItem =
320 menu.add(R.string.moveToTop);
321 moveToTopMenuItem.setOnMenuItemClickListener(new
322 android.view.MenuItem.OnMenuItemClickListener() {
324 public boolean onMenuItemClick(android.view.MenuItem item) {
325 application.moveDictionaryToTop(row.dictionaryInfo);
333 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
335 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
337 public boolean onMenuItemClick(android.view.MenuItem item) {
338 application.deleteDictionary(row.dictionaryInfo);
346 private void onShowLocalChanged() {
348 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
349 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
353 // private void onClick(int index) {
354 // final DictionaryInfo dictionaryInfo = adapter.getItem(index);
355 // final DictionaryInfo downloadable =
356 // application.getDownloadable(dictionaryInfo.uncompressedFilename);
358 // (!application.isDictionaryOnDevice(dictionaryInfo.uncompressedFilename)
359 // && downloadable != null) {
360 // final Intent intent = getDownloadIntent(downloadable);
361 // startActivity(intent);
363 // final Intent intent =
364 // DictionaryActivity.getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
366 // startActivity(intent);
371 class MyListAdapter extends BaseAdapter {
373 List<DictionaryInfo> dictionariesOnDevice;
374 List<DictionaryInfo> downloadableDictionaries;
377 DictionaryInfo dictionaryInfo;
380 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
381 this.dictionaryInfo = dictinoaryInfo;
382 this.onDevice = onDevice;
387 private MyListAdapter(final String[] filters) {
388 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
389 if (showDownloadable.isChecked()) {
390 downloadableDictionaries = application.getDownloadableDictionaries(filters);
392 downloadableDictionaries = Collections.emptyList();
397 public int getCount() {
398 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
402 public Row getItem(int position) {
404 return new Row(null, true);
408 if (position < dictionariesOnDevice.size()) {
409 return new Row(dictionariesOnDevice.get(position), true);
411 position -= dictionariesOnDevice.size();
414 return new Row(null, false);
418 assert position < downloadableDictionaries.size();
419 return new Row(downloadableDictionaries.get(position), false);
423 public long getItemId(int position) {
428 public View getView(int position, View convertView, ViewGroup parent) {
429 if (convertView instanceof LinearLayout &&
430 convertView != dictionariesOnDeviceHeaderRow &&
431 convertView != downloadableDictionariesHeaderRow) {
432 ((LinearLayout)convertView).removeAllViews();
435 final Row row = getItem(position);
438 if (row.dictionaryInfo == null) {
439 return dictionariesOnDeviceHeaderRow;
441 return createDictionaryRow(row.dictionaryInfo,
442 parent, R.layout.dictionaries_on_device_row, true);
445 if (row.dictionaryInfo == null) {
446 return downloadableDictionariesHeaderRow;
448 return createDictionaryRow(row.dictionaryInfo,
449 parent, R.layout.downloadable_dictionary_row, false);
454 private void setListAdapater() {
455 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery().toString();
456 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
457 setListAdapter(new MyListAdapter(filters));
460 private View createDictionaryRow(final DictionaryInfo dictionaryInfo, final ViewGroup parent,
461 final int viewResource, final boolean canLaunch) {
463 View row = LayoutInflater.from(parent.getContext()).inflate(
464 viewResource, parent, false);
465 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
466 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
467 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
470 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
471 downloadButton.setText(getString(R.string.downloadButton, dictionaryInfo.zipBytes / 1024.0 / 1024.0));
472 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
473 downloadButton.setOnClickListener(new OnClickListener() {
475 public void onClick(View arg0) {
476 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
477 Request request = new Request(
478 Uri.parse(dictionaryInfo.downloadUrl));
480 final String destFile = new File(new URL(dictionaryInfo.downloadUrl).getFile()).getName();
481 Log.d(LOG, "Downloading to: " + destFile);
483 request.setDestinationUri(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), destFile)));
484 } catch (MalformedURLException e) {
485 throw new RuntimeException(e);
487 downloadManager.enqueue(request);
492 final StringBuilder builder = new StringBuilder();
493 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
494 final List<IndexInfo> sortedIndexInfos = application.sortedIndexInfos(dictionaryInfo.indexInfos);
495 for (IndexInfo indexInfo : sortedIndexInfos) {
496 final View button = application.createButton(buttons.getContext(), dictionaryInfo, indexInfo);
497 buttons.addView(button);
500 button.setOnClickListener(
501 new IntentLauncher(buttons.getContext(),
502 DictionaryActivity.getLaunchIntent(
503 application.getPath(dictionaryInfo.uncompressedFilename),
504 indexInfo.shortName, "")));
507 button.setEnabled(false);
509 if (builder.length() != 0) {
510 builder.append("; ");
512 builder.append(getString(R.string.indexInfo, indexInfo.shortName, indexInfo.mainTokenCount));
514 details.setText(builder.toString());
516 row.setClickable(true);
517 row.setFocusable(true);
518 row.setLongClickable(true);
519 row.setBackgroundResource(android.R.drawable.menuitem_background);