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);
190 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
191 Toast.LENGTH_LONG).show();
193 if (unzipInstall(context, Uri.parse(dest), dest, true)) {
194 finishedDownloadIds.add(downloadId);
195 Log.w(LOG, "Unzipping finished: " + dest + " Id: " + downloadId);
201 private boolean unzipInstall(Context context, Uri zipUri, String dest, boolean delete) {
202 File localZipFile = null;
203 InputStream zipFileStream = null;
204 ZipInputStream zipFile = null;
205 FileOutputStream zipOut = null;
206 boolean result = false;
208 if (zipUri.getScheme().equals("content")) {
209 zipFileStream = context.getContentResolver().openInputStream(zipUri);
212 localZipFile = new File(zipUri.getPath());
214 zipFileStream = new FileInputStream(localZipFile);
215 } catch (Exception e) {
216 if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
217 ActivityCompat.requestPermissions(this,
218 new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
219 Manifest.permission.WRITE_EXTERNAL_STORAGE
226 zipFile = new ZipInputStream(new BufferedInputStream(zipFileStream));
227 final ZipEntry zipEntry = zipFile.getNextEntry();
228 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
229 File targetFile = new File(application.getDictDir(), zipEntry.getName());
230 if (targetFile.exists()) {
231 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
232 targetFile = new File(application.getDictDir(), zipEntry.getName());
234 zipOut = new FileOutputStream(targetFile);
235 copyStream(zipFile, zipOut);
236 application.backgroundUpdateDictionaries(dictionaryUpdater);
238 Toast.makeText(context, getString(R.string.installationFinished, dest),
239 Toast.LENGTH_LONG).show();
241 } catch (Exception e) {
242 String msg = getString(R.string.unzippingFailed, dest + ": " + e.getMessage());
243 File dir = application.getDictDir();
244 if (!dir.canWrite() || !application.checkFileCreate(dir)) {
245 msg = getString(R.string.notWritable, dir.getAbsolutePath());
247 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
248 Log.e(LOG, "Failed to unzip.", e);
251 if (zipOut != null) zipOut.close();
252 } catch (IOException e) {}
254 if (zipFile != null) zipFile.close();
255 } catch (IOException e) {}
257 if (zipFileStream != null) zipFileStream.close();
258 } catch (IOException e) {}
259 if (localZipFile != null && delete) localZipFile.delete();
264 public static Intent getLaunchIntent(Context c) {
265 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
266 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
270 public void readableCheckAndError(boolean requestPermission) {
271 final File dictDir = application.getDictDir();
272 if (dictDir.canRead() && dictDir.canExecute()) return;
273 blockAutoLaunch = true;
274 if (requestPermission &&
275 ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
276 ActivityCompat.requestPermissions(this,
277 new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
278 Manifest.permission.WRITE_EXTERNAL_STORAGE
282 blockAutoLaunch = true;
284 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
285 builder.setTitle(getString(R.string.error));
286 builder.setMessage(getString(
287 R.string.unableToReadDictionaryDir,
288 dictDir.getAbsolutePath(),
289 Environment.getExternalStorageDirectory()));
290 builder.setNeutralButton("Close", null);
291 builder.create().show();
295 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
296 readableCheckAndError(false);
298 application.backgroundUpdateDictionaries(dictionaryUpdater);
304 public void onCreate(Bundle savedInstanceState) {
305 DictionaryApplication.INSTANCE.init(getApplicationContext());
306 application = DictionaryApplication.INSTANCE;
307 // This must be first, otherwise the action bar doesn't get
309 setTheme(application.getSelectedTheme().themeId);
311 super.onCreate(savedInstanceState);
312 Log.d(LOG, "onCreate:" + this);
314 setTheme(application.getSelectedTheme().themeId);
316 blockAutoLaunch = false;
319 setContentView(R.layout.dictionary_manager_activity);
321 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
322 getListView().getContext()).inflate(
323 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
325 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
326 getListView().getContext()).inflate(
327 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
329 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
330 .findViewById(R.id.hideDownloadable);
331 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
333 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
334 onShowDownloadableChanged();
338 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
339 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
340 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
341 thanksForUpdatingLatestVersion)) {
342 blockAutoLaunch = true;
343 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
344 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
348 registerReceiver(broadcastReceiver, new IntentFilter(
349 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
352 registerForContextMenu(getListView());
353 getListView().setItemsCanFocus(true);
355 readableCheckAndError(true);
357 onCreateSetupActionBar();
359 final Intent intent = getIntent();
360 if (intent != null && intent.getAction() != null &&
361 intent.getAction().equals(Intent.ACTION_VIEW)) {
362 blockAutoLaunch = true;
363 Uri uri = intent.getData();
364 unzipInstall(this, uri, uri.getLastPathSegment(), false);
368 private void onCreateSetupActionBar() {
369 ActionBar actionBar = getSupportActionBar();
370 actionBar.setDisplayShowTitleEnabled(false);
371 actionBar.setDisplayShowHomeEnabled(false);
372 actionBar.setDisplayHomeAsUpEnabled(false);
374 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
375 filterSearchView.setIconifiedByDefault(false);
376 // filterSearchView.setIconified(false); // puts the magnifying glass in
379 filterSearchView.setQueryHint(getString(R.string.searchText));
380 filterSearchView.setSubmitButtonEnabled(false);
381 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
382 FrameLayout.LayoutParams.WRAP_CONTENT);
383 filterSearchView.setLayoutParams(lp);
384 filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT);
385 filterSearchView.setImeOptions(
386 EditorInfo.IME_ACTION_DONE |
387 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
388 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
390 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
392 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
394 public boolean onQueryTextSubmit(String query) {
395 filterSearchView.clearFocus();
400 public boolean onQueryTextChange(String filterText) {
405 filterSearchView.setFocusable(true);
407 actionBar.setCustomView(filterSearchView);
408 actionBar.setDisplayShowCustomEnabled(true);
410 // Avoid wasting space on large left inset
411 Toolbar tb = (Toolbar)filterSearchView.getParent();
412 tb.setContentInsetsRelative(0, 0);
416 public void onDestroy() {
418 unregisterReceiver(broadcastReceiver);
421 private static void copyStream(final InputStream ins, final FileOutputStream outs)
423 ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 64);
424 FileChannel out = outs.getChannel();
427 final byte[] bytes = new byte[1024 * 64];
429 bytesRead = ins.read(bytes, pos, bytes.length - pos);
430 if (bytesRead != -1) pos += bytesRead;
431 if (bytesRead == -1 ? pos != 0 : 2*pos >= bytes.length) {
432 buf.put(bytes, 0, pos);
435 while (buf.hasRemaining()) out.write(buf);
438 } while (bytesRead != -1);
442 protected void onStart() {
444 uiHandler = new Handler();
448 protected void onStop() {
454 protected void onResume() {
457 if (PreferenceActivity.prefsMightHaveChanged) {
458 PreferenceActivity.prefsMightHaveChanged = false;
460 startActivity(getIntent());
463 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
464 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
466 if (!blockAutoLaunch &&
467 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
468 prefs.contains(C.DICT_FILE) &&
469 prefs.contains(C.INDEX_SHORT_NAME)) {
470 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
471 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
472 new File(prefs.getString(C.DICT_FILE, "")),
473 prefs.getString(C.INDEX_SHORT_NAME, ""),
479 // Remove the active dictionary from the prefs so we won't autolaunch
481 prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
483 application.backgroundUpdateDictionaries(dictionaryUpdater);
489 public boolean onCreateOptionsMenu(final Menu menu) {
490 if ("true".equals(Settings.System.getString(getContentResolver(), "firebase.test.lab")))
492 return false; // testing the menu is not very interesting
494 final MenuItem sort = menu.add(getString(R.string.sortDicts));
495 MenuItemCompat.setShowAsAction(sort, MenuItem.SHOW_AS_ACTION_NEVER);
496 sort.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
497 public boolean onMenuItemClick(final MenuItem menuItem) {
498 application.sortDictionaries();
504 final MenuItem browserDownload = menu.add(getString(R.string.browserDownload));
505 MenuItemCompat.setShowAsAction(browserDownload, MenuItem.SHOW_AS_ACTION_NEVER);
506 browserDownload.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
507 public boolean onMenuItemClick(final MenuItem menuItem) {
508 final Intent intent = new Intent(Intent.ACTION_VIEW);
510 .parse("https://github.com/rdoeffinger/Dictionary/releases/v0.2-dictionaries"));
511 startActivity(intent);
516 application.onCreateGlobalOptionsMenu(this, menu);
521 public void onCreateContextMenu(final ContextMenu menu, final View view,
522 final ContextMenuInfo menuInfo) {
523 super.onCreateContextMenu(menu, view, menuInfo);
524 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
526 final AdapterContextMenuInfo adapterContextMenuInfo =
527 (AdapterContextMenuInfo) menuInfo;
528 final int position = adapterContextMenuInfo.position;
529 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
531 if (row.dictionaryInfo == null) {
535 if (position > 0 && row.onDevice) {
536 final android.view.MenuItem moveToTopMenuItem =
537 menu.add(R.string.moveToTop);
538 moveToTopMenuItem.setOnMenuItemClickListener(new
539 android.view.MenuItem.OnMenuItemClickListener() {
541 public boolean onMenuItemClick(android.view.MenuItem item) {
542 application.moveDictionaryToTop(row.dictionaryInfo);
550 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
552 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
554 public boolean onMenuItemClick(android.view.MenuItem item) {
555 application.deleteDictionary(row.dictionaryInfo);
563 private void onShowDownloadableChanged() {
565 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
566 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
570 class MyListAdapter extends BaseAdapter {
572 List<DictionaryInfo> dictionariesOnDevice;
573 List<DictionaryInfo> downloadableDictionaries;
576 DictionaryInfo dictionaryInfo;
579 private Row(DictionaryInfo dictionaryInfo, boolean onDevice) {
580 this.dictionaryInfo = dictionaryInfo;
581 this.onDevice = onDevice;
585 private MyListAdapter(final String[] filters) {
586 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
587 if (showDownloadable.isChecked()) {
588 downloadableDictionaries = application.getDownloadableDictionaries(filters);
590 downloadableDictionaries = Collections.emptyList();
595 public int getCount() {
596 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
600 public Row getItem(int position) {
602 return new Row(null, true);
606 if (position < dictionariesOnDevice.size()) {
607 return new Row(dictionariesOnDevice.get(position), true);
609 position -= dictionariesOnDevice.size();
612 return new Row(null, false);
616 assert position < downloadableDictionaries.size();
617 return new Row(downloadableDictionaries.get(position), false);
621 public long getItemId(int position) {
626 public int getViewTypeCount() {
631 public int getItemViewType(int position) {
632 final Row row = getItem(position);
633 if (row.dictionaryInfo == null) {
634 return row.onDevice ? 0 : 1;
636 assert row.dictionaryInfo.indexInfos.size() <= 2;
641 public View getView(int position, View convertView, ViewGroup parent) {
642 if (convertView == dictionariesOnDeviceHeaderRow ||
643 convertView == downloadableDictionariesHeaderRow) {
647 final Row row = getItem(position);
649 if (row.dictionaryInfo == null) {
650 assert convertView == null;
651 return row.onDevice ? dictionariesOnDeviceHeaderRow : downloadableDictionariesHeaderRow;
653 return createDictionaryRow(row.dictionaryInfo, parent, convertView, row.onDevice);
658 private void setMyListAdapater() {
659 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
661 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
662 setListAdapter(new MyListAdapter(filters));
665 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
666 final ViewGroup parent, View row, boolean canLaunch) {
669 row = LayoutInflater.from(parent.getContext()).inflate(
670 R.layout.dictionary_manager_row, parent, false);
672 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
673 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
674 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
676 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
677 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
678 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
679 boolean broken = false;
680 if (!dictionaryInfo.isValid()) {
684 if (downloadable != null && (!canLaunch || updateAvailable)) {
687 R.string.downloadButton,
688 downloadable.zipBytes / 1024.0 / 1024.0));
689 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
690 downloadButton.setOnClickListener(new OnClickListener() {
692 public void onClick(View arg0) {
693 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
696 downloadButton.setVisibility(View.VISIBLE);
698 downloadButton.setVisibility(View.GONE);
701 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
703 final List<IndexInfo> sortedIndexInfos = application
704 .sortedIndexInfos(dictionaryInfo.indexInfos);
705 final StringBuilder builder = new StringBuilder();
706 if (updateAvailable) {
707 builder.append(getString(R.string.updateAvailable));
709 assert buttons.getChildCount() == 4;
710 for (int i = 0; i < 2; i++) {
711 final Button textButton = (Button)buttons.getChildAt(2*i);
712 final ImageButton imageButton = (ImageButton)buttons.getChildAt(2*i + 1);
713 if (i >= sortedIndexInfos.size()) {
714 textButton.setVisibility(View.GONE);
715 imageButton.setVisibility(View.GONE);
718 final IndexInfo indexInfo = sortedIndexInfos.get(i);
719 final View button = IsoUtils.INSTANCE.setupButton(textButton, imageButton, dictionaryInfo,
720 indexInfo, application.languageButtonPixels);
723 button.setOnClickListener(
724 new IntentLauncher(buttons.getContext(),
725 DictionaryActivity.getLaunchIntent(getApplicationContext(),
726 application.getPath(dictionaryInfo.uncompressedFilename),
727 indexInfo.shortName, "")));
730 button.setEnabled(canLaunch);
731 button.setFocusable(canLaunch);
732 if (builder.length() != 0) {
733 builder.append("; ");
735 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
736 indexInfo.mainTokenCount));
738 builder.append("; ");
739 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
741 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
742 builder.append("; Cannot be used, redownload, check hardware/file system");
744 details.setText(builder.toString());
747 row.setOnClickListener(new IntentLauncher(parent.getContext(),
748 DictionaryActivity.getLaunchIntent(getApplicationContext(),
749 application.getPath(dictionaryInfo.uncompressedFilename),
750 dictionaryInfo.indexInfos.get(0).shortName, "")));
751 // do not setFocusable, for keyboard navigation
752 // offering only the index buttons is better.
754 row.setClickable(canLaunch);
755 // Allow deleting, even if we cannot open
756 row.setLongClickable(broken || canLaunch);
757 row.setBackgroundResource(android.R.drawable.menuitem_background);
762 private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
765 destFile = new File(new URL(downloadUrl).getPath()).getName();
766 } catch (MalformedURLException e) {
767 throw new RuntimeException("Invalid download URL!", e);
769 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
770 final DownloadManager.Query query = new DownloadManager.Query();
771 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
772 final Cursor cursor = downloadManager.query(query);
774 // Due to a bug, cursor is null instead of empty when
775 // the download manager is disabled.
776 if (cursor == null) {
777 String msg = getString(R.string.downloadManagerQueryFailed);
778 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
779 .setMessage(getString(R.string.downloadFailed, msg))
780 .setNeutralButton("Close", null).show();
784 while (cursor.moveToNext()) {
785 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
787 if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE))))
790 if (!cursor.isAfterLast()) {
791 downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
794 R.string.downloadButton,
795 bytes / 1024.0 / 1024.0));
800 Request request = new Request(
801 Uri.parse(downloadUrl));
803 Log.d(LOG, "Downloading to: " + destFile);
804 request.setTitle(destFile);
806 File destFilePath = new File(application.getDictDir(), destFile);
807 destFilePath.delete();
809 request.setDestinationUri(Uri.fromFile(destFilePath));
810 } catch (Exception e) {
814 downloadManager.enqueue(request);
815 } catch (SecurityException e) {
816 request = new Request(Uri.parse(downloadUrl));
817 request.setTitle(destFile);
818 downloadManager.enqueue(request);
820 Log.w(LOG, "Download started: " + destFile);
821 downloadButton.setText("X");