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