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