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