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