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.Manifest;
18 import android.app.AlertDialog;
19 import android.app.DownloadManager;
20 import android.app.DownloadManager.Request;
21 import android.content.BroadcastReceiver;
22 import android.content.ContentResolver;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.IntentFilter;
26 import android.content.SharedPreferences;
27 import android.content.SharedPreferences.Editor;
28 import android.content.pm.PackageManager;
29 import android.database.Cursor;
30 import android.net.Uri;
31 import android.os.Bundle;
32 import android.os.Environment;
33 import android.os.Handler;
34 import android.preference.PreferenceManager;
35 import android.provider.Settings;
36 import android.support.v4.app.ActivityCompat;
37 import android.support.v4.content.ContextCompat;
38 import android.support.v4.view.MenuItemCompat;
39 import android.support.v7.app.ActionBar;
40 import android.support.v7.app.ActionBarActivity;
41 import android.support.v7.widget.SearchView;
42 import android.support.v7.widget.SearchView.OnQueryTextListener;
43 import android.support.v7.widget.Toolbar;
44 import android.text.InputType;
45 import android.util.Log;
46 import android.util.TypedValue;
47 import android.view.ContextMenu;
48 import android.view.ContextMenu.ContextMenuInfo;
49 import android.view.LayoutInflater;
50 import android.view.Menu;
51 import android.view.MenuItem;
52 import android.view.View;
53 import android.view.View.OnClickListener;
54 import android.view.ViewGroup;
55 import android.view.inputmethod.EditorInfo;
56 import android.view.inputmethod.InputMethodManager;
57 import android.widget.AdapterView.AdapterContextMenuInfo;
58 import android.widget.BaseAdapter;
59 import android.widget.Button;
60 import android.widget.CompoundButton;
61 import android.widget.CompoundButton.OnCheckedChangeListener;
62 import android.widget.FrameLayout;
63 import android.widget.ImageButton;
64 import android.widget.LinearLayout;
65 import android.widget.ListAdapter;
66 import android.widget.ListView;
67 import android.widget.TextView;
68 import android.widget.Toast;
69 import android.widget.ToggleButton;
71 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
72 import com.hughes.android.util.IntentLauncher;
74 import java.io.BufferedInputStream;
76 import java.io.FileInputStream;
77 import java.io.FileOutputStream;
78 import java.io.IOException;
79 import java.io.InputStream;
80 import java.io.OutputStream;
81 import java.net.MalformedURLException;
83 import java.nio.ByteBuffer;
84 import java.nio.channels.FileChannel;
85 import java.util.Collections;
86 import java.util.HashSet;
87 import java.util.List;
89 import java.util.zip.ZipEntry;
90 import java.util.zip.ZipFile;
91 import java.util.zip.ZipInputStream;
94 // Delete, move to top.
96 public class DictionaryManagerActivity extends ActionBarActivity {
98 static final String LOG = "QuickDic";
99 static boolean blockAutoLaunch = false;
101 private ListView listView;
102 private ListView getListView() {
103 if (listView == null) {
104 listView = (ListView)findViewById(android.R.id.list);
108 private void setListAdapter(ListAdapter adapter) {
109 getListView().setAdapter(adapter);
111 private ListAdapter getListAdapter() {
112 return getListView().getAdapter();
115 // For DownloadManager bug workaround
116 private Set<Long> finishedDownloadIds = new HashSet<Long>();
118 DictionaryApplication application;
120 SearchView filterSearchView;
121 ToggleButton showDownloadable;
123 LinearLayout dictionariesOnDeviceHeaderRow;
124 LinearLayout downloadableDictionariesHeaderRow;
128 Runnable dictionaryUpdater = new Runnable() {
131 if (uiHandler == null) {
134 uiHandler.post(new Runnable() {
143 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
145 public synchronized void onReceive(Context context, Intent intent) {
146 final String action = intent.getAction();
148 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
149 final long downloadId = intent.getLongExtra(
150 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
151 if (finishedDownloadIds.contains(downloadId)) return; // ignore double notifications
152 final DownloadManager.Query query = new DownloadManager.Query();
153 query.setFilterById(downloadId);
154 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
155 final Cursor cursor = downloadManager.query(query);
157 if (cursor == null || !cursor.moveToFirst()) {
158 Log.e(LOG, "Couldn't find download.");
162 final String dest = cursor
163 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
164 final int status = cursor
166 .getColumnIndex(DownloadManager.COLUMN_STATUS));
167 if (DownloadManager.STATUS_SUCCESSFUL != status) {
168 final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
170 "Download failed: status=" + status +
171 ", reason=" + reason);
172 String msg = Integer.toString(reason);
174 case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
177 case DownloadManager.ERROR_FILE_ERROR:
180 case DownloadManager.ERROR_INSUFFICIENT_SPACE:
181 msg = "Not enough space";
184 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, msg)).setNeutralButton("Close", null).show();
188 Log.w(LOG, "Download finished: " + dest + " Id: " + downloadId);
189 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
190 Toast.LENGTH_LONG).show();
192 if (unzipInstall(context, Uri.parse(dest), dest, true)) {
193 finishedDownloadIds.add(downloadId);
194 Log.w(LOG, "Unzipping finished: " + dest + " Id: " + downloadId);
200 private boolean unzipInstall(Context context, Uri zipUri, String dest, boolean delete) {
201 File localZipFile = null;
202 InputStream zipFileStream = null;
203 ZipInputStream zipFile = null;
204 FileOutputStream zipOut = null;
205 boolean result = false;
207 if (zipUri.getScheme().equals("content")) {
208 zipFileStream = context.getContentResolver().openInputStream(zipUri);
211 localZipFile = new File(zipUri.getPath());
213 zipFileStream = new FileInputStream(localZipFile);
214 } catch (Exception e) {
215 if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
216 ActivityCompat.requestPermissions(this,
217 new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
218 Manifest.permission.WRITE_EXTERNAL_STORAGE
225 zipFile = new ZipInputStream(new BufferedInputStream(zipFileStream));
226 final ZipEntry zipEntry = zipFile.getNextEntry();
227 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
228 File targetFile = new File(application.getDictDir(), zipEntry.getName());
229 if (targetFile.exists()) {
230 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
231 targetFile = new File(application.getDictDir(), zipEntry.getName());
233 zipOut = new FileOutputStream(targetFile);
234 copyStream(zipFile, zipOut);
235 application.backgroundUpdateDictionaries(dictionaryUpdater);
236 Toast.makeText(context, getString(R.string.installationFinished, dest),
237 Toast.LENGTH_LONG).show();
239 } catch (Exception e) {
240 String msg = getString(R.string.unzippingFailed, dest + ": " + e.getMessage());
241 File dir = application.getDictDir();
242 if (!dir.canWrite() || !application.checkFileCreate(dir)) {
243 msg = getString(R.string.notWritable, dir.getAbsolutePath());
245 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
246 Log.e(LOG, "Failed to unzip.", e);
249 if (zipOut != null) zipOut.close();
250 } catch (IOException e) {}
252 if (zipFile != null) zipFile.close();
253 } catch (IOException e) {}
255 if (zipFileStream != null) zipFileStream.close();
256 } catch (IOException e) {}
257 if (localZipFile != null && delete) localZipFile.delete();
262 public static Intent getLaunchIntent(Context c) {
263 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
264 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
268 public void readableCheckAndError(boolean requestPermission) {
269 final File dictDir = application.getDictDir();
270 if (dictDir.canRead() && dictDir.canExecute()) return;
271 blockAutoLaunch = true;
272 if (requestPermission &&
273 ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
274 ActivityCompat.requestPermissions(this,
275 new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
276 Manifest.permission.WRITE_EXTERNAL_STORAGE
280 blockAutoLaunch = true;
282 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
283 builder.setTitle(getString(R.string.error));
284 builder.setMessage(getString(
285 R.string.unableToReadDictionaryDir,
286 dictDir.getAbsolutePath(),
287 Environment.getExternalStorageDirectory()));
288 builder.setNeutralButton("Close", null);
289 builder.create().show();
293 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
294 readableCheckAndError(false);
296 application.backgroundUpdateDictionaries(dictionaryUpdater);
302 public void onCreate(Bundle savedInstanceState) {
303 DictionaryApplication.INSTANCE.init(getApplicationContext());
304 application = DictionaryApplication.INSTANCE;
305 // This must be first, otherwise the action bar doesn't get
307 setTheme(application.getSelectedTheme().themeId);
309 super.onCreate(savedInstanceState);
310 Log.d(LOG, "onCreate:" + this);
312 setTheme(application.getSelectedTheme().themeId);
314 blockAutoLaunch = false;
317 setContentView(R.layout.dictionary_manager_activity);
319 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
320 getListView().getContext()).inflate(
321 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
323 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
324 getListView().getContext()).inflate(
325 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
327 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
328 .findViewById(R.id.hideDownloadable);
329 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
331 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
332 onShowDownloadableChanged();
336 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
337 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
338 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
339 thanksForUpdatingLatestVersion)) {
340 blockAutoLaunch = true;
341 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
342 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
346 registerReceiver(broadcastReceiver, new IntentFilter(
347 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
350 registerForContextMenu(getListView());
351 getListView().setItemsCanFocus(true);
353 readableCheckAndError(true);
355 onCreateSetupActionBar();
357 final Intent intent = getIntent();
358 if (intent != null && intent.getAction() != null &&
359 intent.getAction().equals(Intent.ACTION_VIEW)) {
360 blockAutoLaunch = true;
361 Uri uri = intent.getData();
362 unzipInstall(this, uri, uri.getLastPathSegment(), false);
366 private void onCreateSetupActionBar() {
367 ActionBar actionBar = getSupportActionBar();
368 actionBar.setDisplayShowTitleEnabled(false);
369 actionBar.setDisplayShowHomeEnabled(false);
370 actionBar.setDisplayHomeAsUpEnabled(false);
372 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
373 filterSearchView.setIconifiedByDefault(false);
374 // filterSearchView.setIconified(false); // puts the magnifying glass in
377 filterSearchView.setQueryHint(getString(R.string.searchText));
378 filterSearchView.setSubmitButtonEnabled(false);
379 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
380 FrameLayout.LayoutParams.WRAP_CONTENT);
381 filterSearchView.setLayoutParams(lp);
382 filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT);
383 filterSearchView.setImeOptions(
384 EditorInfo.IME_ACTION_DONE |
385 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
386 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
388 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
390 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
392 public boolean onQueryTextSubmit(String query) {
393 filterSearchView.clearFocus();
398 public boolean onQueryTextChange(String filterText) {
403 filterSearchView.setFocusable(true);
405 actionBar.setCustomView(filterSearchView);
406 actionBar.setDisplayShowCustomEnabled(true);
408 // Avoid wasting space on large left inset
409 Toolbar tb = (Toolbar)filterSearchView.getParent();
410 tb.setContentInsetsRelative(0, 0);
414 public void onDestroy() {
416 unregisterReceiver(broadcastReceiver);
419 private static void copyStream(final InputStream ins, final FileOutputStream outs)
421 ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 64);
422 FileChannel out = outs.getChannel();
425 final byte[] bytes = new byte[1024 * 64];
427 bytesRead = ins.read(bytes, pos, bytes.length - pos);
428 if (bytesRead != -1) pos += bytesRead;
429 if (bytesRead == -1 ? pos != 0 : 2*pos >= bytes.length) {
430 buf.put(bytes, 0, pos);
433 while (buf.hasRemaining()) out.write(buf);
436 } while (bytesRead != -1);
440 protected void onStart() {
442 uiHandler = new Handler();
446 protected void onStop() {
452 protected void onResume() {
455 if (PreferenceActivity.prefsMightHaveChanged) {
456 PreferenceActivity.prefsMightHaveChanged = false;
458 startActivity(getIntent());
461 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
462 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
464 if (!blockAutoLaunch &&
465 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
466 prefs.contains(C.DICT_FILE) &&
467 prefs.contains(C.INDEX_SHORT_NAME)) {
468 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
469 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
470 new File(prefs.getString(C.DICT_FILE, "")),
471 prefs.getString(C.INDEX_SHORT_NAME, ""),
477 // Remove the active dictionary from the prefs so we won't autolaunch
479 prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
481 application.backgroundUpdateDictionaries(dictionaryUpdater);
487 public boolean onCreateOptionsMenu(final Menu menu) {
488 if ("true".equals(Settings.System.getString(getContentResolver(), "firebase.test.lab")))
490 return false; // testing the menu is not very interesting
492 final MenuItem sort = menu.add(getString(R.string.sortDicts));
493 MenuItemCompat.setShowAsAction(sort, MenuItem.SHOW_AS_ACTION_NEVER);
494 sort.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
495 public boolean onMenuItemClick(final MenuItem menuItem) {
496 application.sortDictionaries();
502 application.onCreateGlobalOptionsMenu(this, menu);
507 public void onCreateContextMenu(final ContextMenu menu, final View view,
508 final ContextMenuInfo menuInfo) {
509 super.onCreateContextMenu(menu, view, menuInfo);
510 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
512 final AdapterContextMenuInfo adapterContextMenuInfo =
513 (AdapterContextMenuInfo) menuInfo;
514 final int position = adapterContextMenuInfo.position;
515 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
517 if (row.dictionaryInfo == null) {
521 if (position > 0 && row.onDevice) {
522 final android.view.MenuItem moveToTopMenuItem =
523 menu.add(R.string.moveToTop);
524 moveToTopMenuItem.setOnMenuItemClickListener(new
525 android.view.MenuItem.OnMenuItemClickListener() {
527 public boolean onMenuItemClick(android.view.MenuItem item) {
528 application.moveDictionaryToTop(row.dictionaryInfo);
536 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
538 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
540 public boolean onMenuItemClick(android.view.MenuItem item) {
541 application.deleteDictionary(row.dictionaryInfo);
549 private void onShowDownloadableChanged() {
551 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
552 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
556 class MyListAdapter extends BaseAdapter {
558 List<DictionaryInfo> dictionariesOnDevice;
559 List<DictionaryInfo> downloadableDictionaries;
562 DictionaryInfo dictionaryInfo;
565 private Row(DictionaryInfo dictionaryInfo, boolean onDevice) {
566 this.dictionaryInfo = dictionaryInfo;
567 this.onDevice = onDevice;
571 private MyListAdapter(final String[] filters) {
572 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
573 if (showDownloadable.isChecked()) {
574 downloadableDictionaries = application.getDownloadableDictionaries(filters);
576 downloadableDictionaries = Collections.emptyList();
581 public int getCount() {
582 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
586 public Row getItem(int position) {
588 return new Row(null, true);
592 if (position < dictionariesOnDevice.size()) {
593 return new Row(dictionariesOnDevice.get(position), true);
595 position -= dictionariesOnDevice.size();
598 return new Row(null, false);
602 assert position < downloadableDictionaries.size();
603 return new Row(downloadableDictionaries.get(position), false);
607 public long getItemId(int position) {
612 public int getViewTypeCount() {
617 public int getItemViewType(int position) {
618 final Row row = getItem(position);
619 if (row.dictionaryInfo == null) {
620 return row.onDevice ? 0 : 1;
622 assert row.dictionaryInfo.indexInfos.size() <= 2;
627 public View getView(int position, View convertView, ViewGroup parent) {
628 if (convertView == dictionariesOnDeviceHeaderRow ||
629 convertView == downloadableDictionariesHeaderRow) {
633 final Row row = getItem(position);
635 if (row.dictionaryInfo == null) {
636 assert convertView == null;
637 return row.onDevice ? dictionariesOnDeviceHeaderRow : downloadableDictionariesHeaderRow;
639 return createDictionaryRow(row.dictionaryInfo, parent, convertView, row.onDevice);
644 private void setMyListAdapater() {
645 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
647 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
648 setListAdapter(new MyListAdapter(filters));
651 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
652 final ViewGroup parent, View row, boolean canLaunch) {
655 row = LayoutInflater.from(parent.getContext()).inflate(
656 R.layout.dictionary_manager_row, parent, false);
658 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
659 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
660 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
662 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
663 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
664 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
665 boolean broken = false;
666 if (!dictionaryInfo.isValid()) {
670 if (downloadable != null && (!canLaunch || updateAvailable)) {
673 R.string.downloadButton,
674 downloadable.zipBytes / 1024.0 / 1024.0));
675 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
676 downloadButton.setOnClickListener(new OnClickListener() {
678 public void onClick(View arg0) {
679 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
682 downloadButton.setVisibility(View.VISIBLE);
684 downloadButton.setVisibility(View.GONE);
687 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
689 final List<IndexInfo> sortedIndexInfos = application
690 .sortedIndexInfos(dictionaryInfo.indexInfos);
691 final StringBuilder builder = new StringBuilder();
692 if (updateAvailable) {
693 builder.append(getString(R.string.updateAvailable));
695 assert buttons.getChildCount() == 4;
696 for (int i = 0; i < 2; i++) {
697 final Button textButton = (Button)buttons.getChildAt(2*i);
698 final ImageButton imageButton = (ImageButton)buttons.getChildAt(2*i + 1);
699 if (i >= sortedIndexInfos.size()) {
700 textButton.setVisibility(View.GONE);
701 imageButton.setVisibility(View.GONE);
704 final IndexInfo indexInfo = sortedIndexInfos.get(i);
705 final View button = IsoUtils.INSTANCE.setupButton(textButton, imageButton, dictionaryInfo,
706 indexInfo, application.languageButtonPixels);
709 button.setOnClickListener(
710 new IntentLauncher(buttons.getContext(),
711 DictionaryActivity.getLaunchIntent(getApplicationContext(),
712 application.getPath(dictionaryInfo.uncompressedFilename),
713 indexInfo.shortName, "")));
716 button.setEnabled(canLaunch);
717 button.setFocusable(canLaunch);
718 if (builder.length() != 0) {
719 builder.append("; ");
721 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
722 indexInfo.mainTokenCount));
724 builder.append("; ");
725 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
727 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
728 builder.append("; Cannot be used, redownload, check hardware/file system");
730 details.setText(builder.toString());
733 row.setOnClickListener(new IntentLauncher(parent.getContext(),
734 DictionaryActivity.getLaunchIntent(getApplicationContext(),
735 application.getPath(dictionaryInfo.uncompressedFilename),
736 dictionaryInfo.indexInfos.get(0).shortName, "")));
737 // do not setFocusable, for keyboard navigation
738 // offering only the index buttons is better.
740 row.setClickable(canLaunch);
741 // Allow deleting, even if we cannot open
742 row.setLongClickable(broken || canLaunch);
743 row.setBackgroundResource(android.R.drawable.menuitem_background);
748 private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
751 destFile = new File(new URL(downloadUrl).getPath()).getName();
752 } catch (MalformedURLException e) {
753 throw new RuntimeException("Invalid download URL!", e);
755 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
756 final DownloadManager.Query query = new DownloadManager.Query();
757 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
758 final Cursor cursor = downloadManager.query(query);
760 // Due to a bug, cursor is null instead of empty when
761 // the download manager is disabled.
762 if (cursor == null) {
763 String msg = getString(R.string.downloadManagerQueryFailed);
764 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
765 .setMessage(getString(R.string.downloadFailed, msg))
766 .setNeutralButton("Close", null).show();
770 while (cursor.moveToNext()) {
771 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
773 if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE))))
776 if (!cursor.isAfterLast()) {
777 downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
780 R.string.downloadButton,
781 bytes / 1024.0 / 1024.0));
786 Request request = new Request(
787 Uri.parse(downloadUrl));
789 Log.d(LOG, "Downloading to: " + destFile);
790 request.setTitle(destFile);
792 File destFilePath = new File(application.getDictDir(), destFile);
793 destFilePath.delete();
795 request.setDestinationUri(Uri.fromFile(destFilePath));
796 } catch (Exception e) {
800 downloadManager.enqueue(request);
801 } catch (SecurityException e) {
802 request = new Request(Uri.parse(downloadUrl));
803 request.setTitle(destFile);
804 downloadManager.enqueue(request);
806 Log.w(LOG, "Download started: " + destFile);
807 downloadButton.setText("X");