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