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));
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 ignored) {}
263 if (zipFile != null) zipFile.close();
264 } catch (IOException ignored) {}
266 if (zipFileStream != null) zipFileStream.close();
267 } catch (IOException ignored) {}
268 if (localZipFile != null && delete) //noinspection ResultOfMethodCallIgnored
269 localZipFile.delete();
274 public static Intent getLaunchIntent(Context c) {
275 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
276 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
280 private void readableCheckAndError(boolean requestPermission) {
281 final File dictDir = application.getDictDir();
282 if (dictDir.canRead() && dictDir.canExecute()) return;
283 blockAutoLaunch = true;
284 if (requestPermission &&
285 ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
286 ActivityCompat.requestPermissions(this,
287 new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
288 Manifest.permission.WRITE_EXTERNAL_STORAGE
292 blockAutoLaunch = true;
294 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
295 builder.setTitle(getString(R.string.error));
296 builder.setMessage(getString(
297 R.string.unableToReadDictionaryDir,
298 dictDir.getAbsolutePath(),
299 Environment.getExternalStorageDirectory()));
300 builder.setNeutralButton("Close", null);
301 builder.create().show();
305 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
306 readableCheckAndError(false);
308 application.backgroundUpdateDictionaries(dictionaryUpdater);
314 public void onCreate(Bundle savedInstanceState) {
315 DictionaryApplication.INSTANCE.init(getApplicationContext());
316 application = DictionaryApplication.INSTANCE;
317 // This must be first, otherwise the action bar doesn't get
319 setTheme(application.getSelectedTheme().themeId);
321 super.onCreate(savedInstanceState);
322 Log.d(LOG, "onCreate:" + this);
324 setTheme(application.getSelectedTheme().themeId);
326 blockAutoLaunch = false;
329 setContentView(R.layout.dictionary_manager_activity);
331 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
332 getListView().getContext()).inflate(
333 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
335 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
336 getListView().getContext()).inflate(
337 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
339 showDownloadable = downloadableDictionariesHeaderRow
340 .findViewById(R.id.hideDownloadable);
341 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
343 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
344 onShowDownloadableChanged();
348 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
349 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
350 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
351 thanksForUpdatingLatestVersion)) {
352 blockAutoLaunch = true;
353 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
354 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
357 IntentFilter downloadManagerIntents = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
358 downloadManagerIntents.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
359 registerReceiver(broadcastReceiver, downloadManagerIntents);
362 registerForContextMenu(getListView());
363 getListView().setItemsCanFocus(true);
365 readableCheckAndError(true);
367 onCreateSetupActionBar();
369 final Intent intent = getIntent();
370 if (intent != null && intent.getAction() != null &&
371 intent.getAction().equals(Intent.ACTION_VIEW)) {
372 blockAutoLaunch = true;
373 Uri uri = intent.getData();
374 unzipInstall(this, uri, uri.getLastPathSegment(), false);
378 private void onCreateSetupActionBar() {
379 ActionBar actionBar = getSupportActionBar();
380 actionBar.setDisplayShowTitleEnabled(false);
381 actionBar.setDisplayShowHomeEnabled(false);
382 actionBar.setDisplayHomeAsUpEnabled(false);
384 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
385 filterSearchView.setIconifiedByDefault(false);
386 // filterSearchView.setIconified(false); // puts the magnifying glass in
389 filterSearchView.setQueryHint(getString(R.string.searchText));
390 filterSearchView.setSubmitButtonEnabled(false);
391 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
392 FrameLayout.LayoutParams.WRAP_CONTENT);
393 filterSearchView.setLayoutParams(lp);
394 filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT);
395 filterSearchView.setImeOptions(
396 EditorInfo.IME_ACTION_DONE |
397 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
398 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
400 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
402 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
404 public boolean onQueryTextSubmit(String query) {
405 filterSearchView.clearFocus();
410 public boolean onQueryTextChange(String filterText) {
415 filterSearchView.setFocusable(true);
417 actionBar.setCustomView(filterSearchView);
418 actionBar.setDisplayShowCustomEnabled(true);
420 // Avoid wasting space on large left inset
421 Toolbar tb = (Toolbar)filterSearchView.getParent();
422 tb.setContentInsetsRelative(0, 0);
426 public void onDestroy() {
428 unregisterReceiver(broadcastReceiver);
431 private static void copyStream(final InputStream ins, final FileOutputStream outs)
433 ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 64);
434 FileChannel out = outs.getChannel();
437 final byte[] bytes = new byte[1024 * 64];
439 bytesRead = ins.read(bytes, pos, bytes.length - pos);
440 if (bytesRead != -1) pos += bytesRead;
441 if (bytesRead == -1 ? pos != 0 : 2*pos >= bytes.length) {
442 buf.put(bytes, 0, pos);
445 while (buf.hasRemaining()) out.write(buf);
448 } while (bytesRead != -1);
452 protected void onStart() {
454 uiHandler = new Handler();
458 protected void onStop() {
464 protected void onResume() {
467 if (PreferenceActivity.prefsMightHaveChanged) {
468 PreferenceActivity.prefsMightHaveChanged = false;
470 startActivity(getIntent());
473 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
474 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
476 if (!blockAutoLaunch &&
477 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
478 prefs.contains(C.DICT_FILE) &&
479 prefs.contains(C.INDEX_SHORT_NAME)) {
480 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
481 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
482 new File(prefs.getString(C.DICT_FILE, "")),
483 prefs.getString(C.INDEX_SHORT_NAME, ""),
489 // Remove the active dictionary from the prefs so we won't autolaunch
491 prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
493 application.backgroundUpdateDictionaries(dictionaryUpdater);
499 public boolean onCreateOptionsMenu(final Menu menu) {
500 if ("true".equals(Settings.System.getString(getContentResolver(), "firebase.test.lab")))
502 return false; // testing the menu is not very interesting
504 final MenuItem sort = menu.add(getString(R.string.sortDicts));
505 MenuItemCompat.setShowAsAction(sort, MenuItem.SHOW_AS_ACTION_NEVER);
506 sort.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
507 public boolean onMenuItemClick(final MenuItem menuItem) {
508 application.sortDictionaries();
514 final MenuItem browserDownload = menu.add(getString(R.string.browserDownload));
515 MenuItemCompat.setShowAsAction(browserDownload, MenuItem.SHOW_AS_ACTION_NEVER);
516 browserDownload.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
517 public boolean onMenuItemClick(final MenuItem menuItem) {
518 final Intent intent = new Intent(Intent.ACTION_VIEW);
520 .parse("https://github.com/rdoeffinger/Dictionary/releases/v0.2-dictionaries"));
521 startActivity(intent);
526 DictionaryApplication.onCreateGlobalOptionsMenu(this, menu);
531 public void onCreateContextMenu(final ContextMenu menu, final View view,
532 final ContextMenuInfo menuInfo) {
533 super.onCreateContextMenu(menu, view, menuInfo);
534 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
536 final AdapterContextMenuInfo adapterContextMenuInfo =
537 (AdapterContextMenuInfo) menuInfo;
538 final int position = adapterContextMenuInfo.position;
539 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
541 if (row.dictionaryInfo == null) {
545 if (position > 0 && row.onDevice) {
546 final android.view.MenuItem moveToTopMenuItem =
547 menu.add(R.string.moveToTop);
548 moveToTopMenuItem.setOnMenuItemClickListener(new
549 android.view.MenuItem.OnMenuItemClickListener() {
551 public boolean onMenuItemClick(android.view.MenuItem item) {
552 application.moveDictionaryToTop(row.dictionaryInfo);
560 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
562 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
564 public boolean onMenuItemClick(android.view.MenuItem item) {
565 application.deleteDictionary(row.dictionaryInfo);
573 private void onShowDownloadableChanged() {
575 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
576 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
580 class MyListAdapter extends BaseAdapter {
582 final List<DictionaryInfo> dictionariesOnDevice;
583 final List<DictionaryInfo> downloadableDictionaries;
586 final DictionaryInfo dictionaryInfo;
587 final boolean onDevice;
589 private Row(DictionaryInfo dictionaryInfo, boolean onDevice) {
590 this.dictionaryInfo = dictionaryInfo;
591 this.onDevice = onDevice;
595 private MyListAdapter(final String[] filters) {
596 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
597 if (showDownloadable.isChecked()) {
598 downloadableDictionaries = application.getDownloadableDictionaries(filters);
600 downloadableDictionaries = Collections.emptyList();
605 public int getCount() {
606 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
610 public Row getItem(int position) {
612 return new Row(null, true);
616 if (position < dictionariesOnDevice.size()) {
617 return new Row(dictionariesOnDevice.get(position), true);
619 position -= dictionariesOnDevice.size();
622 return new Row(null, false);
626 assert position < downloadableDictionaries.size();
627 return new Row(downloadableDictionaries.get(position), false);
631 public long getItemId(int position) {
636 public int getViewTypeCount() {
641 public int getItemViewType(int position) {
642 final Row row = getItem(position);
643 if (row.dictionaryInfo == null) {
644 return row.onDevice ? 0 : 1;
646 assert row.dictionaryInfo.indexInfos.size() <= 2;
651 public View getView(int position, View convertView, ViewGroup parent) {
652 if (convertView == dictionariesOnDeviceHeaderRow ||
653 convertView == downloadableDictionariesHeaderRow) {
657 final Row row = getItem(position);
659 if (row.dictionaryInfo == null) {
660 assert convertView == null;
661 return row.onDevice ? dictionariesOnDeviceHeaderRow : downloadableDictionariesHeaderRow;
663 return createDictionaryRow(row.dictionaryInfo, parent, convertView, row.onDevice);
668 private void setMyListAdapter() {
669 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
671 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
672 setListAdapter(new MyListAdapter(filters));
675 private boolean isDownloadActive(String downloadUrl, boolean cancel) {
676 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
677 final DownloadManager.Query query = new DownloadManager.Query();
678 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
679 final Cursor cursor = downloadManager.query(query);
681 // Due to a bug, cursor is null instead of empty when
682 // the download manager is disabled.
683 if (cursor == null) {
685 String msg = getString(R.string.downloadManagerQueryFailed);
686 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
687 .setMessage(getString(R.string.downloadFailed, msg))
688 .setNeutralButton("Close", null).show();
695 destFile = new File(new URL(downloadUrl).getPath()).getName();
696 } catch (MalformedURLException e) {
697 throw new RuntimeException("Invalid download URL!", e);
699 while (cursor.moveToNext()) {
700 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
702 if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE))))
705 boolean active = !cursor.isAfterLast();
706 if (active && cancel) {
707 long downloadId = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
708 finishedDownloadIds.add(downloadId);
709 downloadManager.remove(downloadId);
715 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
716 final ViewGroup parent, View row, boolean canLaunch) {
719 row = LayoutInflater.from(parent.getContext()).inflate(
720 R.layout.dictionary_manager_row, parent, false);
722 final TextView name = row.findViewById(R.id.dictionaryName);
723 final TextView details = row.findViewById(R.id.dictionaryDetails);
724 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
726 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
727 final Button downloadButton = row.findViewById(R.id.downloadButton);
728 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
729 boolean broken = false;
730 if (!dictionaryInfo.isValid()) {
734 if (downloadable != null && (!canLaunch || updateAvailable)) {
737 R.string.downloadButton,
738 downloadable.zipBytes / 1024.0 / 1024.0));
739 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
740 downloadButton.setOnClickListener(new OnClickListener() {
742 public void onClick(View arg0) {
743 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
746 downloadButton.setVisibility(View.VISIBLE);
748 if (isDownloadActive(downloadable.downloadUrl, false))
749 downloadButton.setText("X");
751 downloadButton.setVisibility(View.GONE);
754 LinearLayout buttons = row.findViewById(R.id.dictionaryLauncherButtons);
756 final List<IndexInfo> sortedIndexInfos = application
757 .sortedIndexInfos(dictionaryInfo.indexInfos);
758 final StringBuilder builder = new StringBuilder();
759 if (updateAvailable) {
760 builder.append(getString(R.string.updateAvailable));
762 assert buttons.getChildCount() == 4;
763 for (int i = 0; i < 2; i++) {
764 final Button textButton = (Button)buttons.getChildAt(2*i);
765 final ImageButton imageButton = (ImageButton)buttons.getChildAt(2*i + 1);
766 if (i >= sortedIndexInfos.size()) {
767 textButton.setVisibility(View.GONE);
768 imageButton.setVisibility(View.GONE);
771 final IndexInfo indexInfo = sortedIndexInfos.get(i);
772 final View button = IsoUtils.INSTANCE.setupButton(textButton, imageButton,
776 button.setOnClickListener(
777 new IntentLauncher(buttons.getContext(),
778 DictionaryActivity.getLaunchIntent(getApplicationContext(),
779 application.getPath(dictionaryInfo.uncompressedFilename),
780 indexInfo.shortName, "")));
783 button.setEnabled(canLaunch);
784 button.setFocusable(canLaunch);
785 if (builder.length() != 0) {
786 builder.append("; ");
788 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
789 indexInfo.mainTokenCount));
791 builder.append("; ");
792 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
794 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
795 builder.append("; Cannot be used, redownload, check hardware/file system");
797 details.setText(builder.toString());
800 row.setOnClickListener(new IntentLauncher(parent.getContext(),
801 DictionaryActivity.getLaunchIntent(getApplicationContext(),
802 application.getPath(dictionaryInfo.uncompressedFilename),
803 dictionaryInfo.indexInfos.get(0).shortName, "")));
804 // do not setFocusable, for keyboard navigation
805 // offering only the index buttons is better.
807 row.setClickable(canLaunch);
808 // Allow deleting, even if we cannot open
809 row.setLongClickable(broken || canLaunch);
810 row.setBackgroundResource(android.R.drawable.menuitem_background);
815 private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
816 if (isDownloadActive(downloadUrl, true)) {
819 R.string.downloadButton,
820 bytes / 1024.0 / 1024.0));
823 Request request = new Request(
824 Uri.parse(downloadUrl));
828 destFile = new File(new URL(downloadUrl).getPath()).getName();
829 } catch (MalformedURLException e) {
830 throw new RuntimeException("Invalid download URL!", e);
832 Log.d(LOG, "Downloading to: " + destFile);
833 request.setTitle(destFile);
834 File destFilePath = new File(application.getDictDir(), destFile);
835 destFilePath.delete();
837 request.setDestinationUri(Uri.fromFile(destFilePath));
838 } catch (Exception e) {
841 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
843 if (downloadManager == null) {
844 String msg = getString(R.string.downloadManagerQueryFailed);
845 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
846 .setMessage(getString(R.string.downloadFailed, msg))
847 .setNeutralButton("Close", null).show();
852 downloadManager.enqueue(request);
853 } catch (SecurityException e) {
854 request = new Request(Uri.parse(downloadUrl));
855 request.setTitle(destFile);
856 downloadManager.enqueue(request);
858 Log.w(LOG, "Download started: " + destFile);
859 downloadButton.setText("X");