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