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_NOTIFICATION_CLICKED.equals(action)) {
145 startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP));
147 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
148 final long downloadId = intent.getLongExtra(
149 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
150 if (finishedDownloadIds.contains(downloadId)) return; // ignore double notifications
151 final DownloadManager.Query query = new DownloadManager.Query();
152 query.setFilterById(downloadId);
153 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
154 final Cursor cursor = downloadManager.query(query);
156 if (cursor == null || !cursor.moveToFirst()) {
157 Log.e(LOG, "Couldn't find download.");
161 final String dest = cursor
162 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
163 final int status = cursor
165 .getColumnIndex(DownloadManager.COLUMN_STATUS));
166 if (DownloadManager.STATUS_SUCCESSFUL != status) {
167 final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
169 "Download failed: status=" + status +
170 ", reason=" + reason);
171 String msg = Integer.toString(reason);
173 case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
176 case DownloadManager.ERROR_FILE_ERROR:
179 case DownloadManager.ERROR_INSUFFICIENT_SPACE:
180 msg = "Not enough space";
183 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, msg)).setNeutralButton("Close", null).show();
187 Log.w(LOG, "Download finished: " + dest + " Id: " + downloadId);
189 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
190 Toast.LENGTH_LONG).show();
192 if (unzipInstall(context, Uri.parse(dest), dest, true)) {
193 finishedDownloadIds.add(downloadId);
194 Log.w(LOG, "Unzipping finished: " + dest + " Id: " + downloadId);
200 private boolean unzipInstall(Context context, Uri zipUri, String dest, boolean delete) {
201 File localZipFile = null;
202 InputStream zipFileStream = null;
203 ZipInputStream zipFile = null;
204 FileOutputStream zipOut = null;
205 boolean result = false;
207 if (zipUri.getScheme().equals("content")) {
208 zipFileStream = context.getContentResolver().openInputStream(zipUri);
211 localZipFile = new File(zipUri.getPath());
213 zipFileStream = new FileInputStream(localZipFile);
214 } catch (Exception e) {
215 if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
216 ActivityCompat.requestPermissions(this,
217 new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
218 Manifest.permission.WRITE_EXTERNAL_STORAGE
225 zipFile = new ZipInputStream(new BufferedInputStream(zipFileStream));
226 final ZipEntry zipEntry = zipFile.getNextEntry();
227 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
228 File targetFile = new File(application.getDictDir(), zipEntry.getName());
229 if (targetFile.exists()) {
230 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
231 targetFile = new File(application.getDictDir(), zipEntry.getName());
233 zipOut = new FileOutputStream(targetFile);
234 copyStream(zipFile, zipOut);
235 application.backgroundUpdateDictionaries(dictionaryUpdater);
237 Toast.makeText(context, getString(R.string.installationFinished, dest),
238 Toast.LENGTH_LONG).show();
240 } catch (Exception e) {
241 String msg = getString(R.string.unzippingFailed, dest + ": " + e.getMessage());
242 File dir = application.getDictDir();
243 if (!dir.canWrite() || !DictionaryApplication.checkFileCreate(dir)) {
244 msg = getString(R.string.notWritable, dir.getAbsolutePath());
246 new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
247 Log.e(LOG, "Failed to unzip.", e);
250 if (zipOut != null) zipOut.close();
251 } catch (IOException e) {}
253 if (zipFile != null) zipFile.close();
254 } catch (IOException e) {}
256 if (zipFileStream != null) zipFileStream.close();
257 } catch (IOException e) {}
258 if (localZipFile != null && delete) localZipFile.delete();
263 public static Intent getLaunchIntent(Context c) {
264 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
265 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
269 private void readableCheckAndError(boolean requestPermission) {
270 final File dictDir = application.getDictDir();
271 if (dictDir.canRead() && dictDir.canExecute()) return;
272 blockAutoLaunch = true;
273 if (requestPermission &&
274 ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
275 ActivityCompat.requestPermissions(this,
276 new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
277 Manifest.permission.WRITE_EXTERNAL_STORAGE
281 blockAutoLaunch = true;
283 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
284 builder.setTitle(getString(R.string.error));
285 builder.setMessage(getString(
286 R.string.unableToReadDictionaryDir,
287 dictDir.getAbsolutePath(),
288 Environment.getExternalStorageDirectory()));
289 builder.setNeutralButton("Close", null);
290 builder.create().show();
294 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
295 readableCheckAndError(false);
297 application.backgroundUpdateDictionaries(dictionaryUpdater);
303 public void onCreate(Bundle savedInstanceState) {
304 DictionaryApplication.INSTANCE.init(getApplicationContext());
305 application = DictionaryApplication.INSTANCE;
306 // This must be first, otherwise the action bar doesn't get
308 setTheme(application.getSelectedTheme().themeId);
310 super.onCreate(savedInstanceState);
311 Log.d(LOG, "onCreate:" + this);
313 setTheme(application.getSelectedTheme().themeId);
315 blockAutoLaunch = false;
318 setContentView(R.layout.dictionary_manager_activity);
320 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
321 getListView().getContext()).inflate(
322 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
324 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
325 getListView().getContext()).inflate(
326 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
328 showDownloadable = downloadableDictionariesHeaderRow
329 .findViewById(R.id.hideDownloadable);
330 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
332 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
333 onShowDownloadableChanged();
337 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
338 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
339 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
340 thanksForUpdatingLatestVersion)) {
341 blockAutoLaunch = true;
342 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
343 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
346 IntentFilter downloadManagerIntents = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
347 downloadManagerIntents.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
348 registerReceiver(broadcastReceiver, downloadManagerIntents);
351 registerForContextMenu(getListView());
352 getListView().setItemsCanFocus(true);
354 readableCheckAndError(true);
356 onCreateSetupActionBar();
358 final Intent intent = getIntent();
359 if (intent != null && intent.getAction() != null &&
360 intent.getAction().equals(Intent.ACTION_VIEW)) {
361 blockAutoLaunch = true;
362 Uri uri = intent.getData();
363 unzipInstall(this, uri, uri.getLastPathSegment(), false);
367 private void onCreateSetupActionBar() {
368 ActionBar actionBar = getSupportActionBar();
369 actionBar.setDisplayShowTitleEnabled(false);
370 actionBar.setDisplayShowHomeEnabled(false);
371 actionBar.setDisplayHomeAsUpEnabled(false);
373 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
374 filterSearchView.setIconifiedByDefault(false);
375 // filterSearchView.setIconified(false); // puts the magnifying glass in
378 filterSearchView.setQueryHint(getString(R.string.searchText));
379 filterSearchView.setSubmitButtonEnabled(false);
380 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
381 FrameLayout.LayoutParams.WRAP_CONTENT);
382 filterSearchView.setLayoutParams(lp);
383 filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT);
384 filterSearchView.setImeOptions(
385 EditorInfo.IME_ACTION_DONE |
386 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
387 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
389 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
391 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
393 public boolean onQueryTextSubmit(String query) {
394 filterSearchView.clearFocus();
399 public boolean onQueryTextChange(String filterText) {
404 filterSearchView.setFocusable(true);
406 actionBar.setCustomView(filterSearchView);
407 actionBar.setDisplayShowCustomEnabled(true);
409 // Avoid wasting space on large left inset
410 Toolbar tb = (Toolbar)filterSearchView.getParent();
411 tb.setContentInsetsRelative(0, 0);
415 public void onDestroy() {
417 unregisterReceiver(broadcastReceiver);
420 private static void copyStream(final InputStream ins, final FileOutputStream outs)
422 ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 64);
423 FileChannel out = outs.getChannel();
426 final byte[] bytes = new byte[1024 * 64];
428 bytesRead = ins.read(bytes, pos, bytes.length - pos);
429 if (bytesRead != -1) pos += bytesRead;
430 if (bytesRead == -1 ? pos != 0 : 2*pos >= bytes.length) {
431 buf.put(bytes, 0, pos);
434 while (buf.hasRemaining()) out.write(buf);
437 } while (bytesRead != -1);
441 protected void onStart() {
443 uiHandler = new Handler();
447 protected void onStop() {
453 protected void onResume() {
456 if (PreferenceActivity.prefsMightHaveChanged) {
457 PreferenceActivity.prefsMightHaveChanged = false;
459 startActivity(getIntent());
462 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
463 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
465 if (!blockAutoLaunch &&
466 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
467 prefs.contains(C.DICT_FILE) &&
468 prefs.contains(C.INDEX_SHORT_NAME)) {
469 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
470 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
471 new File(prefs.getString(C.DICT_FILE, "")),
472 prefs.getString(C.INDEX_SHORT_NAME, ""),
478 // Remove the active dictionary from the prefs so we won't autolaunch
480 prefs.edit().remove(C.DICT_FILE).remove(C.INDEX_SHORT_NAME).commit();
482 application.backgroundUpdateDictionaries(dictionaryUpdater);
488 public boolean onCreateOptionsMenu(final Menu menu) {
489 if ("true".equals(Settings.System.getString(getContentResolver(), "firebase.test.lab")))
491 return false; // testing the menu is not very interesting
493 final MenuItem sort = menu.add(getString(R.string.sortDicts));
494 MenuItemCompat.setShowAsAction(sort, MenuItem.SHOW_AS_ACTION_NEVER);
495 sort.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
496 public boolean onMenuItemClick(final MenuItem menuItem) {
497 application.sortDictionaries();
503 final MenuItem browserDownload = menu.add(getString(R.string.browserDownload));
504 MenuItemCompat.setShowAsAction(browserDownload, MenuItem.SHOW_AS_ACTION_NEVER);
505 browserDownload.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
506 public boolean onMenuItemClick(final MenuItem menuItem) {
507 final Intent intent = new Intent(Intent.ACTION_VIEW);
509 .parse("https://github.com/rdoeffinger/Dictionary/releases/v0.2-dictionaries"));
510 startActivity(intent);
515 DictionaryApplication.onCreateGlobalOptionsMenu(this, menu);
520 public void onCreateContextMenu(final ContextMenu menu, final View view,
521 final ContextMenuInfo menuInfo) {
522 super.onCreateContextMenu(menu, view, menuInfo);
523 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
525 final AdapterContextMenuInfo adapterContextMenuInfo =
526 (AdapterContextMenuInfo) menuInfo;
527 final int position = adapterContextMenuInfo.position;
528 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
530 if (row.dictionaryInfo == null) {
534 if (position > 0 && row.onDevice) {
535 final android.view.MenuItem moveToTopMenuItem =
536 menu.add(R.string.moveToTop);
537 moveToTopMenuItem.setOnMenuItemClickListener(new
538 android.view.MenuItem.OnMenuItemClickListener() {
540 public boolean onMenuItemClick(android.view.MenuItem item) {
541 application.moveDictionaryToTop(row.dictionaryInfo);
549 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
551 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
553 public boolean onMenuItemClick(android.view.MenuItem item) {
554 application.deleteDictionary(row.dictionaryInfo);
562 private void onShowDownloadableChanged() {
564 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
565 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
569 class MyListAdapter extends BaseAdapter {
571 final List<DictionaryInfo> dictionariesOnDevice;
572 final List<DictionaryInfo> downloadableDictionaries;
575 final DictionaryInfo dictionaryInfo;
576 final boolean onDevice;
578 private Row(DictionaryInfo dictionaryInfo, boolean onDevice) {
579 this.dictionaryInfo = dictionaryInfo;
580 this.onDevice = onDevice;
584 private MyListAdapter(final String[] filters) {
585 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
586 if (showDownloadable.isChecked()) {
587 downloadableDictionaries = application.getDownloadableDictionaries(filters);
589 downloadableDictionaries = Collections.emptyList();
594 public int getCount() {
595 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
599 public Row getItem(int position) {
601 return new Row(null, true);
605 if (position < dictionariesOnDevice.size()) {
606 return new Row(dictionariesOnDevice.get(position), true);
608 position -= dictionariesOnDevice.size();
611 return new Row(null, false);
615 assert position < downloadableDictionaries.size();
616 return new Row(downloadableDictionaries.get(position), false);
620 public long getItemId(int position) {
625 public int getViewTypeCount() {
630 public int getItemViewType(int position) {
631 final Row row = getItem(position);
632 if (row.dictionaryInfo == null) {
633 return row.onDevice ? 0 : 1;
635 assert row.dictionaryInfo.indexInfos.size() <= 2;
640 public View getView(int position, View convertView, ViewGroup parent) {
641 if (convertView == dictionariesOnDeviceHeaderRow ||
642 convertView == downloadableDictionariesHeaderRow) {
646 final Row row = getItem(position);
648 if (row.dictionaryInfo == null) {
649 assert convertView == null;
650 return row.onDevice ? dictionariesOnDeviceHeaderRow : downloadableDictionariesHeaderRow;
652 return createDictionaryRow(row.dictionaryInfo, parent, convertView, row.onDevice);
657 private void setMyListAdapter() {
658 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
660 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
661 setListAdapter(new MyListAdapter(filters));
664 private boolean isDownloadActive(String downloadUrl, boolean cancel) {
665 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
666 final DownloadManager.Query query = new DownloadManager.Query();
667 query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
668 final Cursor cursor = downloadManager.query(query);
670 // Due to a bug, cursor is null instead of empty when
671 // the download manager is disabled.
672 if (cursor == null) {
674 String msg = getString(R.string.downloadManagerQueryFailed);
675 new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
676 .setMessage(getString(R.string.downloadFailed, msg))
677 .setNeutralButton("Close", null).show();
684 destFile = new File(new URL(downloadUrl).getPath()).getName();
685 } catch (MalformedURLException e) {
686 throw new RuntimeException("Invalid download URL!", e);
688 while (cursor.moveToNext()) {
689 if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
691 if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE))))
694 boolean active = !cursor.isAfterLast();
695 if (active && cancel) {
696 long downloadId = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
697 finishedDownloadIds.add(downloadId);
698 downloadManager.remove(downloadId);
704 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
705 final ViewGroup parent, View row, boolean canLaunch) {
708 row = LayoutInflater.from(parent.getContext()).inflate(
709 R.layout.dictionary_manager_row, parent, false);
711 final TextView name = row.findViewById(R.id.dictionaryName);
712 final TextView details = row.findViewById(R.id.dictionaryDetails);
713 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
715 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
716 final Button downloadButton = row.findViewById(R.id.downloadButton);
717 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
718 boolean broken = false;
719 if (!dictionaryInfo.isValid()) {
723 if (downloadable != null && (!canLaunch || updateAvailable)) {
726 R.string.downloadButton,
727 downloadable.zipBytes / 1024.0 / 1024.0));
728 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
729 downloadButton.setOnClickListener(new OnClickListener() {
731 public void onClick(View arg0) {
732 downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
735 downloadButton.setVisibility(View.VISIBLE);
737 if (isDownloadActive(downloadable.downloadUrl, false))
738 downloadButton.setText("X");
740 downloadButton.setVisibility(View.GONE);
743 LinearLayout buttons = row.findViewById(R.id.dictionaryLauncherButtons);
745 final List<IndexInfo> sortedIndexInfos = application
746 .sortedIndexInfos(dictionaryInfo.indexInfos);
747 final StringBuilder builder = new StringBuilder();
748 if (updateAvailable) {
749 builder.append(getString(R.string.updateAvailable));
751 assert buttons.getChildCount() == 4;
752 for (int i = 0; i < 2; i++) {
753 final Button textButton = (Button)buttons.getChildAt(2*i);
754 final ImageButton imageButton = (ImageButton)buttons.getChildAt(2*i + 1);
755 if (i >= sortedIndexInfos.size()) {
756 textButton.setVisibility(View.GONE);
757 imageButton.setVisibility(View.GONE);
760 final IndexInfo indexInfo = sortedIndexInfos.get(i);
761 final View button = IsoUtils.INSTANCE.setupButton(textButton, imageButton,
765 button.setOnClickListener(
766 new IntentLauncher(buttons.getContext(),
767 DictionaryActivity.getLaunchIntent(getApplicationContext(),
768 application.getPath(dictionaryInfo.uncompressedFilename),
769 indexInfo.shortName, "")));
772 button.setEnabled(canLaunch);
773 button.setFocusable(canLaunch);
774 if (builder.length() != 0) {
775 builder.append("; ");
777 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
778 indexInfo.mainTokenCount));
780 builder.append("; ");
781 builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
783 name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
784 builder.append("; Cannot be used, redownload, check hardware/file system");
786 details.setText(builder.toString());
789 row.setOnClickListener(new IntentLauncher(parent.getContext(),
790 DictionaryActivity.getLaunchIntent(getApplicationContext(),
791 application.getPath(dictionaryInfo.uncompressedFilename),
792 dictionaryInfo.indexInfos.get(0).shortName, "")));
793 // do not setFocusable, for keyboard navigation
794 // offering only the index buttons is better.
796 row.setClickable(canLaunch);
797 // Allow deleting, even if we cannot open
798 row.setLongClickable(broken || canLaunch);
799 row.setBackgroundResource(android.R.drawable.menuitem_background);
804 private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
805 if (isDownloadActive(downloadUrl, true)) {
808 R.string.downloadButton,
809 bytes / 1024.0 / 1024.0));
812 Request request = new Request(
813 Uri.parse(downloadUrl));
817 destFile = new File(new URL(downloadUrl).getPath()).getName();
818 } catch (MalformedURLException e) {
819 throw new RuntimeException("Invalid download URL!", e);
821 Log.d(LOG, "Downloading to: " + destFile);
822 request.setTitle(destFile);
823 File destFilePath = new File(application.getDictDir(), destFile);
824 destFilePath.delete();
826 request.setDestinationUri(Uri.fromFile(destFilePath));
827 } catch (Exception e) {
830 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
833 downloadManager.enqueue(request);
834 } catch (SecurityException e) {
835 request = new Request(Uri.parse(downloadUrl));
836 request.setTitle(destFile);
837 downloadManager.enqueue(request);
839 Log.w(LOG, "Download started: " + destFile);
840 downloadButton.setText("X");