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 application.onCreateGlobalOptionsMenu(this, menu);
356 public void onCreateContextMenu(final ContextMenu menu, final View view,
357 final ContextMenuInfo menuInfo) {
358 super.onCreateContextMenu(menu, view, menuInfo);
359 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
361 final AdapterContextMenuInfo adapterContextMenuInfo =
362 (AdapterContextMenuInfo) menuInfo;
363 final int position = adapterContextMenuInfo.position;
364 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
366 if (row.dictionaryInfo == null) {
370 if (position > 0 && row.onDevice) {
371 final android.view.MenuItem moveToTopMenuItem =
372 menu.add(R.string.moveToTop);
373 moveToTopMenuItem.setOnMenuItemClickListener(new
374 android.view.MenuItem.OnMenuItemClickListener() {
376 public boolean onMenuItemClick(android.view.MenuItem item) {
377 application.moveDictionaryToTop(row.dictionaryInfo);
385 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
387 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
389 public boolean onMenuItemClick(android.view.MenuItem item) {
390 application.deleteDictionary(row.dictionaryInfo);
398 private void onShowLocalChanged() {
400 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
401 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
405 class MyListAdapter extends BaseAdapter {
407 List<DictionaryInfo> dictionariesOnDevice;
408 List<DictionaryInfo> downloadableDictionaries;
411 DictionaryInfo dictionaryInfo;
414 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
415 this.dictionaryInfo = dictinoaryInfo;
416 this.onDevice = onDevice;
421 private MyListAdapter(final String[] filters) {
422 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
423 if (showDownloadable.isChecked()) {
424 downloadableDictionaries = application.getDownloadableDictionaries(filters);
426 downloadableDictionaries = Collections.emptyList();
431 public int getCount() {
432 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
436 public Row getItem(int position) {
438 return new Row(null, true);
442 if (position < dictionariesOnDevice.size()) {
443 return new Row(dictionariesOnDevice.get(position), true);
445 position -= dictionariesOnDevice.size();
448 return new Row(null, false);
452 assert position < downloadableDictionaries.size();
453 return new Row(downloadableDictionaries.get(position), false);
457 public long getItemId(int position) {
462 public View getView(int position, View convertView, ViewGroup parent) {
463 if (convertView instanceof LinearLayout &&
464 convertView != dictionariesOnDeviceHeaderRow &&
465 convertView != downloadableDictionariesHeaderRow) {
466 /* This is done to try to avoid leaking memory that used to
467 * happen on Android 4.0.3 */
468 ((LinearLayout)convertView).removeAllViews();
471 final Row row = getItem(position);
474 if (row.dictionaryInfo == null) {
475 return dictionariesOnDeviceHeaderRow;
477 return createDictionaryRow(row.dictionaryInfo, parent, true);
480 if (row.dictionaryInfo == null) {
481 return downloadableDictionariesHeaderRow;
483 return createDictionaryRow(row.dictionaryInfo, parent, false);
488 private void setListAdapater() {
489 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery().toString();
490 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
491 setListAdapter(new MyListAdapter(filters));
494 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
495 final ViewGroup parent, final boolean canLaunch) {
497 View row = LayoutInflater.from(parent.getContext()).inflate(
498 R.layout.dictionary_manager_row, parent, false);
499 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
500 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
501 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
503 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
504 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
505 if (!canLaunch || updateAvailable) {
506 downloadButton.setText(getString(R.string.downloadButton, application.getDownloadable(dictionaryInfo.uncompressedFilename).zipBytes / 1024.0 / 1024.0));
507 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
508 downloadButton.setOnClickListener(new OnClickListener() {
510 public void onClick(View arg0) {
511 downloadDictionary(dictionaryInfo);
515 downloadButton.setVisibility(View.INVISIBLE);
518 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
519 final List<IndexInfo> sortedIndexInfos = application.sortedIndexInfos(dictionaryInfo.indexInfos);
520 final StringBuilder builder = new StringBuilder();
521 if (updateAvailable) {
522 builder.append(getString(R.string.updateButton));
524 for (IndexInfo indexInfo : sortedIndexInfos) {
525 final View button = application.createButton(buttons.getContext(), dictionaryInfo, indexInfo);
526 buttons.addView(button);
529 button.setOnClickListener(
530 new IntentLauncher(buttons.getContext(),
531 DictionaryActivity.getLaunchIntent(
532 application.getPath(dictionaryInfo.uncompressedFilename),
533 indexInfo.shortName, "")));
536 button.setEnabled(false);
538 if (builder.length() != 0) {
539 builder.append("; ");
541 builder.append(getString(R.string.indexInfo, indexInfo.shortName, indexInfo.mainTokenCount));
543 details.setText(builder.toString());
546 row.setClickable(true);
547 row.setOnClickListener(new IntentLauncher(parent.getContext(),
548 DictionaryActivity.getLaunchIntent(
549 application.getPath(dictionaryInfo.uncompressedFilename),
550 dictionaryInfo.indexInfos.get(0).shortName, "")));
551 row.setFocusable(true);
552 row.setLongClickable(true);
554 row.setBackgroundResource(android.R.drawable.menuitem_background);
559 private void downloadDictionary(final DictionaryInfo dictionaryInfo) {
560 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
561 Request request = new Request(
562 Uri.parse(dictionaryInfo.downloadUrl));
564 final String destFile = new File(new URL(dictionaryInfo.downloadUrl).getFile()).getName();
565 Log.d(LOG, "Downloading to: " + destFile);
567 request.setDestinationUri(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), destFile)));
568 } catch (MalformedURLException e) {
569 throw new RuntimeException(e);
571 downloadManager.enqueue(request);