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