1 // Copyright 2011 Google Inc. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 package com.hughes.android.dictionary;
17 import android.app.AlertDialog;
18 import android.app.DownloadManager;
19 import android.app.DownloadManager.Request;
20 import android.content.BroadcastReceiver;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.IntentFilter;
24 import android.content.SharedPreferences;
25 import android.content.SharedPreferences.Editor;
26 import android.database.Cursor;
27 import android.net.Uri;
28 import android.os.Bundle;
29 import android.os.Environment;
30 import android.os.Handler;
31 import android.preference.PreferenceManager;
32 import android.support.v7.app.ActionBar;
33 import android.support.v7.app.ActionBarActivity;
34 import android.support.v7.widget.SearchView;
35 import android.support.v7.widget.SearchView.OnQueryTextListener;
36 import android.util.Log;
37 import android.util.TypedValue;
38 import android.view.ContextMenu;
39 import android.view.ContextMenu.ContextMenuInfo;
40 import android.view.LayoutInflater;
41 import android.view.Menu;
42 import android.view.View;
43 import android.view.View.OnClickListener;
44 import android.view.ViewGroup;
45 import android.view.inputmethod.EditorInfo;
46 import android.widget.AdapterView.AdapterContextMenuInfo;
47 import android.widget.BaseAdapter;
48 import android.widget.Button;
49 import android.widget.CompoundButton;
50 import android.widget.CompoundButton.OnCheckedChangeListener;
51 import android.widget.FrameLayout;
52 import android.widget.LinearLayout;
53 import android.widget.ListAdapter;
54 import android.widget.ListView;
55 import android.widget.TextView;
56 import android.widget.Toast;
57 import android.widget.ToggleButton;
59 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
60 import com.hughes.android.util.IntentLauncher;
63 import java.io.FileOutputStream;
64 import java.io.IOException;
65 import java.io.InputStream;
66 import java.io.OutputStream;
67 import java.net.MalformedURLException;
69 import java.util.Collections;
70 import java.util.List;
71 import java.util.zip.ZipEntry;
72 import java.util.zip.ZipFile;
75 // Delete, move to top.
77 public class DictionaryManagerActivity extends ActionBarActivity {
79 static final String LOG = "QuickDic";
80 static boolean blockAutoLaunch = false;
82 private ListView listView;
83 private ListView getListView() {
84 if (listView == null) {
85 listView = (ListView)findViewById(android.R.id.list);
89 private void setListAdapter(ListAdapter adapter) {
90 getListView().setAdapter(adapter);
92 private ListAdapter getListAdapter() {
93 return getListView().getAdapter();
96 DictionaryApplication application;
98 SearchView filterSearchView;
99 ToggleButton showDownloadable;
101 LinearLayout dictionariesOnDeviceHeaderRow;
102 LinearLayout downloadableDictionariesHeaderRow;
106 Runnable dictionaryUpdater = new Runnable() {
109 if (uiHandler == null) {
112 uiHandler.post(new Runnable() {
121 final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
123 public void onReceive(Context context, Intent intent) {
124 final String action = intent.getAction();
126 if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
127 final long downloadId = intent.getLongExtra(
128 DownloadManager.EXTRA_DOWNLOAD_ID, 0);
129 final DownloadManager.Query query = new DownloadManager.Query();
130 query.setFilterById(downloadId);
131 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
132 final Cursor cursor = downloadManager.query(query);
134 if (!cursor.moveToFirst()) {
135 Log.e(LOG, "Couldn't find download.");
139 final String dest = cursor
140 .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
141 final int status = cursor
143 .getColumnIndex(DownloadManager.COLUMN_STATUS));
144 if (DownloadManager.STATUS_SUCCESSFUL != status) {
146 "Download failed: status=" + status +
147 ", reason=" + cursor.getString(cursor
148 .getColumnIndex(DownloadManager.COLUMN_REASON)));
149 Toast.makeText(context, getString(R.string.downloadFailed, dest),
150 Toast.LENGTH_LONG).show();
154 Log.w(LOG, "Download finished: " + dest);
155 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
156 Toast.LENGTH_LONG).show();
159 final File localZipFile = new File(Uri.parse(dest).getPath());
161 ZipFile zipFile = new ZipFile(localZipFile);
162 final ZipEntry zipEntry = zipFile.entries().nextElement();
163 Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
164 final InputStream zipIn = zipFile.getInputStream(zipEntry);
165 File targetFile = new File(application.getDictDir(), zipEntry.getName());
166 if (targetFile.exists()) {
167 targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
168 targetFile = new File(application.getDictDir(), zipEntry.getName());
170 final OutputStream zipOut = new FileOutputStream(targetFile);
171 copyStream(zipIn, zipOut);
173 application.backgroundUpdateDictionaries(dictionaryUpdater);
174 Toast.makeText(context, getString(R.string.installationFinished, dest),
175 Toast.LENGTH_LONG).show();
176 } catch (Exception e) {
177 Toast.makeText(context, getString(R.string.unzippingFailed, dest),
178 Toast.LENGTH_LONG).show();
179 Log.e(LOG, "Failed to unzip.", e);
181 localZipFile.delete();
187 public static Intent getLaunchIntent(Context c) {
188 final Intent intent = new Intent(c, DictionaryManagerActivity.class);
189 intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
194 public void onCreate(Bundle savedInstanceState) {
195 // This must be first, otherwise the actiona bar doesn't get
197 setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
199 super.onCreate(savedInstanceState);
200 Log.d(LOG, "onCreate:" + this);
202 application = (DictionaryApplication) getApplication();
204 blockAutoLaunch = false;
207 setContentView(R.layout.dictionary_manager_activity);
209 dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
210 getListView().getContext()).inflate(
211 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
213 downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
214 getListView().getContext()).inflate(
215 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
217 showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
218 .findViewById(R.id.hideDownloadable);
219 showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
221 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
222 onShowDownloadableChanged();
226 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
227 final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
228 if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
229 thanksForUpdatingLatestVersion)) {
230 blockAutoLaunch = true;
231 startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
232 prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
236 registerReceiver(broadcastReceiver, new IntentFilter(
237 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
240 registerForContextMenu(getListView());
242 final File dictDir = application.getDictDir();
243 if (!dictDir.canRead() || !dictDir.canExecute()) {
244 blockAutoLaunch = true;
246 AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
247 builder.setTitle(getString(R.string.error));
248 builder.setMessage(getString(
249 R.string.unableToReadDictionaryDir,
250 dictDir.getAbsolutePath(),
251 Environment.getExternalStorageDirectory()));
252 builder.create().show();
255 onCreateSetupActionBar();
258 private void onCreateSetupActionBar() {
259 ActionBar actionBar = getSupportActionBar();
260 actionBar.setDisplayShowTitleEnabled(false);
262 filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
263 filterSearchView.setIconifiedByDefault(false);
264 // filterSearchView.setIconified(false); // puts the magnifying glass in
267 filterSearchView.setQueryHint(getString(R.string.searchText));
268 filterSearchView.setSubmitButtonEnabled(false);
269 final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
270 getResources().getDisplayMetrics());
271 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
272 FrameLayout.LayoutParams.WRAP_CONTENT);
273 filterSearchView.setLayoutParams(lp);
274 filterSearchView.setImeOptions(
275 EditorInfo.IME_ACTION_SEARCH |
276 EditorInfo.IME_FLAG_NO_EXTRACT_UI |
277 EditorInfo.IME_FLAG_NO_ENTER_ACTION |
278 // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
280 EditorInfo.IME_MASK_ACTION |
281 EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
283 filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
285 public boolean onQueryTextSubmit(String query) {
290 public boolean onQueryTextChange(String filterText) {
295 filterSearchView.setFocusable(true);
297 actionBar.setCustomView(filterSearchView);
298 actionBar.setDisplayShowCustomEnabled(true);
302 public void onDestroy() {
304 unregisterReceiver(broadcastReceiver);
307 private static int copyStream(final InputStream in, final OutputStream out)
310 final byte[] bytes = new byte[1024 * 16];
311 while ((bytesRead = in.read(bytes)) != -1) {
312 out.write(bytes, 0, bytesRead);
320 protected void onStart() {
322 uiHandler = new Handler();
326 protected void onStop() {
332 protected void onResume() {
335 if (PreferenceActivity.prefsMightHaveChanged) {
336 PreferenceActivity.prefsMightHaveChanged = false;
338 startActivity(getIntent());
341 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
342 showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
344 if (!blockAutoLaunch &&
345 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
346 prefs.contains(C.DICT_FILE) &&
347 prefs.contains(C.INDEX_SHORT_NAME)) {
348 Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
349 startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
350 new File(prefs.getString(C.DICT_FILE, "")),
351 prefs.getString(C.INDEX_SHORT_NAME, ""),
352 prefs.getString(C.SEARCH_TOKEN, "")));
357 // Remove the active dictionary from the prefs so we won't autolaunch
359 final Editor editor = prefs.edit();
360 editor.remove(C.DICT_FILE);
361 editor.remove(C.INDEX_SHORT_NAME);
362 editor.remove(C.SEARCH_TOKEN);
365 application.backgroundUpdateDictionaries(dictionaryUpdater);
371 public boolean onCreateOptionsMenu(final Menu menu) {
372 application.onCreateGlobalOptionsMenu(this, menu);
377 public void onCreateContextMenu(final ContextMenu menu, final View view,
378 final ContextMenuInfo menuInfo) {
379 super.onCreateContextMenu(menu, view, menuInfo);
380 Log.d(LOG, "onCreateContextMenu, " + menuInfo);
382 final AdapterContextMenuInfo adapterContextMenuInfo =
383 (AdapterContextMenuInfo) menuInfo;
384 final int position = adapterContextMenuInfo.position;
385 final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
387 if (row.dictionaryInfo == null) {
391 if (position > 0 && row.onDevice) {
392 final android.view.MenuItem moveToTopMenuItem =
393 menu.add(R.string.moveToTop);
394 moveToTopMenuItem.setOnMenuItemClickListener(new
395 android.view.MenuItem.OnMenuItemClickListener() {
397 public boolean onMenuItemClick(android.view.MenuItem item) {
398 application.moveDictionaryToTop(row.dictionaryInfo);
406 final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
408 .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
410 public boolean onMenuItemClick(android.view.MenuItem item) {
411 application.deleteDictionary(row.dictionaryInfo);
419 private void onShowDownloadableChanged() {
421 Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
422 prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
426 class MyListAdapter extends BaseAdapter {
428 List<DictionaryInfo> dictionariesOnDevice;
429 List<DictionaryInfo> downloadableDictionaries;
432 DictionaryInfo dictionaryInfo;
435 private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
436 this.dictionaryInfo = dictinoaryInfo;
437 this.onDevice = onDevice;
441 private MyListAdapter(final String[] filters) {
442 dictionariesOnDevice = application.getDictionariesOnDevice(filters);
443 if (showDownloadable.isChecked()) {
444 downloadableDictionaries = application.getDownloadableDictionaries(filters);
446 downloadableDictionaries = Collections.emptyList();
451 public int getCount() {
452 return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
456 public Row getItem(int position) {
458 return new Row(null, true);
462 if (position < dictionariesOnDevice.size()) {
463 return new Row(dictionariesOnDevice.get(position), true);
465 position -= dictionariesOnDevice.size();
468 return new Row(null, false);
472 assert position < downloadableDictionaries.size();
473 return new Row(downloadableDictionaries.get(position), false);
477 public long getItemId(int position) {
482 public View getView(int position, View convertView, ViewGroup parent) {
483 if (convertView instanceof LinearLayout &&
484 convertView != dictionariesOnDeviceHeaderRow &&
485 convertView != downloadableDictionariesHeaderRow) {
487 * This is done to try to avoid leaking memory that used to
488 * happen on Android 4.0.3
490 ((LinearLayout) convertView).removeAllViews();
493 final Row row = getItem(position);
496 if (row.dictionaryInfo == null) {
497 return dictionariesOnDeviceHeaderRow;
499 return createDictionaryRow(row.dictionaryInfo, parent, true);
502 if (row.dictionaryInfo == null) {
503 return downloadableDictionariesHeaderRow;
505 return createDictionaryRow(row.dictionaryInfo, parent, false);
510 private void setMyListAdapater() {
511 final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
513 final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
514 setListAdapter(new MyListAdapter(filters));
517 private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
518 final ViewGroup parent, final boolean canLaunch) {
520 View row = LayoutInflater.from(parent.getContext()).inflate(
521 R.layout.dictionary_manager_row, parent, false);
522 final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
523 final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
524 name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
526 final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
527 final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
528 if (!canLaunch || updateAvailable) {
529 final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
532 R.string.downloadButton,
533 downloadable.zipBytes / 1024.0 / 1024.0));
534 downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
535 downloadButton.setOnClickListener(new OnClickListener() {
537 public void onClick(View arg0) {
538 downloadDictionary(downloadable.downloadUrl);
542 downloadButton.setVisibility(View.INVISIBLE);
545 LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
546 final List<IndexInfo> sortedIndexInfos = application
547 .sortedIndexInfos(dictionaryInfo.indexInfos);
548 final StringBuilder builder = new StringBuilder();
549 if (updateAvailable) {
550 builder.append(getString(R.string.updateAvailable));
552 for (IndexInfo indexInfo : sortedIndexInfos) {
553 final View button = application.createButton(buttons.getContext(), dictionaryInfo,
555 buttons.addView(button);
558 button.setOnClickListener(
559 new IntentLauncher(buttons.getContext(),
560 DictionaryActivity.getLaunchIntent(getApplicationContext(),
561 application.getPath(dictionaryInfo.uncompressedFilename),
562 indexInfo.shortName, "")));
565 button.setEnabled(false);
567 if (builder.length() != 0) {
568 builder.append("; ");
570 builder.append(getString(R.string.indexInfo, indexInfo.shortName,
571 indexInfo.mainTokenCount));
573 details.setText(builder.toString());
576 row.setClickable(true);
577 row.setOnClickListener(new IntentLauncher(parent.getContext(),
578 DictionaryActivity.getLaunchIntent(getApplicationContext(),
579 application.getPath(dictionaryInfo.uncompressedFilename),
580 dictionaryInfo.indexInfos.get(0).shortName, "")));
581 row.setFocusable(true);
582 row.setLongClickable(true);
584 row.setBackgroundResource(android.R.drawable.menuitem_background);
589 private void downloadDictionary(final String downloadUrl) {
590 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
591 Request request = new Request(
592 Uri.parse(downloadUrl));
594 final String destFile = new File(new URL(downloadUrl).getFile())
596 Log.d(LOG, "Downloading to: " + destFile);
598 request.setDestinationUri(Uri.fromFile(new File(Environment
599 .getExternalStorageDirectory(), destFile)));
600 } catch (MalformedURLException e) {
601 throw new RuntimeException(e);
603 downloadManager.enqueue(request);