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