]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryManagerActivity.java
Apply astyle code formattting.
[Dictionary.git] / src / com / hughes / android / dictionary / DictionaryManagerActivity.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
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
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 package com.hughes.android.dictionary;
16
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.support.v4.app.ActivityCompat;
36 import android.support.v4.content.ContextCompat;
37 import android.support.v4.view.MenuItemCompat;
38 import android.support.v7.app.ActionBar;
39 import android.support.v7.app.ActionBarActivity;
40 import android.support.v7.widget.SearchView;
41 import android.support.v7.widget.SearchView.OnQueryTextListener;
42 import android.support.v7.widget.Toolbar;
43 import android.text.InputType;
44 import android.util.Log;
45 import android.util.TypedValue;
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.view.inputmethod.InputMethodManager;
56 import android.widget.AdapterView.AdapterContextMenuInfo;
57 import android.widget.BaseAdapter;
58 import android.widget.Button;
59 import android.widget.CompoundButton;
60 import android.widget.CompoundButton.OnCheckedChangeListener;
61 import android.widget.FrameLayout;
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;
68
69 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
70 import com.hughes.android.util.IntentLauncher;
71
72 import java.io.File;
73 import java.io.FileInputStream;
74 import java.io.FileOutputStream;
75 import java.io.IOException;
76 import java.io.InputStream;
77 import java.io.OutputStream;
78 import java.net.MalformedURLException;
79 import java.net.URL;
80 import java.util.Collections;
81 import java.util.HashSet;
82 import java.util.List;
83 import java.util.Set;
84 import java.util.zip.ZipEntry;
85 import java.util.zip.ZipFile;
86 import java.util.zip.ZipInputStream;
87
88 // Right-click:
89 //  Delete, move to top.
90
91 public class DictionaryManagerActivity extends ActionBarActivity {
92
93     static final String LOG = "QuickDic";
94     static boolean blockAutoLaunch = false;
95
96     private ListView listView;
97     private ListView getListView() {
98         if (listView == null) {
99             listView = (ListView)findViewById(android.R.id.list);
100         }
101         return listView;
102     }
103     private void setListAdapter(ListAdapter adapter) {
104         getListView().setAdapter(adapter);
105     }
106     private ListAdapter getListAdapter() {
107         return getListView().getAdapter();
108     }
109
110     // For DownloadManager bug workaround
111     private Set<Long> finishedDownloadIds = new HashSet<Long>();
112
113     DictionaryApplication application;
114
115     SearchView filterSearchView;
116     ToggleButton showDownloadable;
117
118     LinearLayout dictionariesOnDeviceHeaderRow;
119     LinearLayout downloadableDictionariesHeaderRow;
120
121     Handler uiHandler;
122
123     Runnable dictionaryUpdater = new Runnable() {
124         @Override
125         public void run() {
126             if (uiHandler == null) {
127                 return;
128             }
129             uiHandler.post(new Runnable() {
130                 @Override
131                 public void run() {
132                     setMyListAdapater();
133                 }
134             });
135         }
136     };
137
138     final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
139         @Override
140         public synchronized void onReceive(Context context, Intent intent) {
141             final String action = intent.getAction();
142
143             if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
144                 final long downloadId = intent.getLongExtra(
145                                             DownloadManager.EXTRA_DOWNLOAD_ID, 0);
146                 if (finishedDownloadIds.contains(downloadId)) return; // ignore double notifications
147                 final DownloadManager.Query query = new DownloadManager.Query();
148                 query.setFilterById(downloadId);
149                 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
150                 final Cursor cursor = downloadManager.query(query);
151
152                 if (cursor == null || !cursor.moveToFirst()) {
153                     Log.e(LOG, "Couldn't find download.");
154                     return;
155                 }
156
157                 final String dest = cursor
158                                     .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
159                 final int status = cursor
160                                    .getInt(cursor
161                                            .getColumnIndex(DownloadManager.COLUMN_STATUS));
162                 if (DownloadManager.STATUS_SUCCESSFUL != status) {
163                     final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
164                     Log.w(LOG,
165                           "Download failed: status=" + status +
166                           ", reason=" + reason);
167                     String msg = Integer.toString(reason);
168                     switch (reason) {
169                     case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
170                         msg = "File exists";
171                         break;
172                     case DownloadManager.ERROR_FILE_ERROR:
173                         msg = "File error";
174                         break;
175                     case DownloadManager.ERROR_INSUFFICIENT_SPACE:
176                         msg = "Not enough space";
177                         break;
178                     }
179                     new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, msg)).setNeutralButton("Close", null).show();
180                     return;
181                 }
182
183                 Log.w(LOG, "Download finished: " + dest + " Id: " + downloadId);
184                 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
185                                Toast.LENGTH_LONG).show();
186
187
188                 final Uri zipUri = Uri.parse(dest);
189                 File localZipFile = null;
190                 InputStream zipFileStream = null;
191                 ZipInputStream zipFile = null;
192                 OutputStream zipOut = null;
193                 try {
194                     if (zipUri.getScheme().equals("content")) {
195                         zipFileStream = context.getContentResolver().openInputStream(zipUri);
196                         localZipFile = null;
197                     } else {
198                         localZipFile = new File(zipUri.getPath());
199                         zipFileStream = new FileInputStream(localZipFile);
200                     }
201                     zipFile = new ZipInputStream(zipFileStream);
202                     final ZipEntry zipEntry = zipFile.getNextEntry();
203                     Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
204                     File targetFile = new File(application.getDictDir(), zipEntry.getName());
205                     if (targetFile.exists()) {
206                         targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
207                         targetFile = new File(application.getDictDir(), zipEntry.getName());
208                     }
209                     zipOut = new FileOutputStream(targetFile);
210                     copyStream(zipFile, zipOut);
211                     application.backgroundUpdateDictionaries(dictionaryUpdater);
212                     Toast.makeText(context, getString(R.string.installationFinished, dest),
213                                    Toast.LENGTH_LONG).show();
214                     finishedDownloadIds.add(downloadId);
215                     Log.w(LOG, "Unzipping finished: " + dest + " Id: " + downloadId);
216                 } catch (Exception e) {
217                     String msg = getString(R.string.unzippingFailed, dest);
218                     File dir = application.getDictDir();
219                     if (!dir.canWrite() || !application.checkFileCreate(dir)) {
220                         msg = getString(R.string.notWritable, dir.getAbsolutePath());
221                     }
222                     new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
223                     Log.e(LOG, "Failed to unzip.", e);
224                 } finally {
225                     try {
226                         if (zipOut != null) zipOut.close();
227                     } catch (IOException e) {}
228                     try {
229                         if (zipFile != null) zipFile.close();
230                     } catch (IOException e) {}
231                     try {
232                         if (zipFileStream != null) zipFileStream.close();
233                     } catch (IOException e) {}
234                     if (localZipFile != null) localZipFile.delete();
235                 }
236             }
237         }
238     };
239
240     public static Intent getLaunchIntent(Context c) {
241         final Intent intent = new Intent(c, DictionaryManagerActivity.class);
242         intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
243         return intent;
244     }
245
246     public void readableCheckAndError(boolean requestPermission) {
247         final File dictDir = application.getDictDir();
248         if (dictDir.canRead() && dictDir.canExecute()) return;
249         blockAutoLaunch = true;
250         if (requestPermission &&
251                 ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
252             ActivityCompat.requestPermissions(this,
253                                               new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
254                                                       Manifest.permission.WRITE_EXTERNAL_STORAGE
255                                                            }, 0);
256             return;
257         }
258         blockAutoLaunch = true;
259
260         AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
261         builder.setTitle(getString(R.string.error));
262         builder.setMessage(getString(
263                                R.string.unableToReadDictionaryDir,
264                                dictDir.getAbsolutePath(),
265                                Environment.getExternalStorageDirectory()));
266         builder.setNeutralButton("Close", null);
267         builder.create().show();
268     }
269
270     @Override
271     public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
272         readableCheckAndError(false);
273
274         application.backgroundUpdateDictionaries(dictionaryUpdater);
275
276         setMyListAdapater();
277     }
278
279     @Override
280     public void onCreate(Bundle savedInstanceState) {
281         // This must be first, otherwise the actiona bar doesn't get
282         // styled properly.
283         setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
284
285         super.onCreate(savedInstanceState);
286         Log.d(LOG, "onCreate:" + this);
287
288         application = (DictionaryApplication) getApplication();
289
290         blockAutoLaunch = false;
291
292         // UI init.
293         setContentView(R.layout.dictionary_manager_activity);
294
295         dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
296                                             getListView().getContext()).inflate(
297                                             R.layout.dictionary_manager_header_row_on_device, getListView(), false);
298
299         downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
300                                                 getListView().getContext()).inflate(
301                                                 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
302
303         showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
304                            .findViewById(R.id.hideDownloadable);
305         showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
306             @Override
307             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
308                 onShowDownloadableChanged();
309             }
310         });
311
312         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
313         final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
314         if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
315                     thanksForUpdatingLatestVersion)) {
316             blockAutoLaunch = true;
317             startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
318             prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
319             .commit();
320         }
321
322         registerReceiver(broadcastReceiver, new IntentFilter(
323                              DownloadManager.ACTION_DOWNLOAD_COMPLETE));
324
325         setMyListAdapater();
326         registerForContextMenu(getListView());
327
328         readableCheckAndError(true);
329
330         onCreateSetupActionBar();
331     }
332
333     private void onCreateSetupActionBar() {
334         ActionBar actionBar = getSupportActionBar();
335         actionBar.setDisplayShowTitleEnabled(false);
336         actionBar.setDisplayShowHomeEnabled(false);
337         actionBar.setDisplayHomeAsUpEnabled(false);
338
339         filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
340         filterSearchView.setIconifiedByDefault(false);
341         // filterSearchView.setIconified(false); // puts the magnifying glass in
342         // the
343         // wrong place.
344         filterSearchView.setQueryHint(getString(R.string.searchText));
345         filterSearchView.setSubmitButtonEnabled(false);
346         FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
347                 FrameLayout.LayoutParams.WRAP_CONTENT);
348         filterSearchView.setLayoutParams(lp);
349         filterSearchView.setInputType(InputType.TYPE_CLASS_TEXT);
350         filterSearchView.setImeOptions(
351             EditorInfo.IME_ACTION_DONE |
352             EditorInfo.IME_FLAG_NO_EXTRACT_UI |
353             // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
354             // 11
355             EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
356
357         filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
358             @Override
359             public boolean onQueryTextSubmit(String query) {
360                 filterSearchView.clearFocus();
361                 return false;
362             }
363
364             @Override
365             public boolean onQueryTextChange(String filterText) {
366                 setMyListAdapater();
367                 return true;
368             }
369         });
370         filterSearchView.setFocusable(true);
371
372         actionBar.setCustomView(filterSearchView);
373         actionBar.setDisplayShowCustomEnabled(true);
374
375         // Avoid wasting space on large left inset
376         Toolbar tb = (Toolbar)filterSearchView.getParent();
377         tb.setContentInsetsRelative(0, 0);
378     }
379
380     @Override
381     public void onDestroy() {
382         super.onDestroy();
383         unregisterReceiver(broadcastReceiver);
384     }
385
386     private static int copyStream(final InputStream in, final OutputStream out)
387     throws IOException {
388         int bytesRead;
389         final byte[] bytes = new byte[1024 * 16];
390         while ((bytesRead = in.read(bytes)) != -1) {
391             out.write(bytes, 0, bytesRead);
392         }
393         in.close();
394         out.close();
395         return bytesRead;
396     }
397
398     @Override
399     protected void onStart() {
400         super.onStart();
401         uiHandler = new Handler();
402     }
403
404     @Override
405     protected void onStop() {
406         super.onStop();
407         uiHandler = null;
408     }
409
410     @Override
411     protected void onResume() {
412         super.onResume();
413
414         if (PreferenceActivity.prefsMightHaveChanged) {
415             PreferenceActivity.prefsMightHaveChanged = false;
416             finish();
417             startActivity(getIntent());
418         }
419
420         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
421         showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
422
423         if (!blockAutoLaunch &&
424                 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
425                 prefs.contains(C.DICT_FILE) &&
426                 prefs.contains(C.INDEX_SHORT_NAME)) {
427             Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
428             startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
429                           new File(prefs.getString(C.DICT_FILE, "")),
430                           prefs.getString(C.INDEX_SHORT_NAME, ""),
431                           prefs.getString(C.SEARCH_TOKEN, "")));
432             finish();
433             return;
434         }
435
436         // Remove the active dictionary from the prefs so we won't autolaunch
437         // next time.
438         final Editor editor = prefs.edit();
439         editor.remove(C.DICT_FILE);
440         editor.remove(C.INDEX_SHORT_NAME);
441         editor.remove(C.SEARCH_TOKEN);
442         editor.commit();
443
444         application.backgroundUpdateDictionaries(dictionaryUpdater);
445
446         setMyListAdapater();
447     }
448
449     @Override
450     public boolean onCreateOptionsMenu(final Menu menu) {
451         final MenuItem sort = menu.add(getString(R.string.sortDicts));
452         MenuItemCompat.setShowAsAction(sort, MenuItem.SHOW_AS_ACTION_NEVER);
453         sort.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
454             public boolean onMenuItemClick(final MenuItem menuItem) {
455                 application.sortDictionaries();
456                 setMyListAdapater();
457                 return true;
458             }
459         });
460
461         application.onCreateGlobalOptionsMenu(this, menu);
462         return true;
463     }
464
465     @Override
466     public void onCreateContextMenu(final ContextMenu menu, final View view,
467                                     final ContextMenuInfo menuInfo) {
468         super.onCreateContextMenu(menu, view, menuInfo);
469         Log.d(LOG, "onCreateContextMenu, " + menuInfo);
470
471         final AdapterContextMenuInfo adapterContextMenuInfo =
472             (AdapterContextMenuInfo) menuInfo;
473         final int position = adapterContextMenuInfo.position;
474         final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
475
476         if (row.dictionaryInfo == null) {
477             return;
478         }
479
480         if (position > 0 && row.onDevice) {
481             final android.view.MenuItem moveToTopMenuItem =
482                 menu.add(R.string.moveToTop);
483             moveToTopMenuItem.setOnMenuItemClickListener(new
484             android.view.MenuItem.OnMenuItemClickListener() {
485                 @Override
486                 public boolean onMenuItemClick(android.view.MenuItem item) {
487                     application.moveDictionaryToTop(row.dictionaryInfo);
488                     setMyListAdapater();
489                     return true;
490                 }
491             });
492         }
493
494         if (row.onDevice) {
495             final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
496             deleteMenuItem
497             .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
498                 @Override
499                 public boolean onMenuItemClick(android.view.MenuItem item) {
500                     application.deleteDictionary(row.dictionaryInfo);
501                     setMyListAdapater();
502                     return true;
503                 }
504             });
505         }
506     }
507
508     private void onShowDownloadableChanged() {
509         setMyListAdapater();
510         Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
511         prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
512         prefs.commit();
513     }
514
515     class MyListAdapter extends BaseAdapter {
516
517         List<DictionaryInfo> dictionariesOnDevice;
518         List<DictionaryInfo> downloadableDictionaries;
519
520         class Row {
521             DictionaryInfo dictionaryInfo;
522             boolean onDevice;
523
524             private Row(DictionaryInfo dictionaryInfo, boolean onDevice) {
525                 this.dictionaryInfo = dictionaryInfo;
526                 this.onDevice = onDevice;
527             }
528         }
529
530         private MyListAdapter(final String[] filters) {
531             dictionariesOnDevice = application.getDictionariesOnDevice(filters);
532             if (showDownloadable.isChecked()) {
533                 downloadableDictionaries = application.getDownloadableDictionaries(filters);
534             } else {
535                 downloadableDictionaries = Collections.emptyList();
536             }
537         }
538
539         @Override
540         public int getCount() {
541             return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
542         }
543
544         @Override
545         public Row getItem(int position) {
546             if (position == 0) {
547                 return new Row(null, true);
548             }
549             position -= 1;
550
551             if (position < dictionariesOnDevice.size()) {
552                 return new Row(dictionariesOnDevice.get(position), true);
553             }
554             position -= dictionariesOnDevice.size();
555
556             if (position == 0) {
557                 return new Row(null, false);
558             }
559             position -= 1;
560
561             assert position < downloadableDictionaries.size();
562             return new Row(downloadableDictionaries.get(position), false);
563         }
564
565         @Override
566         public long getItemId(int position) {
567             return position;
568         }
569
570         @Override
571         public View getView(int position, View convertView, ViewGroup parent) {
572             if (convertView instanceof LinearLayout &&
573                     convertView != dictionariesOnDeviceHeaderRow &&
574                     convertView != downloadableDictionariesHeaderRow) {
575                 /*
576                  * This is done to try to avoid leaking memory that used to
577                  * happen on Android 4.0.3
578                  */
579                 ((LinearLayout) convertView).removeAllViews();
580             }
581
582             final Row row = getItem(position);
583
584             if (row.onDevice) {
585                 if (row.dictionaryInfo == null) {
586                     return dictionariesOnDeviceHeaderRow;
587                 }
588                 return createDictionaryRow(row.dictionaryInfo, parent, true);
589             }
590
591             if (row.dictionaryInfo == null) {
592                 return downloadableDictionariesHeaderRow;
593             }
594             return createDictionaryRow(row.dictionaryInfo, parent, false);
595         }
596
597     }
598
599     private void setMyListAdapater() {
600         final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
601                               .toString();
602         final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
603         setListAdapter(new MyListAdapter(filters));
604     }
605
606     private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
607                                      final ViewGroup parent, boolean canLaunch) {
608
609         View row = LayoutInflater.from(parent.getContext()).inflate(
610                        R.layout.dictionary_manager_row, parent, false);
611         final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
612         final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
613         name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
614
615         final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
616         final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
617         final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
618         boolean broken = false;
619         if (!dictionaryInfo.isValid()) {
620             broken = true;
621             canLaunch = false;
622         }
623         if (downloadable != null && (!canLaunch || updateAvailable)) {
624             downloadButton
625             .setText(getString(
626                          R.string.downloadButton,
627                          downloadable.zipBytes / 1024.0 / 1024.0));
628             downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
629             downloadButton.setOnClickListener(new OnClickListener() {
630                 @Override
631                 public void onClick(View arg0) {
632                     downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
633                 }
634             });
635         } else {
636             downloadButton.setVisibility(View.INVISIBLE);
637         }
638
639         LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
640         final List<IndexInfo> sortedIndexInfos = application
641                 .sortedIndexInfos(dictionaryInfo.indexInfos);
642         final StringBuilder builder = new StringBuilder();
643         if (updateAvailable) {
644             builder.append(getString(R.string.updateAvailable));
645         }
646         for (IndexInfo indexInfo : sortedIndexInfos) {
647             final View button = application.createButton(buttons.getContext(), dictionaryInfo,
648                                 indexInfo);
649             buttons.addView(button);
650
651             if (canLaunch) {
652                 button.setOnClickListener(
653                     new IntentLauncher(buttons.getContext(),
654                                        DictionaryActivity.getLaunchIntent(getApplicationContext(),
655                                                application.getPath(dictionaryInfo.uncompressedFilename),
656                                                indexInfo.shortName, "")));
657
658             } else {
659                 button.setEnabled(false);
660             }
661             if (builder.length() != 0) {
662                 builder.append("; ");
663             }
664             builder.append(getString(R.string.indexInfo, indexInfo.shortName,
665                                      indexInfo.mainTokenCount));
666         }
667         builder.append("; ");
668         builder.append(getString(R.string.downloadButton, dictionaryInfo.uncompressedBytes / 1024.0 / 1024.0));
669         if (broken) {
670             name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
671             builder.append("; Cannot be used, redownload, check hardware/file system");
672             // Allow deleting, but cannot open
673             row.setLongClickable(true);
674         }
675         details.setText(builder.toString());
676
677         if (canLaunch) {
678             row.setClickable(true);
679             row.setOnClickListener(new IntentLauncher(parent.getContext(),
680                                    DictionaryActivity.getLaunchIntent(getApplicationContext(),
681                                            application.getPath(dictionaryInfo.uncompressedFilename),
682                                            dictionaryInfo.indexInfos.get(0).shortName, "")));
683             row.setFocusable(true);
684             row.setLongClickable(true);
685         }
686         row.setBackgroundResource(android.R.drawable.menuitem_background);
687
688         return row;
689     }
690
691     private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
692         String destFile;
693         try {
694             destFile = new File(new URL(downloadUrl).getPath()).getName();
695         } catch (MalformedURLException e) {
696             throw new RuntimeException("Invalid download URL!", e);
697         }
698         DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
699         final DownloadManager.Query query = new DownloadManager.Query();
700         query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
701         final Cursor cursor = downloadManager.query(query);
702
703         // Due to a bug, cursor is null instead of empty when
704         // the download manager is disabled.
705         if (cursor == null) {
706             new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
707             .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
708             .setNeutralButton("Close", null).show();
709             return;
710         }
711
712         while (cursor.moveToNext()) {
713             if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
714                 break;
715             if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE))))
716                 break;
717         }
718         if (!cursor.isAfterLast()) {
719             downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
720             downloadButton
721             .setText(getString(
722                          R.string.downloadButton,
723                          bytes / 1024.0 / 1024.0));
724             cursor.close();
725             return;
726         }
727         cursor.close();
728         Request request = new Request(
729             Uri.parse(downloadUrl));
730
731         Log.d(LOG, "Downloading to: " + destFile);
732         request.setTitle(destFile);
733
734         File destFilePath = new File(application.getDictDir(), destFile);
735         destFilePath.delete();
736         try {
737             request.setDestinationUri(Uri.fromFile(destFilePath));
738         } catch (Exception e) {
739         }
740
741         try {
742             downloadManager.enqueue(request);
743         } catch (SecurityException e) {
744             request = new Request(Uri.parse(downloadUrl));
745             request.setTitle(destFile);
746             downloadManager.enqueue(request);
747         }
748         Log.w(LOG, "Download started: " + destFile);
749         downloadButton.setText("X");
750     }
751
752 }