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