]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryManagerActivity.java
Auto-format everything.
[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(
192                 getListView().getContext()).inflate(
193                 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
194
195         downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
196                 getListView().getContext()).inflate(
197                 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
198
199         showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
200                 .findViewById(R.id.hideDownloadable);
201         showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
202             @Override
203             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
204                 onShowLocalChanged();
205             }
206         });
207
208         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
209         final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
210         if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
211                 thanksForUpdatingLatestVersion)) {
212             blockAutoLaunch = true;
213             startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent());
214             prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
215                     .commit();
216         }
217
218         registerReceiver(broadcastReceiver, new IntentFilter(
219                 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
220
221         setListAdapater();
222         registerForContextMenu(getListView());
223
224         final File dictDir = application.getDictDir();
225         if (!dictDir.canRead() || !dictDir.canExecute()) {
226             blockAutoLaunch = true;
227
228             AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
229             builder.setTitle(getString(R.string.error));
230             builder.setMessage(getString(
231                     R.string.unableToReadDictionaryDir,
232                     dictDir.getAbsolutePath(),
233                     Environment.getExternalStorageDirectory()));
234             builder.create().show();
235         }
236
237         onCreateSetupActionBar();
238     }
239
240     private void onCreateSetupActionBar() {
241         ActionBar actionBar = getSupportActionBar();
242         actionBar.setDisplayShowTitleEnabled(false);
243
244         filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
245         filterSearchView.setIconifiedByDefault(false);
246         // filterSearchView.setIconified(false); // puts the magnifying glass in
247         // the
248         // wrong place.
249         filterSearchView.setQueryHint(getString(R.string.searchText));
250         filterSearchView.setSubmitButtonEnabled(false);
251         final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
252                 getResources().getDisplayMetrics());
253         FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
254                 FrameLayout.LayoutParams.WRAP_CONTENT);
255         filterSearchView.setLayoutParams(lp);
256         filterSearchView.setImeOptions(
257                 EditorInfo.IME_ACTION_SEARCH |
258                         EditorInfo.IME_FLAG_NO_EXTRACT_UI |
259                         EditorInfo.IME_FLAG_NO_ENTER_ACTION |
260                         // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
261                         // 11
262                         EditorInfo.IME_MASK_ACTION |
263                         EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
264
265         filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
266             @Override
267             public boolean onQueryTextSubmit(String query) {
268                 return true;
269             }
270
271             @Override
272             public boolean onQueryTextChange(String filterText) {
273                 setListAdapater();
274                 return true;
275             }
276         });
277         filterSearchView.setFocusable(true);
278
279         actionBar.setCustomView(filterSearchView);
280         actionBar.setDisplayShowCustomEnabled(true);
281     }
282
283     @Override
284     public void onDestroy() {
285         super.onDestroy();
286         unregisterReceiver(broadcastReceiver);
287     }
288
289     private static int copyStream(final InputStream in, final OutputStream out)
290             throws IOException {
291         int bytesRead;
292         final byte[] bytes = new byte[1024 * 16];
293         while ((bytesRead = in.read(bytes)) != -1) {
294             out.write(bytes, 0, bytesRead);
295         }
296         in.close();
297         out.close();
298         return bytesRead;
299     }
300
301     @Override
302     protected void onStart() {
303         super.onStart();
304         uiHandler = new Handler();
305     }
306
307     @Override
308     protected void onStop() {
309         super.onStop();
310         uiHandler = null;
311     }
312
313     @Override
314     protected void onResume() {
315         super.onResume();
316
317         if (PreferenceActivity.prefsMightHaveChanged) {
318             PreferenceActivity.prefsMightHaveChanged = false;
319             finish();
320             startActivity(getIntent());
321         }
322
323         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
324         showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, false));
325
326         if (!blockAutoLaunch &&
327                 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
328                 prefs.contains(C.DICT_FILE) &&
329                 prefs.contains(C.INDEX_SHORT_NAME)) {
330             Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
331             startActivity(DictionaryActivity.getLaunchIntent(
332                     new File(prefs.getString(C.DICT_FILE, "")),
333                     prefs.getString(C.INDEX_SHORT_NAME, ""),
334                     prefs.getString(C.SEARCH_TOKEN, "")));
335             finish();
336             return;
337         }
338
339         // Remove the active dictionary from the prefs so we won't autolaunch
340         // next time.
341         final Editor editor = prefs.edit();
342         editor.remove(C.DICT_FILE);
343         editor.remove(C.INDEX_SHORT_NAME);
344         editor.remove(C.SEARCH_TOKEN);
345         editor.commit();
346
347         application.backgroundUpdateDictionaries(dictionaryUpdater);
348
349         setListAdapater();
350     }
351
352     @Override
353     public boolean onCreateOptionsMenu(final Menu menu) {
354         application.onCreateGlobalOptionsMenu(this, menu);
355         return true;
356     }
357
358     @Override
359     public void onCreateContextMenu(final ContextMenu menu, final View view,
360             final ContextMenuInfo menuInfo) {
361         super.onCreateContextMenu(menu, view, menuInfo);
362         Log.d(LOG, "onCreateContextMenu, " + menuInfo);
363
364         final AdapterContextMenuInfo adapterContextMenuInfo =
365                 (AdapterContextMenuInfo) menuInfo;
366         final int position = adapterContextMenuInfo.position;
367         final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
368
369         if (row.dictionaryInfo == null) {
370             return;
371         }
372
373         if (position > 0 && row.onDevice) {
374             final android.view.MenuItem moveToTopMenuItem =
375                     menu.add(R.string.moveToTop);
376             moveToTopMenuItem.setOnMenuItemClickListener(new
377                     android.view.MenuItem.OnMenuItemClickListener() {
378                         @Override
379                         public boolean onMenuItemClick(android.view.MenuItem item) {
380                             application.moveDictionaryToTop(row.dictionaryInfo);
381                             setListAdapater();
382                             return true;
383                         }
384                     });
385         }
386
387         if (row.onDevice) {
388             final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
389             deleteMenuItem
390                     .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
391                         @Override
392                         public boolean onMenuItemClick(android.view.MenuItem item) {
393                             application.deleteDictionary(row.dictionaryInfo);
394                             setListAdapater();
395                             return true;
396                         }
397                     });
398         }
399     }
400
401     private void onShowLocalChanged() {
402         setListAdapater();
403         Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
404         prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
405         prefs.commit();
406     }
407
408     class MyListAdapter extends BaseAdapter {
409
410         List<DictionaryInfo> dictionariesOnDevice;
411         List<DictionaryInfo> downloadableDictionaries;
412
413         class Row {
414             DictionaryInfo dictionaryInfo;
415             boolean onDevice;
416
417             private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
418                 this.dictionaryInfo = dictinoaryInfo;
419                 this.onDevice = onDevice;
420             }
421         }
422
423         private MyListAdapter(final String[] filters) {
424             dictionariesOnDevice = application.getDictionariesOnDevice(filters);
425             if (showDownloadable.isChecked()) {
426                 downloadableDictionaries = application.getDownloadableDictionaries(filters);
427             } else {
428                 downloadableDictionaries = Collections.emptyList();
429             }
430         }
431
432         @Override
433         public int getCount() {
434             return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
435         }
436
437         @Override
438         public Row getItem(int position) {
439             if (position == 0) {
440                 return new Row(null, true);
441             }
442             position -= 1;
443
444             if (position < dictionariesOnDevice.size()) {
445                 return new Row(dictionariesOnDevice.get(position), true);
446             }
447             position -= dictionariesOnDevice.size();
448
449             if (position == 0) {
450                 return new Row(null, false);
451             }
452             position -= 1;
453
454             assert position < downloadableDictionaries.size();
455             return new Row(downloadableDictionaries.get(position), false);
456         }
457
458         @Override
459         public long getItemId(int position) {
460             return position;
461         }
462
463         @Override
464         public View getView(int position, View convertView, ViewGroup parent) {
465             if (convertView instanceof LinearLayout &&
466                     convertView != dictionariesOnDeviceHeaderRow &&
467                     convertView != downloadableDictionariesHeaderRow) {
468                 /*
469                  * This is done to try to avoid leaking memory that used to
470                  * happen on Android 4.0.3
471                  */
472                 ((LinearLayout) convertView).removeAllViews();
473             }
474
475             final Row row = getItem(position);
476
477             if (row.onDevice) {
478                 if (row.dictionaryInfo == null) {
479                     return dictionariesOnDeviceHeaderRow;
480                 }
481                 return createDictionaryRow(row.dictionaryInfo, parent, true);
482             }
483
484             if (row.dictionaryInfo == null) {
485                 return downloadableDictionariesHeaderRow;
486             }
487             return createDictionaryRow(row.dictionaryInfo, parent, false);
488         }
489
490     }
491
492     private void setListAdapater() {
493         final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
494                 .toString();
495         final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
496         setListAdapter(new MyListAdapter(filters));
497     }
498
499     private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
500             final ViewGroup parent, final boolean canLaunch) {
501
502         View row = LayoutInflater.from(parent.getContext()).inflate(
503                 R.layout.dictionary_manager_row, parent, false);
504         final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
505         final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
506         name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
507
508         final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
509         final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
510         if (!canLaunch || updateAvailable) {
511             downloadButton
512                     .setText(getString(
513                             R.string.downloadButton,
514                             application.getDownloadable(dictionaryInfo.uncompressedFilename).zipBytes / 1024.0 / 1024.0));
515             downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
516             downloadButton.setOnClickListener(new OnClickListener() {
517                 @Override
518                 public void onClick(View arg0) {
519                     downloadDictionary(dictionaryInfo);
520                 }
521             });
522         } else {
523             downloadButton.setVisibility(View.INVISIBLE);
524         }
525
526         LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
527         final List<IndexInfo> sortedIndexInfos = application
528                 .sortedIndexInfos(dictionaryInfo.indexInfos);
529         final StringBuilder builder = new StringBuilder();
530         if (updateAvailable) {
531             builder.append(getString(R.string.updateButton));
532         }
533         for (IndexInfo indexInfo : sortedIndexInfos) {
534             final View button = application.createButton(buttons.getContext(), dictionaryInfo,
535                     indexInfo);
536             buttons.addView(button);
537
538             if (canLaunch) {
539                 button.setOnClickListener(
540                         new IntentLauncher(buttons.getContext(),
541                                 DictionaryActivity.getLaunchIntent(
542                                         application.getPath(dictionaryInfo.uncompressedFilename),
543                                         indexInfo.shortName, "")));
544
545             } else {
546                 button.setEnabled(false);
547             }
548             if (builder.length() != 0) {
549                 builder.append("; ");
550             }
551             builder.append(getString(R.string.indexInfo, indexInfo.shortName,
552                     indexInfo.mainTokenCount));
553         }
554         details.setText(builder.toString());
555
556         if (canLaunch) {
557             row.setClickable(true);
558             row.setOnClickListener(new IntentLauncher(parent.getContext(),
559                     DictionaryActivity.getLaunchIntent(
560                             application.getPath(dictionaryInfo.uncompressedFilename),
561                             dictionaryInfo.indexInfos.get(0).shortName, "")));
562             row.setFocusable(true);
563             row.setLongClickable(true);
564         }
565         row.setBackgroundResource(android.R.drawable.menuitem_background);
566
567         return row;
568     }
569
570     private void downloadDictionary(final DictionaryInfo dictionaryInfo) {
571         DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
572         Request request = new Request(
573                 Uri.parse(dictionaryInfo.downloadUrl));
574         try {
575             final String destFile = new File(new URL(dictionaryInfo.downloadUrl).getFile())
576                     .getName();
577             Log.d(LOG, "Downloading to: " + destFile);
578
579             request.setDestinationUri(Uri.fromFile(new File(Environment
580                     .getExternalStorageDirectory(), destFile)));
581         } catch (MalformedURLException e) {
582             throw new RuntimeException(e);
583         }
584         downloadManager.enqueue(request);
585     }
586
587 }