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.regex.Pattern;
87 import java.util.zip.ZipEntry;
88 import java.util.zip.ZipInputStream;
91 // Delete, move to top.
93 public class DictionaryManagerActivity extends AppCompatActivity {
95 private static final String LOG = "QuickDic";
96 private static boolean blockAutoLaunch = false;
98 private ListView listView;
99 private ListView getListView() {
100 if (listView == null) {
101 listView = (ListView)findViewById(android.R.id.list);
105 private void setListAdapter(ListAdapter adapter) {
106 getListView().setAdapter(adapter);
108 private ListAdapter getListAdapter() {
109 return getListView().getAdapter();
112 // For DownloadManager bug workaround
113 private final Set<Long> finishedDownloadIds = new HashSet<>();
115 private DictionaryApplication application;
117 private SearchView filterSearchView;
118 private ToggleButton showDownloadable;
120 private LinearLayout dictionariesOnDeviceHeaderRow;
121 private LinearLayout downloadableDictionariesHeaderRow;
123 private Handler uiHandler;
125 private final Runnable dictionaryUpdater = new Runnable() {
128 if (uiHandler == null) {
131 uiHandler.post(new Runnable() {
140 private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
142 public synchronized void onReceive(Context context, Intent intent) {
143 final String action = intent.getAction();
145 if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
146 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP));
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 ZipEntry zipEntry = null;
228 while ((zipEntry = zipFile.getNextEntry()) != null) {
229 // Note: this check prevents security issues like accidental path
230 // traversal, which unfortunately ZipInputStream has no protection against.
231 // So take extra care when changing it.
232 if (!Pattern.matches("[-A-Za-z]+\\.quickdic", zipEntry.getName())) {
233 Log.w(LOG, "Invalid zip entry: " + zipEntry.getName());
236 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
237 File targetFile = new File(application.getDictDir(), zipEntry.getName());
238 if (targetFile.exists()) {
239 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
240 targetFile = new File(application.getDictDir(), zipEntry.getName());
242 zipOut = new FileOutputStream(targetFile);
243 copyStream(zipFile, zipOut);
245 application.backgroundUpdateDictionaries(dictionaryUpdater);
247 Toast.makeText(context, getString(R.string.installationFinished, dest),
248 Toast.LENGTH_LONG).show();
250 } catch (Exception e) {
251 String msg = getString(R.string.unzippingFailed, dest + ": " + e.getMessage());
252 File dir = application.getDictDir();
253 if (!dir.canWrite() || !DictionaryApplication.checkFileCreate(dir)) {
254 msg = getString(R.string.notWritable, dir.getAbsolutePath());
256 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
257 Log.e(LOG, "Failed to unzip.", e);
260 if (zipOut != null) zipOut.close();
261 } catch (IOException e) {}
263 if (zipFile != null) zipFile.close();
264 } catch (IOException e) {}
266 if (zipFileStream != null) zipFileStream.close();
267 } catch (IOException e) {}
268 if (localZipFile != null && delete) localZipFile.delete();
273 public static Intent getLaunchIntent(Context c) {
274 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
275 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
279 private void readableCheckAndError(boolean requestPermission) {
280 final File dictDir = application.getDictDir();
281 if (dictDir.canRead() && dictDir.canExecute()) return;
282 blockAutoLaunch = true;
283 if (requestPermission &&
284 ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
285 ActivityCompat.requestPermissions(this,
286 new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
287 Manifest.permission.WRITE_EXTERNAL_STORAGE
291 blockAutoLaunch = true;
293 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
294 builder.setTitle(getString(R.string.error));
295 builder.setMessage(getString(
296 R.string.unableToReadDictionaryDir,
297 dictDir.getAbsolutePath(),
298 Environment.getExternalStorageDirectory()));
299 builder.setNeutralButton("Close", null);
300 builder.create().show();
304 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
305 readableCheckAndError(false);
307 application.backgroundUpdateDictionaries(dictionaryUpdater);
313 public void onCreate(Bundle savedInstanceState) {
314 DictionaryApplication.INSTANCE.init(getApplicationContext());
315 application = DictionaryApplication.INSTANCE;
316 // This must be first, otherwise the action bar doesn't get
318 setTheme(application.getSelectedTheme().themeId);
320 super.onCreate(savedInstanceState);
321 Log.d(LOG, "onCreate:" + this);
323 setTheme(application.getSelectedTheme().themeId);
325 blockAutoLaunch = false;
328 setContentView(R.layout.dictionary_manager_activity);
330 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
331 getListView().getContext()).inflate(
332 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
334 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
335 getListView().getContext()).inflate(
336 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
338 showDownloadable = downloadableDictionariesHeaderRow
339 .findViewById(R.id.hideDownloadable);
340 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
342 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
343 onShowDownloadableChanged();
347 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
348 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
349 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
350 thanksForUpdatingLatestVersion)) {
351 blockAutoLaunch = true;
352 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
353 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
356 IntentFilter downloadManagerIntents = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
357 downloadManagerIntents.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
358 registerReceiver(broadcastReceiver, downloadManagerIntents);
361 registerForContextMenu(getListView());
362 getListView().setItemsCanFocus(true);
364 readableCheckAndError(true);
366 onCreateSetupActionBar();
368 final Intent intent = getIntent();
369 if (intent != null && intent.getAction() != null &&
370 intent.getAction().equals(Intent.ACTION_VIEW)) {
371 blockAutoLaunch = true;
372 Uri uri = intent.getData();
373 unzipInstall(this, uri, uri.getLastPathSegment(), false);
377 private void onCreateSetupActionBar() {
378 ActionBar actionBar = getSupportActionBar();
379 actionBar.setDisplayShowTitleEnabled(false);
380 actionBar.setDisplayShowHomeEnabled(false);
381 actionBar.setDisplayHomeAsUpEnabled(false);
383 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
384 filterSearchView.setIconifiedByDefault(false);
385 // filterSearchView.setIconified(false); // puts the magnifying glass in
388 filterSearchView.setQueryHint(getString(R.string.searchText));
389 filterSearchView.setSubmitButtonEnabled(false);
390 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
391 FrameLayout.LayoutParams.WRAP_CONTENT);
392 filterSearchView.setLayoutParams(lp);
393 filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT);
394 filterSearchView.setImeOptions(
395 EditorInfo.IME_ACTION_DONE |
396 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
397 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
399 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
401 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
403 public boolean onQueryTextSubmit(String query) {
404 filterSearchView.clearFocus();
409 public boolean onQueryTextChange(String filterText) {
414 filterSearchView.setFocusable(true);
416 actionBar.setCustomView(filterSearchView);
417 actionBar.setDisplayShowCustomEnabled(true);
419 // Avoid wasting space on large left inset
420 Toolbar tb = (Toolbar)filterSearchView.getParent();
421 tb.setContentInsetsRelative(0, 0);
425 public void onDestroy() {
427 unregisterReceiver(broadcastReceiver);
430 private static void copyStream(final InputStream ins, final FileOutputStream outs)
432 ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 64);
433 FileChannel out = outs.getChannel();
436 final byte[] bytes = new byte[1024 * 64];
438 bytesRead = ins.read(bytes, pos, bytes.length - pos);
439 if (bytesRead != -1) pos += bytesRead;
440 if (bytesRead == -1 ? pos != 0 : 2*pos >= bytes.length) {
441 buf.put(bytes, 0, pos);
444 while (buf.hasRemaining()) out.write(buf);
447 } while (bytesRead != -1);
451 protected void onStart() {
453 uiHandler = new Handler();
457 protected void onStop() {
463 protected void onResume() {
466 if (PreferenceActivity.prefsMightHaveChanged) {
467 PreferenceActivity.prefsMightHaveChanged = false;
469 startActivity(getIntent());
472 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
473 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
475 if (!blockAutoLaunch &&
476 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
477 prefs.contains(C.DICT_FILE) &&
478 prefs.contains(C.INDEX_SHORT_NAME)) {
479 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
480 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
481 new File(prefs.getString(C.DICT_FILE, "")),
482 prefs.getString(C.INDEX_SHORT_NAME, ""),
488 // Remove the active dictionary from the prefs so we won't autolaunch
490 prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
492 application.backgroundUpdateDictionaries(dictionaryUpdater);
498 public boolean onCreateOptionsMenu(final Menu menu) {
499 if ("true".equals(Settings.System.getString(getContentResolver(), "firebase.test.lab")))
501 return false; // testing the menu is not very interesting
503 final MenuItem sort = menu.add(getString(R.string.sortDicts));
504 MenuItemCompat.setShowAsAction(sort, MenuItem.SHOW_AS_ACTION_NEVER);
505 sort.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
506 public boolean onMenuItemClick(final MenuItem menuItem) {
507 application.sortDictionaries();
513 final MenuItem browserDownload = menu.add(getString(R.string.browserDownload));
514 MenuItemCompat.setShowAsAction(browserDownload, MenuItem.SHOW_AS_ACTION_NEVER);
515 browserDownload.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
516 public boolean onMenuItemClick(final MenuItem menuItem) {
517 final Intent intent = new Intent(Intent.ACTION_VIEW);
519 .parse("https://github.com/rdoeffinger/Dictionary/releases/v0.2-dictionaries"));
520 startActivity(intent);
525 DictionaryApplication.onCreateGlobalOptionsMenu(this, menu);
530 public void onCreateContextMenu(final ContextMenu menu, final View view,
531 final ContextMenuInfo menuInfo) {
532 super.onCreateContextMenu(menu, view, menuInfo);
533 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
535 final AdapterContextMenuInfo adapterContextMenuInfo =
536 (AdapterContextMenuInfo) menuInfo;
537 final int position = adapterContextMenuInfo.position;
538 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
540 if (row.dictionaryInfo == null) {
544 if (position > 0 && row.onDevice) {
545 final android.view.MenuItem moveToTopMenuItem =
546 menu.add(R.string.moveToTop);
547 moveToTopMenuItem.setOnMenuItemClickListener(new
548 android.view.MenuItem.OnMenuItemClickListener() {
550 public boolean onMenuItemClick(android.view.MenuItem item) {
551 application.moveDictionaryToTop(row.dictionaryInfo);
559 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
561 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
563 public boolean onMenuItemClick(android.view.MenuItem item) {
564 application.deleteDictionary(row.dictionaryInfo);
572 private void onShowDownloadableChanged() {
574 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
575 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
579 class MyListAdapter extends BaseAdapter {
581 final List<DictionaryInfo> dictionariesOnDevice;
582 final List<DictionaryInfo> downloadableDictionaries;
585 final DictionaryInfo dictionaryInfo;
586 final boolean onDevice;
588 private Row(DictionaryInfo dictionaryInfo, boolean onDevice) {
589 this.dictionaryInfo = dictionaryInfo;
590 this.onDevice = onDevice;
594 private MyListAdapter(final String[] filters) {
595 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
596 if (showDownloadable.isChecked()) {
597 downloadableDictionaries = application.getDownloadableDictionaries(filters);
599 downloadableDictionaries = Collections.emptyList();
604 public int getCount() {
605 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
609 public Row getItem(int position) {
611 return new Row(null, true);
615 if (position < dictionariesOnDevice.size()) {
616 return new Row(dictionariesOnDevice.get(position), true);
618 position -= dictionariesOnDevice.size();
621 return new Row(null, false);
625 assert position < downloadableDictionaries.size();
626 return new Row(downloadableDictionaries.get(position), false);
630 public long getItemId(int position) {
635 public int getViewTypeCount() {
640 public int getItemViewType(int position) {
641 final Row row = getItem(position);
642 if (row.dictionaryInfo == null) {
643 return row.onDevice ? 0 : 1;
645 assert row.dictionaryInfo.indexInfos.size() <= 2;
650 public View getView(int position, View convertView, ViewGroup parent) {
651 if (convertView == dictionariesOnDeviceHeaderRow ||
652 convertView == downloadableDictionariesHeaderRow) {
656 final Row row = getItem(position);
658 if (row.dictionaryInfo == null) {
659 assert convertView == null;
660 return row.onDevice ? dictionariesOnDeviceHeaderRow : downloadableDictionariesHeaderRow;
662 return createDictionaryRow(row.dictionaryInfo, parent, convertView, row.onDevice);
667 private void setMyListAdapter() {
668 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
670 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
671 setListAdapter(new MyListAdapter(filters));
674 private boolean isDownloadActive(String downloadUrl, boolean cancel) {
675 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
676 final DownloadManager.Query query = new DownloadManager.Query();
677 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
678 final Cursor cursor = downloadManager.query(query);
680 // Due to a bug, cursor is null instead of empty when
681 // the download manager is disabled.
682 if (cursor == null) {
684 String msg = getString(R.string.downloadManagerQueryFailed);
685 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
686 .setMessage(getString(R.string.downloadFailed, msg))
687 .setNeutralButton("Close", null).show();
694 destFile = new File(new URL(downloadUrl).getPath()).getName();
695 } catch (MalformedURLException e) {
696 throw new RuntimeException("Invalid download URL!", e);
698 while (cursor.moveToNext()) {
699 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
701 if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE))))
704 boolean active = !cursor.isAfterLast();
705 if (active && cancel) {
706 long downloadId = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
707 finishedDownloadIds.add(downloadId);
708 downloadManager.remove(downloadId);
714 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
715 final ViewGroup parent, View row, boolean canLaunch) {
718 row = LayoutInflater.from(parent.getContext()).inflate(
719 R.layout.dictionary_manager_row, parent, false);
721 final TextView name = row.findViewById(R.id.dictionaryName);
722 final TextView details = row.findViewById(R.id.dictionaryDetails);
723 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
725 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
726 final Button downloadButton = row.findViewById(R.id.downloadButton);
727 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
728 boolean broken = false;
729 if (!dictionaryInfo.isValid()) {
733 if (downloadable != null && (!canLaunch || updateAvailable)) {
736 R.string.downloadButton,
737 downloadable.zipBytes / 1024.0 / 1024.0));
738 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
739 downloadButton.setOnClickListener(new OnClickListener() {
741 public void onClick(View arg0) {
742 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
745 downloadButton.setVisibility(View.VISIBLE);
747 if (isDownloadActive(downloadable.downloadUrl, false))
748 downloadButton.setText("X");
750 downloadButton.setVisibility(View.GONE);
753 LinearLayout buttons = row.findViewById(R.id.dictionaryLauncherButtons);
755 final List<IndexInfo> sortedIndexInfos = application
756 .sortedIndexInfos(dictionaryInfo.indexInfos);
757 final StringBuilder builder = new StringBuilder();
758 if (updateAvailable) {
759 builder.append(getString(R.string.updateAvailable));
761 assert buttons.getChildCount() == 4;
762 for (int i = 0; i < 2; i++) {
763 final Button textButton = (Button)buttons.getChildAt(2*i);
764 final ImageButton imageButton = (ImageButton)buttons.getChildAt(2*i + 1);
765 if (i >= sortedIndexInfos.size()) {
766 textButton.setVisibility(View.GONE);
767 imageButton.setVisibility(View.GONE);
770 final IndexInfo indexInfo = sortedIndexInfos.get(i);
771 final View button = IsoUtils.INSTANCE.setupButton(textButton, imageButton,
775 button.setOnClickListener(
776 new IntentLauncher(buttons.getContext(),
777 DictionaryActivity.getLaunchIntent(getApplicationContext(),
778 application.getPath(dictionaryInfo.uncompressedFilename),
779 indexInfo.shortName, "")));
782 button.setEnabled(canLaunch);
783 button.setFocusable(canLaunch);
784 if (builder.length() != 0) {
785 builder.append("; ");
787 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
788 indexInfo.mainTokenCount));
790 builder.append("; ");
791 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
793 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
794 builder.append("; Cannot be used, redownload, check hardware/file system");
796 details.setText(builder.toString());
799 row.setOnClickListener(new IntentLauncher(parent.getContext(),
800 DictionaryActivity.getLaunchIntent(getApplicationContext(),
801 application.getPath(dictionaryInfo.uncompressedFilename),
802 dictionaryInfo.indexInfos.get(0).shortName, "")));
803 // do not setFocusable, for keyboard navigation
804 // offering only the index buttons is better.
806 row.setClickable(canLaunch);
807 // Allow deleting, even if we cannot open
808 row.setLongClickable(broken || canLaunch);
809 row.setBackgroundResource(android.R.drawable.menuitem_background);
814 private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
815 if (isDownloadActive(downloadUrl, true)) {
818 R.string.downloadButton,
819 bytes / 1024.0 / 1024.0));
822 Request request = new Request(
823 Uri.parse(downloadUrl));
827 destFile = new File(new URL(downloadUrl).getPath()).getName();
828 } catch (MalformedURLException e) {
829 throw new RuntimeException("Invalid download URL!", e);
831 Log.d(LOG, "Downloading to: " + destFile);
832 request.setTitle(destFile);
833 File destFilePath = new File(application.getDictDir(), destFile);
834 destFilePath.delete();
836 request.setDestinationUri(Uri.fromFile(destFilePath));
837 } catch (Exception e) {
840 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
843 downloadManager.enqueue(request);
844 } catch (SecurityException e) {
845 request = new Request(Uri.parse(downloadUrl));
846 request.setTitle(destFile);
847 downloadManager.enqueue(request);
849 Log.w(LOG, "Download started: " + destFile);
850 downloadButton.setText("X");