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