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.support.v7.app.ActionBar;
33 import android.support.v7.app.ActionBarActivity;
34 import android.support.v7.widget.SearchView;
35 import android.support.v7.widget.SearchView.OnQueryTextListener;
36 import android.util.Log;
37 import android.util.TypedValue;
38 import android.view.ContextMenu;
39 import android.view.ContextMenu.ContextMenuInfo;
40 import android.view.LayoutInflater;
41 import android.view.Menu;
42 import android.view.View;
43 import android.view.View.OnClickListener;
44 import android.view.ViewGroup;
45 import android.view.inputmethod.EditorInfo;
46 import android.widget.AdapterView.AdapterContextMenuInfo;
47 import android.widget.BaseAdapter;
48 import android.widget.Button;
49 import android.widget.CompoundButton;
50 import android.widget.CompoundButton.OnCheckedChangeListener;
51 import android.widget.FrameLayout;
52 import android.widget.LinearLayout;
53 import android.widget.ListAdapter;
54 import android.widget.ListView;
55 import android.widget.TextView;
56 import android.widget.Toast;
57 import android.widget.ToggleButton;
59 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
60 import com.hughes.android.util.IntentLauncher;
63 import java.io.FileOutputStream;
64 import java.io.IOException;
65 import java.io.InputStream;
66 import java.io.OutputStream;
67 import java.net.MalformedURLException;
69 import java.util.Collections;
70 import java.util.List;
71 import java.util.zip.ZipEntry;
72 import java.util.zip.ZipFile;
75 // Delete, move to top.
77 public class DictionaryManagerActivity extends ActionBarActivity {
79 static final String LOG = "QuickDic";
80 static boolean blockAutoLaunch = false;
82 private ListView listView;
83 private ListView getListView() {
84 if (listView == null) {
85 listView = (ListView)findViewById(android.R.id.list);
89 private void setListAdapter(ListAdapter adapter) {
90 getListView().setAdapter(adapter);
92 private ListAdapter getListAdapter() {
93 return getListView().getAdapter();
96 DictionaryApplication application;
98 SearchView filterSearchView;
99 ToggleButton showDownloadable;
101 LinearLayout dictionariesOnDeviceHeaderRow;
102 LinearLayout downloadableDictionariesHeaderRow;
106 Runnable dictionaryUpdater = new Runnable() {
109 if (uiHandler == null) {
112 uiHandler.post(new Runnable() {
121 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
123 public void onReceive(Context context, Intent intent) {
124 final String action = intent.getAction();
126 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
127 final long downloadId = intent.getLongExtra(
128 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
129 final DownloadManager.Query query = new DownloadManager.Query();
130 query.setFilterById(downloadId);
131 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
132 final Cursor cursor = downloadManager.query(query);
134 if (!cursor.moveToFirst()) {
135 Log.e(LOG, "Couldn't find download.");
139 final String dest = cursor
140 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
141 final int status = cursor
143 .getColumnIndex(DownloadManager.COLUMN_STATUS));
144 if (DownloadManager.STATUS_SUCCESSFUL != status) {
146 "Download failed: status=" + status +
147 ", reason=" + cursor.getString(cursor
148 .getColumnIndex(DownloadManager.COLUMN_REASON)));
149 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, dest)).setNeutralButton("Close", null).show();
153 Log.w(LOG, "Download finished: " + dest);
154 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
155 Toast.LENGTH_LONG).show();
158 final File localZipFile = new File(Uri.parse(dest).getPath());
160 ZipFile zipFile = new ZipFile(localZipFile);
161 final ZipEntry zipEntry = zipFile.entries().nextElement();
162 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
163 final InputStream zipIn = zipFile.getInputStream(zipEntry);
164 File targetFile = new File(application.getDictDir(), zipEntry.getName());
165 if (targetFile.exists()) {
166 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
167 targetFile = new File(application.getDictDir(), zipEntry.getName());
169 final OutputStream zipOut = new FileOutputStream(targetFile);
170 copyStream(zipIn, zipOut);
172 application.backgroundUpdateDictionaries(dictionaryUpdater);
173 Toast.makeText(context, getString(R.string.installationFinished, dest),
174 Toast.LENGTH_LONG).show();
175 } catch (Exception e) {
176 String msg = getString(R.string.unzippingFailed, dest);
177 File dir = application.getDictDir();
178 if (!dir.canWrite() || !application.checkFileCreate(dir)) {
179 msg = getString(R.string.notWritable, dir.getAbsolutePath());
181 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
182 Log.e(LOG, "Failed to unzip.", e);
184 localZipFile.delete();
190 public static Intent getLaunchIntent(Context c) {
191 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
192 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
197 public void onCreate(Bundle savedInstanceState) {
198 // This must be first, otherwise the actiona bar doesn't get
200 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
202 super.onCreate(savedInstanceState);
203 Log.d(LOG, "onCreate:" + this);
205 application = (DictionaryApplication) getApplication();
207 blockAutoLaunch = false;
210 setContentView(R.layout.dictionary_manager_activity);
212 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
213 getListView().getContext()).inflate(
214 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
216 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
217 getListView().getContext()).inflate(
218 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
220 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
221 .findViewById(R.id.hideDownloadable);
222 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
224 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
225 onShowDownloadableChanged();
229 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
230 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
231 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
232 thanksForUpdatingLatestVersion)) {
233 blockAutoLaunch = true;
234 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
235 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
239 registerReceiver(broadcastReceiver, new IntentFilter(
240 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
243 registerForContextMenu(getListView());
245 final File dictDir = application.getDictDir();
246 if (!dictDir.canRead() || !dictDir.canExecute()) {
247 blockAutoLaunch = true;
249 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
250 builder.setTitle(getString(R.string.error));
251 builder.setMessage(getString(
252 R.string.unableToReadDictionaryDir,
253 dictDir.getAbsolutePath(),
254 Environment.getExternalStorageDirectory()));
255 builder.setNeutralButton("Close", null);
256 builder.create().show();
259 onCreateSetupActionBar();
262 private void onCreateSetupActionBar() {
263 ActionBar actionBar = getSupportActionBar();
264 actionBar.setDisplayShowTitleEnabled(false);
266 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
267 filterSearchView.setIconifiedByDefault(false);
268 // filterSearchView.setIconified(false); // puts the magnifying glass in
271 filterSearchView.setQueryHint(getString(R.string.searchText));
272 filterSearchView.setSubmitButtonEnabled(false);
273 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
274 getResources().getDisplayMetrics());
275 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
276 FrameLayout.LayoutParams.WRAP_CONTENT);
277 filterSearchView.setLayoutParams(lp);
278 filterSearchView.setImeOptions(
279 EditorInfo.IME_ACTION_SEARCH |
280 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
281 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
282 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
284 EditorInfo.IME_MASK_ACTION |
285 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
287 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
289 public boolean onQueryTextSubmit(String query) {
294 public boolean onQueryTextChange(String filterText) {
299 filterSearchView.setFocusable(true);
301 actionBar.setCustomView(filterSearchView);
302 actionBar.setDisplayShowCustomEnabled(true);
306 public void onDestroy() {
308 unregisterReceiver(broadcastReceiver);
311 private static int copyStream(final InputStream in, final OutputStream out)
314 final byte[] bytes = new byte[1024 * 16];
315 while ((bytesRead = in.read(bytes)) != -1) {
316 out.write(bytes, 0, bytesRead);
324 protected void onStart() {
326 uiHandler = new Handler();
330 protected void onStop() {
336 protected void onResume() {
339 if (PreferenceActivity.prefsMightHaveChanged) {
340 PreferenceActivity.prefsMightHaveChanged = false;
342 startActivity(getIntent());
345 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
346 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
348 if (!blockAutoLaunch &&
349 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
350 prefs.contains(C.DICT_FILE) &&
351 prefs.contains(C.INDEX_SHORT_NAME)) {
352 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
353 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
354 new File(prefs.getString(C.DICT_FILE, "")),
355 prefs.getString(C.INDEX_SHORT_NAME, ""),
356 prefs.getString(C.SEARCH_TOKEN, "")));
361 // Remove the active dictionary from the prefs so we won't autolaunch
363 final Editor editor = prefs.edit();
364 editor.remove(C.DICT_FILE);
365 editor.remove(C.INDEX_SHORT_NAME);
366 editor.remove(C.SEARCH_TOKEN);
369 application.backgroundUpdateDictionaries(dictionaryUpdater);
375 public boolean onCreateOptionsMenu(final Menu menu) {
376 application.onCreateGlobalOptionsMenu(this, menu);
381 public void onCreateContextMenu(final ContextMenu menu, final View view,
382 final ContextMenuInfo menuInfo) {
383 super.onCreateContextMenu(menu, view, menuInfo);
384 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
386 final AdapterContextMenuInfo adapterContextMenuInfo =
387 (AdapterContextMenuInfo) menuInfo;
388 final int position = adapterContextMenuInfo.position;
389 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
391 if (row.dictionaryInfo == null) {
395 if (position > 0 && row.onDevice) {
396 final android.view.MenuItem moveToTopMenuItem =
397 menu.add(R.string.moveToTop);
398 moveToTopMenuItem.setOnMenuItemClickListener(new
399 android.view.MenuItem.OnMenuItemClickListener() {
401 public boolean onMenuItemClick(android.view.MenuItem item) {
402 application.moveDictionaryToTop(row.dictionaryInfo);
410 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
412 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
414 public boolean onMenuItemClick(android.view.MenuItem item) {
415 application.deleteDictionary(row.dictionaryInfo);
423 private void onShowDownloadableChanged() {
425 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
426 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
430 class MyListAdapter extends BaseAdapter {
432 List<DictionaryInfo> dictionariesOnDevice;
433 List<DictionaryInfo> downloadableDictionaries;
436 DictionaryInfo dictionaryInfo;
439 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
440 this.dictionaryInfo = dictinoaryInfo;
441 this.onDevice = onDevice;
445 private MyListAdapter(final String[] filters) {
446 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
447 if (showDownloadable.isChecked()) {
448 downloadableDictionaries = application.getDownloadableDictionaries(filters);
450 downloadableDictionaries = Collections.emptyList();
455 public int getCount() {
456 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
460 public Row getItem(int position) {
462 return new Row(null, true);
466 if (position < dictionariesOnDevice.size()) {
467 return new Row(dictionariesOnDevice.get(position), true);
469 position -= dictionariesOnDevice.size();
472 return new Row(null, false);
476 assert position < downloadableDictionaries.size();
477 return new Row(downloadableDictionaries.get(position), false);
481 public long getItemId(int position) {
486 public View getView(int position, View convertView, ViewGroup parent) {
487 if (convertView instanceof LinearLayout &&
488 convertView != dictionariesOnDeviceHeaderRow &&
489 convertView != downloadableDictionariesHeaderRow) {
491 * This is done to try to avoid leaking memory that used to
492 * happen on Android 4.0.3
494 ((LinearLayout) convertView).removeAllViews();
497 final Row row = getItem(position);
500 if (row.dictionaryInfo == null) {
501 return dictionariesOnDeviceHeaderRow;
503 return createDictionaryRow(row.dictionaryInfo, parent, true);
506 if (row.dictionaryInfo == null) {
507 return downloadableDictionariesHeaderRow;
509 return createDictionaryRow(row.dictionaryInfo, parent, false);
514 private void setMyListAdapater() {
515 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
517 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
518 setListAdapter(new MyListAdapter(filters));
521 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
522 final ViewGroup parent, final boolean canLaunch) {
524 View row = LayoutInflater.from(parent.getContext()).inflate(
525 R.layout.dictionary_manager_row, parent, false);
526 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
527 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
528 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
530 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
531 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
532 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
533 if (!canLaunch || updateAvailable) {
536 R.string.downloadButton,
537 downloadable.zipBytes / 1024.0 / 1024.0));
538 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
539 downloadButton.setOnClickListener(new OnClickListener() {
541 public void onClick(View arg0) {
542 downloadDictionary(downloadable.downloadUrl);
546 downloadButton.setVisibility(View.INVISIBLE);
549 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
550 final List<IndexInfo> sortedIndexInfos = application
551 .sortedIndexInfos(dictionaryInfo.indexInfos);
552 final StringBuilder builder = new StringBuilder();
553 if (updateAvailable) {
554 builder.append(getString(R.string.updateAvailable));
556 for (IndexInfo indexInfo : sortedIndexInfos) {
557 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
559 buttons.addView(button);
562 button.setOnClickListener(
563 new IntentLauncher(buttons.getContext(),
564 DictionaryActivity.getLaunchIntent(getApplicationContext(),
565 application.getPath(dictionaryInfo.uncompressedFilename),
566 indexInfo.shortName, "")));
569 button.setEnabled(false);
571 if (builder.length() != 0) {
572 builder.append("; ");
574 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
575 indexInfo.mainTokenCount));
577 builder.append("; ");
578 builder.append(getString(R.string.downloadButton, downloadable.uncompressedBytes / 1024.0 / 1024.0));
579 details.setText(builder.toString());
582 row.setClickable(true);
583 row.setOnClickListener(new IntentLauncher(parent.getContext(),
584 DictionaryActivity.getLaunchIntent(getApplicationContext(),
585 application.getPath(dictionaryInfo.uncompressedFilename),
586 dictionaryInfo.indexInfos.get(0).shortName, "")));
587 row.setFocusable(true);
588 row.setLongClickable(true);
590 row.setBackgroundResource(android.R.drawable.menuitem_background);
595 private void downloadDictionary(final String downloadUrl) {
596 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
597 Request request = new Request(
598 Uri.parse(downloadUrl));
600 final String destFile = new File(new URL(downloadUrl).getFile())
602 Log.d(LOG, "Downloading to: " + destFile);
604 request.setDestinationUri(Uri.fromFile(new File(Environment
605 .getExternalStorageDirectory(), destFile)));
606 } catch (MalformedURLException e) {
607 throw new RuntimeException(e);
609 downloadManager.enqueue(request);