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