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.support.v7.widget.Toolbar;
37 import android.util.Log;
38 import android.util.TypedValue;
39 import android.view.ContextMenu;
40 import android.view.ContextMenu.ContextMenuInfo;
41 import android.view.LayoutInflater;
42 import android.view.Menu;
43 import android.view.View;
44 import android.view.View.OnClickListener;
45 import android.view.ViewGroup;
46 import android.view.inputmethod.EditorInfo;
47 import android.view.inputmethod.InputMethodManager;
48 import android.widget.AdapterView.AdapterContextMenuInfo;
49 import android.widget.BaseAdapter;
50 import android.widget.Button;
51 import android.widget.CompoundButton;
52 import android.widget.CompoundButton.OnCheckedChangeListener;
53 import android.widget.FrameLayout;
54 import android.widget.LinearLayout;
55 import android.widget.ListAdapter;
56 import android.widget.ListView;
57 import android.widget.TextView;
58 import android.widget.Toast;
59 import android.widget.ToggleButton;
61 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
62 import com.hughes.android.util.IntentLauncher;
65 import java.io.FileOutputStream;
66 import java.io.IOException;
67 import java.io.InputStream;
68 import java.io.OutputStream;
69 import java.net.MalformedURLException;
71 import java.util.Collections;
72 import java.util.List;
73 import java.util.zip.ZipEntry;
74 import java.util.zip.ZipFile;
77 // Delete, move to top.
79 public class DictionaryManagerActivity extends ActionBarActivity {
81 static final String LOG = "QuickDic";
82 static boolean blockAutoLaunch = false;
84 private ListView listView;
85 private ListView getListView() {
86 if (listView == null) {
87 listView = (ListView)findViewById(android.R.id.list);
91 private void setListAdapter(ListAdapter adapter) {
92 getListView().setAdapter(adapter);
94 private ListAdapter getListAdapter() {
95 return getListView().getAdapter();
98 DictionaryApplication application;
100 SearchView filterSearchView;
101 ToggleButton showDownloadable;
103 LinearLayout dictionariesOnDeviceHeaderRow;
104 LinearLayout downloadableDictionariesHeaderRow;
108 Runnable dictionaryUpdater = new Runnable() {
111 if (uiHandler == null) {
114 uiHandler.post(new Runnable() {
123 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
125 public void onReceive(Context context, Intent intent) {
126 final String action = intent.getAction();
128 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
129 final long downloadId = intent.getLongExtra(
130 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
131 final DownloadManager.Query query = new DownloadManager.Query();
132 query.setFilterById(downloadId);
133 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
134 final Cursor cursor = downloadManager.query(query);
136 if (cursor == null || !cursor.moveToFirst()) {
137 Log.e(LOG, "Couldn't find download.");
141 final String dest = cursor
142 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
143 final int status = cursor
145 .getColumnIndex(DownloadManager.COLUMN_STATUS));
146 if (DownloadManager.STATUS_SUCCESSFUL != status) {
147 final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
149 "Download failed: status=" + status +
150 ", reason=" + reason);
151 String msg = Integer.toString(reason);
153 case DownloadManager.ERROR_FILE_ALREADY_EXISTS: msg = "File exists"; break;
154 case DownloadManager.ERROR_FILE_ERROR: msg = "File error"; break;
155 case DownloadManager.ERROR_INSUFFICIENT_SPACE: msg = "Not enough space"; break;
157 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, reason)).setNeutralButton("Close", null).show();
161 Log.w(LOG, "Download finished: " + dest);
162 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
163 Toast.LENGTH_LONG).show();
166 final File localZipFile = new File(Uri.parse(dest).getPath());
167 ZipFile zipFile = null;
168 InputStream zipIn = null;
169 OutputStream zipOut = null;
171 zipFile = new ZipFile(localZipFile);
172 final ZipEntry zipEntry = zipFile.entries().nextElement();
173 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
174 zipIn = zipFile.getInputStream(zipEntry);
175 File targetFile = new File(application.getDictDir(), zipEntry.getName());
176 if (targetFile.exists()) {
177 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
178 targetFile = new File(application.getDictDir(), zipEntry.getName());
180 zipOut = new FileOutputStream(targetFile);
181 copyStream(zipIn, zipOut);
182 application.backgroundUpdateDictionaries(dictionaryUpdater);
183 Toast.makeText(context, getString(R.string.installationFinished, dest),
184 Toast.LENGTH_LONG).show();
185 } catch (Exception e) {
186 String msg = getString(R.string.unzippingFailed, dest);
187 File dir = application.getDictDir();
188 if (!dir.canWrite() || !application.checkFileCreate(dir)) {
189 msg = getString(R.string.notWritable, dir.getAbsolutePath());
191 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
192 Log.e(LOG, "Failed to unzip.", e);
194 try { if (zipOut != null) zipOut.close(); } catch (IOException e) {}
195 try { if (zipIn != null) zipIn.close(); } catch (IOException e) {}
196 try { if (zipFile != null) zipFile.close(); } catch (IOException e) {}
197 localZipFile.delete();
203 public static Intent getLaunchIntent(Context c) {
204 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
205 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
210 public void onCreate(Bundle savedInstanceState) {
211 // This must be first, otherwise the actiona bar doesn't get
213 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
215 super.onCreate(savedInstanceState);
216 Log.d(LOG, "onCreate:" + this);
218 application = (DictionaryApplication) getApplication();
220 blockAutoLaunch = false;
223 setContentView(R.layout.dictionary_manager_activity);
225 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
226 getListView().getContext()).inflate(
227 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
229 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
230 getListView().getContext()).inflate(
231 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
233 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
234 .findViewById(R.id.hideDownloadable);
235 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
237 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
238 onShowDownloadableChanged();
242 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
243 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
244 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
245 thanksForUpdatingLatestVersion)) {
246 blockAutoLaunch = true;
247 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
248 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
252 registerReceiver(broadcastReceiver, new IntentFilter(
253 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
256 registerForContextMenu(getListView());
258 final File dictDir = application.getDictDir();
259 if (!dictDir.canRead() || !dictDir.canExecute()) {
260 blockAutoLaunch = true;
262 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
263 builder.setTitle(getString(R.string.error));
264 builder.setMessage(getString(
265 R.string.unableToReadDictionaryDir,
266 dictDir.getAbsolutePath(),
267 Environment.getExternalStorageDirectory()));
268 builder.setNeutralButton("Close", null);
269 builder.create().show();
272 onCreateSetupActionBar();
275 private void onCreateSetupActionBar() {
276 ActionBar actionBar = getSupportActionBar();
277 actionBar.setDisplayShowTitleEnabled(false);
278 actionBar.setDisplayShowHomeEnabled(false);
279 actionBar.setDisplayHomeAsUpEnabled(false);
281 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
282 filterSearchView.setIconifiedByDefault(false);
283 // filterSearchView.setIconified(false); // puts the magnifying glass in
286 filterSearchView.setQueryHint(getString(R.string.searchText));
287 filterSearchView.setSubmitButtonEnabled(false);
288 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
289 FrameLayout.LayoutParams.WRAP_CONTENT);
290 filterSearchView.setLayoutParams(lp);
291 filterSearchView.setImeOptions(
292 EditorInfo.IME_ACTION_DONE |
293 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
294 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
296 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
298 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
300 public boolean onQueryTextSubmit(String query) {
301 filterSearchView.clearFocus();
306 public boolean onQueryTextChange(String filterText) {
311 filterSearchView.setFocusable(true);
313 actionBar.setCustomView(filterSearchView);
314 actionBar.setDisplayShowCustomEnabled(true);
316 // Avoid wasting space on large left inset
317 Toolbar tb = (Toolbar)filterSearchView.getParent();
318 tb.setContentInsetsRelative(0, 0);
322 public void onDestroy() {
324 unregisterReceiver(broadcastReceiver);
327 private static int copyStream(final InputStream in, final OutputStream out)
330 final byte[] bytes = new byte[1024 * 16];
331 while ((bytesRead = in.read(bytes)) != -1) {
332 out.write(bytes, 0, bytesRead);
340 protected void onStart() {
342 uiHandler = new Handler();
346 protected void onStop() {
352 protected void onResume() {
355 if (PreferenceActivity.prefsMightHaveChanged) {
356 PreferenceActivity.prefsMightHaveChanged = false;
358 startActivity(getIntent());
361 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
362 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
364 if (!blockAutoLaunch &&
365 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
366 prefs.contains(C.DICT_FILE) &&
367 prefs.contains(C.INDEX_SHORT_NAME)) {
368 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
369 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
370 new File(prefs.getString(C.DICT_FILE, "")),
371 prefs.getString(C.INDEX_SHORT_NAME, ""),
372 prefs.getString(C.SEARCH_TOKEN, "")));
377 // Remove the active dictionary from the prefs so we won't autolaunch
379 final Editor editor = prefs.edit();
380 editor.remove(C.DICT_FILE);
381 editor.remove(C.INDEX_SHORT_NAME);
382 editor.remove(C.SEARCH_TOKEN);
385 application.backgroundUpdateDictionaries(dictionaryUpdater);
391 public boolean onCreateOptionsMenu(final Menu menu) {
392 application.onCreateGlobalOptionsMenu(this, menu);
397 public void onCreateContextMenu(final ContextMenu menu, final View view,
398 final ContextMenuInfo menuInfo) {
399 super.onCreateContextMenu(menu, view, menuInfo);
400 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
402 final AdapterContextMenuInfo adapterContextMenuInfo =
403 (AdapterContextMenuInfo) menuInfo;
404 final int position = adapterContextMenuInfo.position;
405 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
407 if (row.dictionaryInfo == null) {
411 if (position > 0 && row.onDevice) {
412 final android.view.MenuItem moveToTopMenuItem =
413 menu.add(R.string.moveToTop);
414 moveToTopMenuItem.setOnMenuItemClickListener(new
415 android.view.MenuItem.OnMenuItemClickListener() {
417 public boolean onMenuItemClick(android.view.MenuItem item) {
418 application.moveDictionaryToTop(row.dictionaryInfo);
426 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
428 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
430 public boolean onMenuItemClick(android.view.MenuItem item) {
431 application.deleteDictionary(row.dictionaryInfo);
439 private void onShowDownloadableChanged() {
441 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
442 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
446 class MyListAdapter extends BaseAdapter {
448 List<DictionaryInfo> dictionariesOnDevice;
449 List<DictionaryInfo> downloadableDictionaries;
452 DictionaryInfo dictionaryInfo;
455 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
456 this.dictionaryInfo = dictinoaryInfo;
457 this.onDevice = onDevice;
461 private MyListAdapter(final String[] filters) {
462 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
463 if (showDownloadable.isChecked()) {
464 downloadableDictionaries = application.getDownloadableDictionaries(filters);
466 downloadableDictionaries = Collections.emptyList();
471 public int getCount() {
472 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
476 public Row getItem(int position) {
478 return new Row(null, true);
482 if (position < dictionariesOnDevice.size()) {
483 return new Row(dictionariesOnDevice.get(position), true);
485 position -= dictionariesOnDevice.size();
488 return new Row(null, false);
492 assert position < downloadableDictionaries.size();
493 return new Row(downloadableDictionaries.get(position), false);
497 public long getItemId(int position) {
502 public View getView(int position, View convertView, ViewGroup parent) {
503 if (convertView instanceof LinearLayout &&
504 convertView != dictionariesOnDeviceHeaderRow &&
505 convertView != downloadableDictionariesHeaderRow) {
507 * This is done to try to avoid leaking memory that used to
508 * happen on Android 4.0.3
510 ((LinearLayout) convertView).removeAllViews();
513 final Row row = getItem(position);
516 if (row.dictionaryInfo == null) {
517 return dictionariesOnDeviceHeaderRow;
519 return createDictionaryRow(row.dictionaryInfo, parent, true);
522 if (row.dictionaryInfo == null) {
523 return downloadableDictionariesHeaderRow;
525 return createDictionaryRow(row.dictionaryInfo, parent, false);
530 private void setMyListAdapater() {
531 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
533 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
534 setListAdapter(new MyListAdapter(filters));
537 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
538 final ViewGroup parent, boolean canLaunch) {
540 View row = LayoutInflater.from(parent.getContext()).inflate(
541 R.layout.dictionary_manager_row, parent, false);
542 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
543 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
544 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
546 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
547 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
548 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
549 boolean broken = false;
550 if (!dictionaryInfo.isValid()) {
554 if (downloadable != null && (!canLaunch || updateAvailable)) {
557 R.string.downloadButton,
558 downloadable.zipBytes / 1024.0 / 1024.0));
559 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
560 downloadButton.setOnClickListener(new OnClickListener() {
562 public void onClick(View arg0) {
563 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
567 downloadButton.setVisibility(View.INVISIBLE);
570 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
571 final List<IndexInfo> sortedIndexInfos = application
572 .sortedIndexInfos(dictionaryInfo.indexInfos);
573 final StringBuilder builder = new StringBuilder();
574 if (updateAvailable) {
575 builder.append(getString(R.string.updateAvailable));
577 for (IndexInfo indexInfo : sortedIndexInfos) {
578 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
580 buttons.addView(button);
583 button.setOnClickListener(
584 new IntentLauncher(buttons.getContext(),
585 DictionaryActivity.getLaunchIntent(getApplicationContext(),
586 application.getPath(dictionaryInfo.uncompressedFilename),
587 indexInfo.shortName, "")));
590 button.setEnabled(false);
592 if (builder.length() != 0) {
593 builder.append("; ");
595 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
596 indexInfo.mainTokenCount));
598 builder.append("; ");
599 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
601 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
602 builder.append("; Cannot be used, redownload, check hardware/file system");
603 // Allow deleting, but cannot open
604 row.setLongClickable(true);
606 details.setText(builder.toString());
609 row.setClickable(true);
610 row.setOnClickListener(new IntentLauncher(parent.getContext(),
611 DictionaryActivity.getLaunchIntent(getApplicationContext(),
612 application.getPath(dictionaryInfo.uncompressedFilename),
613 dictionaryInfo.indexInfos.get(0).shortName, "")));
614 row.setFocusable(true);
615 row.setLongClickable(true);
617 row.setBackgroundResource(android.R.drawable.menuitem_background);
622 private void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
623 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
624 final DownloadManager.Query query = new DownloadManager.Query();
625 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
626 final Cursor cursor = downloadManager.query(query);
628 // Due to a bug, cursor is null instead of empty when
629 // the download manager is disabled.
630 if (cursor == null) {
631 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
632 .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
633 .setNeutralButton("Close", null).show();
637 while (cursor.moveToNext()) {
638 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
641 if (!cursor.isAfterLast()) {
642 downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
645 R.string.downloadButton,
646 bytes / 1024.0 / 1024.0));
651 Request request = new Request(
652 Uri.parse(downloadUrl));
654 final String destFile = new File(new URL(downloadUrl).getFile())
656 Log.d(LOG, "Downloading to: " + destFile);
659 request.setDestinationInExternalFilesDir(getApplicationContext(), null, destFile);
660 } catch (IllegalStateException e) {
661 request.setDestinationUri(Uri.fromFile(new File(Environment
662 .getExternalStorageDirectory(), destFile)));
664 } catch (MalformedURLException e) {
665 throw new RuntimeException(e);
667 downloadManager.enqueue(request);
668 downloadButton.setText("X");