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(
192 getListView().getContext()).inflate(
193 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
195 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
196 getListView().getContext()).inflate(
197 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
199 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
200 .findViewById(R.id.hideDownloadable);
201 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
203 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
204 onShowLocalChanged();
208 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
209 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
210 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
211 thanksForUpdatingLatestVersion)) {
212 blockAutoLaunch = true;
213 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent());
214 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
218 registerReceiver(broadcastReceiver, new IntentFilter(
219 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
222 registerForContextMenu(getListView());
224 final File dictDir = application.getDictDir();
225 if (!dictDir.canRead() || !dictDir.canExecute()) {
226 blockAutoLaunch = true;
228 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
229 builder.setTitle(getString(R.string.error));
230 builder.setMessage(getString(
231 R.string.unableToReadDictionaryDir,
232 dictDir.getAbsolutePath(),
233 Environment.getExternalStorageDirectory()));
234 builder.create().show();
237 onCreateSetupActionBar();
240 private void onCreateSetupActionBar() {
241 ActionBar actionBar = getSupportActionBar();
242 actionBar.setDisplayShowTitleEnabled(false);
244 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
245 filterSearchView.setIconifiedByDefault(false);
246 // filterSearchView.setIconified(false); // puts the magnifying glass in
249 filterSearchView.setQueryHint(getString(R.string.searchText));
250 filterSearchView.setSubmitButtonEnabled(false);
251 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
252 getResources().getDisplayMetrics());
253 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
254 FrameLayout.LayoutParams.WRAP_CONTENT);
255 filterSearchView.setLayoutParams(lp);
256 filterSearchView.setImeOptions(
257 EditorInfo.IME_ACTION_SEARCH |
258 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
259 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
260 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
262 EditorInfo.IME_MASK_ACTION |
263 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
265 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
267 public boolean onQueryTextSubmit(String query) {
272 public boolean onQueryTextChange(String filterText) {
277 filterSearchView.setFocusable(true);
279 actionBar.setCustomView(filterSearchView);
280 actionBar.setDisplayShowCustomEnabled(true);
284 public void onDestroy() {
286 unregisterReceiver(broadcastReceiver);
289 private static int copyStream(final InputStream in, final OutputStream out)
292 final byte[] bytes = new byte[1024 * 16];
293 while ((bytesRead = in.read(bytes)) != -1) {
294 out.write(bytes, 0, bytesRead);
302 protected void onStart() {
304 uiHandler = new Handler();
308 protected void onStop() {
314 protected void onResume() {
317 if (PreferenceActivity.prefsMightHaveChanged) {
318 PreferenceActivity.prefsMightHaveChanged = false;
320 startActivity(getIntent());
323 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
324 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, false));
326 if (!blockAutoLaunch &&
327 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
328 prefs.contains(C.DICT_FILE) &&
329 prefs.contains(C.INDEX_SHORT_NAME)) {
330 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
331 startActivity(DictionaryActivity.getLaunchIntent(
332 new File(prefs.getString(C.DICT_FILE, "")),
333 prefs.getString(C.INDEX_SHORT_NAME, ""),
334 prefs.getString(C.SEARCH_TOKEN, "")));
339 // Remove the active dictionary from the prefs so we won't autolaunch
341 final Editor editor = prefs.edit();
342 editor.remove(C.DICT_FILE);
343 editor.remove(C.INDEX_SHORT_NAME);
344 editor.remove(C.SEARCH_TOKEN);
347 application.backgroundUpdateDictionaries(dictionaryUpdater);
353 public boolean onCreateOptionsMenu(final Menu menu) {
354 application.onCreateGlobalOptionsMenu(this, menu);
359 public void onCreateContextMenu(final ContextMenu menu, final View view,
360 final ContextMenuInfo menuInfo) {
361 super.onCreateContextMenu(menu, view, menuInfo);
362 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
364 final AdapterContextMenuInfo adapterContextMenuInfo =
365 (AdapterContextMenuInfo) menuInfo;
366 final int position = adapterContextMenuInfo.position;
367 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
369 if (row.dictionaryInfo == null) {
373 if (position > 0 && row.onDevice) {
374 final android.view.MenuItem moveToTopMenuItem =
375 menu.add(R.string.moveToTop);
376 moveToTopMenuItem.setOnMenuItemClickListener(new
377 android.view.MenuItem.OnMenuItemClickListener() {
379 public boolean onMenuItemClick(android.view.MenuItem item) {
380 application.moveDictionaryToTop(row.dictionaryInfo);
388 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
390 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
392 public boolean onMenuItemClick(android.view.MenuItem item) {
393 application.deleteDictionary(row.dictionaryInfo);
401 private void onShowLocalChanged() {
403 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
404 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
408 class MyListAdapter extends BaseAdapter {
410 List<DictionaryInfo> dictionariesOnDevice;
411 List<DictionaryInfo> downloadableDictionaries;
414 DictionaryInfo dictionaryInfo;
417 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
418 this.dictionaryInfo = dictinoaryInfo;
419 this.onDevice = onDevice;
423 private MyListAdapter(final String[] filters) {
424 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
425 if (showDownloadable.isChecked()) {
426 downloadableDictionaries = application.getDownloadableDictionaries(filters);
428 downloadableDictionaries = Collections.emptyList();
433 public int getCount() {
434 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
438 public Row getItem(int position) {
440 return new Row(null, true);
444 if (position < dictionariesOnDevice.size()) {
445 return new Row(dictionariesOnDevice.get(position), true);
447 position -= dictionariesOnDevice.size();
450 return new Row(null, false);
454 assert position < downloadableDictionaries.size();
455 return new Row(downloadableDictionaries.get(position), false);
459 public long getItemId(int position) {
464 public View getView(int position, View convertView, ViewGroup parent) {
465 if (convertView instanceof LinearLayout &&
466 convertView != dictionariesOnDeviceHeaderRow &&
467 convertView != downloadableDictionariesHeaderRow) {
469 * This is done to try to avoid leaking memory that used to
470 * happen on Android 4.0.3
472 ((LinearLayout) convertView).removeAllViews();
475 final Row row = getItem(position);
478 if (row.dictionaryInfo == null) {
479 return dictionariesOnDeviceHeaderRow;
481 return createDictionaryRow(row.dictionaryInfo, parent, true);
484 if (row.dictionaryInfo == null) {
485 return downloadableDictionariesHeaderRow;
487 return createDictionaryRow(row.dictionaryInfo, parent, false);
492 private void setListAdapater() {
493 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
495 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
496 setListAdapter(new MyListAdapter(filters));
499 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
500 final ViewGroup parent, final boolean canLaunch) {
502 View row = LayoutInflater.from(parent.getContext()).inflate(
503 R.layout.dictionary_manager_row, parent, false);
504 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
505 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
506 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
508 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
509 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
510 if (!canLaunch || updateAvailable) {
513 R.string.downloadButton,
514 application.getDownloadable(dictionaryInfo.uncompressedFilename).zipBytes / 1024.0 / 1024.0));
515 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
516 downloadButton.setOnClickListener(new OnClickListener() {
518 public void onClick(View arg0) {
519 downloadDictionary(dictionaryInfo);
523 downloadButton.setVisibility(View.INVISIBLE);
526 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
527 final List<IndexInfo> sortedIndexInfos = application
528 .sortedIndexInfos(dictionaryInfo.indexInfos);
529 final StringBuilder builder = new StringBuilder();
530 if (updateAvailable) {
531 builder.append(getString(R.string.updateButton));
533 for (IndexInfo indexInfo : sortedIndexInfos) {
534 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
536 buttons.addView(button);
539 button.setOnClickListener(
540 new IntentLauncher(buttons.getContext(),
541 DictionaryActivity.getLaunchIntent(
542 application.getPath(dictionaryInfo.uncompressedFilename),
543 indexInfo.shortName, "")));
546 button.setEnabled(false);
548 if (builder.length() != 0) {
549 builder.append("; ");
551 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
552 indexInfo.mainTokenCount));
554 details.setText(builder.toString());
557 row.setClickable(true);
558 row.setOnClickListener(new IntentLauncher(parent.getContext(),
559 DictionaryActivity.getLaunchIntent(
560 application.getPath(dictionaryInfo.uncompressedFilename),
561 dictionaryInfo.indexInfos.get(0).shortName, "")));
562 row.setFocusable(true);
563 row.setLongClickable(true);
565 row.setBackgroundResource(android.R.drawable.menuitem_background);
570 private void downloadDictionary(final DictionaryInfo dictionaryInfo) {
571 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
572 Request request = new Request(
573 Uri.parse(dictionaryInfo.downloadUrl));
575 final String destFile = new File(new URL(dictionaryInfo.downloadUrl).getFile())
577 Log.d(LOG, "Downloading to: " + destFile);
579 request.setDestinationUri(Uri.fromFile(new File(Environment
580 .getExternalStorageDirectory(), destFile)));
581 } catch (MalformedURLException e) {
582 throw new RuntimeException(e);
584 downloadManager.enqueue(request);