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 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
183 super.onCreate(savedInstanceState);
184 Log.d(LOG, "onCreate:" + this);
186 application = (DictionaryApplication) getApplication();
188 blockAutoLaunch = false;
191 setContentView(R.layout.dictionary_manager_activity);
193 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
194 getListView().getContext()).inflate(
195 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
197 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
198 getListView().getContext()).inflate(
199 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
201 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
202 .findViewById(R.id.hideDownloadable);
203 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
205 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
206 onShowLocalChanged();
210 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
211 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
212 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
213 thanksForUpdatingLatestVersion)) {
214 blockAutoLaunch = true;
215 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent());
216 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
220 registerReceiver(broadcastReceiver, new IntentFilter(
221 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
224 registerForContextMenu(getListView());
226 final File dictDir = application.getDictDir();
227 if (!dictDir.canRead() || !dictDir.canExecute()) {
228 blockAutoLaunch = true;
230 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
231 builder.setTitle(getString(R.string.error));
232 builder.setMessage(getString(
233 R.string.unableToReadDictionaryDir,
234 dictDir.getAbsolutePath(),
235 Environment.getExternalStorageDirectory()));
236 builder.create().show();
239 onCreateSetupActionBar();
242 private void onCreateSetupActionBar() {
243 ActionBar actionBar = getSupportActionBar();
244 actionBar.setDisplayShowTitleEnabled(false);
246 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
247 filterSearchView.setIconifiedByDefault(false);
248 // filterSearchView.setIconified(false); // puts the magnifying glass in
251 filterSearchView.setQueryHint(getString(R.string.searchText));
252 filterSearchView.setSubmitButtonEnabled(false);
253 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
254 getResources().getDisplayMetrics());
255 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
256 FrameLayout.LayoutParams.WRAP_CONTENT);
257 filterSearchView.setLayoutParams(lp);
258 filterSearchView.setImeOptions(
259 EditorInfo.IME_ACTION_SEARCH |
260 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
261 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
262 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
264 EditorInfo.IME_MASK_ACTION |
265 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
267 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
269 public boolean onQueryTextSubmit(String query) {
274 public boolean onQueryTextChange(String filterText) {
279 filterSearchView.setFocusable(true);
281 actionBar.setCustomView(filterSearchView);
282 actionBar.setDisplayShowCustomEnabled(true);
286 public void onDestroy() {
288 unregisterReceiver(broadcastReceiver);
291 private static int copyStream(final InputStream in, final OutputStream out)
294 final byte[] bytes = new byte[1024 * 16];
295 while ((bytesRead = in.read(bytes)) != -1) {
296 out.write(bytes, 0, bytesRead);
304 protected void onStart() {
306 uiHandler = new Handler();
310 protected void onStop() {
316 protected void onResume() {
319 if (PreferenceActivity.prefsMightHaveChanged) {
320 PreferenceActivity.prefsMightHaveChanged = false;
322 startActivity(getIntent());
325 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
326 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, false));
328 if (!blockAutoLaunch &&
329 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
330 prefs.contains(C.DICT_FILE) &&
331 prefs.contains(C.INDEX_SHORT_NAME)) {
332 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
333 startActivity(DictionaryActivity.getLaunchIntent(
334 new File(prefs.getString(C.DICT_FILE, "")),
335 prefs.getString(C.INDEX_SHORT_NAME, ""),
336 prefs.getString(C.SEARCH_TOKEN, "")));
341 // Remove the active dictionary from the prefs so we won't autolaunch
343 final Editor editor = prefs.edit();
344 editor.remove(C.DICT_FILE);
345 editor.remove(C.INDEX_SHORT_NAME);
346 editor.remove(C.SEARCH_TOKEN);
349 application.backgroundUpdateDictionaries(dictionaryUpdater);
355 public boolean onCreateOptionsMenu(final Menu menu) {
356 application.onCreateGlobalOptionsMenu(this, menu);
361 public void onCreateContextMenu(final ContextMenu menu, final View view,
362 final ContextMenuInfo menuInfo) {
363 super.onCreateContextMenu(menu, view, menuInfo);
364 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
366 final AdapterContextMenuInfo adapterContextMenuInfo =
367 (AdapterContextMenuInfo) menuInfo;
368 final int position = adapterContextMenuInfo.position;
369 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
371 if (row.dictionaryInfo == null) {
375 if (position > 0 && row.onDevice) {
376 final android.view.MenuItem moveToTopMenuItem =
377 menu.add(R.string.moveToTop);
378 moveToTopMenuItem.setOnMenuItemClickListener(new
379 android.view.MenuItem.OnMenuItemClickListener() {
381 public boolean onMenuItemClick(android.view.MenuItem item) {
382 application.moveDictionaryToTop(row.dictionaryInfo);
390 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
392 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
394 public boolean onMenuItemClick(android.view.MenuItem item) {
395 application.deleteDictionary(row.dictionaryInfo);
403 private void onShowLocalChanged() {
405 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
406 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
410 class MyListAdapter extends BaseAdapter {
412 List<DictionaryInfo> dictionariesOnDevice;
413 List<DictionaryInfo> downloadableDictionaries;
416 DictionaryInfo dictionaryInfo;
419 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
420 this.dictionaryInfo = dictinoaryInfo;
421 this.onDevice = onDevice;
425 private MyListAdapter(final String[] filters) {
426 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
427 if (showDownloadable.isChecked()) {
428 downloadableDictionaries = application.getDownloadableDictionaries(filters);
430 downloadableDictionaries = Collections.emptyList();
435 public int getCount() {
436 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
440 public Row getItem(int position) {
442 return new Row(null, true);
446 if (position < dictionariesOnDevice.size()) {
447 return new Row(dictionariesOnDevice.get(position), true);
449 position -= dictionariesOnDevice.size();
452 return new Row(null, false);
456 assert position < downloadableDictionaries.size();
457 return new Row(downloadableDictionaries.get(position), false);
461 public long getItemId(int position) {
466 public View getView(int position, View convertView, ViewGroup parent) {
467 if (convertView instanceof LinearLayout &&
468 convertView != dictionariesOnDeviceHeaderRow &&
469 convertView != downloadableDictionariesHeaderRow) {
471 * This is done to try to avoid leaking memory that used to
472 * happen on Android 4.0.3
474 ((LinearLayout) convertView).removeAllViews();
477 final Row row = getItem(position);
480 if (row.dictionaryInfo == null) {
481 return dictionariesOnDeviceHeaderRow;
483 return createDictionaryRow(row.dictionaryInfo, parent, true);
486 if (row.dictionaryInfo == null) {
487 return downloadableDictionariesHeaderRow;
489 return createDictionaryRow(row.dictionaryInfo, parent, false);
494 private void setListAdapater() {
495 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
497 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
498 setListAdapter(new MyListAdapter(filters));
501 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
502 final ViewGroup parent, final boolean canLaunch) {
504 View row = LayoutInflater.from(parent.getContext()).inflate(
505 R.layout.dictionary_manager_row, parent, false);
506 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
507 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
508 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
510 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
511 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
512 if (!canLaunch || updateAvailable) {
515 R.string.downloadButton,
516 application.getDownloadable(dictionaryInfo.uncompressedFilename).zipBytes / 1024.0 / 1024.0));
517 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
518 downloadButton.setOnClickListener(new OnClickListener() {
520 public void onClick(View arg0) {
521 downloadDictionary(dictionaryInfo);
525 downloadButton.setVisibility(View.INVISIBLE);
528 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
529 final List<IndexInfo> sortedIndexInfos = application
530 .sortedIndexInfos(dictionaryInfo.indexInfos);
531 final StringBuilder builder = new StringBuilder();
532 if (updateAvailable) {
533 builder.append(getString(R.string.updateButton));
535 for (IndexInfo indexInfo : sortedIndexInfos) {
536 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
538 buttons.addView(button);
541 button.setOnClickListener(
542 new IntentLauncher(buttons.getContext(),
543 DictionaryActivity.getLaunchIntent(
544 application.getPath(dictionaryInfo.uncompressedFilename),
545 indexInfo.shortName, "")));
548 button.setEnabled(false);
550 if (builder.length() != 0) {
551 builder.append("; ");
553 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
554 indexInfo.mainTokenCount));
556 details.setText(builder.toString());
559 row.setClickable(true);
560 row.setOnClickListener(new IntentLauncher(parent.getContext(),
561 DictionaryActivity.getLaunchIntent(
562 application.getPath(dictionaryInfo.uncompressedFilename),
563 dictionaryInfo.indexInfos.get(0).shortName, "")));
564 row.setFocusable(true);
565 row.setLongClickable(true);
567 row.setBackgroundResource(android.R.drawable.menuitem_background);
572 private void downloadDictionary(final DictionaryInfo dictionaryInfo) {
573 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
574 Request request = new Request(
575 Uri.parse(dictionaryInfo.downloadUrl));
577 final String destFile = new File(new URL(dictionaryInfo.downloadUrl).getFile())
579 Log.d(LOG, "Downloading to: " + destFile);
581 request.setDestinationUri(Uri.fromFile(new File(Environment
582 .getExternalStorageDirectory(), destFile)));
583 } catch (MalformedURLException e) {
584 throw new RuntimeException(e);
586 downloadManager.enqueue(request);