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.LayoutInflater;
33 import android.view.View;
34 import android.view.View.OnClickListener;
35 import android.view.ViewGroup;
36 import android.widget.BaseAdapter;
37 import android.widget.Button;
38 import android.widget.CompoundButton;
39 import android.widget.CompoundButton.OnCheckedChangeListener;
40 import android.widget.LinearLayout;
41 import android.widget.TextView;
42 import android.widget.ToggleButton;
44 import com.actionbarsherlock.app.SherlockListActivity;
45 import com.actionbarsherlock.view.Menu;
46 import com.actionbarsherlock.view.MenuInflater;
47 import com.actionbarsherlock.widget.SearchView;
48 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
49 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
50 import com.hughes.android.util.IntentLauncher;
53 import java.io.FileOutputStream;
54 import java.io.IOException;
55 import java.io.InputStream;
56 import java.io.OutputStream;
57 import java.net.MalformedURLException;
59 import java.util.Collections;
60 import java.util.List;
61 import java.util.zip.ZipEntry;
62 import java.util.zip.ZipFile;
66 // Delete, move to top.
68 public class DictionaryManagerActivity extends SherlockListActivity {
70 static final String LOG = "QuickDic";
71 static boolean blockAutoLaunch = false;
73 DictionaryApplication application;
76 // EditText filterText;
77 SearchView filterSearchView;
78 ToggleButton showDownloadable;
80 LinearLayout dictionariesOnDeviceHeaderRow;
81 LinearLayout downloadableDictionariesHeaderRow;
85 Runnable dictionaryUpdater = new Runnable() {
88 if (uiHandler == null) {
91 uiHandler.post(new Runnable() {
100 public static Intent getLaunchIntent() {
101 final Intent intent = new Intent();
102 intent.setClassName(DictionaryManagerActivity.class.getPackage().getName(),
103 DictionaryManagerActivity.class.getName());
104 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
108 public void onCreate(Bundle savedInstanceState) {
109 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
111 super.onCreate(savedInstanceState);
112 Log.d(LOG, "onCreate:" + this);
114 application = (DictionaryApplication) getApplication();
117 setContentView(R.layout.dictionary_manager_activity);
119 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
120 R.layout.dictionaries_on_device_header_row, getListView(), false);
122 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
123 R.layout.downloadable_dictionaries_header_row, getListView(), false);
125 // filterText = (EditText) findViewById(R.id.filterText);
127 // filterText.addTextChangedListener(new TextWatcher() {
129 // public void onTextChanged(CharSequence s, int start, int before, int
134 // public void beforeTextChanged(CharSequence s, int start, int count,
139 // public void afterTextChanged(Editable s) {
140 // onFilterTextChanged();
144 // final ImageButton clearSearchText = (ImageButton)
145 // findViewById(R.id.ClearSearchTextButton);
146 // clearSearchText.setOnClickListener(new View.OnClickListener() {
148 // public void onClick(View arg0) {
149 // filterText.setText("");
150 // filterText.requestFocus();
154 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow.findViewById(R.id.hideDownloadable);
155 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
157 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
158 onShowLocalChanged();
163 // registerForContextMenu(getListView());
165 blockAutoLaunch = false;
166 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
167 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
168 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
169 thanksForUpdatingLatestVersion)) {
170 blockAutoLaunch = true;
171 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent());
172 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
176 BroadcastReceiver receiver = new BroadcastReceiver() {
178 public void onReceive(Context context, Intent intent) {
179 final String action = intent.getAction();
180 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
181 final long downloadId = intent.getLongExtra(
182 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
183 final DownloadManager.Query query = new DownloadManager.Query();
184 query.setFilterById(downloadId);
185 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
186 final Cursor cursor = downloadManager.query(query);
188 if (!cursor.moveToFirst()) {
189 Log.e(LOG, "Couldn't find download.");
193 final int status = cursor
195 .getColumnIndex(DownloadManager.COLUMN_STATUS));
196 if (DownloadManager.STATUS_SUCCESSFUL != status){
197 Log.w(LOG, "Download failed: status=" + status + ", reason=" + cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)));
201 final String dest = cursor
202 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
203 Log.w(LOG, "Download finished: " + dest);
204 final File destFile = new File(Uri.parse(dest).getPath());
207 ZipFile zipFile = new ZipFile(destFile);
208 final ZipEntry zipEntry = zipFile.entries().nextElement();
209 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
210 final InputStream zipIn = zipFile.getInputStream(zipEntry);
211 final OutputStream zipOut = new FileOutputStream(new File(application.getDictDir(), zipEntry.getName()));
212 copyStream(zipIn, zipOut);
215 application.backgroundUpdateDictionaries(dictionaryUpdater);
216 } catch (Exception e) {
217 Log.e(LOG, "Failed to unzip.", e);
223 registerReceiver(receiver, new IntentFilter(
224 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
229 private static int copyStream(final InputStream in, final OutputStream out)
232 final byte[] bytes = new byte[1024 * 16];
233 while ((bytesRead = in.read(bytes)) != -1) {
234 out.write(bytes, 0, bytesRead);
242 protected void onStart() {
244 uiHandler = new Handler();
248 protected void onStop() {
254 protected void onResume() {
257 if (PreferenceActivity.prefsMightHaveChanged) {
258 PreferenceActivity.prefsMightHaveChanged = false;
260 startActivity(getIntent());
263 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
264 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, false));
266 if (!blockAutoLaunch &&
267 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
268 prefs.contains(C.DICT_FILE) &&
269 prefs.contains(C.INDEX_SHORT_NAME)) {
270 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
271 startActivity(DictionaryActivity.getLaunchIntent(
272 new File(prefs.getString(C.DICT_FILE, "")), prefs.getString(C.INDEX_SHORT_NAME, ""),
273 prefs.getString(C.SEARCH_TOKEN, "")));
278 // Remove the active dictionary from the prefs so we won't autolaunch
280 final Editor editor = prefs.edit();
281 editor.remove(C.DICT_FILE);
282 editor.remove(C.INDEX_SHORT_NAME);
283 editor.remove(C.SEARCH_TOKEN);
286 application.backgroundUpdateDictionaries(dictionaryUpdater);
292 public boolean onCreateOptionsMenu(final Menu menu) {
293 MenuInflater inflater = getSupportMenuInflater();
294 inflater.inflate(R.menu.dictionary_manager_options_menu, menu);
296 filterSearchView = (SearchView) menu.findItem(R.id.filterText).getActionView();
297 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
299 public boolean onQueryTextSubmit(String query) {
304 public boolean onQueryTextChange(String filterText) {
309 filterSearchView.setIconifiedByDefault(false);
311 application.onCreateGlobalOptionsMenu(this, menu);
316 // public void onCreateContextMenu(final ContextMenu menu, final View
318 // final ContextMenuInfo menuInfo) {
319 // super.onCreateContextMenu(menu, view, menuInfo);
321 // final AdapterContextMenuInfo adapterContextMenuInfo =
322 // (AdapterContextMenuInfo) menuInfo;
323 // final int position = adapterContextMenuInfo.position;
324 // final DictionaryInfo dictionaryInfo = adapter.getItem(position);
326 // if (position > 0 &&
327 // application.isDictionaryOnDevice(dictionaryInfo.uncompressedFilename))
329 // final android.view.MenuItem moveToTopMenuItem =
330 // menu.add(R.string.moveToTop);
331 // moveToTopMenuItem.setOnMenuItemClickListener(new
332 // android.view.MenuItem.OnMenuItemClickListener() {
334 // public boolean onMenuItemClick(android.view.MenuItem item) {
335 // application.moveDictionaryToTop(dictionaryInfo);
336 // setListAdapter(adapter = new Adapter());
342 // final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
344 // .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
346 // public boolean onMenuItemClick(android.view.MenuItem item) {
347 // application.deleteDictionary(dictionaryInfo);
348 // setListAdapter(adapter = new Adapter());
353 // final DictionaryInfo downloadable = application
354 // .getDownloadable(dictionaryInfo.uncompressedFilename);
355 // if (downloadable != null) {
356 // final android.view.MenuItem downloadMenuItem = menu.add(getString(
357 // R.string.downloadButton, downloadable.zipBytes / 1024.0 / 1024.0));
359 // .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
361 // public boolean onMenuItemClick(android.view.MenuItem item) {
362 // final Intent intent = getDownloadIntent(downloadable);
363 // startActivity(intent);
364 // setListAdapter(adapter = new Adapter());
372 private void onShowLocalChanged() {
373 // downloadableDictionaries.setVisibility(showDownloadable.isChecked() ? View.GONE
376 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
377 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
381 // private void onClick(int index) {
382 // final DictionaryInfo dictionaryInfo = adapter.getItem(index);
383 // final DictionaryInfo downloadable =
384 // application.getDownloadable(dictionaryInfo.uncompressedFilename);
386 // (!application.isDictionaryOnDevice(dictionaryInfo.uncompressedFilename)
387 // && downloadable != null) {
388 // final Intent intent = getDownloadIntent(downloadable);
389 // startActivity(intent);
391 // final Intent intent =
392 // DictionaryActivity.getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
394 // startActivity(intent);
398 class MyListAdapter extends BaseAdapter {
400 List<DictionaryInfo> dictionariesOnDevice;
401 List<DictionaryInfo> downloadableDictionaries;
403 private MyListAdapter(final String[] filters) {
404 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
405 if (showDownloadable.isChecked()) {
406 downloadableDictionaries = application.getDownloadableDictionaries(filters);
408 downloadableDictionaries = Collections.emptyList();
413 public int getCount() {
414 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
418 public Object getItem(int position) {
419 return Integer.valueOf(position);
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();
434 // Dictionaries on device.
436 return dictionariesOnDeviceHeaderRow;
440 if (position < dictionariesOnDevice.size()) {
441 return createDictionaryRow(dictionariesOnDevice.get(position),
442 parent, R.layout.dictionaries_on_device_row, true);
444 position -= dictionariesOnDevice.size();
446 // Downloadable dictionaries.
448 return downloadableDictionariesHeaderRow;
452 assert position < downloadableDictionaries.size();
453 return createDictionaryRow(downloadableDictionaries.get(position),
454 parent, R.layout.downloadable_dictionary_row, false);
460 private void setListAdapater() {
461 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery().toString();
462 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
463 setListAdapter(new MyListAdapter(filters));
466 private View createDictionaryRow(final DictionaryInfo dictionaryInfo, final ViewGroup parent,
467 final int viewResource, final boolean canLaunch) {
469 View row = LayoutInflater.from(parent.getContext()).inflate(
470 viewResource, parent, false);
471 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
472 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
473 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
476 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
477 downloadButton.setText(getString(R.string.downloadButton, dictionaryInfo.zipBytes / 1024.0 / 1024.0));
478 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
479 downloadButton.setOnClickListener(new OnClickListener() {
481 public void onClick(View arg0) {
482 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
483 Request request = new Request(
484 Uri.parse(dictionaryInfo.downloadUrl));
486 final String destFile = new File(new URL(dictionaryInfo.downloadUrl).getFile()).getName();
487 Log.d(LOG, "Downloading to: " + destFile);
489 request.setDestinationUri(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), destFile)));
490 } catch (MalformedURLException e) {
491 throw new RuntimeException(e);
493 downloadManager.enqueue(request);
498 final StringBuilder builder = new StringBuilder();
499 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
500 final List<IndexInfo> sortedIndexInfos = application.sortedIndexInfos(dictionaryInfo.indexInfos);
501 for (IndexInfo indexInfo : sortedIndexInfos) {
502 final View button = application.createButton(buttons.getContext(), dictionaryInfo, indexInfo);
503 buttons.addView(button);
506 button.setOnClickListener(
507 new IntentLauncher(buttons.getContext(),
508 DictionaryActivity.getLaunchIntent(
509 application.getPath(dictionaryInfo.uncompressedFilename),
510 indexInfo.shortName, "")));
513 button.setEnabled(false);
515 if (builder.length() != 0) {
516 builder.append("; ");
518 builder.append(getString(R.string.indexInfo, indexInfo.shortName, indexInfo.mainTokenCount));
520 details.setText(builder.toString());