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.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.content.pm.PackageManager;
28 import android.database.Cursor;
29 import android.net.Uri;
30 import android.os.Bundle;
31 import android.os.Environment;
32 import android.os.Handler;
33 import android.preference.PreferenceManager;
34 import android.provider.Settings;
35 import android.support.annotation.NonNull;
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.AppCompatActivity;
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.view.ContextMenu;
47 import android.view.ContextMenu.ContextMenuInfo;
48 import android.view.LayoutInflater;
49 import android.view.Menu;
50 import android.view.MenuItem;
51 import android.view.View;
52 import android.view.View.OnClickListener;
53 import android.view.ViewGroup;
54 import android.view.inputmethod.EditorInfo;
55 import android.widget.AdapterView.AdapterContextMenuInfo;
56 import android.widget.BaseAdapter;
57 import android.widget.Button;
58 import android.widget.CompoundButton;
59 import android.widget.CompoundButton.OnCheckedChangeListener;
60 import android.widget.FrameLayout;
61 import android.widget.ImageButton;
62 import android.widget.LinearLayout;
63 import android.widget.ListAdapter;
64 import android.widget.ListView;
65 import android.widget.TextView;
66 import android.widget.Toast;
67 import android.widget.ToggleButton;
69 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
70 import com.hughes.android.util.IntentLauncher;
72 import java.io.BufferedInputStream;
74 import java.io.FileInputStream;
75 import java.io.FileOutputStream;
76 import java.io.IOException;
77 import java.io.InputStream;
78 import java.net.MalformedURLException;
80 import java.nio.ByteBuffer;
81 import java.nio.channels.FileChannel;
82 import java.util.Collections;
83 import java.util.HashSet;
84 import java.util.List;
86 import java.util.zip.ZipEntry;
87 import java.util.zip.ZipInputStream;
90 // Delete, move to top.
92 public class DictionaryManagerActivity extends AppCompatActivity {
94 private static final String LOG = "QuickDic";
95 private static boolean blockAutoLaunch = false;
97 private ListView listView;
98 private ListView getListView() {
99 if (listView == null) {
100 listView = (ListView)findViewById(android.R.id.list);
104 private void setListAdapter(ListAdapter adapter) {
105 getListView().setAdapter(adapter);
107 private ListAdapter getListAdapter() {
108 return getListView().getAdapter();
111 // For DownloadManager bug workaround
112 private final Set<Long> finishedDownloadIds = new HashSet<>();
114 private DictionaryApplication application;
116 private SearchView filterSearchView;
117 private ToggleButton showDownloadable;
119 private LinearLayout dictionariesOnDeviceHeaderRow;
120 private LinearLayout downloadableDictionariesHeaderRow;
122 private Handler uiHandler;
124 private final Runnable dictionaryUpdater = new Runnable() {
127 if (uiHandler == null) {
130 uiHandler.post(new Runnable() {
139 private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
141 public synchronized void onReceive(Context context, Intent intent) {
142 final String action = intent.getAction();
144 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
145 final long downloadId = intent.getLongExtra(
146 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
147 if (finishedDownloadIds.contains(downloadId)) return; // ignore double notifications
148 final DownloadManager.Query query = new DownloadManager.Query();
149 query.setFilterById(downloadId);
150 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
151 final Cursor cursor = downloadManager.query(query);
153 if (cursor == null || !cursor.moveToFirst()) {
154 Log.e(LOG, "Couldn't find download.");
158 final String dest = cursor
159 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
160 final int status = cursor
162 .getColumnIndex(DownloadManager.COLUMN_STATUS));
163 if (DownloadManager.STATUS_SUCCESSFUL != status) {
164 final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
166 "Download failed: status=" + status +
167 ", reason=" + reason);
168 String msg = Integer.toString(reason);
170 case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
173 case DownloadManager.ERROR_FILE_ERROR:
176 case DownloadManager.ERROR_INSUFFICIENT_SPACE:
177 msg = "Not enough space";
180 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, msg)).setNeutralButton("Close", null).show();
184 Log.w(LOG, "Download finished: " + dest + " Id: " + downloadId);
186 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
187 Toast.LENGTH_LONG).show();
189 if (unzipInstall(context, Uri.parse(dest), dest, true)) {
190 finishedDownloadIds.add(downloadId);
191 Log.w(LOG, "Unzipping finished: " + dest + " Id: " + downloadId);
197 private boolean unzipInstall(Context context, Uri zipUri, String dest, boolean delete) {
198 File localZipFile = null;
199 InputStream zipFileStream = null;
200 ZipInputStream zipFile = null;
201 FileOutputStream zipOut = null;
202 boolean result = false;
204 if (zipUri.getScheme().equals("content")) {
205 zipFileStream = context.getContentResolver().openInputStream(zipUri);
208 localZipFile = new File(zipUri.getPath());
210 zipFileStream = new FileInputStream(localZipFile);
211 } catch (Exception e) {
212 if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
213 ActivityCompat.requestPermissions(this,
214 new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
215 Manifest.permission.WRITE_EXTERNAL_STORAGE
222 zipFile = new ZipInputStream(new BufferedInputStream(zipFileStream));
223 final ZipEntry zipEntry = zipFile.getNextEntry();
224 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
225 File targetFile = new File(application.getDictDir(), zipEntry.getName());
226 if (targetFile.exists()) {
227 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
228 targetFile = new File(application.getDictDir(), zipEntry.getName());
230 zipOut = new FileOutputStream(targetFile);
231 copyStream(zipFile, zipOut);
232 application.backgroundUpdateDictionaries(dictionaryUpdater);
234 Toast.makeText(context, getString(R.string.installationFinished, dest),
235 Toast.LENGTH_LONG).show();
237 } catch (Exception e) {
238 String msg = getString(R.string.unzippingFailed, dest + ": " + e.getMessage());
239 File dir = application.getDictDir();
240 if (!dir.canWrite() || !DictionaryApplication.checkFileCreate(dir)) {
241 msg = getString(R.string.notWritable, dir.getAbsolutePath());
243 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
244 Log.e(LOG, "Failed to unzip.", e);
247 if (zipOut != null) zipOut.close();
248 } catch (IOException e) {}
250 if (zipFile != null) zipFile.close();
251 } catch (IOException e) {}
253 if (zipFileStream != null) zipFileStream.close();
254 } catch (IOException e) {}
255 if (localZipFile != null && delete) localZipFile.delete();
260 public static Intent getLaunchIntent(Context c) {
261 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
262 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
266 private void readableCheckAndError(boolean requestPermission) {
267 final File dictDir = application.getDictDir();
268 if (dictDir.canRead() && dictDir.canExecute()) return;
269 blockAutoLaunch = true;
270 if (requestPermission &&
271 ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
272 ActivityCompat.requestPermissions(this,
273 new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
274 Manifest.permission.WRITE_EXTERNAL_STORAGE
278 blockAutoLaunch = true;
280 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
281 builder.setTitle(getString(R.string.error));
282 builder.setMessage(getString(
283 R.string.unableToReadDictionaryDir,
284 dictDir.getAbsolutePath(),
285 Environment.getExternalStorageDirectory()));
286 builder.setNeutralButton("Close", null);
287 builder.create().show();
291 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
292 readableCheckAndError(false);
294 application.backgroundUpdateDictionaries(dictionaryUpdater);
300 public void onCreate(Bundle savedInstanceState) {
301 DictionaryApplication.INSTANCE.init(getApplicationContext());
302 application = DictionaryApplication.INSTANCE;
303 // This must be first, otherwise the action bar doesn't get
305 setTheme(application.getSelectedTheme().themeId);
307 super.onCreate(savedInstanceState);
308 Log.d(LOG, "onCreate:" + this);
310 setTheme(application.getSelectedTheme().themeId);
312 blockAutoLaunch = false;
315 setContentView(R.layout.dictionary_manager_activity);
317 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
318 getListView().getContext()).inflate(
319 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
321 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
322 getListView().getContext()).inflate(
323 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
325 showDownloadable = downloadableDictionariesHeaderRow
326 .findViewById(R.id.hideDownloadable);
327 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
329 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
330 onShowDownloadableChanged();
334 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
335 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
336 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
337 thanksForUpdatingLatestVersion)) {
338 blockAutoLaunch = true;
339 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
340 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
344 registerReceiver(broadcastReceiver, new IntentFilter(
345 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
348 registerForContextMenu(getListView());
349 getListView().setItemsCanFocus(true);
351 readableCheckAndError(true);
353 onCreateSetupActionBar();
355 final Intent intent = getIntent();
356 if (intent != null && intent.getAction() != null &&
357 intent.getAction().equals(Intent.ACTION_VIEW)) {
358 blockAutoLaunch = true;
359 Uri uri = intent.getData();
360 unzipInstall(this, uri, uri.getLastPathSegment(), false);
364 private void onCreateSetupActionBar() {
365 ActionBar actionBar = getSupportActionBar();
366 actionBar.setDisplayShowTitleEnabled(false);
367 actionBar.setDisplayShowHomeEnabled(false);
368 actionBar.setDisplayHomeAsUpEnabled(false);
370 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
371 filterSearchView.setIconifiedByDefault(false);
372 // filterSearchView.setIconified(false); // puts the magnifying glass in
375 filterSearchView.setQueryHint(getString(R.string.searchText));
376 filterSearchView.setSubmitButtonEnabled(false);
377 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
378 FrameLayout.LayoutParams.WRAP_CONTENT);
379 filterSearchView.setLayoutParams(lp);
380 filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT);
381 filterSearchView.setImeOptions(
382 EditorInfo.IME_ACTION_DONE |
383 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
384 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
386 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
388 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
390 public boolean onQueryTextSubmit(String query) {
391 filterSearchView.clearFocus();
396 public boolean onQueryTextChange(String filterText) {
401 filterSearchView.setFocusable(true);
403 actionBar.setCustomView(filterSearchView);
404 actionBar.setDisplayShowCustomEnabled(true);
406 // Avoid wasting space on large left inset
407 Toolbar tb = (Toolbar)filterSearchView.getParent();
408 tb.setContentInsetsRelative(0, 0);
412 public void onDestroy() {
414 unregisterReceiver(broadcastReceiver);
417 private static void copyStream(final InputStream ins, final FileOutputStream outs)
419 ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 64);
420 FileChannel out = outs.getChannel();
423 final byte[] bytes = new byte[1024 * 64];
425 bytesRead = ins.read(bytes, pos, bytes.length - pos);
426 if (bytesRead != -1) pos += bytesRead;
427 if (bytesRead == -1 ? pos != 0 : 2*pos >= bytes.length) {
428 buf.put(bytes, 0, pos);
431 while (buf.hasRemaining()) out.write(buf);
434 } while (bytesRead != -1);
438 protected void onStart() {
440 uiHandler = new Handler();
444 protected void onStop() {
450 protected void onResume() {
453 if (PreferenceActivity.prefsMightHaveChanged) {
454 PreferenceActivity.prefsMightHaveChanged = false;
456 startActivity(getIntent());
459 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
460 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
462 if (!blockAutoLaunch &&
463 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
464 prefs.contains(C.DICT_FILE) &&
465 prefs.contains(C.INDEX_SHORT_NAME)) {
466 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
467 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
468 new File(prefs.getString(C.DICT_FILE, "")),
469 prefs.getString(C.INDEX_SHORT_NAME, ""),
475 // Remove the active dictionary from the prefs so we won't autolaunch
477 prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
479 application.backgroundUpdateDictionaries(dictionaryUpdater);
485 public boolean onCreateOptionsMenu(final Menu menu) {
486 if ("true".equals(Settings.System.getString(getContentResolver(), "firebase.test.lab")))
488 return false; // testing the menu is not very interesting
490 final MenuItem sort = menu.add(getString(R.string.sortDicts));
491 MenuItemCompat.setShowAsAction(sort, MenuItem.SHOW_AS_ACTION_NEVER);
492 sort.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
493 public boolean onMenuItemClick(final MenuItem menuItem) {
494 application.sortDictionaries();
500 final MenuItem browserDownload = menu.add(getString(R.string.browserDownload));
501 MenuItemCompat.setShowAsAction(browserDownload, MenuItem.SHOW_AS_ACTION_NEVER);
502 browserDownload.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
503 public boolean onMenuItemClick(final MenuItem menuItem) {
504 final Intent intent = new Intent(Intent.ACTION_VIEW);
506 .parse("https://github.com/rdoeffinger/Dictionary/releases/v0.2-dictionaries"));
507 startActivity(intent);
512 DictionaryApplication.onCreateGlobalOptionsMenu(this, menu);
517 public void onCreateContextMenu(final ContextMenu menu, final View view,
518 final ContextMenuInfo menuInfo) {
519 super.onCreateContextMenu(menu, view, menuInfo);
520 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
522 final AdapterContextMenuInfo adapterContextMenuInfo =
523 (AdapterContextMenuInfo) menuInfo;
524 final int position = adapterContextMenuInfo.position;
525 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
527 if (row.dictionaryInfo == null) {
531 if (position > 0 && row.onDevice) {
532 final android.view.MenuItem moveToTopMenuItem =
533 menu.add(R.string.moveToTop);
534 moveToTopMenuItem.setOnMenuItemClickListener(new
535 android.view.MenuItem.OnMenuItemClickListener() {
537 public boolean onMenuItemClick(android.view.MenuItem item) {
538 application.moveDictionaryToTop(row.dictionaryInfo);
546 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
548 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
550 public boolean onMenuItemClick(android.view.MenuItem item) {
551 application.deleteDictionary(row.dictionaryInfo);
559 private void onShowDownloadableChanged() {
561 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
562 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
566 class MyListAdapter extends BaseAdapter {
568 final List<DictionaryInfo> dictionariesOnDevice;
569 final List<DictionaryInfo> downloadableDictionaries;
572 final DictionaryInfo dictionaryInfo;
573 final boolean onDevice;
575 private Row(DictionaryInfo dictionaryInfo, boolean onDevice) {
576 this.dictionaryInfo = dictionaryInfo;
577 this.onDevice = onDevice;
581 private MyListAdapter(final String[] filters) {
582 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
583 if (showDownloadable.isChecked()) {
584 downloadableDictionaries = application.getDownloadableDictionaries(filters);
586 downloadableDictionaries = Collections.emptyList();
591 public int getCount() {
592 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
596 public Row getItem(int position) {
598 return new Row(null, true);
602 if (position < dictionariesOnDevice.size()) {
603 return new Row(dictionariesOnDevice.get(position), true);
605 position -= dictionariesOnDevice.size();
608 return new Row(null, false);
612 assert position < downloadableDictionaries.size();
613 return new Row(downloadableDictionaries.get(position), false);
617 public long getItemId(int position) {
622 public int getViewTypeCount() {
627 public int getItemViewType(int position) {
628 final Row row = getItem(position);
629 if (row.dictionaryInfo == null) {
630 return row.onDevice ? 0 : 1;
632 assert row.dictionaryInfo.indexInfos.size() <= 2;
637 public View getView(int position, View convertView, ViewGroup parent) {
638 if (convertView == dictionariesOnDeviceHeaderRow ||
639 convertView == downloadableDictionariesHeaderRow) {
643 final Row row = getItem(position);
645 if (row.dictionaryInfo == null) {
646 assert convertView == null;
647 return row.onDevice ? dictionariesOnDeviceHeaderRow : downloadableDictionariesHeaderRow;
649 return createDictionaryRow(row.dictionaryInfo, parent, convertView, row.onDevice);
654 private void setMyListAdapter() {
655 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
657 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
658 setListAdapter(new MyListAdapter(filters));
661 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
662 final ViewGroup parent, View row, boolean canLaunch) {
665 row = LayoutInflater.from(parent.getContext()).inflate(
666 R.layout.dictionary_manager_row, parent, false);
668 final TextView name = row.findViewById(R.id.dictionaryName);
669 final TextView details = row.findViewById(R.id.dictionaryDetails);
670 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
672 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
673 final Button downloadButton = row.findViewById(R.id.downloadButton);
674 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
675 boolean broken = false;
676 if (!dictionaryInfo.isValid()) {
680 if (downloadable != null && (!canLaunch || updateAvailable)) {
683 R.string.downloadButton,
684 downloadable.zipBytes / 1024.0 / 1024.0));
685 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
686 downloadButton.setOnClickListener(new OnClickListener() {
688 public void onClick(View arg0) {
689 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
692 downloadButton.setVisibility(View.VISIBLE);
694 downloadButton.setVisibility(View.GONE);
697 LinearLayout buttons = row.findViewById(R.id.dictionaryLauncherButtons);
699 final List<IndexInfo> sortedIndexInfos = application
700 .sortedIndexInfos(dictionaryInfo.indexInfos);
701 final StringBuilder builder = new StringBuilder();
702 if (updateAvailable) {
703 builder.append(getString(R.string.updateAvailable));
705 assert buttons.getChildCount() == 4;
706 for (int i = 0; i < 2; i++) {
707 final Button textButton = (Button)buttons.getChildAt(2*i);
708 final ImageButton imageButton = (ImageButton)buttons.getChildAt(2*i + 1);
709 if (i >= sortedIndexInfos.size()) {
710 textButton.setVisibility(View.GONE);
711 imageButton.setVisibility(View.GONE);
714 final IndexInfo indexInfo = sortedIndexInfos.get(i);
715 final View button = IsoUtils.INSTANCE.setupButton(textButton, imageButton,
719 button.setOnClickListener(
720 new IntentLauncher(buttons.getContext(),
721 DictionaryActivity.getLaunchIntent(getApplicationContext(),
722 application.getPath(dictionaryInfo.uncompressedFilename),
723 indexInfo.shortName, "")));
726 button.setEnabled(canLaunch);
727 button.setFocusable(canLaunch);
728 if (builder.length() != 0) {
729 builder.append("; ");
731 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
732 indexInfo.mainTokenCount));
734 builder.append("; ");
735 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
737 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
738 builder.append("; Cannot be used, redownload, check hardware/file system");
740 details.setText(builder.toString());
743 row.setOnClickListener(new IntentLauncher(parent.getContext(),
744 DictionaryActivity.getLaunchIntent(getApplicationContext(),
745 application.getPath(dictionaryInfo.uncompressedFilename),
746 dictionaryInfo.indexInfos.get(0).shortName, "")));
747 // do not setFocusable, for keyboard navigation
748 // offering only the index buttons is better.
750 row.setClickable(canLaunch);
751 // Allow deleting, even if we cannot open
752 row.setLongClickable(broken || canLaunch);
753 row.setBackgroundResource(android.R.drawable.menuitem_background);
758 private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
761 destFile = new File(new URL(downloadUrl).getPath()).getName();
762 } catch (MalformedURLException e) {
763 throw new RuntimeException("Invalid download URL!", e);
765 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
766 final DownloadManager.Query query = new DownloadManager.Query();
767 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
768 final Cursor cursor = downloadManager.query(query);
770 // Due to a bug, cursor is null instead of empty when
771 // the download manager is disabled.
772 if (cursor == null) {
773 String msg = getString(R.string.downloadManagerQueryFailed);
774 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
775 .setMessage(getString(R.string.downloadFailed, msg))
776 .setNeutralButton("Close", null).show();
780 while (cursor.moveToNext()) {
781 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
783 if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE))))
786 if (!cursor.isAfterLast()) {
787 downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
790 R.string.downloadButton,
791 bytes / 1024.0 / 1024.0));
796 Request request = new Request(
797 Uri.parse(downloadUrl));
799 Log.d(LOG, "Downloading to: " + destFile);
800 request.setTitle(destFile);
802 File destFilePath = new File(application.getDictDir(), destFile);
803 destFilePath.delete();
805 request.setDestinationUri(Uri.fromFile(destFilePath));
806 } catch (Exception e) {
810 downloadManager.enqueue(request);
811 } catch (SecurityException e) {
812 request = new Request(Uri.parse(downloadUrl));
813 request.setTitle(destFile);
814 downloadManager.enqueue(request);
816 Log.w(LOG, "Download started: " + destFile);
817 downloadButton.setText("X");