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