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