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