]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryManagerActivity.java
Using ListView again for DictionaryManager, downloads working with
[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.app.DownloadManager;
18 import android.app.DownloadManager.Request;
19 import android.content.BroadcastReceiver;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
23 import android.content.SharedPreferences;
24 import android.content.SharedPreferences.Editor;
25 import android.database.Cursor;
26 import android.net.Uri;
27 import android.os.Bundle;
28 import android.os.Environment;
29 import android.os.Handler;
30 import android.preference.PreferenceManager;
31 import android.util.Log;
32 import android.view.LayoutInflater;
33 import android.view.View;
34 import android.view.View.OnClickListener;
35 import android.view.ViewGroup;
36 import android.widget.BaseAdapter;
37 import android.widget.Button;
38 import android.widget.CompoundButton;
39 import android.widget.CompoundButton.OnCheckedChangeListener;
40 import android.widget.LinearLayout;
41 import android.widget.TextView;
42 import android.widget.ToggleButton;
43
44 import com.actionbarsherlock.app.SherlockListActivity;
45 import com.actionbarsherlock.view.Menu;
46 import com.actionbarsherlock.view.MenuInflater;
47 import com.actionbarsherlock.widget.SearchView;
48 import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
49 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
50 import com.hughes.android.util.IntentLauncher;
51
52 import java.io.File;
53 import java.io.FileOutputStream;
54 import java.io.IOException;
55 import java.io.InputStream;
56 import java.io.OutputStream;
57 import java.net.MalformedURLException;
58 import java.net.URL;
59 import java.util.Collections;
60 import java.util.List;
61 import java.util.zip.ZipEntry;
62 import java.util.zip.ZipFile;
63
64 // Filters
65 // Right-click:
66 //  Delete, move to top.
67
68 public class DictionaryManagerActivity extends SherlockListActivity {
69
70     static final String LOG = "QuickDic";
71     static boolean blockAutoLaunch = false;
72
73     DictionaryApplication application;
74 //    Adapter adapter;
75
76     // EditText filterText;
77     SearchView filterSearchView;
78     ToggleButton showDownloadable;
79
80     LinearLayout dictionariesOnDeviceHeaderRow;
81     LinearLayout downloadableDictionariesHeaderRow;
82
83     Handler uiHandler;
84     
85     Runnable dictionaryUpdater = new Runnable() {
86         @Override
87         public void run() {
88             if (uiHandler == null) {
89                 return;
90             }
91             uiHandler.post(new Runnable() {
92                 @Override
93                 public void run() {
94                     setListAdapater();
95                 }
96             });
97         }
98     };
99
100     public static Intent getLaunchIntent() {
101         final Intent intent = new Intent();
102         intent.setClassName(DictionaryManagerActivity.class.getPackage().getName(),
103                 DictionaryManagerActivity.class.getName());
104         intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
105         return intent;
106     }
107
108     public void onCreate(Bundle savedInstanceState) {
109         setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
110
111         super.onCreate(savedInstanceState);
112         Log.d(LOG, "onCreate:" + this);
113
114         application = (DictionaryApplication) getApplication();
115
116         // UI init.
117         setContentView(R.layout.dictionary_manager_activity);
118
119         dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
120                 R.layout.dictionaries_on_device_header_row, getListView(), false);
121
122         downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(getListView().getContext()).inflate(
123                 R.layout.downloadable_dictionaries_header_row, getListView(), false);
124
125         // filterText = (EditText) findViewById(R.id.filterText);
126         //
127         // filterText.addTextChangedListener(new TextWatcher() {
128         // @Override
129         // public void onTextChanged(CharSequence s, int start, int before, int
130         // count) {
131         // }
132         //
133         // @Override
134         // public void beforeTextChanged(CharSequence s, int start, int count,
135         // int after) {
136         // }
137         //
138         // @Override
139         // public void afterTextChanged(Editable s) {
140         // onFilterTextChanged();
141         // }
142         // });
143
144         // final ImageButton clearSearchText = (ImageButton)
145         // findViewById(R.id.ClearSearchTextButton);
146         // clearSearchText.setOnClickListener(new View.OnClickListener() {
147         // @Override
148         // public void onClick(View arg0) {
149         // filterText.setText("");
150         // filterText.requestFocus();
151         // }
152         // });
153
154         showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow.findViewById(R.id.hideDownloadable);
155         showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
156             @Override
157             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
158                 onShowLocalChanged();
159             }
160         });
161
162         // ContextMenu.
163         // registerForContextMenu(getListView());
164
165         blockAutoLaunch = false;
166         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
167         final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
168         if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
169                 thanksForUpdatingLatestVersion)) {
170             blockAutoLaunch = true;
171             startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent());
172             prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
173                     .commit();
174         }
175         
176         BroadcastReceiver receiver = new BroadcastReceiver() {
177             @Override
178             public void onReceive(Context context, Intent intent) {
179                 final String action = intent.getAction();
180                 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
181                     final long downloadId = intent.getLongExtra(
182                             DownloadManager.EXTRA_DOWNLOAD_ID, 0);
183                     final DownloadManager.Query query = new DownloadManager.Query();
184                     query.setFilterById(downloadId);
185                     final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
186                     final Cursor cursor = downloadManager.query(query);
187                     
188                     if (!cursor.moveToFirst()) {
189                         Log.e(LOG, "Couldn't find download.");
190                         return;
191                     }
192                     
193                     final int status = cursor
194                             .getInt(cursor
195                                     .getColumnIndex(DownloadManager.COLUMN_STATUS));
196                     if (DownloadManager.STATUS_SUCCESSFUL != status){
197                     Log.w(LOG, "Download failed: status=" + status + ", reason=" + cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)));
198                     return;
199                 }
200
201                 final String dest = cursor
202                         .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
203                 Log.w(LOG, "Download finished: " + dest);
204                 final File destFile = new File(Uri.parse(dest).getPath());
205                 
206                 try {
207                     ZipFile zipFile = new ZipFile(destFile);
208                     final ZipEntry zipEntry = zipFile.entries().nextElement();
209                     Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
210                     final InputStream zipIn = zipFile.getInputStream(zipEntry);
211                     final OutputStream zipOut = new FileOutputStream(new File(application.getDictDir(), zipEntry.getName()));
212                     copyStream(zipIn, zipOut);
213                     destFile.delete();
214                     zipFile.close();
215                     application.backgroundUpdateDictionaries(dictionaryUpdater);
216                 } catch (Exception e) {
217                     Log.e(LOG, "Failed to unzip.", e);
218                 }
219               }
220             }
221         };
222  
223         registerReceiver(receiver, new IntentFilter(
224                 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
225         
226         setListAdapater();
227     }
228     
229     private static int copyStream(final InputStream in, final OutputStream out)
230             throws IOException {
231         int bytesRead;
232         final byte[] bytes = new byte[1024 * 16];
233         while ((bytesRead = in.read(bytes)) != -1) {
234             out.write(bytes, 0, bytesRead);
235         }
236         in.close();
237         out.close();
238         return bytesRead;
239     }
240
241     @Override
242     protected void onStart() {
243         super.onStart();
244         uiHandler = new Handler();
245     }
246
247     @Override
248     protected void onStop() {
249         super.onStop();
250         uiHandler = null;
251     }
252
253     @Override
254     protected void onResume() {
255         super.onResume();
256
257         if (PreferenceActivity.prefsMightHaveChanged) {
258             PreferenceActivity.prefsMightHaveChanged = false;
259             finish();
260             startActivity(getIntent());
261         }
262
263         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
264         showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, false));
265
266         if (!blockAutoLaunch &&
267                 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
268                 prefs.contains(C.DICT_FILE) &&
269                 prefs.contains(C.INDEX_SHORT_NAME)) {
270             Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
271             startActivity(DictionaryActivity.getLaunchIntent(
272                     new File(prefs.getString(C.DICT_FILE, "")), prefs.getString(C.INDEX_SHORT_NAME, ""),
273                     prefs.getString(C.SEARCH_TOKEN, "")));
274             finish();
275             return;
276         }
277         
278         // Remove the active dictionary from the prefs so we won't autolaunch
279         // next time.
280         final Editor editor = prefs.edit();
281         editor.remove(C.DICT_FILE);
282         editor.remove(C.INDEX_SHORT_NAME);
283         editor.remove(C.SEARCH_TOKEN);
284         editor.commit();
285
286         application.backgroundUpdateDictionaries(dictionaryUpdater);
287
288         setListAdapater();
289     }
290
291     @Override
292     public boolean onCreateOptionsMenu(final Menu menu) {
293         MenuInflater inflater = getSupportMenuInflater();
294         inflater.inflate(R.menu.dictionary_manager_options_menu, menu);
295         
296         filterSearchView = (SearchView) menu.findItem(R.id.filterText).getActionView();
297         filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
298             @Override
299             public boolean onQueryTextSubmit(String query) {
300                 return true;
301             }
302             
303             @Override
304             public boolean onQueryTextChange(String filterText) {
305                 setListAdapater();
306                 return true;
307             }
308         });
309         filterSearchView.setIconifiedByDefault(false);
310
311         application.onCreateGlobalOptionsMenu(this, menu);
312         return true;
313     }
314
315         // @Override
316         // public void onCreateContextMenu(final ContextMenu menu, final View
317         // view,
318         // final ContextMenuInfo menuInfo) {
319         // super.onCreateContextMenu(menu, view, menuInfo);
320         //
321         // final AdapterContextMenuInfo adapterContextMenuInfo =
322         // (AdapterContextMenuInfo) menuInfo;
323         // final int position = adapterContextMenuInfo.position;
324         // final DictionaryInfo dictionaryInfo = adapter.getItem(position);
325         //
326         // if (position > 0 &&
327         // application.isDictionaryOnDevice(dictionaryInfo.uncompressedFilename))
328         // {
329         // final android.view.MenuItem moveToTopMenuItem =
330         // menu.add(R.string.moveToTop);
331         // moveToTopMenuItem.setOnMenuItemClickListener(new
332         // android.view.MenuItem.OnMenuItemClickListener() {
333         // @Override
334         // public boolean onMenuItemClick(android.view.MenuItem item) {
335         // application.moveDictionaryToTop(dictionaryInfo);
336         // setListAdapter(adapter = new Adapter());
337         // return true;
338         // }
339         // });
340         // }
341 //
342 //        final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
343 //        deleteMenuItem
344 //                .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
345 //                    @Override
346 //                    public boolean onMenuItemClick(android.view.MenuItem item) {
347 //                        application.deleteDictionary(dictionaryInfo);
348 //                        setListAdapter(adapter = new Adapter());
349 //                        return true;
350 //                    }
351 //                });
352 //
353 //        final DictionaryInfo downloadable = application
354 //                .getDownloadable(dictionaryInfo.uncompressedFilename);
355 //        if (downloadable != null) {
356 //            final android.view.MenuItem downloadMenuItem = menu.add(getString(
357 //                    R.string.downloadButton, downloadable.zipBytes / 1024.0 / 1024.0));
358 //            downloadMenuItem
359 //                    .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
360 //                        @Override
361 //                        public boolean onMenuItemClick(android.view.MenuItem item) {
362 //                            final Intent intent = getDownloadIntent(downloadable);
363 //                            startActivity(intent);
364 //                            setListAdapter(adapter = new Adapter());
365 //                            return true;
366 //                        }
367 //                    });
368 //        }
369 //
370 //    }
371
372     private void onShowLocalChanged() {
373 //        downloadableDictionaries.setVisibility(showDownloadable.isChecked() ? View.GONE
374 //                : View.VISIBLE);
375         setListAdapater();
376         Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
377         prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
378         prefs.commit();
379     }
380
381     // private void onClick(int index) {
382     // final DictionaryInfo dictionaryInfo = adapter.getItem(index);
383     // final DictionaryInfo downloadable =
384     // application.getDownloadable(dictionaryInfo.uncompressedFilename);
385     // if
386     // (!application.isDictionaryOnDevice(dictionaryInfo.uncompressedFilename)
387     // && downloadable != null) {
388     // final Intent intent = getDownloadIntent(downloadable);
389     // startActivity(intent);
390     // } else {
391     // final Intent intent =
392     // DictionaryActivity.getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename),
393     // 0, "");
394     // startActivity(intent);
395     // }
396     // }
397     
398     class MyListAdapter extends BaseAdapter {
399         
400         List<DictionaryInfo> dictionariesOnDevice;
401         List<DictionaryInfo> downloadableDictionaries;
402         
403         private MyListAdapter(final String[] filters) {
404             dictionariesOnDevice = application.getDictionariesOnDevice(filters);
405             if (showDownloadable.isChecked()) {
406                 downloadableDictionaries = application.getDownloadableDictionaries(filters);
407             } else {
408                 downloadableDictionaries = Collections.emptyList();
409             }
410         }
411
412         @Override
413         public int getCount() {
414             return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
415         }
416
417         @Override
418         public Object getItem(int position) {
419             return Integer.valueOf(position);
420         }
421
422         @Override
423         public long getItemId(int position) {
424             return position;
425         }
426
427         @Override
428         public View getView(int position, View convertView, ViewGroup parent) {
429             if (convertView instanceof LinearLayout && 
430                     convertView != dictionariesOnDeviceHeaderRow && 
431                     convertView != downloadableDictionariesHeaderRow) {
432                 ((LinearLayout)convertView).removeAllViews();
433             }
434             // Dictionaries on device.
435             if (position == 0) {
436                 return dictionariesOnDeviceHeaderRow;
437             }
438             --position;
439             
440             if (position < dictionariesOnDevice.size()) {
441                 return createDictionaryRow(dictionariesOnDevice.get(position), 
442                                 parent, R.layout.dictionaries_on_device_row, true);
443             }
444             position -= dictionariesOnDevice.size();
445             
446             // Downloadable dictionaries.
447             if (position == 0) {
448                 return downloadableDictionariesHeaderRow;
449             }
450             --position;
451             
452             assert position < downloadableDictionaries.size();
453             return createDictionaryRow(downloadableDictionaries.get(position), 
454                             parent, R.layout.downloadable_dictionary_row, false);
455         }
456         
457     }
458     
459
460     private void setListAdapater() {
461         final String filter = filterSearchView == null ? "" : filterSearchView.getQuery().toString();
462         final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
463         setListAdapter(new MyListAdapter(filters));
464     }
465
466     private View createDictionaryRow(final DictionaryInfo dictionaryInfo, final ViewGroup parent, 
467             final int viewResource, final boolean canLaunch) {
468         
469         View row = LayoutInflater.from(parent.getContext()).inflate(
470                 viewResource, parent, false);
471         final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
472         final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
473         name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
474
475         if (!canLaunch) {
476             final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
477             downloadButton.setText(getString(R.string.downloadButton, dictionaryInfo.zipBytes / 1024.0 / 1024.0));
478             downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
479             downloadButton.setOnClickListener(new OnClickListener() {
480                 @Override
481                 public void onClick(View arg0) {
482                     DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
483                     Request request = new Request(
484                             Uri.parse(dictionaryInfo.downloadUrl));
485                     try {
486                         final String destFile = new File(new URL(dictionaryInfo.downloadUrl).getFile()).getName(); 
487                         Log.d(LOG, "Downloading to: " + destFile);
488                         
489                         request.setDestinationUri(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), destFile)));
490                     } catch (MalformedURLException e) {
491                         throw new RuntimeException(e);
492                     }
493                     downloadManager.enqueue(request);
494                 }
495             });
496         }
497
498         final StringBuilder builder = new StringBuilder();
499         LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
500         final List<IndexInfo> sortedIndexInfos = application.sortedIndexInfos(dictionaryInfo.indexInfos);
501         for (IndexInfo indexInfo : sortedIndexInfos) {
502             final View button = application.createButton(buttons.getContext(), dictionaryInfo, indexInfo);
503             buttons.addView(button);
504             
505             if (canLaunch) {
506                 button.setOnClickListener(
507                         new IntentLauncher(buttons.getContext(), 
508                         DictionaryActivity.getLaunchIntent(
509                                 application.getPath(dictionaryInfo.uncompressedFilename), 
510                                 indexInfo.shortName, "")));
511
512             } else {
513                 button.setEnabled(false);
514             }
515             if (builder.length() != 0) {
516                 builder.append("; ");
517             }
518             builder.append(getString(R.string.indexInfo, indexInfo.shortName, indexInfo.mainTokenCount));
519         }
520         details.setText(builder.toString());
521         
522         return row;
523     }
524
525 }