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.text.InputType;
38 import android.util.Log;
39 import android.util.TypedValue;
40 import android.view.ContextMenu;
41 import android.view.ContextMenu.ContextMenuInfo;
42 import android.view.LayoutInflater;
43 import android.view.Menu;
44 import android.view.View;
45 import android.view.View.OnClickListener;
46 import android.view.ViewGroup;
47 import android.view.inputmethod.EditorInfo;
48 import android.view.inputmethod.InputMethodManager;
49 import android.widget.AdapterView.AdapterContextMenuInfo;
50 import android.widget.BaseAdapter;
51 import android.widget.Button;
52 import android.widget.CompoundButton;
53 import android.widget.CompoundButton.OnCheckedChangeListener;
54 import android.widget.FrameLayout;
55 import android.widget.LinearLayout;
56 import android.widget.ListAdapter;
57 import android.widget.ListView;
58 import android.widget.TextView;
59 import android.widget.Toast;
60 import android.widget.ToggleButton;
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 ActionBarActivity {
82 static final String LOG = "QuickDic";
83 static boolean blockAutoLaunch = false;
85 private ListView listView;
86 private ListView getListView() {
87 if (listView == null) {
88 listView = (ListView)findViewById(android.R.id.list);
92 private void setListAdapter(ListAdapter adapter) {
93 getListView().setAdapter(adapter);
95 private ListAdapter getListAdapter() {
96 return getListView().getAdapter();
99 DictionaryApplication application;
101 SearchView filterSearchView;
102 ToggleButton showDownloadable;
104 LinearLayout dictionariesOnDeviceHeaderRow;
105 LinearLayout downloadableDictionariesHeaderRow;
109 Runnable dictionaryUpdater = new Runnable() {
112 if (uiHandler == null) {
115 uiHandler.post(new Runnable() {
124 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
126 public void onReceive(Context context, Intent intent) {
127 final String action = intent.getAction();
129 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
130 final long downloadId = intent.getLongExtra(
131 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
132 final DownloadManager.Query query = new DownloadManager.Query();
133 query.setFilterById(downloadId);
134 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
135 final Cursor cursor = downloadManager.query(query);
137 if (cursor == null || !cursor.moveToFirst()) {
138 Log.e(LOG, "Couldn't find download.");
142 final String dest = cursor
143 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
144 final int status = cursor
146 .getColumnIndex(DownloadManager.COLUMN_STATUS));
147 if (DownloadManager.STATUS_SUCCESSFUL != status) {
148 final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
150 "Download failed: status=" + status +
151 ", reason=" + reason);
152 String msg = Integer.toString(reason);
154 case DownloadManager.ERROR_FILE_ALREADY_EXISTS: msg = "File exists"; break;
155 case DownloadManager.ERROR_FILE_ERROR: msg = "File error"; break;
156 case DownloadManager.ERROR_INSUFFICIENT_SPACE: msg = "Not enough space"; break;
158 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, reason)).setNeutralButton("Close", null).show();
162 Log.w(LOG, "Download finished: " + dest);
163 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
164 Toast.LENGTH_LONG).show();
167 final File localZipFile = new File(Uri.parse(dest).getPath());
168 ZipFile zipFile = null;
169 InputStream zipIn = null;
170 OutputStream zipOut = null;
172 zipFile = new ZipFile(localZipFile);
173 final ZipEntry zipEntry = zipFile.entries().nextElement();
174 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
175 zipIn = zipFile.getInputStream(zipEntry);
176 File targetFile = new File(application.getDictDir(), zipEntry.getName());
177 if (targetFile.exists()) {
178 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
179 targetFile = new File(application.getDictDir(), zipEntry.getName());
181 zipOut = new FileOutputStream(targetFile);
182 copyStream(zipIn, zipOut);
183 application.backgroundUpdateDictionaries(dictionaryUpdater);
184 Toast.makeText(context, getString(R.string.installationFinished, dest),
185 Toast.LENGTH_LONG).show();
186 } catch (Exception e) {
187 String msg = getString(R.string.unzippingFailed, dest);
188 File dir = application.getDictDir();
189 if (!dir.canWrite() || !application.checkFileCreate(dir)) {
190 msg = getString(R.string.notWritable, dir.getAbsolutePath());
192 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
193 Log.e(LOG, "Failed to unzip.", e);
195 try { if (zipOut != null) zipOut.close(); } catch (IOException e) {}
196 try { if (zipIn != null) zipIn.close(); } catch (IOException e) {}
197 try { if (zipFile != null) zipFile.close(); } catch (IOException e) {}
198 localZipFile.delete();
204 public static Intent getLaunchIntent(Context c) {
205 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
206 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
211 public void onCreate(Bundle savedInstanceState) {
212 // This must be first, otherwise the actiona bar doesn't get
214 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
216 super.onCreate(savedInstanceState);
217 Log.d(LOG, "onCreate:" + this);
219 application = (DictionaryApplication) getApplication();
221 blockAutoLaunch = false;
224 setContentView(R.layout.dictionary_manager_activity);
226 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
227 getListView().getContext()).inflate(
228 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
230 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
231 getListView().getContext()).inflate(
232 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
234 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
235 .findViewById(R.id.hideDownloadable);
236 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
238 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
239 onShowDownloadableChanged();
243 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
244 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
245 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
246 thanksForUpdatingLatestVersion)) {
247 blockAutoLaunch = true;
248 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
249 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
253 registerReceiver(broadcastReceiver, new IntentFilter(
254 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
257 registerForContextMenu(getListView());
259 final File dictDir = application.getDictDir();
260 if (!dictDir.canRead() || !dictDir.canExecute()) {
261 blockAutoLaunch = true;
263 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
264 builder.setTitle(getString(R.string.error));
265 builder.setMessage(getString(
266 R.string.unableToReadDictionaryDir,
267 dictDir.getAbsolutePath(),
268 Environment.getExternalStorageDirectory()));
269 builder.setNeutralButton("Close", null);
270 builder.create().show();
273 onCreateSetupActionBar();
276 private void onCreateSetupActionBar() {
277 ActionBar actionBar = getSupportActionBar();
278 actionBar.setDisplayShowTitleEnabled(false);
279 actionBar.setDisplayShowHomeEnabled(false);
280 actionBar.setDisplayHomeAsUpEnabled(false);
282 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
283 filterSearchView.setIconifiedByDefault(false);
284 // filterSearchView.setIconified(false); // puts the magnifying glass in
287 filterSearchView.setQueryHint(getString(R.string.searchText));
288 filterSearchView.setSubmitButtonEnabled(false);
289 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
290 FrameLayout.LayoutParams.WRAP_CONTENT);
291 filterSearchView.setLayoutParams(lp);
292 filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT);
293 filterSearchView.setImeOptions(
294 EditorInfo.IME_ACTION_DONE |
295 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
296 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
298 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
300 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
302 public boolean onQueryTextSubmit(String query) {
303 filterSearchView.clearFocus();
308 public boolean onQueryTextChange(String filterText) {
313 filterSearchView.setFocusable(true);
315 actionBar.setCustomView(filterSearchView);
316 actionBar.setDisplayShowCustomEnabled(true);
318 // Avoid wasting space on large left inset
319 Toolbar tb = (Toolbar)filterSearchView.getParent();
320 tb.setContentInsetsRelative(0, 0);
324 public void onDestroy() {
326 unregisterReceiver(broadcastReceiver);
329 private static int copyStream(final InputStream in, final OutputStream out)
332 final byte[] bytes = new byte[1024 * 16];
333 while ((bytesRead = in.read(bytes)) != -1) {
334 out.write(bytes, 0, bytesRead);
342 protected void onStart() {
344 uiHandler = new Handler();
348 protected void onStop() {
354 protected void onResume() {
357 if (PreferenceActivity.prefsMightHaveChanged) {
358 PreferenceActivity.prefsMightHaveChanged = false;
360 startActivity(getIntent());
363 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
364 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
366 if (!blockAutoLaunch &&
367 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
368 prefs.contains(C.DICT_FILE) &&
369 prefs.contains(C.INDEX_SHORT_NAME)) {
370 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
371 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
372 new File(prefs.getString(C.DICT_FILE, "")),
373 prefs.getString(C.INDEX_SHORT_NAME, ""),
374 prefs.getString(C.SEARCH_TOKEN, "")));
379 // Remove the active dictionary from the prefs so we won't autolaunch
381 final Editor editor = prefs.edit();
382 editor.remove(C.DICT_FILE);
383 editor.remove(C.INDEX_SHORT_NAME);
384 editor.remove(C.SEARCH_TOKEN);
387 application.backgroundUpdateDictionaries(dictionaryUpdater);
393 public boolean onCreateOptionsMenu(final Menu menu) {
394 application.onCreateGlobalOptionsMenu(this, menu);
399 public void onCreateContextMenu(final ContextMenu menu, final View view,
400 final ContextMenuInfo menuInfo) {
401 super.onCreateContextMenu(menu, view, menuInfo);
402 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
404 final AdapterContextMenuInfo adapterContextMenuInfo =
405 (AdapterContextMenuInfo) menuInfo;
406 final int position = adapterContextMenuInfo.position;
407 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
409 if (row.dictionaryInfo == null) {
413 if (position > 0 && row.onDevice) {
414 final android.view.MenuItem moveToTopMenuItem =
415 menu.add(R.string.moveToTop);
416 moveToTopMenuItem.setOnMenuItemClickListener(new
417 android.view.MenuItem.OnMenuItemClickListener() {
419 public boolean onMenuItemClick(android.view.MenuItem item) {
420 application.moveDictionaryToTop(row.dictionaryInfo);
428 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
430 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
432 public boolean onMenuItemClick(android.view.MenuItem item) {
433 application.deleteDictionary(row.dictionaryInfo);
441 private void onShowDownloadableChanged() {
443 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
444 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
448 class MyListAdapter extends BaseAdapter {
450 List<DictionaryInfo> dictionariesOnDevice;
451 List<DictionaryInfo> downloadableDictionaries;
454 DictionaryInfo dictionaryInfo;
457 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
458 this.dictionaryInfo = dictinoaryInfo;
459 this.onDevice = onDevice;
463 private MyListAdapter(final String[] filters) {
464 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
465 if (showDownloadable.isChecked()) {
466 downloadableDictionaries = application.getDownloadableDictionaries(filters);
468 downloadableDictionaries = Collections.emptyList();
473 public int getCount() {
474 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
478 public Row getItem(int position) {
480 return new Row(null, true);
484 if (position < dictionariesOnDevice.size()) {
485 return new Row(dictionariesOnDevice.get(position), true);
487 position -= dictionariesOnDevice.size();
490 return new Row(null, false);
494 assert position < downloadableDictionaries.size();
495 return new Row(downloadableDictionaries.get(position), false);
499 public long getItemId(int position) {
504 public View getView(int position, View convertView, ViewGroup parent) {
505 if (convertView instanceof LinearLayout &&
506 convertView != dictionariesOnDeviceHeaderRow &&
507 convertView != downloadableDictionariesHeaderRow) {
509 * This is done to try to avoid leaking memory that used to
510 * happen on Android 4.0.3
512 ((LinearLayout) convertView).removeAllViews();
515 final Row row = getItem(position);
518 if (row.dictionaryInfo == null) {
519 return dictionariesOnDeviceHeaderRow;
521 return createDictionaryRow(row.dictionaryInfo, parent, true);
524 if (row.dictionaryInfo == null) {
525 return downloadableDictionariesHeaderRow;
527 return createDictionaryRow(row.dictionaryInfo, parent, false);
532 private void setMyListAdapater() {
533 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
535 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
536 setListAdapter(new MyListAdapter(filters));
539 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
540 final ViewGroup parent, boolean canLaunch) {
542 View row = LayoutInflater.from(parent.getContext()).inflate(
543 R.layout.dictionary_manager_row, parent, false);
544 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
545 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
546 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
548 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
549 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
550 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
551 boolean broken = false;
552 if (!dictionaryInfo.isValid()) {
556 if (downloadable != null && (!canLaunch || updateAvailable)) {
559 R.string.downloadButton,
560 downloadable.zipBytes / 1024.0 / 1024.0));
561 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
562 downloadButton.setOnClickListener(new OnClickListener() {
564 public void onClick(View arg0) {
565 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
569 downloadButton.setVisibility(View.INVISIBLE);
572 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
573 final List<IndexInfo> sortedIndexInfos = application
574 .sortedIndexInfos(dictionaryInfo.indexInfos);
575 final StringBuilder builder = new StringBuilder();
576 if (updateAvailable) {
577 builder.append(getString(R.string.updateAvailable));
579 for (IndexInfo indexInfo : sortedIndexInfos) {
580 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
582 buttons.addView(button);
585 button.setOnClickListener(
586 new IntentLauncher(buttons.getContext(),
587 DictionaryActivity.getLaunchIntent(getApplicationContext(),
588 application.getPath(dictionaryInfo.uncompressedFilename),
589 indexInfo.shortName, "")));
592 button.setEnabled(false);
594 if (builder.length() != 0) {
595 builder.append("; ");
597 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
598 indexInfo.mainTokenCount));
600 builder.append("; ");
601 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
603 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
604 builder.append("; Cannot be used, redownload, check hardware/file system");
605 // Allow deleting, but cannot open
606 row.setLongClickable(true);
608 details.setText(builder.toString());
611 row.setClickable(true);
612 row.setOnClickListener(new IntentLauncher(parent.getContext(),
613 DictionaryActivity.getLaunchIntent(getApplicationContext(),
614 application.getPath(dictionaryInfo.uncompressedFilename),
615 dictionaryInfo.indexInfos.get(0).shortName, "")));
616 row.setFocusable(true);
617 row.setLongClickable(true);
619 row.setBackgroundResource(android.R.drawable.menuitem_background);
624 private void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
625 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
626 final DownloadManager.Query query = new DownloadManager.Query();
627 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
628 final Cursor cursor = downloadManager.query(query);
630 // Due to a bug, cursor is null instead of empty when
631 // the download manager is disabled.
632 if (cursor == null) {
633 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
634 .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
635 .setNeutralButton("Close", null).show();
639 while (cursor.moveToNext()) {
640 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
643 if (!cursor.isAfterLast()) {
644 downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
647 R.string.downloadButton,
648 bytes / 1024.0 / 1024.0));
653 Request request = new Request(
654 Uri.parse(downloadUrl));
656 final String destFile = new File(new URL(downloadUrl).getFile())
658 Log.d(LOG, "Downloading to: " + destFile);
661 request.setDestinationInExternalFilesDir(getApplicationContext(), null, destFile);
662 } catch (IllegalStateException e) {
663 request.setDestinationUri(Uri.fromFile(new File(Environment
664 .getExternalStorageDirectory(), destFile)));
666 } catch (MalformedURLException e) {
667 throw new RuntimeException(e);
669 downloadManager.enqueue(request);
670 downloadButton.setText("X");